π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mob][photos] Defer grid rebuilds for hidden galleries
ashil-pilotea169c0cde97
diff --git a/mobile/apps/photos/changes/deferred-gallery-layout.md b/mobile/apps/photos/changes/deferred-gallery-layout.mdnew file mode 100644index 0000000000..8f66125dfe--- /dev/null+++ b/mobile/apps/photos/changes/deferred-gallery-layout.md@@ -0,0 +1 @@+- Reduced unnecessary thumbnail downloads when changing gallery layouts.diff --git a/mobile/apps/photos/lib/ui/tabs/home_widget.dart b/mobile/apps/photos/lib/ui/tabs/home_widget.dartindex 0b5c0fd147..281e578dae 100644--- a/mobile/apps/photos/lib/ui/tabs/home_widget.dart+++ b/mobile/apps/photos/lib/ui/tabs/home_widget.dart@@ -82,6 +82,7 @@ import "package:photos/ui/viewer/actions/file_viewer.dart";import "package:photos/ui/viewer/file/detail_page.dart";import "package:photos/ui/viewer/gallery/collection_page.dart";import "package:photos/ui/viewer/gallery/shared_public_collection_page.dart";+import "package:photos/ui/viewer/gallery/state/gallery_visibility_scope.dart";import "package:photos/ui/viewer/search_tab/search_tab.dart";import "package:photos/utils/collection_util.dart";import "package:photos/utils/dialog_util.dart";@@ -1217,7 +1218,10 @@ class _HomeWidgetState extends State<HomeWidget> {Widget _buildTabHeroMode(int tabIndex, int selectedTabIndex, Widget child) {return ClipRect(- child: HeroMode(enabled: tabIndex == selectedTabIndex, child: child),+ child: GalleryVisibilityScope(+ visible: tabIndex == selectedTabIndex,+ child: HeroMode(enabled: tabIndex == selectedTabIndex, child: child),+ ),);}diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/component/group/group_header_widget.dart b/mobile/apps/photos/lib/ui/viewer/gallery/component/group/group_header_widget.dartindex 7688010250..26f7a32631 100644--- a/mobile/apps/photos/lib/ui/viewer/gallery/component/group/group_header_widget.dart+++ b/mobile/apps/photos/lib/ui/viewer/gallery/component/group/group_header_widget.dart@@ -229,10 +229,13 @@ class _GroupHeaderWidgetState extends State<GroupHeaderWidget> {}void _showLayoutSettingsOverflowMenu(BuildContext context) {+ final gallery = context.findAncestorStateOfType<GalleryState>();components.showBottomSheetComponent<void>(context: context,builder: (BuildContext context) {- return const GalleryLayoutSettings();+ return GalleryLayoutSettings(+ onPreviewVisibilityChanged: gallery?.setLayoutPreviewVisibility,+ );},);}diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/gallery.dart b/mobile/apps/photos/lib/ui/viewer/gallery/gallery.dartindex 33c476b251..a5fe903dee 100644--- a/mobile/apps/photos/lib/ui/viewer/gallery/gallery.dart+++ b/mobile/apps/photos/lib/ui/viewer/gallery/gallery.dart@@ -37,6 +37,7 @@ import "package:photos/ui/viewer/gallery/state/boundary_reporter_mixin.dart";import "package:photos/ui/viewer/gallery/state/gallery_boundaries_provider.dart";import "package:photos/ui/viewer/gallery/state/gallery_context_state.dart";import "package:photos/ui/viewer/gallery/state/gallery_files_inherited_widget.dart";+import "package:photos/ui/viewer/gallery/state/gallery_visibility_scope.dart";import "package:photos/ui/viewer/gallery/state/inherited_search_filter_data.dart";import "package:photos/ui/viewer/gallery/swipe_selection_wrapper.dart";import "package:photos/ui/viewer/gallery/swipe_to_select_helper.dart";@@ -167,6 +168,10 @@ class GalleryState extends State<Gallery> {bool _sortOrderAsc = false;int _layoutChangeGeneration = 0;bool _committingGridZoom = false;+ bool _isGalleryVisible = false;+ bool _isGalleryTabVisible = true;+ ModalRoute<dynamic>? _layoutPreviewRoute;+ bool _needsLayoutRefresh = false;int _activeFileLoads = 0;List<EnteFile> _allGalleryFiles = [];final _scrollController = ScrollController();@@ -213,16 +218,10 @@ class GalleryState extends State<Gallery> {);_layoutChangeSubscription = Bus.instance.on<GalleryLayoutChangedEvent>()- .listen((_) async {+ .listen((_) {if (!mounted || _committingGridZoom) return;- final generation = ++_layoutChangeGeneration;- final scrollAnchor = _captureLayoutScrollAnchor();- _setGroupType();- final measuredHeaderExtent = await _measureGroupHeaderExtent();- if (!mounted || generation != _layoutChangeGeneration) return;- groupHeaderExtent = measuredHeaderExtent;- _updateGalleryGroups();- _restoreLayoutScrollAnchor(scrollAnchor, generation);+ _needsLayoutRefresh = true;+ unawaited(_refreshGalleryLayout());});_sortOrderAsc = widget.sortAsyncFn != null ? widget.sortAsyncFn!() : false;if (widget.reloadEvent != null) {@@ -370,6 +369,14 @@ class GalleryState extends State<Gallery> {@overridevoid didChangeDependencies() {super.didChangeDependencies();+ final isRouteCurrent = ModalRoute.isCurrentOf(context) ?? true;+ _isGalleryTabVisible = GalleryVisibilityScope.isVisibleOf(context);+ final wasVisible = _isGalleryVisible;+ _isGalleryVisible = isRouteCurrent && _isGalleryTabVisible;+ if (wasVisible && !_isGalleryVisible) {+ ++_layoutChangeGeneration;+ if (groupHeaderExtent == null) _needsLayoutRefresh = true;+ }_inheritedSearchFilterData = InheritedSearchFilterData.maybeOf(context);final boundaries = GalleryBoundariesProvider.of(context);if (_boundariesProvider != boundaries) {@@ -382,9 +389,51 @@ class GalleryState extends State<Gallery> {);}_selectedFilesListener();+ if (_canRefreshGalleryLayout && _needsLayoutRefresh) {+ unawaited(_refreshGalleryLayout());+ }+ }++ bool get _canRefreshGalleryLayout =>+ _isGalleryVisible ||+ (_isGalleryTabVisible && (_layoutPreviewRoute?.isCurrent ?? false));++ void setLayoutPreviewVisibility(ModalRoute<dynamic> route, bool visible) {+ if (!mounted) return;+ if (visible) {+ _layoutPreviewRoute = route;+ } else if (identical(_layoutPreviewRoute, route)) {+ _layoutPreviewRoute = null;+ }+ if (_canRefreshGalleryLayout && _needsLayoutRefresh) {+ unawaited(_refreshGalleryLayout());+ }+ }++ Future<void> _refreshGalleryLayout() async {+ if (!mounted || !_canRefreshGalleryLayout || !_needsLayoutRefresh) {+ return;+ }+ final generation = ++_layoutChangeGeneration;+ final scrollAnchor = _captureLayoutScrollAnchor();+ _setGroupType();+ final measuredHeaderExtent = await _measureGroupHeaderExtent();+ if (!mounted ||+ !_canRefreshGalleryLayout ||+ generation != _layoutChangeGeneration) {+ return;+ }+ _needsLayoutRefresh = false;+ groupHeaderExtent = measuredHeaderExtent;+ _updateGalleryGroups();+ _restoreLayoutScrollAnchor(scrollAnchor, generation);}void _updateGalleryGroups({bool callSetState = true}) {+ if (!_canRefreshGalleryLayout) {+ _needsLayoutRefresh = true;+ return;+ }if (groupHeaderExtent == null) return;final widthAvailable = MediaQuery.sizeOf(context).width;// View metrics can be zero during background startup. Skip invalid layouts@@ -901,6 +950,9 @@ class GalleryState extends State<Gallery> {@overrideWidget build(BuildContext context) {_logger.info("Building Gallery ${widget.tagPrefix}");+ if (!_isGalleryVisible && galleryGroups == null) {+ return const SizedBox.shrink();+ }final appBarGeometry = widget.appBar?.resolveGeometry(context);final appBarPinnedHeight = appBarGeometry?.minExtent ?? 0;final appBarCollapseExtent = appBarGeometry?.collapseExtent ?? 0;diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/layout_settings.dart b/mobile/apps/photos/lib/ui/viewer/gallery/layout_settings.dartindex 0d36cb485e..e23558681b 100644--- a/mobile/apps/photos/lib/ui/viewer/gallery/layout_settings.dart+++ b/mobile/apps/photos/lib/ui/viewer/gallery/layout_settings.dart@@ -3,8 +3,35 @@ import "package:ente_strings/ente_strings.dart";import "package:flutter/material.dart";import "package:photos/ui/viewer/gallery/gallery_layout_controls.dart";-class GalleryLayoutSettings extends StatelessWidget {- const GalleryLayoutSettings({super.key});+class GalleryLayoutSettings extends StatefulWidget {+ const GalleryLayoutSettings({super.key, this.onPreviewVisibilityChanged});++ final void Function(ModalRoute<dynamic> route, bool visible)?+ onPreviewVisibilityChanged;++ @override+ State<GalleryLayoutSettings> createState() => _GalleryLayoutSettingsState();+}++class _GalleryLayoutSettingsState extends State<GalleryLayoutSettings> {+ ModalRoute<dynamic>? _route;++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ _route = ModalRoute.of(context);+ if (_route != null) {+ widget.onPreviewVisibilityChanged?.call(_route!, _route!.isCurrent);+ }+ }++ @override+ void dispose() {+ if (_route != null) {+ widget.onPreviewVisibilityChanged?.call(_route!, false);+ }+ super.dispose();+ }@overrideWidget build(BuildContext context) {diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/state/gallery_visibility_scope.dart b/mobile/apps/photos/lib/ui/viewer/gallery/state/gallery_visibility_scope.dartnew file mode 100644index 0000000000..d554f03511--- /dev/null+++ b/mobile/apps/photos/lib/ui/viewer/gallery/state/gallery_visibility_scope.dart@@ -0,0 +1,21 @@+import "package:flutter/widgets.dart";++class GalleryVisibilityScope extends InheritedWidget {+ const GalleryVisibilityScope({+ required this.visible,+ required super.child,+ super.key,+ });++ final bool visible;++ static bool isVisibleOf(BuildContext context) =>+ context+ .dependOnInheritedWidgetOfExactType<GalleryVisibilityScope>()+ ?.visible ??+ true;++ @override+ bool updateShouldNotify(GalleryVisibilityScope oldWidget) =>+ visible != oldWidget.visible;+}diff --git a/mobile/apps/photos/test/ui/viewer/gallery/gallery_layout_changed_event_test.dart b/mobile/apps/photos/test/ui/viewer/gallery/gallery_layout_changed_event_test.dartindex 8fd57bd983..8806925bbf 100644--- a/mobile/apps/photos/test/ui/viewer/gallery/gallery_layout_changed_event_test.dart+++ b/mobile/apps/photos/test/ui/viewer/gallery/gallery_layout_changed_event_test.dart@@ -10,6 +10,7 @@ import "package:photos/core/configuration.dart";import "package:photos/core/event_bus.dart";import "package:photos/ente_theme_data.dart";import "package:photos/events/event.dart";+import "package:photos/events/files_updated_event.dart";import "package:photos/events/gallery_layout_changed_event.dart";import "package:photos/models/file/dummy_file.dart";import "package:photos/models/file/file.dart";@@ -28,6 +29,7 @@ import "package:photos/ui/viewer/gallery/gallery_grid_zoom.dart";import "package:photos/ui/viewer/gallery/layout_settings.dart";import "package:photos/ui/viewer/gallery/state/gallery_boundaries_provider.dart";import "package:photos/ui/viewer/gallery/state/gallery_files_inherited_widget.dart";+import "package:photos/ui/viewer/gallery/state/gallery_visibility_scope.dart";import "package:shared_preferences/shared_preferences.dart";void main() {@@ -536,7 +538,7 @@ void main() {);testWidgets(- "layout changes rebuild every mounted gallery without loading files",+ "layout changes rebuild every visible gallery without loading files",(tester) async {await localSettings.setPhotoGridSize(4);final firstKey = GlobalKey<GalleryState>();@@ -625,6 +627,269 @@ void main() {},);+ testWidgets(+ "covered galleries defer grid rebuilds while file loading continues",+ (tester) async {+ await localSettings.setPhotoGridSize(4);+ final navigation = GlobalKey<NavigatorState>();+ final coveredKey = GlobalKey<GalleryState>();+ final visibleKey = GlobalKey<GalleryState>();+ final files = List<EnteFile>.generate(1000, _justifiedTestFile);+ var loadedFiles = files;+ final reloads = StreamController<FilesUpdatedEvent>.broadcast();+ addTearDown(reloads.close);+ var coveredLoads = 0;+ await tester.pumpWidget(+ MaterialApp(+ navigatorKey: navigation,+ theme: lightThemeData,+ home: _galleryHost(+ Gallery(+ key: coveredKey,+ asyncLoader: (start, end, {limit, asc}) async {+ coveredLoads++;+ return FileLoadResult(loadedFiles, false);+ },+ reloadEvent: reloads.stream,+ tagPrefix: "covered_",+ enableFileGrouping: false,+ showSelectAll: false,+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ final oldGroups = coveredKey.currentState!.galleryGroups!;+ final anchor = files[804];+ final oldGeometry = oldGroups.getGeometryOfFile(anchor)!;+ const progress = 0.5;+ final position = tester+ .state<ScrollableState>(find.byType(Scrollable))+ .position;+ position.jumpTo(oldGeometry.rowOffset + oldGeometry.rowExtent * progress);+ await tester.pump();+ final oldOffset = position.pixels;+ unawaited(+ navigation.currentState!.push<void>(+ MaterialPageRoute(+ builder: (_) => _galleryHost(+ Gallery(+ key: visibleKey,+ asyncLoader: (start, end, {limit, asc}) async =>+ FileLoadResult(files, false),+ tagPrefix: "visible_",+ enableFileGrouping: false,+ showSelectAll: false,+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();++ for (final columns in [6, 3]) {+ await localSettings.setPhotoGridSize(columns);+ Bus.instance.fire(GalleryLayoutChangedEvent());+ await tester.pumpAndSettle();+ expect(visibleKey.currentState!.galleryGroups!.crossAxisCount, columns);+ expect(coveredKey.currentState!.galleryGroups, same(oldGroups));+ expect(position.pixels, oldOffset);+ expect(coveredLoads, 1);+ }++ final addedFile = _justifiedTestFile(1000);+ loadedFiles = [...files, addedFile];+ reloads.add(FilesUpdatedEvent([addedFile]));+ await tester.pump(const Duration(seconds: 2));+ await tester.pumpAndSettle();+ expect(coveredLoads, 2);+ expect(coveredKey.currentState!.galleryGroups, same(oldGroups));+ expect(position.pixels, oldOffset);++ navigation.currentState!.pop();+ await tester.pumpAndSettle();+ final newGroups = coveredKey.currentState!.galleryGroups!;+ expect(newGroups.crossAxisCount, 3);+ expect(newGroups.allFiles.last, same(addedFile));+ final newGeometry = newGroups.getGeometryOfFile(anchor)!;+ expect(+ position.pixels,+ closeTo(+ newGeometry.rowOffset + newGeometry.rowExtent * progress,+ 0.001,+ ),+ );+ expect(coveredLoads, 2);+ await tester.pumpWidget(const SizedBox.shrink());+ await tester.pump(const Duration(milliseconds: 100));+ },+ );++ testWidgets("the layout sheet previews only its own gallery", (tester) async {+ await localSettings.setPhotoGridSize(4);+ await localSettings.setGalleryGroupType(GroupType.day);+ final navigation = GlobalKey<NavigatorState>();+ final coveredKey = GlobalKey<GalleryState>();+ final previewKey = GlobalKey<GalleryState>();+ final files = List<EnteFile>.generate(100, _justifiedTestFile);+ var latestFiles = files;+ final reloads = StreamController<FilesUpdatedEvent>.broadcast();+ addTearDown(reloads.close);+ final loads = [0, 0];+ await tester.pumpWidget(+ MaterialApp(+ navigatorKey: navigation,+ theme: lightThemeData.copyWith(platform: TargetPlatform.iOS),+ localizationsDelegates: StringsLocalizations.localizationsDelegates,+ supportedLocales: StringsLocalizations.supportedLocales,+ home: _galleryHost(+ Gallery(+ key: coveredKey,+ asyncLoader: (start, end, {limit, asc}) async {+ loads[0]++;+ return FileLoadResult(files, false);+ },+ tagPrefix: "behind_preview_",+ enableFileGrouping: false,+ showSelectAll: false,+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ final coveredGroups = coveredKey.currentState!.galleryGroups;+ unawaited(+ navigation.currentState!.push<void>(+ MaterialPageRoute(+ builder: (_) => _galleryHost(+ Gallery(+ key: previewKey,+ asyncLoader: (start, end, {limit, asc}) async {+ loads[1]++;+ return FileLoadResult(latestFiles, false);+ },+ reloadEvent: reloads.stream,+ tagPrefix: "preview_",+ showGallerySettingsCTA: true,+ showSelectAll: false,+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ await tester.tap(find.byIcon(Icons.more_vert_outlined).hitTestable().first);+ await tester.pumpAndSettle();+ expect(find.byType(GalleryLayoutSettings), findsOneWidget);++ final addedFile = _justifiedTestFile(100);+ latestFiles = [...files, addedFile];+ reloads.add(FilesUpdatedEvent([addedFile]));+ await tester.pump(const Duration(seconds: 2));+ await tester.tap(find.byKey(const ValueKey("more-photos-per-row")));+ await tester.pumpAndSettle();+ expect(previewKey.currentState!.galleryGroups!.crossAxisCount, 5);+ expect(previewKey.currentState!.galleryGroups!.allFiles.last, addedFile);+ expect(coveredKey.currentState!.galleryGroups, same(coveredGroups));+ expect(loads, [1, 2]);++ await tester.tap(find.text("Group by"));+ await tester.pumpAndSettle();+ await tester.tap(find.text("Month"));+ await tester.pumpAndSettle();+ expect(find.byType(GalleryLayoutSettings), findsOneWidget);+ expect(previewKey.currentState!.galleryGroups!.groupType, GroupType.month);+ await tester.tap(find.byKey(const ValueKey(GalleryLayoutType.justified)));+ await tester.pumpAndSettle();+ final previewGroups = previewKey.currentState!.galleryGroups!;+ expect(previewGroups.layoutType, GalleryLayoutType.justified);+ expect(coveredKey.currentState!.galleryGroups, same(coveredGroups));+ expect(loads, [1, 2]);++ navigation.currentState!.pop();+ await tester.pumpAndSettle();+ expect(find.byType(GalleryLayoutSettings), findsNothing);+ expect(previewKey.currentState!.galleryGroups!.allFiles.last, addedFile);+ expect(loads, [1, 2]);+ expect(coveredKey.currentState!.galleryGroups, same(coveredGroups));+ await tester.pumpWidget(const SizedBox.shrink());+ await tester.pump(const Duration(milliseconds: 100));+ });++ testWidgets("inactive tabs load files without building their grids", (+ tester,+ ) async {+ await localSettings.setPhotoGridSize(4);+ final visible = ValueNotifier(false);+ addTearDown(visible.dispose);+ final galleryKey = GlobalKey<GalleryState>();+ final files = List<EnteFile>.generate(100, _justifiedTestFile);+ final initialLoad = Completer<FileLoadResult>();+ final loadedLimits = <int?>[];+ await tester.pumpWidget(+ MaterialApp(+ theme: lightThemeData,+ home: ValueListenableBuilder(+ valueListenable: visible,+ builder: (_, isVisible, child) =>+ GalleryVisibilityScope(visible: isVisible, child: child!),+ child: _galleryHost(+ Gallery(+ key: galleryKey,+ asyncLoader: (start, end, {limit, asc}) async {+ loadedLimits.add(limit);+ return loadedLimits.length == 1+ ? initialLoad.future+ : FileLoadResult(files, false);+ },+ tagPrefix: "inactive_tab_",+ enableFileGrouping: false,+ showSelectAll: false,+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(galleryKey.currentState!.galleryGroups, isNull);+ expect(loadedLimits, [GalleryState.kInitialLoadLimit]);+ await localSettings.setPhotoGridSize(6);+ Bus.instance.fire(GalleryLayoutChangedEvent());+ await tester.pumpAndSettle();+ expect(galleryKey.currentState!.galleryGroups, isNull);+ expect(loadedLimits, [GalleryState.kInitialLoadLimit]);++ initialLoad.complete(FileLoadResult(files.take(10).toList(), true));+ await tester.pumpAndSettle();+ expect(galleryKey.currentState!.galleryGroups, isNull);+ expect(loadedLimits, [GalleryState.kInitialLoadLimit, null]);+ await localSettings.setGalleryLayoutType(GalleryLayoutType.justified);+ Bus.instance.fire(GalleryLayoutChangedEvent());+ await tester.pumpAndSettle();+ expect(galleryKey.currentState!.galleryGroups, isNull);++ visible.value = true;+ await tester.pumpAndSettle();+ expect(loadedLimits, [GalleryState.kInitialLoadLimit, null]);+ expect(galleryKey.currentState!.galleryGroups!.allFiles, files);+ expect(+ galleryKey.currentState!.galleryGroups!.layoutType,+ GalleryLayoutType.justified,+ );++ visible.value = false;+ await tester.pump();+ await localSettings.setGalleryLayoutType(GalleryLayoutType.grid);+ Bus.instance.fire(GalleryLayoutChangedEvent());+ await tester.pump();+ visible.value = true;+ await tester.pumpAndSettle();+ expect(galleryKey.currentState!.galleryGroups!.crossAxisCount, 6);+ expect(loadedLimits, [GalleryState.kInitialLoadLimit, null]);+ await tester.pumpWidget(const SizedBox.shrink());+ await tester.pump(const Duration(milliseconds: 100));+ });+testWidgets("a deep layout change preserves partial-row progress", (tester,) async {diff --git a/mobile/apps/photos/test/ui/viewer/gallery/gallery_thumbnail_demand_test.dart b/mobile/apps/photos/test/ui/viewer/gallery/gallery_thumbnail_demand_test.dartnew file mode 100644index 0000000000..60a1e42efc--- /dev/null+++ b/mobile/apps/photos/test/ui/viewer/gallery/gallery_thumbnail_demand_test.dart@@ -0,0 +1,287 @@+import "dart:async";+import "dart:convert";+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_secure_storage/flutter_secure_storage.dart";+import "package:flutter_test/flutter_test.dart";+import "package:package_info_plus/package_info_plus.dart";+import "package:path_provider_platform_interface/path_provider_platform_interface.dart";+import "package:photos/core/cache/thumbnail_in_memory_cache.dart";+import "package:photos/core/configuration.dart";+import "package:photos/core/network/network.dart";+import "package:photos/ente_theme_data.dart";+import "package:photos/models/file/file.dart";+import "package:photos/models/file/file_type.dart";+import "package:photos/models/file_load_result.dart";+import "package:photos/service_locator.dart";+import "package:photos/services/favorites_service.dart";+import "package:photos/settings/local_settings.dart";+import "package:photos/ui/viewer/file/thumbnail_widget.dart";+import "package:photos/ui/viewer/gallery/gallery.dart";+import "package:photos/ui/viewer/gallery/state/gallery_boundaries_provider.dart";+import "package:photos/ui/viewer/gallery/state/gallery_files_inherited_widget.dart";+import "package:shared_preferences/shared_preferences.dart";++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ late Directory directory;+ late PathProviderPlatform previousPathProvider;+ late _HeldThumbnailDownloads downloads;+ late Dio serviceDio;+ const userAgentChannel = MethodChannel("ua_client_hints");++ setUpAll(() async {+ directory = await Directory.systemTemp.createTemp("gallery_thumbnails_");+ previousPathProvider = PathProviderPlatform.instance;+ PathProviderPlatform.instance = _TestPaths(directory.path);+ FlutterSecureStorage.setMockInitialValues({});+ SharedPreferences.setMockInitialValues({+ "remote_flags": '{"disableCFWorker":true}',+ "ls.internal_user_disabled": true,+ });+ final preferences = await SharedPreferences.getInstance();+ final info = PackageInfo(+ appName: "Photos",+ packageName: "photos",+ version: "1.0.0",+ buildNumber: "1",+ );+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(+ userAgentChannel,+ (_) async => <String, String>{"appName": "Photos", "version": "1"},+ );+ serviceDio = Dio()+ ..interceptors.add(+ InterceptorsWrapper(+ onRequest: (options, handler) => handler.resolve(+ Response(+ requestOptions: options,+ data: <String, dynamic>{"disableCFWorker": true},+ ),+ ),+ ),+ );+ ServiceLocator.instance.init(+ preferences,+ serviceDio,+ serviceDio,+ serviceDio,+ info,+ );+ await Configuration.instance.init(preferences);+ await Configuration.instance.setUserID(1);+ await Configuration.instance.setToken("test-token");+ await FavoritesService.instance.initFav();+ await NetworkClient.instance.init(info, preferences);+ downloads = _HeldThumbnailDownloads();+ for (final dio in [+ NetworkClient.instance.enteDio,+ NetworkClient.instance.downloadDio,+ ]) {+ dio.interceptors.clear();+ dio.httpClientAdapter = downloads;+ }+ });++ tearDownAll(() async {+ NetworkClient.instance.enteDio.close(force: true);+ NetworkClient.instance.downloadDio.close(force: true);+ NetworkClient.instance.getDio().close(force: true);+ serviceDio.close(force: true);+ FavoritesService.instance.dispose();+ ThumbnailInMemoryLruCache.clearAll();+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(userAgentChannel, null);+ PathProviderPlatform.instance = previousPathProvider;+ await directory.delete(recursive: true);+ });++ testWidgets("pinching starts no new thumbnails in covered galleries", (+ tester,+ ) async {+ tester.view.physicalSize = const Size(390, 844);+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.reset);+ await localSettings.setGalleryLayoutType(GalleryLayoutType.grid);+ await localSettings.setPhotoGridSize(4);+ ThumbnailInMemoryLruCache.clearAll();+ expect(+ Directory(Configuration.instance.getThumbnailCacheDirectory()).listSync(),+ isEmpty,+ );++ final navigation = GlobalKey<NavigatorState>();+ final keys = List.generate(3, (_) => GlobalKey<GalleryState>());+ final files = List.generate(+ 3,+ (gallery) => List.generate(+ 200,+ (index) => EnteFile()+ ..generatedID = gallery * 1000 + index + 1+ ..uploadedFileID = gallery * 1000 + index + 1+ ..ownerID = 1+ ..collectionID = 1+ ..creationTime = DateTime(2026, 10, 1).microsecondsSinceEpoch+ ..fileType = FileType.image+ ..title = "photo-$gallery-$index.jpg",+ ),+ );+ Widget galleryPage(int index) => GalleryBoundariesProvider(+ child: GalleryFilesState(+ child: Gallery(+ key: keys[index],+ asyncLoader: (start, end, {limit, asc}) async =>+ FileLoadResult(files[index], false),+ tagPrefix: "thumbnails_$index",+ enableFileGrouping: false,+ showSelectAll: false,+ ),+ ),+ );+ await tester.pumpWidget(+ MaterialApp(+ navigatorKey: navigation,+ theme: lightThemeData.copyWith(platform: TargetPlatform.iOS),+ localizationsDelegates: StringsLocalizations.localizationsDelegates,+ supportedLocales: StringsLocalizations.supportedLocales,+ home: galleryPage(0),+ ),+ );+ await _waitForMountedThumbnails(tester, downloads);+ for (var index = 1; index < keys.length; index++) {+ unawaited(+ navigation.currentState!.push<void>(+ MaterialPageRoute(builder: (_) => galleryPage(index)),+ ),+ );+ await _waitForMountedThumbnails(tester, downloads);+ }++ List<int> requestCounts() => List.generate(+ keys.length,+ (gallery) =>+ downloads.requestedIDs.where((id) => id ~/ 1000 == gallery).length,+ );+ final before = requestCounts();+ expect(before, everyElement(greaterThan(0)));+ expect(downloads.pendingIDs.where((id) => id < 2000), isNotEmpty);++ final first = await tester.startGesture(const Offset(115, 400), pointer: 1);+ final second = await tester.startGesture(+ const Offset(275, 400),+ pointer: 2,+ );+ await tester.pump();+ await first.moveTo(const Offset(155, 400));+ await second.moveTo(const Offset(235, 400));+ await tester.pump();+ await first.up();+ await second.up();+ await _waitForMountedThumbnails(tester, downloads);++ expect(keys.last.currentState!.galleryGroups!.crossAxisCount, 6);+ expect(requestCounts().last, greaterThan(before.last));+ expect(requestCounts().take(2), orderedEquals(before.take(2)));+ await tester.pump(const Duration(seconds: 5));+ await _waitForMountedThumbnails(tester, downloads);+ expect(requestCounts().take(2), orderedEquals(before.take(2)));+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox.shrink());+ await tester.pumpAndSettle();+ });+}++Future<void> _waitForMountedThumbnails(+ WidgetTester tester,+ _HeldThumbnailDownloads downloads,+) async {+ await tester.pumpAndSettle();+ final ids = tester+ .widgetList<ThumbnailWidget>(+ find.byType(ThumbnailWidget, skipOffstage: false),+ )+ .map((widget) => widget.file.uploadedFileID!)+ .toSet();+ expect(ids, isNotEmpty);+ final deadline = Stopwatch()..start();+ // Cache checks use real I/O; thumbnail delays use the test clock.+ while (!downloads.startedIDs.containsAll(ids) &&+ deadline.elapsed < const Duration(seconds: 5)) {+ await tester.runAsync(+ () => Future<void>.delayed(const Duration(milliseconds: 10)),+ );+ await tester.pump(const Duration(milliseconds: 16));+ }+ expect(downloads.startedIDs, containsAll(ids));+}++class _HeldThumbnailDownloads implements HttpClientAdapter {+ final requestedIDs = <int>[];+ final startedIDs = <int>{};+ final _pending = <Completer<ResponseBody>, RequestOptions>{};++ Iterable<int> get pendingIDs => _pending.values.map(+ (options) => int.parse(options.uri.pathSegments.last),+ );++ @override+ Future<ResponseBody> fetch(+ RequestOptions options,+ Stream<Uint8List>? requestStream,+ Future<void>? cancelFuture,+ ) async {+ final id = int.parse(options.uri.pathSegments.last);+ if (options.uri.path.startsWith("/files/thumbnail/v3/")) {+ requestedIDs.add(id);+ return ResponseBody.fromString(+ jsonEncode({"url": "https://thumbnail.test/$id"}),+ 200,+ headers: {+ Headers.contentTypeHeader: [Headers.jsonContentType],+ },+ );+ }+ expect(options.uri.host, "thumbnail.test");+ final response = Completer<ResponseBody>();+ _pending[response] = options;+ startedIDs.add(id);+ unawaited(cancelFuture?.then((_) => _cancel(response)));+ return response.future;+ }++ void _cancel(Completer<ResponseBody> response) {+ final options = _pending.remove(response);+ if (options != null) {+ response.completeError(+ DioException(requestOptions: options, type: DioExceptionType.cancel),+ );+ }+ }++ @override+ void close({bool force = false}) {+ for (final response in _pending.keys.toList()) {+ _cancel(response);+ }+ }+}++class _TestPaths extends PathProviderPlatform {+ _TestPaths(this.path);++ final String path;++ @override+ Future<String?> getApplicationDocumentsPath() async => path;++ @override+ Future<String?> getApplicationSupportPath() async => path;++ @override+ Future<String?> getTemporaryPath() async => path;+}diff --git a/mobile/apps/photos/test/ui/viewer/gallery/gallery_viewer_return_test.dart b/mobile/apps/photos/test/ui/viewer/gallery/gallery_viewer_return_test.dartindex 75f48f1560..1c320e6f10 100644--- a/mobile/apps/photos/test/ui/viewer/gallery/gallery_viewer_return_test.dart+++ b/mobile/apps/photos/test/ui/viewer/gallery/gallery_viewer_return_test.dart@@ -1,3 +1,4 @@+import "dart:async";import "dart:convert";import "package:dio/dio.dart";@@ -11,6 +12,7 @@ import "package:photos/core/cache/thumbnail_in_memory_cache.dart";import "package:photos/core/configuration.dart";import "package:photos/core/constants.dart";import "package:photos/ente_theme_data.dart";+import "package:photos/events/files_updated_event.dart";import "package:photos/models/file/file.dart";import "package:photos/models/file/file_type.dart";import "package:photos/models/file_load_result.dart";@@ -52,7 +54,7 @@ void main() {});for (final layout in GalleryLayoutType.values) {- testWidgets("$layout returns to the current photo with a hero flight", (+ testWidgets("$layout returns to the current photo after a hidden refresh", (tester,) async {await localSettings.setGalleryLayoutType(layout);@@ -76,6 +78,10 @@ void main() {ThumbnailInMemoryLruCache.put(file, bytes, thumbnailLargeSize);ThumbnailInMemoryLruCache.put(file, bytes, thumbnailSmallSize);}+ var latestFiles = files;+ var fileLoads = 0;+ final reloads = StreamController<FilesUpdatedEvent>.broadcast();+ addTearDown(reloads.close);addTearDown(ThumbnailInMemoryLruCache.clearAll);final galleryKey = GlobalKey<GalleryState>();final appBar = GalleryAppBarConfig(@@ -101,8 +107,11 @@ void main() {child: Gallery(key: galleryKey,appBar: appBar,- asyncLoader: (start, end, {limit, asc}) async =>- FileLoadResult(files, false),+ asyncLoader: (start, end, {limit, asc}) async {+ fileLoads++;+ return FileLoadResult(latestFiles, false);+ },+ reloadEvent: reloads.stream,tagPrefix: "return_",groupType: GroupType.month,header: const SizedBox(height: 32),@@ -148,6 +157,22 @@ void main() {);expect(targetTile(), findsNothing);+ final oldGroups = gallery.galleryGroups;+ final addedFile = EnteFile()+ ..generatedID = 181+ ..creationTime = DateTime(2026, 10, 15).microsecondsSinceEpoch+ ..fileType = FileType.image+ ..title = "new-photo.jpg"+ ..pubMagicMetadata = PubMagicMetadata(w: 1600, h: 1200);+ ThumbnailInMemoryLruCache.put(addedFile, bytes, thumbnailLargeSize);+ ThumbnailInMemoryLruCache.put(addedFile, bytes, thumbnailSmallSize);+ latestFiles = [addedFile, ...files];+ reloads.add(FilesUpdatedEvent([addedFile]));+ await tester.pumpAndSettle();+ expect(fileLoads, 2);+ expect(gallery.galleryGroups, same(oldGroups));+ expect(scrollChanges, 0);+await tester.binding.handlePopRoute();expect(scrollChanges, 1);await tester.pump();@@ -158,19 +183,25 @@ void main() {isNotNull,);expect(targetTile(), findsOneWidget);- final tileRect = tester.getRect(targetTile());final pinnedHeight =appBar.resolveGeometry(galleryKey.currentContext!).minExtent +gallery.galleryGroups!.groupHeaderExtent;- expect(tileRect.top, greaterThanOrEqualTo(pinnedHeight));- expect(- tileRect.bottom,- lessThanOrEqualTo(scrollPosition.viewportDimension),- );- final returnOffset = scrollPosition.pixels;+ void expectTargetVisible() {+ final tileRect = tester.getRect(targetTile());+ expect(tileRect.top, greaterThanOrEqualTo(pinnedHeight));+ expect(+ tileRect.bottom,+ lessThanOrEqualTo(scrollPosition.viewportDimension),+ );+ }++ expectTargetVisible();await tester.pumpAndSettle();- expect(scrollPosition.pixels, returnOffset);+ expectTargetVisible();+ final returnOffset = scrollPosition.pixels;expect(find.byType(DetailPage), findsNothing);+ expect(gallery.galleryGroups!.allFiles.first, same(addedFile));+ expect(fileLoads, 2);gallery.revealFile(target.copyWith());expect(scrollPosition.pixels, returnOffset);