π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mob][photos] Build the device picker and selected preview
r4khul62e797874d9b
diff --git a/mobile/apps/photos/lib/ui/device_picker/device_picker_page.dart b/mobile/apps/photos/lib/ui/device_picker/device_picker_page.dartnew file mode 100644index 0000000000..0dcf1fbd39--- /dev/null+++ b/mobile/apps/photos/lib/ui/device_picker/device_picker_page.dart@@ -0,0 +1,716 @@+import "dart:async";+import "package:ente_components/ente_components.dart";+import "package:ente_strings/ente_strings.dart";+import "package:flutter/material.dart";+import "package:flutter/services.dart";+import "package:hugeicons/hugeicons.dart";+import "package:logging/logging.dart";+import "package:photo_manager/photo_manager.dart";+import "package:photos/core/constants.dart";+import "package:photos/ente_theme_data.dart";+import "package:photos/module/metadata/local_file.dart";+import "package:photos/ui/components/bottom_action_bar/action_bar_widget.dart";+import "package:photos/ui/components/collection_share_badge.dart";+import "package:photos/ui/components/thumbnail_list_item.dart";+import "package:photos/ui/device_picker/device_media_library.dart";+import "package:photos/ui/device_picker/device_picker_controller.dart";+import "package:photos/ui/device_picker/device_picker_gallery.dart";+import "package:photos/ui/viewer/file/detail_page.dart";+import "package:photos/ui/viewer/file/thumbnail_widget.dart";+import "package:photos/ui/viewer/gallery/state/boundary_reporter_mixin.dart";+import "package:photos/ui/viewer/gallery/state/gallery_boundaries_provider.dart";++Future<List<AssetEntity>?> showDevicePicker(BuildContext context) =>+ Navigator.of(context).push<List<AssetEntity>>(+ MaterialPageRoute(builder: (_) => const DevicePickerPage()),+ );++class DevicePickerPage extends StatefulWidget {+ const DevicePickerPage({super.key, this.library});++ final DeviceMediaLibrary? library;++ @override+ State<DevicePickerPage> createState() => _DevicePickerPageState();+}++class _DevicePickerPageState extends State<DevicePickerPage>+ with WidgetsBindingObserver {+ late final _model = DevicePickerController(+ library: widget.library ?? PhotoManagerDeviceLibrary(),+ );+ final _albumScroll = ScrollController();+ Timer? _refreshTimer;+ bool _albumMenu = false;+ bool _starting = true;+ int _seenRemovals = 0;++ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addObserver(this);+ _model.addListener(_onChanged);+ if (widget.library == null) {+ PhotoManager.addChangeCallback(_onLibraryChange);+ unawaited(+ PhotoManager.startChangeNotify().catchError((Object error) {+ Logger(+ "DevicePicker",+ ).warning("Could not observe photo changes", error);+ }),+ );+ }+ unawaited(_start());+ }++ Future<void> _start() async {+ await _model.refresh(requestPermission: true);+ _starting = false;+ }++ @override+ void didChangeAppLifecycleState(AppLifecycleState state) {+ if (state == AppLifecycleState.resumed && !_starting) _scheduleRefresh();+ }++ void _onLibraryChange(MethodCall _) => _scheduleRefresh();++ void _scheduleRefresh() {+ _refreshTimer?.cancel();+ _refreshTimer = Timer(Motion.slow, () {+ if (mounted && !_starting) unawaited(_model.refresh());+ });+ }++ void _onChanged() {+ if (!mounted) return;+ setState(() {});+ if (_model.removedSelections > _seenRemovals) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted &&+ (ModalRoute.of(context)?.isCurrent ?? false) &&+ _model.removedSelections > _seenRemovals) {+ _seenRemovals = _model.removedSelections;+ showToastComponent(+ context,+ context.strings.devicePickerSelectionChanged,+ );+ }+ });+ }+ }++ Future<void> _addSelected() async {+ try {+ final result = await _model.confirm();+ if (!mounted || ModalRoute.of(context)?.isCurrent != true) return;+ if (result != null) Navigator.pop(context, result);+ } catch (_) {+ if (!mounted || ModalRoute.of(context)?.isCurrent != true) return;+ showToastComponent(+ context,+ context.strings.somethingWentWrongPleaseTryAgain,+ );+ }+ }++ Future<void> _switchAlbum(AssetPathEntity album) async {+ setState(() => _albumMenu = false);+ await _model.openAlbum(album);+ }++ Future<void> _previewSelection() async {+ if (_model.selection.isEmpty || _model.confirming) return;+ setState(() => _albumMenu = false);+ final files = _model.selection+ .map((asset) => fileFromAsset('', asset)..duration = asset.duration)+ .toList();+ final shouldAdd = await Navigator.of(context).push<bool>(+ MaterialPageRoute<bool>(+ builder: (_) => Theme(+ data: darkThemeData,+ child: Builder(+ builder: (previewContext) => AnnotatedRegion<SystemUiOverlayStyle>(+ value: SystemUiOverlayStyle.light.copyWith(+ systemNavigationBarColor:+ previewContext.componentColors.backgroundBase,+ ),+ child: DetailPage(+ DetailPageConfiguration(+ files,+ files.length - 1,+ 'device_picker_selection',+ mode: DetailPageMode.selection,+ isLocalOnlyContext: true,+ showEditAction: false,+ showGalleryFilmstrip: true,+ onSelectionRemoved: (file) => _model.replaceSelection(+ _model.selection.where((asset) => asset.id != file.localID),+ ),+ ),+ bottomBar: ColoredBox(+ color: previewContext.componentColors.backgroundBase,+ child: SafeArea(+ top: false,+ child: _DevicePickerAddButton(+ model: _model,+ onTap: () async => Navigator.pop(previewContext, true),+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ );+ if (!mounted) return;+ final needsReview = _model.removedSelections > _seenRemovals;+ _onChanged();+ if (shouldAdd == true && !needsReview) await _addSelected();+ }++ Future<void> _manageAccess() async {+ await PhotoManager.presentLimited(type: RequestType.common);+ if (mounted) await _model.refresh();+ }++ @override+ void dispose() {+ _refreshTimer?.cancel();+ WidgetsBinding.instance.removeObserver(this);+ if (widget.library == null) {+ PhotoManager.removeChangeCallback(_onLibraryChange);+ }+ _model.removeListener(_onChanged);+ _model.dispose();+ _albumScroll.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ final colors = context.componentColors;+ return GalleryBoundariesProvider(+ child: AnnotatedRegion<SystemUiOverlayStyle>(+ value:+ (Theme.of(context).brightness == Brightness.dark+ ? SystemUiOverlayStyle.light+ : SystemUiOverlayStyle.dark)+ .copyWith(+ statusBarColor: colors.backgroundBase,+ systemNavigationBarColor: colors.backgroundBase,+ ),+ child: PopScope(+ canPop: !_albumMenu,+ onPopInvokedWithResult: (didPop, _) {+ if (!didPop && _albumMenu) setState(() => _albumMenu = false);+ },+ child: Scaffold(+ backgroundColor: colors.backgroundBase,+ body: SafeArea(+ child: Column(+ children: [+ _DevicePickerBoundary(+ position: BoundaryPosition.top,+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: Spacing.sm,+ vertical: Spacing.sm,+ ),+ child: Row(+ children: [+ IconButtonComponent(+ icon: const HugeIcon(+ icon: HugeIcons.strokeRoundedCancel01,+ size: IconSizes.medium,+ ),+ tooltip: context.strings.close,+ size: 48,+ iconSize: IconSizes.medium,+ onTap: () {+ if (_albumMenu) {+ setState(() => _albumMenu = false);+ } else {+ Navigator.pop(context);+ }+ },+ ),+ Expanded(+ child: Center(+ child: SizedBox(+ width: 180,+ child: FilterChipComponent(+ label: _albumName(context, _model.album),+ labelStyle: TextStyles.body,+ padding: const EdgeInsets.symmetric(+ horizontal: Spacing.md,+ vertical: Spacing.sm,+ ),+ tooltip: _albumName(context, _model.album),+ state: _albumMenu+ ? FilterChipComponentState.selected+ : FilterChipComponentState.unselected,+ trailing: HugeIcon(+ icon: _albumMenu+ ? HugeIcons.strokeRoundedArrowUp01+ : HugeIcons.strokeRoundedArrowDown01,+ size: IconSizes.small,+ ),+ onChanged: _model.albums.isEmpty+ ? null+ : (_) => setState(+ () => _albumMenu = !_albumMenu,+ ),+ ),+ ),+ ),+ ),+ SizedBox.square(+ dimension: 48,+ child: ListenableBuilder(+ listenable: _model.selectionChanges,+ builder: (context, _) => _model.selection.isEmpty+ ? const SizedBox.shrink()+ : _SelectionPreviewButton(+ asset: _model.selection.last,+ count: _model.selectionCount,+ onTap: _model.confirming+ ? null+ : _previewSelection,+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ Expanded(+ child: Stack(+ children: [+ ExcludeSemantics(+ excluding: _albumMenu,+ child: Column(+ children: [+ Expanded(+ child: Stack(+ children: [+ Positioned.fill(child: _grid()),+ PositionedDirectional(+ end: Spacing.lg,+ bottom: Spacing.sm,+ child: ListenableBuilder(+ listenable: _model.selectionChanges,+ builder: (context, _) =>+ _model.selectionCount > 0+ ? SelectionControlChip(+ label:+ '${_model.selectionCount}/$maxPickAssetLimit',+ semanticLabel:+ '${context.strings.clearSelection}, ${context.strings.selectedCountWithLimit(count: _model.selectionCount, limit: maxPickAssetLimit)}',+ icon: const HugeIcon(+ icon: HugeIcons+ .strokeRoundedCancel01,+ size: IconSizes.small,+ ),+ onTap: _model.confirming+ ? null+ : _model.clearSelection,+ )+ : const SizedBox.shrink(),+ ),+ ),+ ],+ ),+ ),+ _DevicePickerBoundary(+ position: BoundaryPosition.bottom,+ child: _DevicePickerAddButton(+ model: _model,+ onTap: _addSelected,+ ),+ ),+ ],+ ),+ ),+ if (_albumMenu) ...[+ ModalBarrier(+ color: colors.specialScrim,+ dismissible: true,+ semanticsLabel: context.strings.close,+ onDismiss: () => setState(() => _albumMenu = false),+ ),+ LayoutBuilder(+ builder: (context, constraints) => Align(+ alignment: Alignment.topCenter,+ child: ConstrainedBox(+ constraints: BoxConstraints(+ maxHeight: constraints.maxHeight * 0.72,+ maxWidth: 428,+ ),+ child: Material(+ color: colors.backgroundBase,+ borderRadius: const BorderRadius.vertical(+ bottom: Radius.circular(Radii.lg),+ ),+ clipBehavior: Clip.antiAlias,+ child: Scrollbar(+ controller: _albumScroll,+ thumbVisibility: true,+ radius: const Radius.circular(2),+ child: ListView.separated(+ key: const PageStorageKey('deviceAlbums'),+ controller: _albumScroll,+ shrinkWrap: true,+ padding:+ const EdgeInsetsDirectional.fromSTEB(+ Spacing.md,+ Spacing.sm,+ Spacing.lg,+ Spacing.sm,+ ),+ itemCount: _model.albums.length,+ separatorBuilder: (_, _) =>+ const SizedBox(height: Spacing.sm),+ itemBuilder: (context, index) =>+ _DeviceAlbumRow(+ key: ValueKey(+ _model.albums[index].id,+ ),+ album: _model.albums[index],+ library: _model.library,+ selected:+ _model.albums[index].id ==+ _model.album?.id,+ onTap: () => _switchAlbum(+ _model.albums[index],+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ ],+ ],+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ );+ }++ Widget _grid() {+ if (!_model.hasAccess && !_model.refreshing) {+ return _DevicePickerMessage(+ message: context.strings.devicePickerPermissionHint,+ action: context.strings.openSettings,+ onAction: () => PhotoManager.openSetting(),+ );+ }+ final limitedAccessNotice = _model.permission == PermissionState.limited+ ? Padding(+ padding: const EdgeInsets.symmetric(horizontal: Spacing.lg),+ child: MenuComponent(+ title: context.strings.devicePickerLimitedAccess,+ subtitle: context.strings.selectMorePhotos,+ trailing: const HugeIcon(+ icon: HugeIcons.strokeRoundedAdd01,+ size: IconSizes.medium,+ ),+ onTap: _manageAccess,+ ),+ )+ : null;+ if (_model.media.isEmpty) {+ if (_model.refreshing || _model.loadingMore) {+ return Center(+ child: LoadingComponent(+ semanticsLabel: context.strings.loadingYourPhotos,+ ),+ );+ }+ return _DevicePickerMessage(+ header: limitedAccessNotice,+ message: _model.error == null+ ? context.strings.noPhotosFoundHere+ : context.strings.somethingWentWrong,+ action: context.strings.retry,+ onAction: () => _model.refresh(),+ );+ }+ return DevicePickerGallery(+ model: _model,+ header: limitedAccessNotice,+ footer: Column(+ children: [+ SizedBox(+ height:+ MediaQuery.textScalerOf(context).scale(20) ++ Spacing.xxl ++ Spacing.md,+ ),+ if (_model.loadingMore) const LoadingComponent(),+ if (_model.error != null)+ _DevicePickerMessage(+ message: context.strings.somethingWentWrong,+ action: context.strings.retry,+ onAction: _model.hasMore+ ? _model.loadMore+ : () => _model.refresh(),+ ),+ ],+ ),+ );+ }+}++class _DevicePickerAddButton extends StatelessWidget {+ const _DevicePickerAddButton({required this.model, required this.onTap});++ final DevicePickerController model;+ final Future<void> Function() onTap;++ @override+ Widget build(BuildContext context) => Center(+ heightFactor: 1,+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 428),+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ Spacing.xl,+ Spacing.lg,+ Spacing.xl,+ Spacing.sm,+ ),+ child: ListenableBuilder(+ listenable: Listenable.merge([model, model.selectionChanges]),+ builder: (context, _) => ButtonComponent(+ label: context.strings.addSelected,+ isDisabled: model.selectionCount == 0 || model.refreshing,+ onTap: onTap,+ shouldShowSuccessState: false,+ ),+ ),+ ),+ ),+ );+}++class _SelectionPreviewButton extends StatelessWidget {+ const _SelectionPreviewButton({+ required this.asset,+ required this.count,+ required this.onTap,+ });++ final AssetEntity asset;+ final int count;+ final VoidCallback? onTap;++ @override+ Widget build(BuildContext context) {+ final colors = context.componentColors;+ return Semantics(+ label:+ '${context.strings.preview}, ${context.strings.selectedCount(count: count)}',+ button: true,+ enabled: onTap != null,+ child: Tooltip(+ message: context.strings.preview,+ child: InkWell(+ onTap: onTap,+ borderRadius: BorderRadius.circular(Radii.sm),+ child: ExcludeSemantics(+ child: Stack(+ children: [+ Positioned.fill(+ child: Padding(+ padding: const EdgeInsets.all(Spacing.xs),+ child: ClipRRect(+ borderRadius: BorderRadius.circular(Radii.sm),+ child: ThumbnailWidget(+ fileFromAsset('', asset),+ rawThumbnail: true,+ placeholderColor: colors.fillLight,+ ),+ ),+ ),+ ),+ PositionedDirectional(+ bottom: 0,+ end: 0,+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: Spacing.xs),+ decoration: BoxDecoration(+ color: colors.fillBase,+ borderRadius: BorderRadius.circular(Radii.lg),+ ),+ child: Text(+ '$count',+ style: TextStyles.tiny.copyWith(+ color: colors.textReverse,+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ );+ }+}++String _albumName(BuildContext context, AssetPathEntity? album) =>+ album == null || album.isAll ? context.strings.recent : album.name;++class _DeviceAlbumRow extends StatefulWidget {+ const _DeviceAlbumRow({+ super.key,+ required this.album,+ required this.library,+ required this.selected,+ required this.onTap,+ });+ final AssetPathEntity album;+ final DeviceMediaLibrary library;+ final bool selected;+ final VoidCallback onTap;++ @override+ State<_DeviceAlbumRow> createState() => _DeviceAlbumRowState();+}++class _DeviceAlbumRowState extends State<_DeviceAlbumRow> {+ late Future<List<AssetEntity>> _cover = widget.library.read(+ widget.album,+ start: 0,+ end: 1,+ );+ late Future<int> _count = widget.library.count(widget.album);++ @override+ void didUpdateWidget(covariant _DeviceAlbumRow oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (!identical(oldWidget.album, widget.album)) {+ _cover = widget.library.read(widget.album, start: 0, end: 1);+ _count = widget.library.count(widget.album);+ }+ }++ @override+ Widget build(BuildContext context) {+ final colors = context.componentColors;+ return Semantics(+ selected: widget.selected,+ child: ThumbnailListItem(+ backgroundColor: thumbnailListItemBackgroundColor(context),+ selectedBorderColor: colors.strokeDark,+ isSelected: widget.selected,+ onTap: widget.onTap,+ leading: ClipRRect(+ borderRadius: BorderRadius.circular(+ ThumbnailListItem.defaultLeadingRadius,+ ),+ child: FutureBuilder<List<AssetEntity>>(+ future: _cover,+ builder: (context, snapshot) => snapshot.data?.isNotEmpty == true+ ? ThumbnailWidget(+ fileFromAsset(widget.album.name, snapshot.data!.first),+ rawThumbnail: true,+ )+ : ColoredBox(color: colors.fillLight),+ ),+ ),+ title: Text(+ _albumName(context, widget.album),+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: TextStyles.body.copyWith(color: colors.textBase),+ ),+ subtitle: FutureBuilder<int>(+ future: _count,+ builder: (context, count) => Text(+ count.hasData ? context.strings.itemCount(count: count.data!) : '',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyles.mini.copyWith(color: colors.textLight),+ ),+ ),+ trailing: SizedBox.square(+ dimension: IconSizes.small,+ child: widget.selected+ ? const Center(child: CollectionSelectedBadge())+ : null,+ ),+ ),+ );+ }+}++class _DevicePickerBoundary extends StatefulWidget {+ const _DevicePickerBoundary({required this.position, required this.child});++ final BoundaryPosition position;+ final Widget child;++ @override+ State<_DevicePickerBoundary> createState() => _DevicePickerBoundaryState();+}++class _DevicePickerBoundaryState extends State<_DevicePickerBoundary>+ with BoundaryReporter {+ @override+ Widget build(BuildContext context) =>+ boundaryWidget(position: widget.position, child: widget.child);+}++class _DevicePickerMessage extends StatelessWidget {+ const _DevicePickerMessage({+ required this.message,+ this.action,+ this.onAction,+ this.header,+ });++ final String message;+ final String? action;+ final VoidCallback? onAction;+ final Widget? header;++ @override+ Widget build(BuildContext context) => Center(+ child: SingleChildScrollView(+ padding: const EdgeInsets.all(Spacing.xxl),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ ?header,+ Text(+ message,+ textAlign: TextAlign.center,+ style: TextStyles.body.copyWith(+ color: context.componentColors.textLight,+ ),+ ),+ if (action != null) ...[+ const SizedBox(height: Spacing.lg),+ ButtonComponent(+ label: action!,+ onTap: onAction,+ size: ButtonComponentSize.small,+ variant: ButtonComponentVariant.secondary,+ ),+ ],+ ],+ ),+ ),+ );+}diff --git a/mobile/apps/photos/test/ui/device_picker/device_picker_page_test.dart b/mobile/apps/photos/test/ui/device_picker/device_picker_page_test.dartnew file mode 100644index 0000000000..7d26eee1b1--- /dev/null+++ b/mobile/apps/photos/test/ui/device_picker/device_picker_page_test.dart@@ -0,0 +1,380 @@+import "dart:async";+import "dart:io";++import "package:dio/dio.dart";+import "package:ente_strings/ente_strings.dart";+import "package:flutter/material.dart";+import "package:flutter/services.dart";+import "package:flutter_easyloading/flutter_easyloading.dart";+import "package:flutter_test/flutter_test.dart";+import "package:package_info_plus/package_info_plus.dart";+import "package:photo_manager/photo_manager.dart";+import "package:photos/app_mode.dart";+import "package:photos/core/configuration.dart";+import "package:photos/ente_theme_data.dart";+import "package:photos/module/metadata/local_file.dart";+import "package:photos/service_locator.dart";+import "package:photos/settings/local_settings.dart";+import "package:photos/states/detail_page_state.dart";+import "package:photos/ui/device_picker/device_picker_gallery.dart";+import "package:photos/ui/device_picker/device_picker_page.dart";+import "package:photos/ui/viewer/file/detail_page.dart";+import "package:photos/ui/viewer/file/file_widget.dart";+import "package:photos/ui/viewer/file/image_zoom/image_zoom_viewer.dart";+import "package:photos/ui/viewer/gallery/component/gallery_file_widget.dart";+import "package:shared_preferences/shared_preferences.dart";++import "device_picker_test_helpers.dart";++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ final navigatorKey = GlobalKey<NavigatorState>();+ late FakeDeviceLibrary library;+ late Future<List<AssetEntity>?> result;++ setUpAll(() async {+ SharedPreferences.setMockInitialValues({});+ final preferences = await SharedPreferences.getInstance();+ ServiceLocator.instance.init(+ preferences,+ Dio(),+ Dio(),+ Dio(),+ PackageInfo(+ appName: 'Photos',+ packageName: 'photos',+ version: '1',+ buildNumber: '1',+ ),+ );+ try {+ await Configuration.instance.init(preferences);+ } catch (_) {}++ final fonts = FontLoader('packages/ente_components/Inter');+ for (final name in ['Regular', 'Medium', 'SemiBold', 'Bold']) {+ fonts.addFont(+ rootBundle.load('packages/ente_components/fonts/Inter-$name.ttf'),+ );+ }+ await fonts.load();++ final bytes = File('assets/memories.jpg').readAsBytesSync();+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(+ const MethodChannel('com.fluttercandies/photo_manager'),+ (call) async {+ if (call.method == 'fetchEntityProperties') {+ final id = (call.arguments as Map)['id'] as String;+ return {+ 'id': id,+ 'type': 1,+ 'width': 1200,+ 'height': 800,+ 'title': '$id.jpg',+ 'createDt': 1700000000,+ };+ }+ return switch (call.method) {+ 'getThumb' || 'getOriginBytes' => bytes,+ 'getFullFile' => File('assets/memories.jpg').absolute.path,+ 'assetExists' => true,+ _ => null,+ };+ },+ );+ });++ setUp(() async {+ await localSettings.setGalleryLayoutType(GalleryLayoutType.grid);+ await localSettings.setPhotoGridSize(5);+ await localSettings.setAppMode(AppMode.localGallery);+ library = FakeDeviceLibrary()+ ..items = List.generate(160, (index) => media('$index'));+ });++ Future<void> mount(+ WidgetTester tester, {+ bool withParentRoute = false,+ Size size = const Size(390, 844),+ double textScale = 1,+ String locale = 'en',+ }) async {+ addTearDown(tester.view.resetPhysicalSize);+ addTearDown(tester.view.resetDevicePixelRatio);+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = size;+ await tester.pumpWidget(+ MaterialApp(+ navigatorKey: navigatorKey,+ locale: Locale(locale),+ localizationsDelegates: StringsLocalizations.localizationsDelegates,+ supportedLocales: StringsLocalizations.supportedLocales,+ theme: lightThemeData,+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(+ context,+ ).copyWith(textScaler: TextScaler.linear(textScale)),+ child: EasyLoading.init()(context, child),+ ),+ home: const Scaffold(),+ ),+ );+ if (withParentRoute) {+ unawaited(+ navigatorKey.currentState!.push<void>(+ MaterialPageRoute(+ builder: (_) => const Scaffold(body: Text('Album')),+ ),+ ),+ );+ await tester.pumpAndSettle();+ }+ result = navigatorKey.currentState!.push<List<AssetEntity>>(+ MaterialPageRoute(builder: (_) => DevicePickerPage(library: library)),+ );+ await _settleImages(tester);+ await tester.pump(const Duration(seconds: 5));+ }++ tearDown(() async {+ await EasyLoading.dismiss(animation: false);+ });++ testWidgets(+ 'limited-access notice scrolls so large text does not crowd out the gallery',+ (tester) async {+ library.access = PermissionState.limited;+ await mount(+ tester,+ size: const Size(844, 390),+ textScale: 3,+ locale: 'de',+ );+ expect(tester.takeException(), isNull);+ final strings = StringsLocalizations.of(+ tester.element(find.byType(DevicePickerPage)),+ )!;+ final notice = find.text(strings.devicePickerLimitedAccess);+ expect(notice.hitTestable(), findsOneWidget);+ final scroll = tester+ .widget<CustomScrollView>(find.byType(CustomScrollView))+ .controller!;+ scroll.jumpTo(250);+ await _settleImages(tester);+ expect(notice.hitTestable(), findsNothing);+ await tester.tap(find.byType(GalleryFileWidget).hitTestable().first);+ await tester.pumpAndSettle();+ expect(find.text('1/50').hitTestable(), findsOneWidget);+ expect(find.text(strings.addSelected).hitTestable(), findsOneWidget);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox.shrink());+ await tester.pumpAndSettle();+ },+ );++ testWidgets('device duration fills missing metadata for existing videos', (+ tester,+ ) async {+ final asset = AssetEntity(+ id: 'video',+ typeInt: 2,+ width: 1200,+ height: 800,+ duration: 65,+ title: 'video.mp4',+ createDateSecond: 1700000000,+ );+ library.items = [asset];+ library.knownFiles[asset.id] = fileFromAsset('Camera', asset)+ ..generatedID = 1+ ..duration = 0;+ await mount(tester);+ expect(find.text('1:05'), findsOneWidget);+ await tester.pumpWidget(const SizedBox.shrink());+ await tester.pumpAndSettle();+ });++ testWidgets('Add selected in preview returns the remaining original assets', (+ tester,+ ) async {+ await mount(tester);+ final tiles = find.byType(GalleryFileWidget);+ for (final index in [1, 4, 7]) {+ await tester.tap(tiles.at(index));+ await tester.pumpAndSettle();+ }+ await tester.tap(find.byTooltip('Preview'));+ await _settleImages(tester);+ expect(find.text('3/50 selected'), findsOneWidget);+ expect(+ Theme.of(tester.element(find.byType(DetailPage))).brightness,+ Brightness.dark,+ );+ await tester.tapAt(tester.getCenter(find.byType(PageView)));+ await tester.pump(const Duration(milliseconds: 400));+ tester.widget<FileWidget>(find.byType(FileWidget).first).playbackCallback!(+ true,+ FullScreenRequestReason.playbackStateChange,+ );+ await tester.pumpAndSettle();+ expect(find.byTooltip('Remove').hitTestable(), findsOneWidget);+ expect(find.text('Add selected').hitTestable(), findsOneWidget);+ await tester.tap(find.byIcon(Icons.close));+ await _settleImages(tester);+ expect(find.byType(DevicePickerPage), findsOneWidget);+ expect(+ Theme.of(tester.element(find.byType(DevicePickerPage))).brightness,+ Brightness.light,+ );+ await tester.tap(find.byTooltip('Preview'));+ await _settleImages(tester);+ expect(find.text('3/50 selected'), findsOneWidget);+ await tester.tap(find.byTooltip('Remove'));+ await _settleImages(tester);+ expect(find.text('2/50 selected'), findsOneWidget);+ await tester.tap(find.text('Add selected'));+ await _settleImages(tester);+ expect(find.byType(DetailPage), findsNothing);+ expect(find.byType(DevicePickerPage), findsNothing);+ expect(await result, [library.items[1], library.items[4]]);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox.shrink());+ await tester.pumpAndSettle();+ });++ testWidgets(+ 'missing assets in preview require reviewing the remaining selection',+ (tester) async {+ await mount(tester);+ final model = tester+ .widget<DevicePickerGallery>(find.byType(DevicePickerGallery))+ .model;+ model.replaceSelection(library.items.take(2));+ await _settleImages(tester);+ await tester.tap(find.byTooltip('Preview'));+ await _settleImages(tester);+ library.unavailable.add(library.items.first.id);+ await model.refresh();+ await _settleImages(tester);+ await tester.tap(find.text('Add selected'));+ await _settleImages(tester);+ expect(find.byType(DevicePickerPage), findsOneWidget);+ expect(find.text('1/50'), findsOneWidget);+ expect(+ find.text(+ "Some selected items couldn't be found. Check your selection and try again.",+ ),+ findsOneWidget,+ );+ await tester.pump(const Duration(seconds: 5));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Add selected'));+ await _settleImages(tester);+ expect(await result, [library.items[1]]);+ await tester.pumpWidget(const SizedBox.shrink());+ await tester.pumpAndSettle();+ },+ );++ testWidgets(+ 'scrolling pages device assets without changing selection or gallery preferences',+ (tester) async {+ library.items = List.generate(10000, (i) => media('$i'));+ await mount(tester);+ final model = tester+ .widget<DevicePickerGallery>(find.byType(DevicePickerGallery))+ .model;+ expect(model.media.length, 96);+ await tester.tap(find.byType(GalleryFileWidget).first);+ await tester.pumpAndSettle();+ model.replaceSelection(library.items.take(50));+ await tester.pumpAndSettle();+ expect(library.fileLookupBatches, hasLength(1));+ final scroll = tester+ .widget<CustomScrollView>(find.byType(CustomScrollView))+ .controller!;+ scroll.jumpTo(scroll.position.maxScrollExtent);+ await _settleImages(tester);+ expect(model.media.length, 192);+ expect(library.fileLookupBatches.expand((ids) => ids).length, 192);+ expect(model.selection, library.items.take(50));+ scroll.jumpTo(0);+ await _settleImages(tester);+ expect(library.fileLookupBatches.expand((ids) => ids).length, 192);+ expect(localSettings.getPhotoGridSize(), 5);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox.shrink());+ await tester.pumpAndSettle();+ },+ );++ testWidgets('closing during confirmation leaves the parent route open', (+ tester,+ ) async {+ await mount(tester, withParentRoute: true);+ await tester.tap(find.byType(GalleryFileWidget).first);+ await tester.pumpAndSettle();+ final pending = Completer<AssetEntity?>();+ library.resolveOverride = (_) => pending.future;+ await tester.tap(find.text('Add selected'));+ await tester.pump();+ navigatorKey.currentState!.pop();+ pending.complete(library.items.first);+ await _settleImages(tester);+ expect(await result, isNull);+ expect(find.text('Album'), findsOneWidget);+ expect(navigatorKey.currentState!.canPop(), isTrue);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox.shrink());+ await tester.pumpAndSettle();+ });++ testWidgets('device files remain selectable when metadata lookup fails', (+ tester,+ ) async {+ library.fileLookupError = StateError('Database unavailable');+ await mount(tester);+ await tester.tap(find.byType(GalleryFileWidget).first);+ await tester.pumpAndSettle();+ await tester.tap(find.text('Add selected'));+ await tester.pumpAndSettle();+ expect(await result, [library.items.first]);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox.shrink());+ await tester.pumpAndSettle();+ });+}++Future<void> _settleImages(WidgetTester tester) async {+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 400));+ final context = tester.element(find.byType(Navigator).first);+ final providers = [+ ...tester+ .widgetList<Image>(find.byWidgetPredicate((widget) => widget is Image))+ .map((widget) => widget.image),+ ...tester+ .widgetList<ImageZoomViewer>(find.byType(ImageZoomViewer))+ .map((widget) => widget.imageProvider)+ .whereType<ImageProvider>(),+ ];+ await tester.runAsync(() async {+ var finished = false;+ final loading = Future.wait(+ providers.map((provider) => precacheImage(provider, context)),+ ).whenComplete(() => finished = true);+ final deadline = DateTime.now().add(const Duration(seconds: 10));+ while (!finished && DateTime.now().isBefore(deadline)) {+ await tester.pump(const Duration(milliseconds: 20));+ await Future<void>.delayed(const Duration(milliseconds: 10));+ }+ expect(finished, isTrue, reason: 'Fixture images should finish decoding');+ await loading;+ });+ await tester.pumpAndSettle(+ const Duration(milliseconds: 100),+ EnginePhase.sendSemanticsUpdate,+ const Duration(seconds: 10),+ );+}