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_ui/icons.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_core/project.dart'; import 'package:cutdex_native_flutter/cutdex_native_flutter.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( find.byType(MediaBrowserToolbar), ); container.read(mediaBrowserProvider('project')).selectedAssetId = 'selection'; await tester.pump(); expect( tester.widget(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(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.desktop(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( 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( find.widgetWithText(MenuItemButton, '添加到时间线'), ) .onPressed, isNull, ); await tester.tap(find.text('重命名')); await tester.pumpAndSettle(); expect( tester .widget(find.byType(TextField).last) .controller! .text, 'second.txt', ); await tester.tap(find.text('取消')); await tester.pumpAndSettle(); } expect(tester.takeException(), isNull); }, ); Future platformEvent( WidgetTester tester, String method, Object? args, ) async { final done = Completer(); final eventArgs = { 'phase': method, 'session': 1, 'x': 0.0, 'y': 0.0, 'files': method == 'exit' ? [] : method == 'enter' ? [ {'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 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: touch ? EditorTheme.penLight : EditorTheme.desktop(EditorTheme.penLight), home: Scaffold( body: touch ? const MediaBrowserPage(projectId: 'project') : const MediaPanel(projectId: 'project'), ), ), ), ); await tester.pumpAndSettle(); return container; } for (final touch in [false, true]) { testWidgets( '${touch ? 'touch' : 'desktop'} waits for file selection without a loading bar', (tester) async { final channel = MethodChannel( touch ? 'filegate' : 'cutdex_native/file_picker', ); final cancelled = Completer(); final selected = Completer(); var pickerCalls = 0; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( channel, (_) => pickerCalls++ == 0 ? cancelled.future : selected.future, ); addTearDown( () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( channel, null, ), ); final container = await mount(tester, touch: touch); final projects = container.read(projectsProvider.notifier) as _Projects; final imported = Completer(); projects.importGate = imported.future; final button = find.byKey(const Key('media-import-button')); Future openPicker() async { await tester.tap(button); await tester.pump(); await tester.pump(const Duration(milliseconds: 500)); expect(find.byType(LinearProgressIndicator), findsNothing); expect(tester.widget(button).onPressed, isNull); } await openPicker(); cancelled.complete(null); await tester.pumpAndSettle(); expect(find.byType(LinearProgressIndicator), findsNothing); expect(tester.widget(button).onPressed, isNotNull); expect(projects.received, isEmpty); await openPicker(); selected.complete( touch ? [ { 'path': '/originals/clip.mp4', 'name': 'clip.mp4', 'kind': 'file', }, ] : ['/originals/clip.mp4'], ); await tester.pump(); await tester.pump(); await tester.pump(const Duration(milliseconds: 250)); await tester.pump(); expect(find.byType(LinearProgressIndicator), findsOneWidget); expect(tester.widget(button).onPressed, isNull); imported.complete(); await tester.pumpAndSettle(); expect(find.byType(LinearProgressIndicator), findsNothing); expect(tester.widget(button).onPressed, isNotNull); expect(projects.received.single.localPath, '/originals/clip.mp4'); expect(pickerCalls, 2); expect(tester.takeException(), isNull); }, variant: TargetPlatformVariant.only( touch ? TargetPlatform.android : TargetPlatform.macOS, ), ); } testWidgets( 'desktop list uses a compact cover with real duration beside its name', (tester) async { await tester.binding.setSurfaceSize(const Size(320, 600)); addTearDown(() => tester.binding.setSurfaceSize(null)); const channel = MethodChannel('cutdex_runtime'); final times = []; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( call, ) async { if (call.method == 'probe') { return { 'duration': {'numerator': '290', 'denominator': 1}, 'videoTrackCount': 1, 'videoTrackIds': [1], 'audioTrackCount': 0, 'audioTrackIds': [], 'audioTracks': [], '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 cover = tester.getRect( find.byKey(const ValueKey('desktop-media-cover-/movie.mp4')), ); final name = tester.getRect(find.text('movie.mp4')); final duration = tester.getRect(find.text('04:50')); expect(cover.width, 56); expect(cover.height, closeTo(56 * 9 / 16, .01)); expect(name.left, cover.right + 8); expect(duration.left, greaterThanOrEqualTo(name.left)); expect(duration.center.dy, closeTo(cover.center.dy, .01)); expect(times.every((time) => time == 0), isTrue); expect(tester.takeException(), isNull); await tester.binding.setSurfaceSize(const Size(180, 600)); await tester.pumpWidget( UncontrolledProviderScope( container: container, child: MaterialApp( theme: EditorTheme.desktop(EditorTheme.penLight), locale: const Locale('zh'), localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, home: const Scaffold( body: MediaQuery( data: MediaQueryData(textScaler: TextScaler.linear(1.5)), child: MediaPanel(projectId: 'project'), ), ), ), ), ); await tester.pumpAndSettle(); expect(find.text('04:50'), findsOneWidget); 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( find.byWidgetPredicate((widget) => widget is Draggable), ); expect(drag.maxSimultaneousDrags, 0); expect(tester.takeException(), isNull); } }, ); testWidgets( 'desktop media fits all six themes and keeps selection at narrow widths', (tester) async { final container = await mount(tester); final projects = container.read(projectsProvider.notifier) as _Projects; await projects.importExternalMedia('project', [ const ExternalMediaFile(path: '/long-original-asset-name.txt'), const ExternalMediaFile(path: '/second.txt'), ]); await tester.pumpAndSettle(); final browser = container.read(mediaBrowserProvider('project')); browser.selectedAssetId = '/long-original-asset-name.txt'; for (final palette in AppPalette.values) { for (final brightness in Brightness.values) { for (final width in [180.0, 240.0, 320.0, 560.0]) { for (final grid in [true, false]) { browser.grid = grid; await tester.pumpWidget( UncontrolledProviderScope( container: container, child: MaterialApp( theme: EditorTheme.desktop( EditorTheme.forPalette(palette, brightness), ), localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('en'), home: Scaffold( body: MediaQuery( data: const MediaQueryData( textScaler: TextScaler.linear(1.5), ), child: Align( alignment: Alignment.topLeft, child: SizedBox( width: width, child: const MediaPanel(projectId: 'project'), ), ), ), ), ), ), ); await tester.pumpAndSettle(); expect(browser.selectedAssetId, '/long-original-asset-name.txt'); final cover = tester.getRect( find.byKey( const ValueKey( 'desktop-media-cover-/long-original-asset-name.txt', ), ), ); expect(cover.width / cover.height, closeTo(16 / 9, .01)); expect( tester.takeException(), isNull, reason: '$palette $brightness width=$width grid=$grid', ); } } } } }, ); testWidgets( 'Chinese media cards fit fractional text scaling without overflow', (tester) async { final container = await mount(tester); await (container.read(projectsProvider.notifier) as _Projects) .importExternalMedia('project', [ const ExternalMediaFile(path: '/截屏2026-10-08 21.32.56.txt'), const ExternalMediaFile(path: '/gyp-ÁÉ-long-file-name.txt'), ]); for (final width in [180.0, 241.0, 321.0]) { for (final scale in [1.0, 1.05, 1.1, 1.25, 1.5, 2.0]) { await tester.pumpWidget( UncontrolledProviderScope( container: container, child: MaterialApp( theme: EditorTheme.desktop(EditorTheme.penLight), locale: const Locale('zh'), localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, home: Scaffold( body: Align( alignment: Alignment.topLeft, child: SizedBox( width: width, child: MediaQuery( data: MediaQueryData( textScaler: TextScaler.linear(scale), ), child: const MediaPanel(projectId: 'project'), ), ), ), ), ), ), ); await tester.pumpAndSettle(); expect( tester.takeException(), isNull, reason: 'width=$width scale=$scale', ); final tile = find.byKey(const ValueKey('/截屏2026-10-08 21.32.56.txt')); final metadata = find.descendant(of: tile, matching: find.text('素材')); expect( tester.getRect(tile).bottom - tester.getRect(metadata).bottom, greaterThanOrEqualTo(5), ); final cover = tester.getRect( find.byKey( const ValueKey('desktop-media-cover-/截屏2026-10-08 21.32.56.txt'), ), ); expect(cover.width / cover.height, closeTo(16 / 9, .01)); } } }, ); testWidgets( 'desktop categories filter both layouts and retain shared controls', (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(); final header = tester.getRect( find.byKey(const Key('media-panel-header')), ); final importButton = tester.getRect( find.byKey(const Key('media-import-button')), ); final layoutButton = tester.getRect( find.byKey(const Key('media-layout-toggle')), ); final sortButton = tester.getRect( find.byKey(const Key('media-sort-button')), ); expect(header.height, 64); expect(importButton.height, 24); expect(importButton.top - header.top, 4); expect(header.right - importButton.right, 8); expect(header.right - layoutButton.right, 8); expect(sortButton.top, layoutButton.top); expect(layoutButton.left - sortButton.right, 40); expect(find.byKey(const Key('media-category-button')), findsOneWidget); expect(find.byKey(const ValueKey('media-filter-image')), findsNothing); expect( tester.getRect(find.byKey(const Key('media-panel-body'))).top, header.bottom, ); expect(find.text('4 个素材'), findsOneWidget); for (final entry in { 'image': 'photo.png', 'video': 'movie.mp4', 'audio': 'song.wav', }.entries) { await tester.tap(find.byKey(const Key('media-category-button'))); await tester.pumpAndSettle(); await tester.tap(find.byKey(ValueKey('media-filter-${entry.key}'))); await tester.pumpAndSettle(); expect(find.text('1 个素材'), findsOneWidget); 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.byKey(const Key('media-category-button'))); await tester.pumpAndSettle(); await tester.tap(find.byKey(const ValueKey('media-filter-all'))); await tester.pumpAndSettle(); expect(find.text('4 个素材'), findsOneWidget); expect(find.text('notes.txt'), findsOneWidget); expect(tester.takeException(), isNull); }, ); testWidgets( 'search and sort share selection across layouts and preserve project choices', (tester) async { final container = await mount(tester); final projects = container.read(projectsProvider.notifier) as _Projects; await projects.importExternalMedia('project', [ const ExternalMediaFile(path: '/Zebra.png'), const ExternalMediaFile(path: '/Alpha.png'), const ExternalMediaFile(path: '/song.wav'), ]); await tester.pumpAndSettle(); final browser = container.read(mediaBrowserProvider('project')); final search = find.byKey(const Key('media-search')); await tester.enterText(search, 'ALPHA'); await tester.pumpAndSettle(); expect(find.text('Zebra.png'), findsNothing); expect(find.text('1 个素材'), findsOneWidget); await tester.tap(find.text('Alpha.png')); await tester.pumpAndSettle(); final selected = browser.selectedAssetId!; final before = tester.getSize(find.byKey(ValueKey(selected))); await tester.tap(find.text('Alpha.png')); await tester.pump(); expect(tester.getSize(find.byKey(ValueKey(selected))), before); await tester.tap(find.byTooltip('列表布局')); await tester.pumpAndSettle(); expect(browser.selectedAssetId, selected); expect(tester.widget(search).controller!.text, 'ALPHA'); expect(find.text('已选 1 个'), findsOneWidget); expect( tester.getRect(find.byKey(const Key('media-browser-footer'))).right - tester.getRect(find.text('已选 1 个')).right, 12, ); await tester.enterText(search, 'not found'); await tester.pumpAndSettle(); expect(find.text('没有匹配的素材'), findsOneWidget); expect(find.text('已选 1 个'), findsNothing); await tester.enterText(search, ''); await tester.pumpAndSettle(); await tester.tap(find.byKey(const Key('media-sort-button'))); await tester.pumpAndSettle(); await tester.tap(find.byKey(const ValueKey('media-sort-nameAscending'))); await tester.pumpAndSettle(); expect( tester.getTopLeft(find.text('Alpha.png')).dy, lessThan(tester.getTopLeft(find.text('Zebra.png')).dy), ); expect(browser.sort, MediaSort.nameAscending); final other = container.read(mediaBrowserProvider('second')); expect(other.query, isEmpty); expect(other.sort, MediaSort.importOrder); expect(browser.selectedAssetId, selected); 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(find.byType(GridView)).gridDelegate as SliverGridDelegateWithFixedCrossAxisCount) .crossAxisCount; expect(columns(), 2); 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'); final firstTile = find.byKey( const ValueKey('/originals/very-long-asset-name-0.png'), ); final tileWidget = tester.widget(firstTile); await tester.binding.setSurfaceSize(const Size(520, 600)); await tester.pumpAndSettle(); expect(columns(), 4); expect(tester.widget(firstTile), same(tileWidget)); await tester.binding.setSurfaceSize(const Size(280, 600)); await tester.pumpAndSettle(); expect(columns(), 2); expect(tester.widget(firstTile), same(tileWidget)); 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 [ (120.0, 1), (180.0, 2), (220.0, 2), (260.0, 2), (280.0, 2), (240.0, 2), (360.0, 3), (520.0, 4), (560.0, 5), (900.0, 7), ]) { await tester.binding.setSurfaceSize(Size(width, 600)); await tester.pumpAndSettle(); expect(columns(), count); final grid = tester.widget(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('thumbnail size is project-specific and retains selection', ( tester, ) async { await tester.binding.setSurfaceSize(const Size(720, 500)); addTearDown(() => tester.binding.setSurfaceSize(null)); final container = await mount(tester); await (container.read(projectsProvider.notifier) as _Projects) .importExternalMedia('project', [ for (var i = 0; i < 20; i++) ExternalMediaFile(path: '/asset-$i.txt'), ]); await tester.pumpAndSettle(); final browser = container.read(mediaBrowserProvider('project')); browser.selectedAssetId = '/asset-0.txt'; int columns() => (tester.widget(find.byType(GridView)).gridDelegate as SliverGridDelegateWithFixedCrossAxisCount) .crossAxisCount; expect(columns(), 6); for (final (size, count) in [ (MediaGridSize.small, 7), (MediaGridSize.large, 5), (MediaGridSize.medium, 6), ]) { await tester.tap(find.byKey(const Key('media-size-button'))); await tester.pumpAndSettle(); await tester.tap(find.byKey(ValueKey('media-size-${size.name}'))); await tester.pumpAndSettle(); expect(browser.gridSize, size); expect(columns(), count); expect(browser.selectedAssetId, '/asset-0.txt'); } expect( container.read(mediaBrowserProvider('second')).gridSize, MediaGridSize.medium, ); expect(tester.takeException(), isNull); }); testWidgets( 'narrow toolbar preserves search space and exposes density in its menu', (tester) async { await tester.binding.setSurfaceSize(const Size(280, 600)); addTearDown(() => tester.binding.setSurfaceSize(null)); final container = await mount(tester); expect( tester.getSize(find.byKey(const Key('media-panel-header'))).height, 64, ); expect( tester.getSize(find.byKey(const Key('media-search'))).width, greaterThan(160), ); expect(find.byKey(const Key('media-sort-button')), findsNothing); expect(find.byKey(const Key('media-size-button')), findsNothing); await tester.tap(find.byKey(const Key('media-category-button'))); await tester.pumpAndSettle(); final size = find.byKey(const ValueKey('media-size-small')); await tester.ensureVisible(size); await tester.tap(size); await tester.pumpAndSettle(); expect( container.read(mediaBrowserProvider('project')).gridSize, MediaGridSize.small, ); expect(tester.takeException(), isNull); }, ); testWidgets( 'view and density changes preserve the first visible asset before settling', (tester) async { await tester.binding.setSurfaceSize(const Size(720, 500)); addTearDown(() => tester.binding.setSurfaceSize(null)); final container = await mount(tester); await (container.read( projectsProvider.notifier, ) as _Projects).importExternalMedia('project', [ for (var i = 0; i < 120; i++) ExternalMediaFile(path: '/asset-$i.txt'), ]); await tester.pumpAndSettle(); await tester.drag(find.byType(GridView), const Offset(0, -650)); await tester.pumpAndSettle(); final browser = container.read(mediaBrowserProvider('project')); final anchor = browser.viewportAnchor!; expect(anchor.assetId, isNot('/asset-0.txt')); browser.selectedAssetId = anchor.assetId; browser.grid = false; await tester.pump(); final selected = find.byKey(ValueKey(anchor.assetId)); final firstRect = tester.getRect(selected); expect(firstRect.overlaps(tester.getRect(find.byType(ListView))), isTrue); await tester.pumpAndSettle(); expect(tester.getRect(selected), firstRect); browser.grid = true; browser.gridSize = MediaGridSize.large; await tester.pump(); final gridRect = tester.getRect(selected); expect(gridRect.overlaps(tester.getRect(find.byType(GridView))), isTrue); await tester.pumpAndSettle(); expect(tester.getRect(selected), gridRect); expect(browser.selectedAssetId, anchor.assetId); await tester.binding.setSurfaceSize(const Size(560, 500)); await tester.pump(); final resized = tester.getRect(selected); expect(resized.overlaps(tester.getRect(find.byType(GridView))), isTrue); await tester.pumpAndSettle(); expect(tester.getRect(selected), resized); expect(tester.takeException(), isNull); }, ); testWidgets('empty search and panel remount retain the browse anchor', ( tester, ) async { await tester.binding.setSurfaceSize(const Size(720, 500)); addTearDown(() => tester.binding.setSurfaceSize(null)); final container = await mount(tester); await (container.read( projectsProvider.notifier, ) as _Projects).importExternalMedia('project', [ for (var i = 0; i < 120; i++) ExternalMediaFile(path: '/asset-$i.txt'), ]); await tester.pumpAndSettle(); await tester.drag(find.byType(GridView), const Offset(0, -650)); await tester.pumpAndSettle(); final browser = container.read(mediaBrowserProvider('project')); final anchor = browser.viewportAnchor!; final tile = find.byKey(ValueKey(anchor.assetId)); final original = tester.getRect(tile); browser.query = 'no matching assets'; await tester.pumpAndSettle(); expect(find.byType(GridView), findsNothing); browser.query = ''; await tester.pump(); expect(tester.getRect(tile), original); await tester.pumpAndSettle(); final root = tester.widget(find.byType(UncontrolledProviderScope)); await tester.pumpWidget(const SizedBox()); await tester.pumpWidget(root); await tester.pump(); expect(tester.getRect(tile), original); expect(browser.viewportAnchor, anchor); expect(tester.takeException(), isNull); }); testWidgets('bottom browse position is clamped before the first frame', ( tester, ) async { await tester.binding.setSurfaceSize(const Size(720, 500)); addTearDown(() => tester.binding.setSurfaceSize(null)); final container = await mount(tester); await (container.read( projectsProvider.notifier, ) as _Projects).importExternalMedia('project', [ for (var i = 0; i < 121; i++) ExternalMediaFile(path: '/asset-$i.txt'), ]); await tester.pumpAndSettle(); ScrollPosition position() => tester.state(find.byType(Scrollable).last).position; position().jumpTo(position().maxScrollExtent); await tester.pump(); final browser = container.read(mediaBrowserProvider('project')); for (final size in [MediaGridSize.small, MediaGridSize.large]) { final anchor = browser.viewportAnchor!; browser.gridSize = size; await tester.pump(); final firstOffset = position().pixels; expect(firstOffset, lessThanOrEqualTo(position().maxScrollExtent + 1e-6)); await tester.pumpAndSettle(); expect(position().pixels, closeTo(firstOffset, 1e-6)); expect( tester .getRect(find.byKey(ValueKey(anchor.assetId))) .overlaps(tester.getRect(find.byType(GridView))), isTrue, ); position().jumpTo(position().maxScrollExtent); await tester.pump(); } expect(tester.takeException(), isNull); }); testWidgets('desktop density does not change touch-page geometry', ( tester, ) async { final container = await mount(tester, touch: true); await (container.read(projectsProvider.notifier) as _Projects) .importExternalMedia('project', [ const ExternalMediaFile(path: '/asset.txt'), ]); await tester.pumpAndSettle(); final grid = tester.widget(find.byType(GridView)); final delegate = grid.gridDelegate as SliverGridDelegateWithFixedCrossAxisCount; final element = tester.element(find.byType(GridView)); final tileRect = tester.getRect(find.byKey(const ValueKey('/asset.txt'))); container.read(mediaBrowserProvider('project')).gridSize = MediaGridSize.large; await tester.pump(); final updated = tester.widget(find.byType(GridView)); final updatedDelegate = updated.gridDelegate as SliverGridDelegateWithFixedCrossAxisCount; expect(tester.element(find.byType(GridView)), same(element)); expect(updated.controller, same(grid.controller)); expect(updatedDelegate.crossAxisCount, delegate.crossAxisCount); expect(updatedDelegate.mainAxisExtent, delegate.mainAxisExtent); expect(updatedDelegate.childAspectRatio, delegate.childAspectRatio); expect(tester.getRect(find.byKey(const ValueKey('/asset.txt'))), tileRect); expect(tester.takeException(), isNull); }, variant: TargetPlatformVariant.only(TargetPlatform.android)); testWidgets('native file event imports real paths without a success prompt', ( tester, ) async { final container = await mount(tester); container.read(mediaBrowserProvider('project')).query = 'no match'; await tester.pumpAndSettle(); 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(), ); 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(container.read(mediaBrowserProvider('project')).query, isEmpty); 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')); final browser = container.read(mediaBrowserProvider('project')); browser.query = ' FIRST '; await tester.pumpAndSettle(); 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(browser.query, ' FIRST '); 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(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(AppIcons.audioFile), 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 = []; 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 withAssetMedia( String? projectId, AssetDocument asset, Future Function(MediaReference media) action, ) => action( MediaReference( id: asset.id, uri: Uri.parse(asset.location), isImage: asset.metadata['kind'] == 'image', ), ); @visibleForTesting List received = []; @visibleForTesting Future? importGate; @override Future 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 importExternalMedia( String projectId, List files, { bool Function()? isCancelled, }) async { await importGate; 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: [], ); } }