Files
cutdex/test/media_panel_test.dart
T
lingjhf 1f73765745
Gitea CI / Windows x64 and Android (pull_request) Successful in 16m21s
Gitea CI / Gitea CI passed (pull_request) Successful in 3s
refactor(desktop): reorganize workspace panels and navigation
2026-10-06 12:11:59 +08:00

1023 lines
36 KiB
Dart

import 'package:cutdex/features/media/media_browser_toolbar.dart';
import 'package:cutdex/features/media/media_browser_controller.dart';
import 'package:cutdex/app/editor_theme.dart';
import 'package:cutdex/features/media/media_browser_page.dart';
import 'package:cutdex/l10n/app_localizations.dart';
import 'dart:async';
import 'dart:ui' as ui;
import 'package:cutdex/features/media/media_panel.dart';
import 'package:cutdex/features/media/media_asset_strip.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex/shared/widgets/drop_to_add_overlay.dart';
import 'package:cutdex/workspace/projects.dart';
import 'package:cutdex/workspace/project_state.dart';
import 'package:cutdex/workspace/media_file_extensions.dart';
import 'package:cutdex/workspace/media_import.dart';
import 'package:cutdex/workspace/media_availability.dart';
import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_sdk/runtime.dart';
import 'package:cutdex/integrations/platform/native_project_drop_region.dart';
import 'package:flutter/gestures.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';
void main() {
setUp(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('cutdex_native/file_drop/media-library'),
(_) async => null,
);
});
tearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('cutdex_native/file_drop/media-library'),
null,
);
});
testWidgets('project switching retains media surface and controls', (
tester,
) async {
final projects = _Projects();
final container = ProviderContainer(
overrides: [projectsProvider.overrideWith(() => projects)],
);
addTearDown(container.dispose);
await container.read(projectsProvider.future);
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: Consumer(
builder: (context, ref, _) {
final id = ref.watch(
projectsProvider.select(
(value) => value.value?.activeProject?.id,
),
);
return MediaPanel(projectId: id);
},
),
),
),
),
);
await tester.pumpAndSettle();
final surface = tester.element(
find.byKey(const Key('media-panel-surface')),
);
final header = tester.element(find.byKey(const Key('media-panel-header')));
final body = tester.element(find.byKey(const Key('media-panel-body')));
final filterRow = tester.widget(find.byKey(const Key('media-filter-row')));
final toolbar = tester.widget<MediaBrowserToolbar>(
find.byType(MediaBrowserToolbar),
);
container.read(mediaBrowserProvider('project')).selectedAssetId =
'selection';
await tester.pump();
expect(
tester.widget<MediaBrowserToolbar>(find.byType(MediaBrowserToolbar)),
same(toolbar),
);
projects.switchProject('second');
await tester.pumpAndSettle();
expect(
tester.element(find.byKey(const Key('media-panel-surface'))),
same(surface),
);
expect(
tester.element(find.byKey(const Key('media-panel-header'))),
same(header),
);
expect(
tester.element(find.byKey(const Key('media-panel-body'))),
same(body),
);
expect(
tester
.widget<MediaBrowserToolbar>(find.byType(MediaBrowserToolbar))
.selectedProjectId,
'second',
);
expect(
tester.widget(find.byKey(const Key('media-filter-row'))),
same(filterRow),
);
await tester.tap(find.byKey(const Key('media-layout-toggle')));
await tester.pump();
expect(container.read(mediaBrowserProvider('second')).grid, isFalse);
expect(container.read(mediaBrowserProvider('project')).grid, isTrue);
expect(tester.takeException(), isNull);
});
for (final locale in const [Locale('zh'), Locale('en'), Locale('de')]) {
testWidgets(
'sidebar toolbar fits widths and scaled text in ${locale.languageCode}',
(tester) async {
var imports = 0;
var toggles = 0;
var projectSelections = 0;
for (final width in [120.0, 180.0, 240.0, 360.0]) {
await tester.pumpWidget(
MaterialApp(
locale: locale,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
theme: EditorTheme.penLight,
home: Scaffold(
body: MediaQuery(
data: const MediaQueryData(
textScaler: TextScaler.linear(1.5),
),
child: Align(
alignment: Alignment.topLeft,
child: SizedBox(
width: width,
child: MediaBrowserToolbar(
projects: const [
RecentProject(
id: 'first',
name: 'First project with a long name',
path: '/first',
),
RecentProject(
id: 'second',
name: 'Second project',
path: '/second',
),
],
selectedProjectId: 'first',
onProjectSelected: (project) {
expect(project.id, 'second');
projectSelections++;
},
canImport: true,
onImport: () => imports++,
filter: MediaFilter.all,
onFilterChanged: (_) {},
grid: true,
onToggleGrid: () => toggles++,
),
),
),
),
),
),
);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
if (width == 240) {
expect(find.byKey(const Key('media-header-scroll')), findsNothing);
final projectButton = tester.widget<TextButton>(
find.byKey(const Key('media-project-button')),
);
final ink = Theme.of(
tester.element(find.byKey(const Key('media-project-button'))),
).colorScheme.onSurface;
for (final state in [
WidgetState.hovered,
WidgetState.focused,
WidgetState.pressed,
]) {
expect(
projectButton.style!.backgroundColor!.resolve({state}),
Colors.transparent,
);
expect(
projectButton.style!.overlayColor!.resolve({state}),
ink.withValues(alpha: .05),
);
}
expect(
projectButton.style!.overlayColor!.resolve({
WidgetState.disabled,
WidgetState.hovered,
}),
Colors.transparent,
);
await tester.tap(find.byKey(const Key('media-project-button')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('media-project-second')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('media-import-button')));
await tester.tap(find.byKey(const Key('media-layout-toggle')));
}
}
expect(imports, 1);
expect(toggles, 1);
expect(projectSelections, 1);
},
);
}
testWidgets(
'list and grid share a context menu targeting the clicked asset',
(tester) async {
final container = ProviderContainer(
overrides: [
projectsProvider.overrideWith(_Projects.new),
mediaAvailabilityProvider.overrideWith(
(ref, key) async => MediaAvailability.available,
),
],
);
addTearDown(container.dispose);
await container.read(projectsProvider.future);
final projects = container.read(projectsProvider.notifier) as _Projects;
await projects.importExternalMedia('project', [
const ExternalMediaFile(path: '/first.txt'),
const ExternalMediaFile(path: '/second.txt'),
]);
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
locale: const Locale('zh'),
theme: EditorTheme.penLight,
home: const Scaffold(body: MediaPanel(projectId: 'project')),
),
),
);
await tester.pumpAndSettle();
for (final layout in ['列表布局', '宫格布局']) {
await tester.tap(find.byTooltip(layout));
await tester.pumpAndSettle();
await tester.tap(find.text('first.txt'));
await tester.tap(
find.text('second.txt'),
buttons: kSecondaryMouseButton,
);
await tester.pumpAndSettle();
expect(find.text('添加到时间线'), findsOneWidget);
expect(
tester
.widget<MenuItemButton>(
find.widgetWithText(MenuItemButton, '添加到时间线'),
)
.onPressed,
isNull,
);
await tester.tap(find.text('重命名'));
await tester.pumpAndSettle();
expect(
tester.widget<TextField>(find.byType(TextField)).controller!.text,
'second.txt',
);
await tester.tap(find.text('取消'));
await tester.pumpAndSettle();
}
expect(tester.takeException(), isNull);
},
);
Future<void> platformEvent(
WidgetTester tester,
String method,
Object? args,
) async {
final done = Completer<void>();
final eventArgs = {
'phase': method,
'session': 1,
'x': 0.0,
'y': 0.0,
'files': method == 'exit'
? <Object?>[]
: method == 'enter'
? <Object?>[
{'path': '/originals/video.mp4'},
]
: [
for (final f in args as List)
if (f is String) {'path': f} else {'path': (f as Map)['path']},
],
};
tester.binding.defaultBinaryMessenger.handlePlatformMessage(
'cutdex_native/file_drop/media-library',
const StandardMethodCodec().encodeMethodCall(
MethodCall('event', eventArgs),
),
(_) => done.complete(),
);
await done.future;
await tester.pump();
}
Future<ProviderContainer> mount(
WidgetTester tester, {
MediaAvailability availability = MediaAvailability.available,
bool touch = false,
}) async {
final container = ProviderContainer(
overrides: [
projectsProvider.overrideWith(_Projects.new),
mediaAvailabilityProvider.overrideWith(
(ref, key) async => availability,
),
],
);
addTearDown(container.dispose);
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
locale: const Locale('zh'),
theme: EditorTheme.penLight,
home: Scaffold(
body: touch
? const MediaBrowserPage(projectId: 'project')
: const MediaPanel(projectId: 'project'),
),
),
),
);
await tester.pumpAndSettle();
return container;
}
testWidgets('list uses a filmstrip with real duration above its name', (
tester,
) async {
const channel = MethodChannel('cutdex_runtime');
final times = <int>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
call,
) async {
if (call.method == 'probe') {
return {
'duration': {'numerator': '290', 'denominator': 1},
'videoTrackCount': 1,
'videoTrackIds': [1],
'audioTrackCount': 0,
'audioTrackIds': <int>[],
'audioTracks': <Object?>[],
'isProtected': false,
};
}
if (call.method == 'thumbnail') {
final args = call.arguments as Map;
final time = args['time'] as Map;
times.add(int.parse(time['numerator'].toString()));
}
throw PlatformException(code: 'no-preview');
});
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
channel,
null,
),
);
final container = await mount(tester);
await (container.read(projectsProvider.notifier) as _Projects)
.importExternalMedia('project', [
const ExternalMediaFile(path: '/movie.mp4'),
]);
await tester.pumpAndSettle();
await tester.tap(find.byTooltip('列表布局'));
await tester.pumpAndSettle();
final strip = tester.getRect(find.byType(MediaAssetStrip));
final name = tester.getRect(find.text('movie.mp4'));
final duration = tester.getRect(find.text('04:50'));
expect(strip.height, 46);
expect(name.top, greaterThanOrEqualTo(strip.bottom));
expect(duration.right, lessThanOrEqualTo(strip.right));
expect(duration.left, greaterThan(strip.center.dx));
expect(duration.top, strip.top + 5);
expect(times.any((time) => time > 0), isTrue);
expect(tester.takeException(), isNull);
});
testWidgets(
'missing assets stay named and marked in both layouts without dragging',
(tester) async {
final container = await mount(
tester,
availability: MediaAvailability.missing,
);
final projects = container.read(projectsProvider.notifier) as _Projects;
await projects.importExternalMedia('project', [
const ExternalMediaFile(path: '/missing.mov'),
]);
await tester.pumpAndSettle();
for (final layout in ['列表布局', '宫格布局']) {
await tester.tap(find.byTooltip(layout));
await tester.pumpAndSettle();
expect(find.text('素材缺失'), findsOneWidget);
expect(find.text('missing.mov'), findsOneWidget);
final drag = tester.widget<Draggable>(
find.byWidgetPredicate((widget) => widget is Draggable),
);
expect(drag.maxSimultaneousDrags, 0);
expect(tester.takeException(), isNull);
}
},
);
testWidgets(
'category dropdown filters both layouts and restores all assets',
(tester) async {
final container = await mount(tester);
final projects = container.read(projectsProvider.notifier) as _Projects;
await projects.importExternalMedia('project', [
const ExternalMediaFile(path: '/photo.png'),
const ExternalMediaFile(path: '/movie.mp4'),
const ExternalMediaFile(path: '/song.wav'),
const ExternalMediaFile(path: '/notes.txt'),
]);
await tester.pumpAndSettle();
expect(find.byKey(const Key('media-import-button')), findsOneWidget);
expect(
tester.getSize(find.byKey(const Key('media-panel-header'))).height,
AppControlSize.panelToolbar * 2,
);
expect(
tester.getSize(find.byKey(const Key('media-import-button'))).height,
AppControlSize.headerButton,
);
final header = tester.getRect(
find.byKey(const Key('media-panel-header')),
);
expect(
tester.getRect(find.byKey(const Key('media-panel-body'))).top,
header.bottom,
);
final importButton = tester.getRect(
find.byKey(const Key('media-import-button')),
);
final layoutButton = tester.getRect(
find.byKey(const Key('media-layout-toggle')),
);
final filter = find.byWidgetPredicate(
(widget) => widget is Semantics && widget.properties.label == '素材分类',
);
final filterButton = tester.getRect(
find.descendant(of: filter, matching: find.byType(TextButton)),
);
expect(header.right - importButton.right, AppSidebarMetrics.outerPadding);
expect(importButton.top - header.top, AppSpacing.gap);
expect(layoutButton.top - importButton.top, AppControlSize.panelToolbar);
expect(
tester.getRect(find.byKey(const Key('media-project-button'))).top,
importButton.top,
);
expect(header.right - layoutButton.right, AppSidebarMetrics.outerPadding);
expect(
layoutButton.left - filterButton.right,
greaterThanOrEqualTo(AppSpacing.tiny),
);
expect(tester.getSize(filter).height, AppControlSize.headerButton);
final importStyle = tester
.widget<TextButton>(find.byKey(const Key('media-import-button')))
.style!
.textStyle!
.resolve({})!;
final filterStyle = tester
.widget<TextButton>(find.byKey(const Key('media-category-button')))
.style!
.textStyle!
.resolve({})!;
expect(importStyle.fontSize, 13);
expect(importStyle.height, 18 / 13);
expect(filterStyle.fontSize, importStyle.fontSize);
expect(filterStyle.height, importStyle.height);
expect(find.text('4 个素材'), findsNothing);
for (final entry in {
'图片': 'photo.png',
'视频': 'movie.mp4',
'音频': 'song.wav',
}.entries) {
await tester.tap(
find.descendant(
of: find.byWidgetPredicate(
(widget) =>
widget is Semantics && widget.properties.label == '素材分类',
),
matching: find.byType(TextButton),
),
);
await tester.pumpAndSettle();
await tester.tap(find.widgetWithText(MenuItemButton, entry.key));
await tester.pumpAndSettle();
expect(find.text('1 个素材'), findsNothing);
expect(find.text(entry.value), findsOneWidget);
expect(find.text('notes.txt'), findsNothing);
}
await tester.tap(find.byTooltip('列表布局'));
await tester.pumpAndSettle();
expect(find.text('song.wav'), findsOneWidget);
expect(find.text('movie.mp4'), findsNothing);
await tester.tap(
find.descendant(
of: find.byWidgetPredicate(
(widget) =>
widget is Semantics && widget.properties.label == '素材分类',
),
matching: find.byType(TextButton),
),
);
await tester.pumpAndSettle();
await tester.tap(find.widgetWithText(MenuItemButton, '全部'));
await tester.pumpAndSettle();
expect(find.text('4 个素材'), findsNothing);
expect(find.text('notes.txt'), findsOneWidget);
expect(tester.takeException(), isNull);
},
);
testWidgets(
'media layouts resize columns and retain selection and dragging',
(tester) async {
await tester.binding.setSurfaceSize(const Size(280, 600));
addTearDown(() => tester.binding.setSurfaceSize(null));
final container = await mount(tester);
final controller = container.read(projectsProvider.notifier) as _Projects;
await controller.importExternalMedia('project', [
for (var i = 0; i < 8; i++)
ExternalMediaFile(path: '/originals/very-long-asset-name-$i.png'),
]);
await tester.pumpAndSettle();
int columns() =>
(tester.widget<GridView>(find.byType(GridView)).gridDelegate
as SliverGridDelegateWithFixedCrossAxisCount)
.crossAxisCount;
expect(columns(), 3);
expect(
find.ancestor(
of: find.byType(GridView),
matching: find.byType(ShaderMask),
),
findsOneWidget,
);
expect(
find.ancestor(
of: find.byKey(const Key('media-panel-header')),
matching: find.byType(ShaderMask),
),
findsNothing,
);
final first = find.text('very-long-asset-name-0.png');
await tester.tap(first);
await tester.tap(find.byTooltip('列表布局'));
await tester.pumpAndSettle();
expect(find.byType(GridView), findsNothing);
expect(find.byType(ListView), findsOneWidget);
expect(
find.ancestor(
of: find.byType(ListView),
matching: find.byType(ShaderMask),
),
findsOneWidget,
);
expect(
find.ancestor(
of: first,
matching: find.byWidgetPredicate(
(w) => w is Semantics && w.properties.selected == true,
),
),
findsOneWidget,
);
expect(
find.ancestor(
of: first,
matching: find.byWidgetPredicate((w) => w is Draggable),
),
findsOneWidget,
);
await tester.tap(find.byTooltip('宫格布局'));
await tester.pumpAndSettle();
for (final (width, count) in [
(180.0, 2),
(280.0, 3),
(240.0, 2),
(360.0, 3),
(520.0, 5),
(560.0, 5),
(900.0, 8),
]) {
await tester.binding.setSurfaceSize(Size(width, 600));
await tester.pumpAndSettle();
expect(columns(), count);
final grid = tester.widget<GridView>(find.byType(GridView));
final padding = grid.padding!.resolve(TextDirection.ltr);
final delegate =
grid.gridDelegate as SliverGridDelegateWithFixedCrossAxisCount;
final tileWidth =
(tester.getSize(find.byType(GridView)).width -
padding.horizontal -
delegate.crossAxisSpacing * (count - 1)) /
count;
expect(tileWidth, lessThanOrEqualTo(120));
expect(tester.takeException(), isNull);
}
expect(
find.ancestor(
of: first,
matching: find.byWidgetPredicate(
(w) => w is Semantics && w.properties.selected == true,
),
),
findsOneWidget,
);
},
);
testWidgets('native file event imports real paths without a success prompt', (
tester,
) async {
final container = await mount(tester);
final target = tester.getCenter(find.byType(NativeProjectDropRegion));
await platformEvent(tester, 'enter', [target.dx, target.dy]);
expect(find.byKey(const Key('media-drop-highlight')), findsOneWidget);
expect(
tester.widget(find.byKey(const Key('media-drop-highlight'))),
isA<DropToAddOverlay>(),
);
expect(find.text('松手即可添加'), findsOneWidget);
await platformEvent(tester, 'drop', [
{'path': '/originals/video.mp4'},
{'path': '/originals/audio.wav'},
{'path': '/originals/image.png'},
{'path': '/originals/中文 视频.RMVB'},
{'path': '/originals/中文 视频.flv'},
]);
await tester.pumpAndSettle();
final controller = container.read(projectsProvider.notifier) as _Projects;
expect(controller.received.map((f) => f.localPath!), [
'/originals/video.mp4',
'/originals/audio.wav',
'/originals/image.png',
'/originals/中文 视频.RMVB',
'/originals/中文 视频.flv',
]);
expect(find.text('video.mp4'), findsOneWidget);
expect(find.text('中文 视频.RMVB'), findsOneWidget);
expect(find.text('中文 视频.flv'), findsOneWidget);
expect(find.byType(SnackBar), findsNothing);
expect(find.byKey(const Key('media-drop-highlight')), findsNothing);
expect(tester.takeException(), isNull);
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
testWidgets(
'duplicate native drop selects the existing asset without a prompt',
(tester) async {
final container = await mount(tester);
final controller = container.read(projectsProvider.notifier) as _Projects;
await controller.importExternalMedia('project', [
const ExternalMediaFile(path: '/originals/first.mp4'),
const ExternalMediaFile(path: '/originals/second.wav'),
]);
await tester.pumpAndSettle();
await tester.tap(find.text('second.wav'));
await platformEvent(tester, 'enter', [0.0, 0.0]);
await platformEvent(tester, 'drop', ['/originals/first.mp4']);
await tester.pumpAndSettle();
expect(controller.received.map((file) => file.localPath!), [
'/originals/first.mp4',
'/originals/second.wav',
]);
expect(
container.read(projectsProvider).requireValue.assets,
hasLength(2),
);
expect(
find.ancestor(
of: find.text('first.mp4'),
matching: find.byWidgetPredicate(
(w) => w is Semantics && w.properties.selected == true,
),
),
findsOneWidget,
);
expect(find.byType(SnackBar), findsNothing);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
},
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
testWidgets('native drop without an entered session is ignored', (
tester,
) async {
final container = await mount(tester);
await platformEvent(tester, 'drop', ['/originals/video.mp4']);
await tester.pumpAndSettle();
final controller = container.read(projectsProvider.notifier) as _Projects;
expect(controller.received, isEmpty);
expect(find.byType(SnackBar), findsNothing);
}, variant: TargetPlatformVariant.only(TargetPlatform.windows));
testWidgets('busy project ignores drops and clears active hover', (
tester,
) async {
final container = await mount(tester);
final target = tester.getCenter(find.byType(NativeProjectDropRegion));
await platformEvent(tester, 'enter', [target.dx, target.dy]);
final controller = container.read(projectsProvider.notifier) as _Projects;
controller.setBusy(true);
await tester.pump();
expect(find.byKey(const Key('media-drop-highlight')), findsNothing);
await platformEvent(tester, 'drop', ['/originals/video.mp4']);
expect(controller.received, isEmpty);
expect(tester.takeException(), isNull);
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
testWidgets(
'audio assets display a cached full-source single-sided waveform',
(tester) async {
const channel = MethodChannel('cutdex_runtime');
final messenger = tester.binding.defaultBinaryMessenger;
var requests = 0;
messenger.setMockMethodCallHandler(channel, (call) async {
expect(call.method, 'waveform');
requests++;
return {
'sampleRate': 4.0,
'sourceStartSeconds': 2.0,
'frameCount': 4,
'trackId': 1,
'channelCount': 2,
'levels': [
{
'samplesPerBucket': 2,
'channels': [
[-0.25, 0.0, 0.1, -0.75, 0.0, 0.4],
[0.0, 0.25, 0.1, 0.0, 0.75, 0.4],
],
},
],
};
});
addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
final container = await mount(tester);
final controller = container.read(projectsProvider.notifier) as _Projects;
await controller.importExternalMedia('project', [
const ExternalMediaFile(path: '/originals/song.wav'),
]);
await tester.pumpAndSettle();
final finder = find.byKey(
const ValueKey('audio-waveform-/originals/song.wav'),
);
expect(finder, findsOneWidget);
expect(find.text('song.wav'), findsOneWidget);
final painter = tester.widget<CustomPaint>(finder).painter!;
final recorder = ui.PictureRecorder();
painter.paint(Canvas(recorder), const Size(100, 40));
final picture = recorder.endRecording();
final alpha = await tester.runAsync(() async {
final image = await picture.toImage(100, 40);
try {
final data = (await image.toByteData())!;
return [
for (final (x, y) in [(11, 35), (11, 15), (71, 15), (71, 5)])
data.getUint8((y * 100 + x) * 4 + 3),
];
} finally {
image.dispose();
picture.dispose();
}
});
expect(alpha, [255, 0, 255, 0]);
final pixelRecorder = ui.PictureRecorder();
final pixelCanvas = Canvas(pixelRecorder)..scale(2);
painter.paint(pixelCanvas, const Size(101, 40));
final pixelPicture = pixelRecorder.endRecording();
final barAlphas = await tester.runAsync(() async {
final image = await pixelPicture.toImage(202, 80);
try {
final data = (await image.toByteData())!;
return {
for (var x = 0; x < 202; x++)
if (data.getUint8((78 * 202 + x) * 4 + 3) > 0)
data.getUint8((78 * 202 + x) * 4 + 3),
};
} finally {
image.dispose();
pixelPicture.dispose();
}
});
expect(barAlphas, {255});
controller.setBusy(true);
await tester.pumpAndSettle();
expect(requests, 1);
},
);
testWidgets(
'audio cover failures retain a stable fallback without retry loops',
(tester) async {
const channel = MethodChannel('cutdex_runtime');
final messenger = tester.binding.defaultBinaryMessenger;
var requests = 0;
messenger.setMockMethodCallHandler(channel, (call) async {
requests++;
throw PlatformException(code: 'unsupported');
});
addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
final container = await mount(tester);
final controller = container.read(projectsProvider.notifier) as _Projects;
await controller.importExternalMedia('project', [
const ExternalMediaFile(path: '/originals/bad.wav'),
]);
await tester.pumpAndSettle();
expect(find.byIcon(Icons.audio_file_outlined), findsOneWidget);
final before = tester.getSize(
find.byKey(const ValueKey('audio-cover-/originals/bad.wav')),
);
controller.setBusy(true);
await tester.pumpAndSettle();
expect(
tester.getSize(
find.byKey(const ValueKey('audio-cover-/originals/bad.wav')),
),
before,
);
expect(requests, 2);
expect(tester.takeException(), isNull);
},
);
testWidgets('touch can open media actions without a mouse', (tester) async {
final container = await mount(tester, touch: true);
final projects = container.read(projectsProvider.notifier) as _Projects;
await projects.importExternalMedia('project', [
const ExternalMediaFile(path: '/originals/notes.txt'),
]);
await tester.pumpAndSettle();
await tester.longPress(find.text('notes.txt'));
await tester.pumpAndSettle();
expect(find.text('重命名'), findsOneWidget);
expect(find.widgetWithText(MenuItemButton, '添加到时间线'), findsOneWidget);
expect(tester.takeException(), isNull);
});
testWidgets('mobile file selection imports without native desktop drop', (
tester,
) async {
final channel = const MethodChannel('filegate');
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
channel,
(_) async => [
{'path': '/originals/phone.mp4', 'name': 'phone.mp4', 'kind': 'file'},
],
);
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
channel,
null,
),
);
final container = await mount(tester);
await tester.tap(find.byKey(const Key('media-import-button')));
await tester.pumpAndSettle();
expect(
(container.read(
projectsProvider.notifier,
) as _Projects).received.single.localPath,
'/originals/phone.mp4',
);
expect(find.byType(NativeProjectDropRegion), findsNothing);
expect(find.text('phone.mp4'), findsOneWidget);
expect(tester.takeException(), isNull);
}, variant: TargetPlatformVariant.only(TargetPlatform.android));
testWidgets('mobile shows assets without a desktop drop target', (
tester,
) async {
await mount(tester);
expect(find.byType(NativeProjectDropRegion), findsNothing);
expect(find.text('暂无素材'), findsOneWidget);
}, variant: TargetPlatformVariant.only(TargetPlatform.android));
testWidgets('imported still images request and display native covers', (
tester,
) async {
final recorder = ui.PictureRecorder();
Canvas(recorder).drawColor(Colors.green, BlendMode.src);
final picture = recorder.endRecording();
final bytes = await tester.runAsync(() async {
final image = await picture.toImage(12, 16);
try {
return (await image.toByteData(format: ui.ImageByteFormat.png))!.buffer
.asUint8List();
} finally {
image.dispose();
picture.dispose();
}
});
const channel = MethodChannel('cutdex_runtime');
final messenger = tester.binding.defaultBinaryMessenger;
final requested = <String>[];
messenger.setMockMethodCallHandler(channel, (call) async {
expect(call.method, 'thumbnail');
final args = call.arguments as Map;
final media = args['media'] as Map;
expect(media['isImage'], isTrue);
requested.add(media['uri'] as String);
return {
'requestedTime': args['time'],
'actualTime': args['time'],
'width': 12,
'height': 16,
'format': args['format'],
'data': bytes,
};
});
addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
final container = await mount(tester);
final controller = container.read(projectsProvider.notifier) as _Projects;
await controller.importExternalMedia('project', [
for (final ext in ['heic', 'png', 'jpg'])
ExternalMediaFile(path: '/originals/photo.$ext'),
]);
await tester.pumpAndSettle();
expect(requested, hasLength(3));
expect(find.byType(Image), findsNWidgets(3));
for (final ext in ['heic', 'png', 'jpg']) {
expect(find.text('photo.$ext'), findsOneWidget);
}
expect(tester.takeException(), isNull);
});
}
class _Projects extends Projects {
@override
Future<T> withAssetMedia<T>(
String? projectId,
AssetDocument asset,
Future<T> Function(MediaReference media) action,
) => action(
MediaReference(
id: asset.id,
uri: Uri.parse(asset.location),
isImage: asset.metadata['kind'] == 'image',
),
);
@visibleForTesting
List<ExternalMediaFile> received = [];
@override
Future<ProjectState> build() async => const ProjectState(
activeProject: RecentProject(
id: 'project',
name: 'Project',
path: '/Project.cutdex',
),
);
void switchProject(String id) {
state = AsyncData(
state.requireValue.copyWith(
activeProject: RecentProject(id: id, name: id, path: '/$id.cutdex'),
assets: const [],
),
);
}
void setBusy(bool busy) {
state = AsyncData(state.requireValue.copyWith(projectBusy: busy));
}
@override
Future<MediaImportResult?> importExternalMedia(
String projectId,
List<ExternalMediaFile> files, {
bool Function()? isCancelled,
}) async {
received = files;
final previous = state.requireValue.assets;
final previousIds = {for (final asset in previous) asset.id};
final assets = [
...previous,
for (final file in files)
if (!previousIds.contains(file.localPath!))
AssetDocument(
id: file.localPath!,
name: file.localPath!.split('/').last,
storage: AssetStorage.external,
location: file.sourceUri.toString(),
metadata: {'kind': mediaKindForPath(file.localPath!)},
),
];
state = AsyncData(state.requireValue.copyWith(assets: assets));
return MediaImportResult(
assets: assets,
added: assets.length - previous.length,
duplicates: files
.where((file) => previousIds.contains(file.localPath!))
.length,
failures: [],
);
}
}