Files
cutdex/test/preview_panel_test.dart
T
lingjhf abc1868550
Gitea CI / Check code and tests (push) Successful in 6m37s
Gitea CI / Build Windows x64 app (push) Successful in 3m18s
Gitea CI / Build Android APK (push) Successful in 3m47s
Gitea CI / Audit and package Windows x64 (push) Successful in 1m7s
Gitea CI / Assemble and validate CI artifacts (push) Successful in 50s
Gitea CI / Gitea CI passed (push) Successful in 2s
Gitea Release / Prepare draft Release (push) Successful in 9s
Gitea Release / Upload Android to draft Release (push) Successful in 16s
Gitea Release / Upload Windows to draft Release (push) Successful in 22s
Gitea Release / Verify and publish Release (push) Successful in 14s
feat(workspace): 桌面工作区、主题与交互更新,发布 0.1.2
2026-10-08 18:17:12 +00:00

582 lines
20 KiB
Dart

import 'package:cutdex/app/editor_theme.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:cutdex/workspace/timeline_provider.dart';
import 'package:cutdex/l10n/app_localizations.dart';
import 'package:cutdex/features/properties/canvas_presets.dart';
import 'dart:async';
import 'package:cutdex/features/preview/preview_panel.dart';
import 'package:cutdex_sdk/preview.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex/workspace/media_availability.dart';
import 'package:cutdex/workspace/preview_target.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/preview_fixture.dart';
void main() {
final surface = find.byKey(const Key('preview-surface'));
final toolbar = find.byKey(const Key('preview-toolbar'));
final canvas = find.byKey(const Key('preview-canvas'));
final playButton = find.byWidgetPredicate(
(widget) => widget is IconButton && widget.tooltip == '播放',
);
Future<void> mount(
WidgetTester tester,
Future<PreviewController> Function() load, {
ThemeData? theme,
MediaAvailability availability = MediaAvailability.available,
}) => tester.pumpWidget(
ProviderScope(
overrides: [
mediaAvailabilityProvider.overrideWith(
(ref, key) async => availability,
),
editorPreviewProvider(
'project',
'project',
).overrideWith((ref) => load()),
],
child: MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
locale: const Locale('zh'),
theme: theme ?? EditorTheme.penLight,
home: const Scaffold(
body: EditorPreviewPanel(projectId: 'project', timelineId: 'project'),
),
),
),
);
testWidgets(
'missing source shows the project placeholder and disables playback',
(tester) async {
final preview = _Preview();
addTearDown(preview.dispose);
await mount(
tester,
() async => preview,
availability: MediaAvailability.missing,
);
await tester.pumpAndSettle();
final container = ProviderScope.containerOf(
tester.element(find.byType(EditorPreviewPanel)),
);
container
.read(previewTargetProvider('project', 'project'))
.showAsset(
AssetDocument(
id: 'missing',
name: 'missing.mov',
storage: AssetStorage.external,
location: 'file:///missing.mov',
),
);
await tester.pumpAndSettle();
expect(find.text('素材缺失'), findsOneWidget);
expect(find.byIcon(AppIcons.imageUnavailable), findsOneWidget);
expect(find.textContaining('RuntimeException'), findsNothing);
expect(tester.widget<IconButton>(playButton).onPressed, isNull);
expect(find.byTooltip('画布比例'), findsNothing);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
},
);
testWidgets('workspace follows theme while canvas content stays dark', (
tester,
) async {
final preview = _Preview()..error = 'Preview error';
addTearDown(preview.dispose);
for (final theme in [EditorTheme.penLight, EditorTheme.penDark]) {
await mount(tester, () async => preview, theme: theme);
await tester.pumpAndSettle();
expect(
tester.widget<ColoredBox>(surface).color,
theme.colorScheme.surface,
);
expect(tester.widget<ColoredBox>(canvas).color, Colors.black);
expect(Theme.of(tester.element(toolbar)).brightness, theme.brightness);
expect(
Theme.of(tester.element(find.text('Preview error'))).brightness,
Brightness.dark,
);
}
});
testWidgets('preview has a fixed toolbar below flexible video', (
tester,
) async {
final preview = _Preview();
addTearDown(preview.dispose);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetDevicePixelRatio);
addTearDown(tester.view.resetPhysicalSize);
await mount(tester, () async => preview);
await tester.pumpAndSettle();
for (final size in [const Size(640, 400), const Size(240, 180)]) {
tester.view.physicalSize = size;
await tester.pumpAndSettle();
final videoRect = tester.getRect(surface);
final canvasRect = tester.getRect(canvas);
final toolbarRect = tester.getRect(toolbar);
expect(find.text('视频预览'), findsNothing);
expect(videoRect.left, AppSpacing.panelContentHorizontal);
expect(videoRect.right, size.width - AppSpacing.panelContentHorizontal);
expect(videoRect.top, AppSpacing.small);
expect(videoRect.bottom, toolbarRect.top - AppSpacing.small);
expect(canvasRect.center.dx, closeTo(videoRect.center.dx, 0.01));
expect(canvasRect.center.dy, closeTo(videoRect.center.dy, 0.01));
expect(toolbarRect.bottom, size.height);
expect(toolbarRect.height, AppControlSize.panelHeader);
expect(tester.getCenter(find.byTooltip('播放')).dx, size.width / 2);
expect(
find.descendant(
of: toolbar,
matching: find.text('00:00:00:00 / 02:00:00:00'),
),
findsOneWidget,
);
expect(Theme.of(tester.element(surface)).brightness, Brightness.light);
expect(Theme.of(tester.element(toolbar)).brightness, Brightness.light);
expect(tester.takeException(), isNull);
}
await tester.tap(find.byTooltip('播放'));
await tester.pump();
expect(preview.playing, isTrue);
expect(find.byTooltip('暂停播放'), findsOneWidget);
preview.moveTo(3661 * TimelineClock.ticksPerSecond);
await tester.pump();
expect(find.text('01:01:01:00 / 02:00:00:00'), findsOneWidget);
await tester.tap(find.byTooltip('暂停播放'));
await tester.pump();
expect(preview.playing, isFalse);
await tester.pumpWidget(const SizedBox());
});
testWidgets('empty timeline does not render a video canvas', (tester) async {
final preview = _Preview()..durationTick = 0;
addTearDown(preview.dispose);
await mount(tester, () async => preview);
await tester.pumpAndSettle();
expect(canvas, findsNothing);
expect(find.byKey(const Key('empty-preview-area')), findsOneWidget);
expect(find.text('暂无可预览内容'), findsNothing);
expect(toolbar, findsOneWidget);
expect(tester.takeException(), isNull);
preview.durationTick = TimelineClock.ticksPerSecond;
preview.notifyListeners();
await tester.pump();
expect(canvas, findsOneWidget);
expect(find.byKey(const Key('empty-preview-area')), findsNothing);
preview.durationTick = 0;
preview.notifyListeners();
await tester.pump();
expect(canvas, findsNothing);
expect(find.byKey(const Key('empty-preview-area')), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
testWidgets('empty timeline skips native preview initialization', (
tester,
) async {
final empty = TimelineDto(
id: SequenceId('one'),
name: 'Empty',
format: TimelineFormat.fps30,
primaryStorylineId: StorylineId('primary'),
storylines: [
StorylineDto(id: StorylineId('primary'), elementIds: const []),
],
elements: const [],
);
final fixture = (await tester.runAsync(
() => createPreviewFixture(
Uri.file('/unused.mov'),
timelineOverride: empty,
),
))!;
addTearDown(() async {
await fixture.workspace.close();
await fixture.directory.delete(recursive: true);
});
final calls = <MethodCall>[];
final messenger =
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
const runtimeChannel = MethodChannel('cutdex_runtime');
messenger.setMockMethodCallHandler(runtimeChannel, (call) async {
calls.add(call);
return null;
});
addTearDown(() => messenger.setMockMethodCallHandler(runtimeChannel, null));
final ids = (fixture.workspace.project!.info.id, 'project');
await tester.pumpWidget(
ProviderScope(
overrides: [
editorTimelineProvider(
ids.$1,
ids.$2,
).overrideWith((ref) async => fixture.timeline),
],
child: MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
locale: const Locale('zh'),
theme: EditorTheme.penLight,
home: Scaffold(
body: EditorPreviewPanel(projectId: ids.$1, timelineId: ids.$2),
),
),
),
);
await tester.pumpAndSettle();
expect(find.byKey(const Key('empty-preview-area')), findsOneWidget);
expect(canvas, findsNothing);
expect(find.byType(CircularProgressIndicator), findsNothing);
expect(calls, isEmpty);
expect(tester.takeException(), isNull);
});
testWidgets('time display follows project frames and duration changes', (
tester,
) async {
final preview = _Preview()
..frameDuration = TimelineFormat.fps25.frameDuration;
addTearDown(preview.dispose);
final frame = TimelineClock.standard.toTicks(preview.frameDuration);
preview.durationTick = 129 * frame;
preview.positionTick = 15 * frame;
await mount(tester, () async => preview);
await tester.pumpAndSettle();
expect(find.text('00:00:00:15 / 00:00:05:04'), findsOneWidget);
preview.durationTick = 150 * frame;
preview.moveTo(25 * frame);
await tester.pump();
expect(find.text('00:00:01:00 / 00:00:06:00'), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
testWidgets('editor failure retry recreates the editor provider', (
tester,
) async {
var attempts = 0;
await tester.pumpWidget(
ProviderScope(
overrides: [
editorTimelineProvider('project', 'project').overrideWith((
ref,
) async {
attempts++;
throw StateError('checkpoint failed');
}),
],
child: MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
locale: const Locale('zh'),
theme: EditorTheme.penLight,
home: const Scaffold(
body: EditorPreviewPanel(
projectId: 'project',
timelineId: 'project',
),
),
),
),
);
for (var i = 0; i < 20 && find.text('无法打开时间线编辑器').evaluate().isEmpty; i++) {
await tester.pump(const Duration(milliseconds: 10));
}
await tester.pumpAndSettle();
expect(find.text('无法打开时间线编辑器'), findsOneWidget);
expect(attempts, 1);
await tester.tap(find.text('重试'));
await tester.pumpAndSettle();
expect(attempts, 2);
expect(find.text('无法启动原生预览'), findsNothing);
await tester.pumpWidget(const SizedBox());
});
testWidgets(
'editor startup failure is distinct from native preview failure',
(tester) async {
await mount(
tester,
() async =>
throw EditorSessionStartupException(StateError('checkpoint')),
);
for (
var i = 0;
i < 20 && find.text('无法打开时间线编辑器').evaluate().isEmpty;
i++
) {
await tester.pump(const Duration(milliseconds: 10));
}
await tester.pumpAndSettle();
expect(find.text('无法打开时间线编辑器'), findsOneWidget);
expect(find.text('无法启动原生预览'), findsNothing);
expect(find.text('重试'), findsOneWidget);
expect(tester.widget<IconButton>(playButton).onPressed, isNull);
await tester.pumpWidget(const SizedBox());
},
);
testWidgets('loading and initialization failure keep the toolbar disabled', (
tester,
) async {
final pending = Completer<PreviewController>();
var loads = 0;
await mount(tester, () {
loads++;
return pending.future;
});
final loadingRect = tester.getRect(toolbar);
expect(find.byKey(const Key('preview-default-frame')), findsOneWidget);
expect(find.byType(CircularProgressIndicator), findsNothing);
expect(find.text('00:00:00:00 / 00:00:00:00'), findsOneWidget);
expect(tester.widget<IconButton>(playButton).onPressed, isNull);
pending.completeError(StateError('unavailable'));
await tester.pumpAndSettle();
expect(find.text('无法启动原生预览'), findsOneWidget);
expect(tester.getRect(toolbar), loadingRect);
expect(tester.widget<IconButton>(playButton).onPressed, isNull);
await tester.tap(find.text('重试'));
await tester.pumpAndSettle();
expect(loads, 2);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
});
testWidgets(
'canvas ratio changes independently of the workspace and toolbar',
(tester) async {
final preview = _Preview();
addTearDown(preview.dispose);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetDevicePixelRatio);
addTearDown(tester.view.resetPhysicalSize);
await mount(tester, () async => preview);
await tester.pumpAndSettle();
for (final size in [const Size(640, 400), const Size(240, 180)]) {
tester.view.physicalSize = size;
await tester.pumpAndSettle();
final toolbarRect = tester.getRect(toolbar);
final surfaceRect = tester.getRect(surface);
for (final entry in ProjectCanvasPresets.values.entries) {
await tester.tap(find.byType(AppSelect<ProjectCanvas>));
await tester.pumpAndSettle();
final item = find.text(entry.key).last;
await tester.ensureVisible(item);
await tester.pumpAndSettle();
await tester.tap(item);
await tester.pumpAndSettle();
final rect = tester.getRect(canvas);
expect(
rect.width / rect.height,
closeTo(entry.value.aspectRatio, 0.000001),
);
expect(rect.center.dx, closeTo(surfaceRect.center.dx, 0.000001));
expect(rect.top, closeTo(surfaceRect.top, 0.000001));
expect(rect.left, greaterThan(surfaceRect.left));
expect(rect.right, lessThan(surfaceRect.right));
expect(rect.bottom, lessThanOrEqualTo(surfaceRect.bottom + 0.000001));
expect(tester.getRect(toolbar), toolbarRect);
expect(
tester.widget<ColoredBox>(canvas).color,
isNot(tester.widget<ColoredBox>(surface).color),
);
expect(tester.takeException(), isNull);
}
}
await tester.pumpWidget(const SizedBox());
},
);
testWidgets('clock and playback update only their own preview regions', (
tester,
) async {
final preview = _Preview();
addTearDown(preview.dispose);
await mount(tester, () async => preview);
await tester.pumpAndSettle();
final canvasBefore = tester.widget<PreviewCanvas>(
find.byType(PreviewCanvas),
);
final toolbarBefore = tester.widget(toolbar);
final playBefore = tester.widget<IconButton>(playButton);
final ratioBefore = tester.widget<AppSelect<ProjectCanvas>>(
find.byType(AppSelect<ProjectCanvas>),
);
final timeFinder = find.descendant(
of: find.byKey(const Key('preview-time')),
matching: find.byType(Text),
);
final timeBefore = tester.widget<Text>(timeFinder);
preview.moveTo(TimelineClock.ticksPerSecond);
await tester.pump();
expect(find.text('00:00:01:00 / 02:00:00:00'), findsOneWidget);
expect(tester.widget(toolbar), same(toolbarBefore));
expect(
tester.widget<PreviewCanvas>(find.byType(PreviewCanvas)),
same(canvasBefore),
);
expect(tester.widget<IconButton>(playButton), same(playBefore));
expect(
tester.widget<AppSelect<ProjectCanvas>>(
find.byType(AppSelect<ProjectCanvas>),
),
same(ratioBefore),
);
expect(tester.widget<Text>(timeFinder), isNot(same(timeBefore)));
final timeAfterSeek = tester.widget<Text>(timeFinder);
await preview.togglePlayback();
await tester.pump();
expect(find.byIcon(AppIcons.pause), findsOneWidget);
expect(tester.widget(toolbar), same(toolbarBefore));
expect(
tester.widget<PreviewCanvas>(find.byType(PreviewCanvas)),
same(canvasBefore),
);
expect(tester.widget<Text>(timeFinder), same(timeAfterSeek));
expect(
tester.widget<AppSelect<ProjectCanvas>>(
find.byType(AppSelect<ProjectCanvas>),
),
same(ratioBefore),
);
preview.setCanvas(
ProjectCanvasPresets.values.values.firstWhere(
(value) => value != preview.canvas,
),
);
await tester.pump();
expect(tester.widget(toolbar), same(toolbarBefore));
expect(tester.widget<Text>(timeFinder), same(timeAfterSeek));
expect(
tester.widget<PreviewCanvas>(find.byType(PreviewCanvas)),
isNot(same(canvasBefore)),
);
await tester.pumpWidget(const SizedBox());
});
testWidgets('offline media keeps playback available with a local notice', (
tester,
) async {
final preview = _Preview()
..hasUnavailableMedia = true
..unavailableAtPlayhead = ['image'];
addTearDown(preview.dispose);
await mount(tester, () async => preview);
await tester.pumpAndSettle();
expect(find.text('素材离线或不可用:image'), findsOneWidget);
expect(tester.widget<IconButton>(playButton).onPressed, isNotNull);
expect(find.byTooltip('重试预览'), findsOneWidget);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
});
testWidgets('playback failure offers retry in the bottom toolbar', (
tester,
) async {
final preview = _Preview()..error = '预览失败';
addTearDown(preview.dispose);
await mount(tester, () async => preview);
await tester.pumpAndSettle();
expect(tester.widget<IconButton>(playButton).onPressed, isNull);
expect(
find.descendant(of: toolbar, matching: find.byTooltip('重试预览')),
findsOneWidget,
);
await tester.tap(find.byTooltip('重试预览'));
await tester.pump();
expect(preview.retries, 1);
expect(find.byTooltip('重试预览'), findsNothing);
expect(tester.widget<IconButton>(playButton).onPressed, isNotNull);
await tester.pumpWidget(const SizedBox());
});
}
class _Preview extends ChangeNotifier implements PreviewController {
@override
Listenable get positionChanges => this;
@override
bool hasUnavailableMedia = false;
@override
List<String> unavailableAtPlayhead = [];
@override
ProjectCanvas canvas = ProjectCanvas.widescreen;
@override
void setCanvas(ProjectCanvas value) {
canvas = value;
notifyListeners();
}
@override
RuntimeSession? get session => null;
@override
bool playing = false;
@override
bool busy = false;
@override
Object? error;
@override
int positionTick = 0;
@override
int durationTick = 7200 * TimelineClock.ticksPerSecond;
@override
RationalTime frameDuration = TimelineFormat.fps30.frameDuration;
@override
bool get canPlay => !busy && error == null;
int retries = 0;
void moveTo(int tick) {
positionTick = tick;
notifyListeners();
}
@override
Future<void> togglePlayback() async {
playing = !playing;
notifyListeners();
}
@override
Future<void> pauseForCanvasInteraction() async {
playing = false;
}
@override
Future<void> retry() async {
retries++;
error = null;
notifyListeners();
}
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}