Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[mob][photos] Add continuous pinch transitions between gallery layouts

ashil-pilot45bb087d26f0
diff --git a/mobile/apps/photos/lib/models/gallery/gallery_grid_zoom_layout.dart b/mobile/apps/photos/lib/models/gallery/gallery_grid_zoom_layout.dart
new file mode 100644
index 0000000000..8d6fb5b0c0
--- /dev/null
+++ b/mobile/apps/photos/lib/models/gallery/gallery_grid_zoom_layout.dart
@@ -0,0 +1,346 @@
+import "dart:math" as math;
+
+import "package:flutter/widgets.dart";
+import "package:photos/models/file/dummy_file.dart";
+import "package:photos/models/file/file.dart";
+import "package:photos/models/gallery/justified_layout.dart";
+import "package:photos/ui/viewer/gallery/component/group/type.dart";
+
+class GalleryGridZoomTile {
+ const GalleryGridZoomTile({
+ required this.file,
+ required this.index,
+ required this.rect,
+ });
+
+ final EnteFile file;
+ final int index;
+ final Rect rect;
+}
+
+class GalleryGridZoomHeader {
+ const GalleryGridZoomHeader({
+ required this.id,
+ required this.firstFile,
+ required this.groupType,
+ required this.rect,
+ });
+
+ final String id;
+ final EnteFile firstFile;
+ final GroupType groupType;
+ final Rect rect;
+
+ String title(BuildContext context) => groupType.getTitle(context, firstFile);
+}
+
+class GalleryGridZoomLayout {
+ GalleryGridZoomLayout({
+ required List<EnteFile> files,
+ required List<int> groupEndIndexes,
+ required this.groupType,
+ required this.width,
+ required this.columns,
+ required this.headerExtent,
+ required this.spacing,
+ List<List<JustifiedRowLayout>>? justifiedRows,
+ }) : _files = files,
+ tileExtent = (width - (columns - 1) * spacing) / columns {
+ var start = 0;
+ var offset = 0.0;
+ void addSection(int end) {
+ final rows = columns == 2 ? justifiedRows![_sections.length] : null;
+ final squareRowCount = (end - start + columns - 1) ~/ columns;
+ final bodyExtent =
+ rows?.last.maxOffset ??
+ squareRowCount * tileExtent + (squareRowCount - 1) * spacing;
+ final bottom = offset + headerExtent + bodyExtent;
+ _sections.add(
+ _GridZoomSection(
+ firstFileIndex: start,
+ endFileIndex: end,
+ top: offset,
+ rows: rows,
+ ),
+ );
+ start = end;
+ offset = bottom;
+ }
+
+ if (groupType.showGroupHeader()) {
+ for (final end in groupEndIndexes) {
+ addSection(end);
+ }
+ } else if (columns == 2) {
+ if (files.isNotEmpty) addSection(files.length);
+ } else {
+ while (start < files.length) {
+ addSection(math.min(start + 10 * columns, files.length));
+ }
+ }
+ totalExtent = offset;
+ }
+
+ final List<EnteFile> _files;
+ final List<_GridZoomSection> _sections = [];
+ final GroupType groupType;
+ final double width;
+ final int columns;
+ final double headerExtent;
+ final double spacing;
+ final double tileExtent;
+ late final double totalExtent;
+
+ double get _stride => tileExtent + spacing;
+
+ GalleryGridZoomTile? tileAt(Offset position) {
+ if (_sections.isEmpty ||
+ !position.dx.isFinite ||
+ !position.dy.isFinite ||
+ position.dx < 0 ||
+ position.dx >= width ||
+ position.dy < 0 ||
+ position.dy >= totalExtent) {
+ return null;
+ }
+ final section = _sections[_sectionIndexAt(position.dy)];
+ final rowOffset = position.dy - section.top - headerExtent;
+ if (rowOffset < 0) return null;
+ final justifiedRows = section.rows;
+ if (justifiedRows != null) {
+ final row = justifiedRows[_rowIndexAt(justifiedRows, rowOffset)];
+ for (
+ var fileIndex = row.firstIndex;
+ fileIndex <= row.lastIndex;
+ fileIndex++
+ ) {
+ final tile = _justifiedTile(section, row, fileIndex);
+ if (tile.rect.contains(position) && tile.file is! DummyFile) {
+ return tile;
+ }
+ }
+ return null;
+ }
+ final row = (rowOffset / _stride).floor();
+ final column = (position.dx / _stride).floor();
+ final fileIndex = section.firstFileIndex + row * columns + column;
+ if (fileIndex >= section.endFileIndex) return null;
+ final tile = _tile(section, fileIndex);
+ return tile.rect.contains(position) && tile.file is! DummyFile
+ ? tile
+ : null;
+ }
+
+ List<GalleryGridZoomTile> tilesInViewport(Rect viewport) {
+ final tiles = <GalleryGridZoomTile>[];
+ if (_sections.isEmpty ||
+ viewport.isEmpty ||
+ !viewport.overlaps(Rect.fromLTWH(0, 0, width, totalExtent))) {
+ return tiles;
+ }
+ final firstColumn = (viewport.left / _stride).floor().clamp(0, columns - 1);
+ final lastColumn = (viewport.right / _stride).floor().clamp(0, columns - 1);
+ for (
+ var index = _sectionIndexAt(viewport.top);
+ index < _sections.length && _sections[index].top < viewport.bottom;
+ index++
+ ) {
+ final section = _sections[index];
+ final bodyTop = section.top + headerExtent;
+ final justifiedRows = section.rows;
+ if (justifiedRows != null) {
+ final firstRow = _rowIndexAt(justifiedRows, viewport.top - bodyTop);
+ final lastRow = _rowIndexAt(justifiedRows, viewport.bottom - bodyTop);
+ for (var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++) {
+ final row = justifiedRows[rowIndex];
+ for (
+ var fileIndex = row.firstIndex;
+ fileIndex <= row.lastIndex;
+ fileIndex++
+ ) {
+ final tile = _justifiedTile(section, row, fileIndex);
+ if (tile.rect.overlaps(viewport) && tile.file is! DummyFile) {
+ tiles.add(tile);
+ }
+ }
+ }
+ continue;
+ }
+ final rowCount =
+ (section.endFileIndex - section.firstFileIndex + columns - 1) ~/
+ columns;
+ final firstRow = ((viewport.top - bodyTop) / _stride).floor().clamp(
+ 0,
+ rowCount - 1,
+ );
+ final lastRow = ((viewport.bottom - bodyTop) / _stride).floor().clamp(
+ 0,
+ rowCount - 1,
+ );
+ for (var row = firstRow; row <= lastRow; row++) {
+ for (var column = firstColumn; column <= lastColumn; column++) {
+ final fileIndex = section.firstFileIndex + row * columns + column;
+ if (fileIndex >= section.endFileIndex) break;
+ if (_files[fileIndex] is DummyFile) continue;
+ final tile = _tile(section, fileIndex);
+ if (tile.rect.overlaps(viewport)) tiles.add(tile);
+ }
+ }
+ }
+ return tiles;
+ }
+
+ List<GalleryGridZoomHeader> headersInViewport(Rect viewport) {
+ final headers = <GalleryGridZoomHeader>[];
+ if (!groupType.showGroupHeader() || _sections.isEmpty || viewport.isEmpty) {
+ return headers;
+ }
+ for (
+ var index = _sectionIndexAt(viewport.top);
+ index < _sections.length && _sections[index].top < viewport.bottom;
+ index++
+ ) {
+ final section = _sections[index];
+ final rect = Rect.fromLTWH(0, section.top, width, headerExtent);
+ if (rect.overlaps(viewport)) {
+ headers.add(_header(section));
+ }
+ }
+ return headers;
+ }
+
+ GalleryGridZoomHeader? headerAtOffset(double offset) {
+ if (!groupType.showGroupHeader() ||
+ _sections.isEmpty ||
+ !offset.isFinite ||
+ offset < 0 ||
+ offset >= totalExtent) {
+ return null;
+ }
+ return _header(_sections[_sectionIndexAt(offset)]);
+ }
+
+ GalleryGridZoomHeader _header(_GridZoomSection section) =>
+ GalleryGridZoomHeader(
+ id: "${groupType.name}:${section.firstFileIndex}",
+ firstFile: _files[section.firstFileIndex],
+ groupType: groupType,
+ rect: Rect.fromLTWH(0, section.top, width, headerExtent),
+ );
+
+ GalleryGridZoomTile? tileForIndex(int fileIndex) {
+ if (fileIndex < 0 ||
+ fileIndex >= _files.length ||
+ _files[fileIndex] is DummyFile) {
+ return null;
+ }
+ var low = 0;
+ var high = _sections.length - 1;
+ while (low < high) {
+ final middle = (low + high) >>> 1;
+ if (fileIndex >= _sections[middle].endFileIndex) {
+ low = middle + 1;
+ } else {
+ high = middle;
+ }
+ }
+ return _tile(_sections[low], fileIndex);
+ }
+
+ GalleryGridZoomTile _tile(_GridZoomSection section, int fileIndex) {
+ final indexInSection = fileIndex - section.firstFileIndex;
+ final justifiedRows = section.rows;
+ if (justifiedRows != null) {
+ var low = 0;
+ var high = justifiedRows.length - 1;
+ while (low < high) {
+ final middle = (low + high) >>> 1;
+ if (indexInSection > justifiedRows[middle].lastIndex) {
+ low = middle + 1;
+ } else {
+ high = middle;
+ }
+ }
+ return _justifiedTile(section, justifiedRows[low], indexInSection);
+ }
+ return GalleryGridZoomTile(
+ file: _files[fileIndex],
+ index: fileIndex,
+ rect: Rect.fromLTWH(
+ (indexInSection % columns) * _stride,
+ section.top + headerExtent + (indexInSection ~/ columns) * _stride,
+ tileExtent,
+ tileExtent,
+ ),
+ );
+ }
+
+ GalleryGridZoomTile _justifiedTile(
+ _GridZoomSection section,
+ JustifiedRowLayout row,
+ int indexInSection,
+ ) {
+ final column = indexInSection - row.firstIndex;
+ var left = 0.0;
+ for (var index = 0; index < column; index++) {
+ left += row.itemWidths[index] + spacing;
+ }
+ final fileIndex = section.firstFileIndex + indexInSection;
+ return GalleryGridZoomTile(
+ file: _files[fileIndex],
+ index: fileIndex,
+ rect: Rect.fromLTWH(
+ left,
+ section.top + headerExtent + row.minOffset,
+ row.itemWidths[column],
+ row.height,
+ ),
+ );
+ }
+
+ int _rowIndexAt(List<JustifiedRowLayout> rows, double offset) {
+ var low = 0;
+ var high = rows.length - 1;
+ var result = 0;
+ while (low <= high) {
+ final middle = (low + high) >>> 1;
+ if (rows[middle].minOffset <= offset) {
+ result = middle;
+ low = middle + 1;
+ } else {
+ high = middle - 1;
+ }
+ }
+ return result;
+ }
+
+ int _sectionIndexAt(double offset) {
+ var low = 0;
+ var high = _sections.length - 1;
+ var result = 0;
+ while (low <= high) {
+ final middle = (low + high) >>> 1;
+ if (_sections[middle].top <= offset) {
+ result = middle;
+ low = middle + 1;
+ } else {
+ high = middle - 1;
+ }
+ }
+ return result;
+ }
+}
+
+class _GridZoomSection {
+ const _GridZoomSection({
+ required this.firstFileIndex,
+ required this.endFileIndex,
+ required this.top,
+ required this.rows,
+ });
+
+ final int firstFileIndex;
+ final int endFileIndex;
+ final double top;
+ final List<JustifiedRowLayout>? rows;
+}
diff --git a/mobile/apps/photos/lib/models/gallery/gallery_groups.dart b/mobile/apps/photos/lib/models/gallery/gallery_groups.dart
index 19423e1792..0036387022 100644
--- a/mobile/apps/photos/lib/models/gallery/gallery_groups.dart
+++ b/mobile/apps/photos/lib/models/gallery/gallery_groups.dart
@@ -1,6 +1,8 @@
import "dart:core";
import "dart:math" as math;
+import "dart:typed_data";
+import "package:flutter/foundation.dart";
import "package:flutter/material.dart";
import "package:logging/logging.dart";
import "package:photos/core/configuration.dart";
@@ -10,6 +12,7 @@ import "package:photos/models/file/file.dart";
import "package:photos/models/gallery/fixed_extent_grid_row.dart";
import "package:photos/models/gallery/fixed_extent_section_layout.dart";
import "package:photos/models/gallery/flex_layout.dart";
+import "package:photos/models/gallery/gallery_grid_zoom_layout.dart";
import "package:photos/models/gallery/justified_grid_row.dart";
import "package:photos/models/gallery/justified_layout.dart";
import "package:photos/models/gallery/section_layout.dart";
@@ -22,6 +25,33 @@ import "package:photos/ui/viewer/gallery/component/group/group_header_widget.dar
import "package:photos/ui/viewer/gallery/component/group/type.dart";
import "package:uuid/uuid.dart";
+typedef _JustifiedZoomRequest = ({
+ Float64List aspectRatios,
+ Uint32List groupEndIndexes,
+ double width,
+ double targetRowHeight,
+ double spacing,
+});
+
+List<List<JustifiedRowLayout>> _computeJustifiedZoomRows(
+ _JustifiedZoomRequest request,
+) {
+ final sections = <List<JustifiedRowLayout>>[];
+ var start = 0;
+ for (final end in request.groupEndIndexes) {
+ sections.add(
+ FlexLayoutCalculator.computeRows(
+ aspectRatios: request.aspectRatios.getRange(start, end),
+ availableWidth: request.width,
+ targetRowHeight: request.targetRowHeight,
+ spacing: request.spacing,
+ ),
+ );
+ start = end;
+ }
+ return sections;
+}
+
class GalleryGroups {
final List<EnteFile> allFiles;
final GroupType groupType;
@@ -51,7 +81,23 @@ class GalleryGroups {
this.showGallerySettingsCTA = false,
this.groupHeaderAction,
this.layoutTypeOverride,
+ GalleryGroups? reuseLayoutFrom,
}) {
+ if (reuseLayoutFrom != null &&
+ identical(allFiles, reuseLayoutFrom.allFiles) &&
+ widthAvailable == reuseLayoutFrom.widthAvailable &&
+ groupType == reuseLayoutFrom.groupType &&
+ sortOrderAsc == reuseLayoutFrom.sortOrderAsc) {
+ _justifiedZoomRows = reuseLayoutFrom._justifiedZoomRows;
+ if (_justifiedZoomRows == null &&
+ reuseLayoutFrom.layoutType == GalleryLayoutType.justified) {
+ _justifiedZoomRows = [
+ for (final section in reuseLayoutFrom._groupLayouts)
+ (section as JustifiedSectionLayout).rows,
+ ];
+ }
+ _justifiedZoomRowsFuture = reuseLayoutFrom._justifiedZoomRowsFuture;
+ }
init();
if (!groupType.showGroupHeader()) {
assert(
@@ -71,6 +117,12 @@ class GalleryGroups {
late final GalleryLayoutType layoutType;
late final List<SectionLayout> _groupLayouts;
final List<EnteFile> _allFilesWithDummies = [];
+ final List<int> _groupEndIndexes = [];
+ final Map<(int, double), GalleryGridZoomLayout> _zoomLayouts = {};
+ final Map<double, Future<GalleryGridZoomLayout>> _justifiedZoomPreparations =
+ {};
+ Future<List<List<JustifiedRowLayout>>>? _justifiedZoomRowsFuture;
+ List<List<JustifiedRowLayout>>? _justifiedZoomRows;
final List<String> _groupIds = [];
final Map<String, List<EnteFile>> _groupIdToFilesMap = {};
@@ -99,6 +151,83 @@ class GalleryGroups {
List<EnteFile> get allFilesWithDummies => _allFilesWithDummies;
+ GalleryGridZoomLayout gridZoomLayout({
+ required int columns,
+ required double headerExtent,
+ }) => _zoomLayouts.putIfAbsent((columns, headerExtent), () {
+ if (columns == 2) {
+ if (layoutType == GalleryLayoutType.justified) {
+ _justifiedZoomRows ??= [
+ for (final section in _groupLayouts)
+ (section as JustifiedSectionLayout).rows,
+ ];
+ }
+ if (_justifiedZoomRows == null) {
+ throw StateError(
+ "Prepare the Justified zoom layout asynchronously first",
+ );
+ }
+ }
+ return GalleryGridZoomLayout(
+ files: allFiles,
+ groupEndIndexes: _groupEndIndexes,
+ groupType: groupType,
+ width: widthAvailable,
+ columns: columns,
+ headerExtent: headerExtent,
+ spacing: spacing,
+ justifiedRows: columns == 2 ? _justifiedZoomRows : null,
+ );
+ });
+
+ GalleryGridZoomLayout? cachedGridZoomLayout({
+ required int columns,
+ required double headerExtent,
+ }) {
+ if (columns == 2 &&
+ (_justifiedZoomRows != null ||
+ layoutType == GalleryLayoutType.justified)) {
+ return gridZoomLayout(columns: columns, headerExtent: headerExtent);
+ }
+ return _zoomLayouts[(columns, headerExtent)];
+ }
+
+ Future<GalleryGridZoomLayout> prepareJustifiedZoomLayout({
+ required double headerExtent,
+ }) => _justifiedZoomPreparations.putIfAbsent(headerExtent, () async {
+ final cached = cachedGridZoomLayout(columns: 2, headerExtent: headerExtent);
+ if (cached != null) return cached;
+ _justifiedZoomRows ??= await (_justifiedZoomRowsFuture ??=
+ _prepareJustifiedZoomRows());
+ return gridZoomLayout(columns: 2, headerExtent: headerExtent);
+ });
+
+ Future<List<List<JustifiedRowLayout>>> _prepareJustifiedZoomRows() async {
+ if (allFiles.isEmpty) return const [];
+ final aspectRatios = Float64List(allFiles.length);
+ const chunkSize = 2048;
+ for (var start = 0; start < allFiles.length; start += chunkSize) {
+ final end = math.min(start + chunkSize, allFiles.length);
+ for (var index = start; index < end; index++) {
+ final file = allFiles[index];
+ aspectRatios[index] = FlexLayoutCalculator.aspectRatioForDimensions(
+ file.width,
+ file.height,
+ );
+ }
+ if (end < allFiles.length) await Future<void>.delayed(Duration.zero);
+ }
+ return compute(_computeJustifiedZoomRows, (
+ aspectRatios: aspectRatios,
+ groupEndIndexes: Uint32List.fromList(
+ groupType.showGroupHeader() ? _groupEndIndexes : [allFiles.length],
+ ),
+ width: widthAvailable,
+ targetRowHeight: _justifiedTargetRowHeight,
+ spacing: spacing,
+ ), debugLabel: "gallery-justified-zoom");
+ }
+
double? getOffsetOfGroupContainingFile(EnteFile file) {
final creationTime = file.creationTime;
if (creationTime == null) {
@@ -443,33 +572,36 @@ class GalleryGroups {
return groupLayouts;
}
- List<SectionLayout> _computeJustifiedGroupLayouts() {
- final stopwatch = Stopwatch()..start();
- final gridTargetRowHeight =
- (widthAvailable - (crossAxisCount - 1) * spacing) / crossAxisCount;
+ double get _justifiedTargetRowHeight {
+ final gridTargetRowHeight = (widthAvailable - spacing) / 2;
final baseTargetRowHeight = gridTargetRowHeight.isFinite
? math.min(gridTargetRowHeight, _maximumJustifiedTargetRowHeight)
: gridTargetRowHeight;
- final targetRowHeight =
- baseTargetRowHeight * _justifiedTargetRowHeightScale;
+ return baseTargetRowHeight * _justifiedTargetRowHeightScale;
+ }
+
+ List<SectionLayout> _computeJustifiedGroupLayouts() {
+ final stopwatch = Stopwatch()..start();
+ final targetRowHeight = _justifiedTargetRowHeight;
final groupLayouts = <SectionLayout>[];
var currentIndex = 0;
var currentOffset = 0.0;
for (final groupID in _groupIdToFilesMap.keys) {
final filesInGroup = _groupIdToFilesMap[groupID]!;
- final aspectRatios = filesInGroup.map(
- (file) => FlexLayoutCalculator.aspectRatioForDimensions(
- file.width,
- file.height,
- ),
- );
- final rows = FlexLayoutCalculator.computeRows(
- aspectRatios: aspectRatios,
- availableWidth: widthAvailable,
- targetRowHeight: targetRowHeight,
- spacing: spacing,
- );
+ final rows =
+ _justifiedZoomRows?[groupLayouts.length] ??
+ FlexLayoutCalculator.computeRows(
+ aspectRatios: filesInGroup.map(
+ (file) => FlexLayoutCalculator.aspectRatioForDimensions(
+ file.width,
+ file.height,
+ ),
+ ),
+ availableWidth: widthAvailable,
+ targetRowHeight: targetRowHeight,
+ spacing: spacing,
+ );
final firstIndex = currentIndex == 0 ? currentIndex : currentIndex + 1;
final lastIndex = firstIndex + rows.length;
final minOffset = currentOffset;
@@ -551,6 +683,7 @@ class GalleryGroups {
if (groupType.showGroupHeader()) {
var start = 0;
for (final end in _timeGroupEndIndexes()) {
+ _groupEndIndexes.add(end);
_createNewGroup(_copyFilesInRange(start, end), yearsInGroups);
start = end;
}
diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/component/gallery_file_widget.dart b/mobile/apps/photos/lib/ui/viewer/gallery/component/gallery_file_widget.dart
index 0cd3a9c549..2a74c2a0c9 100644
--- a/mobile/apps/photos/lib/ui/viewer/gallery/component/gallery_file_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/gallery/component/gallery_file_widget.dart
@@ -24,6 +24,7 @@ import "package:photos/ui/viewer/file/gallery_photo_page_route.dart";
import "package:photos/ui/viewer/file/hero_image.dart";
import "package:photos/ui/viewer/file/thumbnail_widget.dart";
import "package:photos/ui/viewer/gallery/component/swipe_selectable_file_widget.dart";
+import "package:photos/ui/viewer/gallery/gallery_thumbnail_snapshot.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_swipe_helper.dart";
@@ -59,6 +60,27 @@ class _GalleryFileWidgetState extends State<GalleryFileWidget> {
int? _currentPointerId;
bool _isPointerInside = false;
late final StreamSubscription<FileUploadedEvent> _fileUploadedSubscription;
+ GalleryThumbnailSnapshots? _snapshots;
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ final snapshots = GalleryThumbnailSnapshotScope.of(context);
+ if (_snapshots != snapshots) {
+ _snapshots?.unregister(widget.file, context);
+ _snapshots = snapshots;
+ _snapshots?.register(widget.file, context);
+ }
+ }
+
+ @override
+ void didUpdateWidget(GalleryFileWidget oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (!identical(oldWidget.file, widget.file)) {
+ _snapshots?.unregister(oldWidget.file, context);
+ _snapshots?.register(widget.file, context);
+ }
+ }
@override
void initState() {
@@ -79,6 +101,7 @@ class _GalleryFileWidgetState extends State<GalleryFileWidget> {
@override
void dispose() {
+ _snapshots?.unregister(widget.file, context);
_fileUploadedSubscription.cancel();
widget.selectedFiles?.removeListener(_selectedFilesListener);
super.dispose();
diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/gallery.dart b/mobile/apps/photos/lib/ui/viewer/gallery/gallery.dart
index 6f53bf5f12..4f0cb566db 100644
--- a/mobile/apps/photos/lib/ui/viewer/gallery/gallery.dart
+++ b/mobile/apps/photos/lib/ui/viewer/gallery/gallery.dart
@@ -30,6 +30,7 @@ import "package:photos/ui/viewer/gallery/component/sectioned_sliver_list.dart";
import 'package:photos/ui/viewer/gallery/empty_state.dart';
import "package:photos/ui/viewer/gallery/gallery_app_bar_config.dart";
import "package:photos/ui/viewer/gallery/gallery_app_bar_widget.dart";
+import "package:photos/ui/viewer/gallery/gallery_grid_zoom.dart";
import "package:photos/ui/viewer/gallery/scrollbar/custom_scroll_bar.dart";
import "package:photos/ui/viewer/gallery/state/boundary_reporter_mixin.dart";
import "package:photos/ui/viewer/gallery/state/gallery_boundaries_provider.dart";
@@ -164,10 +165,12 @@ class GalleryState extends State<Gallery> {
late String _logTag;
bool _sortOrderAsc = false;
int _layoutChangeGeneration = 0;
+ bool _committingGridZoom = false;
int _activeFileLoads = 0;
List<EnteFile> _allGalleryFiles = [];
final _scrollController = ScrollController();
final _headerKey = GlobalKey();
+ final _footerKey = GlobalKey();
final _headerHeightNotifier = ValueNotifier<double?>(null);
Timer? _headerHeightRetryTimer;
final scrollBarInUseNotifier = ValueNotifier<bool>(false);
@@ -210,7 +213,7 @@ class GalleryState extends State<Gallery> {
_layoutChangeSubscription = Bus.instance
.on<GalleryLayoutChangedEvent>()
.listen((_) async {
- if (!mounted) return;
+ if (!mounted || _committingGridZoom) return;
final generation = ++_layoutChangeGeneration;
final scrollAnchor = _captureLayoutScrollAnchor();
_setGroupType();
@@ -395,6 +398,7 @@ class GalleryState extends State<Gallery> {
showGallerySettingsCTA: widget.showGallerySettingsCTA,
groupHeaderAction: widget.groupHeaderAction,
layoutTypeOverride: widget.layoutTypeOverride,
+ reuseLayoutFrom: _committingGridZoom ? galleryGroups : null,
);
galleryGroups = groups;
@@ -407,6 +411,44 @@ class GalleryState extends State<Gallery> {
}
}
+ Future<void> _commitGridZoom(int columns, double scrollOffset) async {
+ _committingGridZoom = true;
+ final sourceFiles = _allGalleryFiles;
+ final sourceWidth = galleryGroups?.widthAvailable;
+ final fallbackAnchor = _captureLayoutScrollAnchor();
+ try {
+ if (columns == 2) {
+ await localSettings.setGalleryLayoutType(GalleryLayoutType.justified);
+ } else {
+ await localSettings.setPhotoGridSize(columns);
+ await localSettings.setGalleryLayoutType(GalleryLayoutType.grid);
+ }
+ if (!mounted) return;
+ ++_layoutChangeGeneration;
+ groupHeaderExtent = await _measureGroupHeaderExtent();
+ if (!mounted) return;
+ _updateGalleryGroups();
+ await WidgetsBinding.instance.endOfFrame;
+ if (!mounted) return;
+ if (!identical(sourceFiles, _allGalleryFiles) ||
+ sourceWidth != galleryGroups?.widthAvailable) {
+ _restoreLayoutScrollAnchor(fallbackAnchor, _layoutChangeGeneration);
+ } else if (_scrollController.positions.length == 1) {
+ final position = _scrollController.position;
+ _scrollController.jumpTo(
+ scrollOffset.clamp(
+ position.minScrollExtent,
+ position.maxScrollExtent,
+ ),
+ );
+ }
+ Bus.instance.fire(GalleryLayoutChangedEvent());
+ await WidgetsBinding.instance.endOfFrame;
+ } finally {
+ _committingGridZoom = false;
+ }
+ }
+
_LayoutScrollAnchor? _captureLayoutScrollAnchor() {
final groups = galleryGroups;
if (groups == null || _scrollController.positions.length != 1) return null;
@@ -951,137 +993,164 @@ class GalleryState extends State<Gallery> {
});
}
- return SwipeSelectionWrapper(
- isEnabled: shouldEnableSwipeSelection && !widget.disableSelection,
- swipeHelper: _swipeHelper,
- selectedFiles: widget.selectedFiles,
- swipeActiveNotifier: _swipeActiveNotifier,
+ return GalleryGridZoom(
+ groups: groups,
scrollController: _scrollController,
- child: GalleryContextState(
- sortOrderAsc: _sortOrderAsc,
- inSelectionMode: widget.inSelectionMode,
- disableSelection: widget.disableSelection,
- type: _groupType,
- galleryType: widget.galleryType,
- child: _allGalleryFiles.isEmpty
- ? _GalleryAppBarScrollBody(
- appBar: widget.appBar,
- physics: _scrollPhysics,
- child: Column(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- if (widget.addHeaderOrFooterEmptyState)
- widget.header ?? const SizedBox.shrink(),
- Expanded(child: widget.emptyState),
- if (widget.addHeaderOrFooterEmptyState)
- widget.footer ?? const SizedBox.shrink(),
- ],
- ),
- )
- : CustomScrollBar(
- scrollController: _scrollController,
- galleryGroups: groups,
- inUseNotifier: scrollBarInUseNotifier,
- viewportHeight: MediaQuery.sizeOf(context).height,
- topPadding: widget.disableVerticalPaddingForScrollbar
- ? 0.0
- : appBarPinnedHeight + groupHeaderExtent!,
- bottomPadding: widget.disableVerticalPaddingForScrollbar
- ? ValueNotifier(0.0)
- : scrollbarBottomPaddingNotifier,
- child: NotificationListener<SizeChangedLayoutNotification>(
- onNotification: (notification) {
- final renderBox =
- _headerKey.currentContext?.findRenderObject()
- as RenderBox?;
- if (renderBox != null) {
- _headerHeightNotifier.value = renderBox.size.height;
- } else {
- _logger.info(
- "Header render box is null, cannot get height",
- );
- }
-
- return true;
- },
- child: Stack(
- clipBehavior: Clip.none,
+ sectionOrigin: () =>
+ appBarPinnedHeight +
+ appBarCollapseExtent +
+ _headerHeight -
+ _scrollController.offset,
+ trailingExtent: () {
+ final box = _footerKey.currentContext?.findRenderObject();
+ return box is RenderBox && box.hasSize ? box.size.height : 0;
+ },
+ appBarHeight: appBarPinnedHeight,
+ pinHeaders: !widget.disablePinnedGroupHeader,
+ enabled:
+ !widget.disableScroll &&
+ widget.layoutTypeOverride == null &&
+ !widget.limitSelectionToOne &&
+ !widget.inSelectionMode &&
+ !(widget.selectedFiles?.files.isNotEmpty ?? false) &&
+ _allGalleryFiles.isNotEmpty,
+ onCommit: _commitGridZoom,
+ showSelectAll: widget.showSelectAll && !widget.limitSelectionToOne,
+ showGallerySettingsCTA: widget.showGallerySettingsCTA,
+ groupHeaderAction: widget.groupHeaderAction,
+ child: SwipeSelectionWrapper(
+ isEnabled: shouldEnableSwipeSelection && !widget.disableSelection,
+ swipeHelper: _swipeHelper,
+ selectedFiles: widget.selectedFiles,
+ swipeActiveNotifier: _swipeActiveNotifier,
+ scrollController: _scrollController,
+ child: GalleryContextState(
+ sortOrderAsc: _sortOrderAsc,
+ inSelectionMode: widget.inSelectionMode,
+ disableSelection: widget.disableSelection,
+ type: _groupType,
+ galleryType: widget.galleryType,
+ child: _allGalleryFiles.isEmpty
+ ? _GalleryAppBarScrollBody(
+ appBar: widget.appBar,
+ physics: _scrollPhysics,
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
- ValueListenableBuilder<bool>(
- valueListenable: _swipeActiveNotifier,
- builder: (context, isSwipeActive, child) {
- return Semantics(
- identifier: _automationScrollIdentifier,
- container: true,
- child: CustomScrollView(
- physics: widget.disableScroll || isSwipeActive
- ? const NeverScrollableScrollPhysics()
- : const BouncingScrollPhysics(),
- controller: _scrollController,
- slivers: [
- if (widget.appBar != null)
- widget.appBar!.buildSliver(context),
- SliverToBoxAdapter(
- child: SizeChangedLayoutNotifier(
- child: SizedBox(
- key: _headerKey,
- child:
- widget.header ??
- const SizedBox.shrink(),
+ if (widget.addHeaderOrFooterEmptyState)
+ widget.header ?? const SizedBox.shrink(),
+ Expanded(child: widget.emptyState),
+ if (widget.addHeaderOrFooterEmptyState)
+ widget.footer ?? const SizedBox.shrink(),
+ ],
+ ),
+ )
+ : CustomScrollBar(
+ scrollController: _scrollController,
+ galleryGroups: groups,
+ inUseNotifier: scrollBarInUseNotifier,
+ viewportHeight: MediaQuery.sizeOf(context).height,
+ topPadding: widget.disableVerticalPaddingForScrollbar
+ ? 0.0
+ : appBarPinnedHeight + groupHeaderExtent!,
+ bottomPadding: widget.disableVerticalPaddingForScrollbar
+ ? ValueNotifier(0.0)
+ : scrollbarBottomPaddingNotifier,
+ child: NotificationListener<SizeChangedLayoutNotification>(
+ onNotification: (notification) {
+ final renderBox =
+ _headerKey.currentContext?.findRenderObject()
+ as RenderBox?;
+ if (renderBox != null) {
+ _headerHeightNotifier.value = renderBox.size.height;
+ } else {
+ _logger.info(
+ "Header render box is null, cannot get height",
+ );
+ }
+
+ return true;
+ },
+ child: Stack(
+ clipBehavior: Clip.none,
+ children: [
+ ValueListenableBuilder<bool>(
+ valueListenable: _swipeActiveNotifier,
+ builder: (context, isSwipeActive, child) {
+ return Semantics(
+ identifier: _automationScrollIdentifier,
+ container: true,
+ child: CustomScrollView(
+ physics: widget.disableScroll || isSwipeActive
+ ? const NeverScrollableScrollPhysics()
+ : const BouncingScrollPhysics(),
+ controller: _scrollController,
+ slivers: [
+ if (widget.appBar != null)
+ widget.appBar!.buildSliver(context),
+ SliverToBoxAdapter(
+ child: SizeChangedLayoutNotifier(
+ child: SizedBox(
+ key: _headerKey,
+ child:
+ widget.header ??
+ const SizedBox.shrink(),
+ ),
),
),
- ),
- SectionedListSliver(
- sectionLayouts: groups.groupLayouts,
- ),
- SliverToBoxAdapter(
- child: ValueListenableBuilder<double>(
- valueListenable:
- scrollbarBottomPaddingNotifier,
- builder: (context, height, child) =>
- ConstrainedBox(
- constraints: BoxConstraints(
- minHeight:
- (widget
- .selectedFiles
- ?.files
- .isNotEmpty ??
- false)
- ? height
- : 0,
+ SectionedListSliver(
+ sectionLayouts: groups.groupLayouts,
+ ),
+ SliverToBoxAdapter(
+ child: ValueListenableBuilder<double>(
+ key: _footerKey,
+ valueListenable:
+ scrollbarBottomPaddingNotifier,
+ builder: (context, height, child) =>
+ ConstrainedBox(
+ constraints: BoxConstraints(
+ minHeight:
+ (widget
+ .selectedFiles
+ ?.files
+ .isNotEmpty ??
+ false)
+ ? height
+ : 0,
+ ),
+ child: child,
),
- child: child,
- ),
- child: widget.footer,
+ child: widget.footer,
+ ),
),
- ),
- ],
- ),
- );
- },
- ),
- groups.groupType.showGroupHeader() &&
- !widget.disablePinnedGroupHeader
- ? PinnedGroupHeader(
- scrollController: _scrollController,
- galleryGroups: groups,
- headerHeightNotifier: _headerHeightNotifier,
- scrollOffsetBase: appBarCollapseExtent,
- topOffset: appBarPinnedHeight,
- selectedFiles: widget.selectedFiles,
- showSelectAll:
- widget.showSelectAll &&
- !widget.limitSelectionToOne,
- scrollbarInUseNotifier: scrollBarInUseNotifier,
- showGallerySettingsCTA:
- widget.showGallerySettingsCTA,
- groupHeaderAction: widget.groupHeaderAction,
- )
- : const SizedBox.shrink(),
- ],
+ ],
+ ),
+ );
+ },
+ ),
+ groups.groupType.showGroupHeader() &&
+ !widget.disablePinnedGroupHeader
+ ? PinnedGroupHeader(
+ scrollController: _scrollController,
+ galleryGroups: groups,
+ headerHeightNotifier: _headerHeightNotifier,
+ scrollOffsetBase: appBarCollapseExtent,
+ topOffset: appBarPinnedHeight,
+ selectedFiles: widget.selectedFiles,
+ showSelectAll:
+ widget.showSelectAll &&
+ !widget.limitSelectionToOne,
+ scrollbarInUseNotifier: scrollBarInUseNotifier,
+ showGallerySettingsCTA:
+ widget.showGallerySettingsCTA,
+ groupHeaderAction: widget.groupHeaderAction,
+ )
+ : const SizedBox.shrink(),
+ ],
+ ),
),
),
- ),
+ ),
),
);
}
diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/gallery_grid_zoom.dart b/mobile/apps/photos/lib/ui/viewer/gallery/gallery_grid_zoom.dart
new file mode 100644
index 0000000000..460881cff4
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/viewer/gallery/gallery_grid_zoom.dart
@@ -0,0 +1,692 @@
+import "dart:async";
+import "dart:math" as math;
+import "dart:ui" as ui;
+
+import "package:flutter/material.dart";
+import "package:flutter/scheduler.dart";
+import "package:logging/logging.dart";
+import "package:photos/core/constants.dart";
+import "package:photos/models/file/file.dart";
+import "package:photos/models/gallery/gallery_grid_zoom_layout.dart";
+import "package:photos/models/gallery/gallery_groups.dart";
+import "package:photos/ui/viewer/file/thumbnail_widget.dart";
+import "package:photos/ui/viewer/gallery/component/group/group_header_widget.dart";
+import "package:photos/ui/viewer/gallery/component/group/type.dart";
+import "package:photos/ui/viewer/gallery/gallery_app_bar_widget.dart";
+import "package:photos/ui/viewer/gallery/gallery_pinch_detector.dart";
+import "package:photos/ui/viewer/gallery/gallery_thumbnail_snapshot.dart";
+import "package:photos/ui/viewer/gallery/gallery_zoom_image.dart";
+
+class GalleryGridZoom extends StatefulWidget {
+ const GalleryGridZoom({
+ required this.groups,
+ required this.scrollController,
+ required this.sectionOrigin,
+ required this.appBarHeight,
+ this.trailingExtent,
+ required this.pinHeaders,
+ required this.enabled,
+ required this.onCommit,
+ required this.child,
+ this.showSelectAll = false,
+ this.showGallerySettingsCTA = false,
+ this.groupHeaderAction,
+ this.thumbnailBuilder,
+ super.key,
+ });
+
+ final GalleryGroups groups;
+ final ScrollController scrollController;
+ final double Function() sectionOrigin;
+ final double appBarHeight;
+ final double Function()? trailingExtent;
+ final bool pinHeaders;
+ final bool enabled;
+ final Future<void> Function(int columns, double scrollOffset) onCommit;
+ final bool showSelectAll;
+ final bool showGallerySettingsCTA;
+ final Widget? groupHeaderAction;
+ final Widget Function(EnteFile)? thumbnailBuilder;
+ final Widget child;
+
+ @override
+ State<GalleryGridZoom> createState() => _GalleryGridZoomState();
+}
+
+class _GalleryGridZoomState extends State<GalleryGridZoom>
+ with TickerProviderStateMixin {
+ static final _logger = Logger("GalleryGridZoom");
+ final _snapshots = GalleryThumbnailSnapshots();
+ late final _density = AnimationController.unbounded(vsync: this);
+ late final _opacity = AnimationController(vsync: this, value: 1);
+ late final _justifiedCatchup = AnimationController(
+ vsync: this,
+ duration: const Duration(milliseconds: 90),
+ );
+ _ZoomSession? _session;
+ ScrollHoldController? _hold;
+ List<_ZoomItem> _items = [];
+ int _lower = 0;
+ int _upper = 0;
+ bool _settling = false;
+ bool _committing = false;
+ double _requestedDensity = 3;
+ double _catchupGap = 0;
+ Timer? _warmupTimer;
+
+ @override
+ void initState() {
+ super.initState();
+ _density.addListener(_updateSegment);
+ _justifiedCatchup.addListener(_applyRequestedDensity);
+ }
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ _warmLayouts();
+ }
+
+ void _warmLayouts() {
+ final groups = widget.groups;
+ _warmupTimer?.cancel();
+ _warmupTimer = Timer(const Duration(milliseconds: 350), () {
+ if (!mounted ||
+ widget.groups != groups ||
+ !widget.enabled ||
+ _session != null) {
+ return;
+ }
+ if (SchedulerBinding.instance.transientCallbackCount > 0) {
+ _warmLayouts();
+ return;
+ }
+ unawaited(
+ groups
+ .prepareJustifiedZoomLayout(headerExtent: _headerExtent(groups, 2))
+ .then<void>((_) {})
+ .catchError((Object error, StackTrace stack) {
+ _logger.warning("Could not prepare zoom layout", error, stack);
+ }),
+ );
+ for (
+ var columns = photoGridSizeMin;
+ columns <= photoGridSizeMax;
+ columns++
+ ) {
+ groups.gridZoomLayout(
+ columns: columns,
+ headerExtent: _headerExtent(groups, columns),
+ );
+ }
+ });
+ }
+
+ double _headerExtent(GalleryGroups groups, int columns) =>
+ groups.groupType.showGroupHeader()
+ ? groups.groupHeaderExtent +
+ (columns == photoGridSizeMax ? 4 : 0) -
+ (groups.crossAxisCount == photoGridSizeMax ? 4 : 0)
+ : GalleryGroups.spacing;
+
+ @override
+ void didUpdateWidget(GalleryGridZoom oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (oldWidget.groups != widget.groups) _warmLayouts();
+ if (!widget.enabled ||
+ !identical(oldWidget.groups.allFiles, widget.groups.allFiles) ||
+ oldWidget.groups.widthAvailable != widget.groups.widthAvailable ||
+ (!_committing && oldWidget.groups != widget.groups)) {
+ _clear();
+ }
+ }
+
+ void _start(Offset focalPoint) {
+ if (_session != null ||
+ !widget.enabled ||
+ widget.scrollController.positions.length != 1) {
+ return;
+ }
+ final box = context.findRenderObject() as RenderBox;
+ final position = widget.scrollController.position;
+ if (position.outOfRange) return;
+ final groups = widget.groups;
+ final origin = widget.sectionOrigin();
+ final sourceScrollOffset = position.pixels;
+ final trailingExtent = widget.trailingExtent?.call() ?? 0;
+ final source = groups.gridZoomLayout(
+ columns: groups.crossAxisCount,
+ headerExtent: groups.groupHeaderExtent,
+ );
+ final point = focalPoint - Offset(0, origin);
+ final anchor =
+ source.tileAt(point) ??
+ source
+ .tilesInViewport(
+ Rect.fromLTWH(
+ 0,
+ point.dy,
+ source.width,
+ source.headerExtent + source.tileExtent * 2,
+ ),
+ )
+ .firstOrNull;
+ if (anchor == null || focalPoint.dy < widget.appBarHeight) return;
+ _hold = position.hold(() {});
+ final fraction = ((point.dy - anchor.rect.top) / anchor.rect.height).clamp(
+ 0.0,
+ 1.0,
+ );
+ final layouts = <int, GalleryGridZoomLayout>{};
+ final offsets = <int, double>{};
+ final origins = <int, double>{};
+ void addLayout(GalleryGridZoomLayout layout) {
+ final columns = layout.columns;
+ final target = layout.tileForIndex(anchor.index)!;
+ final delta =
+ target.rect.top -
+ anchor.rect.top +
+ fraction * (target.rect.height - anchor.rect.height);
+ final maxScroll = math.max(
+ 0.0,
+ origin +
+ sourceScrollOffset +
+ layout.totalExtent +
+ trailingExtent -
+ position.viewportDimension,
+ );
+ final scroll =
+ (sourceScrollOffset + (origin > widget.appBarHeight ? 0 : delta))
+ .clamp(0.0, maxScroll);
+ layouts[columns] = layout;
+ offsets[columns] = scroll;
+ origins[columns] = origin - (scroll - sourceScrollOffset);
+ }
+
+ for (var columns = 2; columns <= photoGridSizeMax; columns++) {
+ final headerExtent = _headerExtent(groups, columns);
+ final layout = columns == source.columns
+ ? source
+ : columns == 2
+ ? groups.cachedGridZoomLayout(
+ columns: columns,
+ headerExtent: headerExtent,
+ )
+ : groups.gridZoomLayout(columns: columns, headerExtent: headerExtent);
+ if (layout != null) addLayout(layout);
+ }
+ _requestedDensity = source.columns.toDouble();
+ _density.value = source.columns.toDouble();
+ _opacity.value = 1;
+ final session = _session = _ZoomSession(
+ initialColumns: source.columns,
+ layouts: layouts,
+ scrollOffsets: offsets,
+ origins: origins,
+ size: box.size,
+ clipTop: math.max(widget.appBarHeight, origin),
+ images: _snapshots.capture(),
+ );
+ _lower = -1;
+ _updateSegment();
+ if (!layouts.containsKey(2)) {
+ session.justifiedReady = groups
+ .prepareJustifiedZoomLayout(headerExtent: _headerExtent(groups, 2))
+ .then((layout) {
+ if (!mounted || _session != session) return;
+ addLayout(layout);
+ if (_settling) return;
+ if (_density.value == photoGridSizeMin &&
+ _requestedDensity < photoGridSizeMin &&
+ !MediaQuery.disableAnimationsOf(context)) {
+ _catchupGap = photoGridSizeMin - _requestedDensity;
+ _justifiedCatchup.value = 1;
+ unawaited(
+ _justifiedCatchup.animateBack(0, curve: Curves.easeOutCubic),
+ );
+ } else {
+ _applyRequestedDensity();
+ }
+ })
+ .catchError((Object error, StackTrace stack) {
+ _logger.warning("Could not prepare zoom layout", error, stack);
+ });
+ }
+ }
+
+ void _update(double scale, Offset focalPoint) {
+ final session = _session;
+ if (session == null || _settling || !scale.isFinite || scale <= 0) return;
+ final densityDelta =
+ session.initialColumns / scale - session.initialColumns;
+ _requestedDensity = (session.initialColumns + densityDelta * 0.5).clamp(
+ 2.0,
+ photoGridSizeMax.toDouble(),
+ );
+ if (_requestedDensity >= photoGridSizeMin) {
+ _justifiedCatchup.stop();
+ _catchupGap = 0;
+ }
+ _applyRequestedDensity();
+ }
+
+ void _applyRequestedDensity() {
+ final session = _session;
+ if (session == null || _settling) return;
+ final remainingGap = math.min(
+ _catchupGap * _justifiedCatchup.value,
+ math.max(0.0, photoGridSizeMin - _requestedDensity),
+ );
+ _density.value = math.max(
+ session.layouts.containsKey(2) ? 2.0 : photoGridSizeMin.toDouble(),
+ _requestedDensity + remainingGap,
+ );
+ }
+
+ void _updateSegment() {
+ final session = _session;
+ if (session == null) return;
+ final lower = _density.value.floor().clamp(2, photoGridSizeMax);
+ final upper = math.min(lower + 1, photoGridSizeMax);
+ if (_lower == lower && _upper == upper) return;
+ _lower = lower;
+ _upper = upper;
+ final start = session.layouts[lower]!;
+ final end = session.layouts[upper]!;
+ final startOrigin = session.origins[lower]!;
+ final endOrigin = session.origins[upper]!;
+ final viewport = Rect.fromLTRB(
+ 0,
+ session.clipTop,
+ session.size.width,
+ session.size.height,
+ );
+ final startViewport = viewport.shift(Offset(0, -startOrigin));
+ final endViewport = viewport.shift(Offset(0, -endOrigin));
+ final indices = <int>{
+ for (final tile in start.tilesInViewport(startViewport)) tile.index,
+ for (final tile in end.tilesInViewport(endViewport)) tile.index,
+ }.toList()..sort();
+ final items = <_ZoomItem>[];
+ for (final index in indices) {
+ final first = start.tileForIndex(index)!;
+ final last = end.tileForIndex(index)!;
+ final from = first.rect.shift(Offset(0, startOrigin));
+ final to = last.rect.shift(Offset(0, endOrigin));
+ items.add(
+ _ZoomItem(
+ key: ValueKey(("gallery-grid-zoom-tile", index)),
+ from: from,
+ to: to,
+ fromOpacity: from.overlaps(viewport) ? 1 : 0,
+ toOpacity: to.overlaps(viewport) ? 1 : 0,
+ fadeDuringReflow:
+ from.overlaps(viewport) &&
+ to.overlaps(viewport) &&
+ (from.left - to.left).abs() > (from.width + to.width) / 2,
+ file: first.file,
+ ),
+ );
+ }
+ Map<String, ({GalleryGridZoomHeader header, Rect rect})> headers(
+ GalleryGridZoomLayout layout,
+ Rect visible,
+ double origin,
+ ) {
+ final list = layout.headersInViewport(visible).toList();
+ final pinned = widget.pinHeaders
+ ? layout.headerAtOffset(visible.top)
+ : null;
+ if (pinned != null && !list.any((header) => header.id == pinned.id)) {
+ list.insert(0, pinned);
+ }
+ return {
+ for (final header in list)
+ header.id: (
+ header: header,
+ rect: header.rect.shift(
+ Offset(
+ 0,
+ header.id == pinned?.id
+ ? math.max(origin, session.clipTop - header.rect.top)
+ : origin,
+ ),
+ ),
+ ),
+ };
+ }
+
+ final startHeaders = headers(start, startViewport, startOrigin);
+ final endHeaders = headers(end, endViewport, endOrigin);
+ final pinnedFrom = widget.pinHeaders
+ ? start.headerAtOffset(startViewport.top)?.id
+ : null;
+ final pinnedTo = widget.pinHeaders
+ ? end.headerAtOffset(endViewport.top)?.id
+ : null;
+ for (final id in {...startHeaders.keys, ...endHeaders.keys}) {
+ final first = startHeaders[id];
+ final last = endHeaders[id];
+ items.add(
+ _ZoomItem(
+ key: ValueKey(("gallery-grid-zoom-header", id)),
+ from: first?.rect ?? last!.rect,
+ to: last?.rect ?? first!.rect,
+ fromOpacity: first == null ? 0 : 1,
+ toOpacity: last == null ? 0 : 1,
+ header: (first ?? last)!.header,
+ pinnedFrom: id == pinnedFrom,
+ pinnedTo: id == pinnedTo,
+ headerActions:
+ id == pinnedFrom ||
+ id == pinnedTo ||
+ identical(
+ (first ?? last)!.header.firstFile,
+ widget.groups.allFiles.first,
+ ),
+ ),
+ );
+ }
+ setState(() => _items = items);
+ }
+
+ Future<void> _end(bool cancelled) async {
+ final session = _session;
+ if (session == null || _settling) return;
+ _settling = true;
+ _justifiedCatchup.stop();
+ _catchupGap = 0;
+ var target = cancelled ? session.initialColumns : _requestedDensity.round();
+ try {
+ if (target == 2 && !session.layouts.containsKey(2)) {
+ await session.justifiedReady;
+ if (!mounted || _session != session) return;
+ if (!session.layouts.containsKey(2)) target = photoGridSizeMin;
+ }
+ await _density
+ .animateTo(
+ target.toDouble(),
+ duration: MediaQuery.disableAnimationsOf(context)
+ ? Duration.zero
+ : const Duration(milliseconds: 180),
+ curve: Curves.easeOutCubic,
+ )
+ .orCancel;
+ if (!mounted || _session != session) return;
+ if (target != session.initialColumns) {
+ _committing = true;
+ await widget.onCommit(target, session.scrollOffsets[target]!);
+ if (!mounted || _session != session) return;
+ }
+ await WidgetsBinding.instance.endOfFrame;
+ if (!mounted || _session != session) return;
+ await _opacity
+ .animateTo(
+ 0,
+ duration: MediaQuery.disableAnimationsOf(context)
+ ? Duration.zero
+ : const Duration(milliseconds: 90),
+ )
+ .orCancel;
+ } on TickerCanceled {
+ return;
+ } finally {
+ if (mounted && _session == session) setState(_clear);
+ }
+ }
+
+ void _clear() {
+ final images = _session?.images.values.toList() ?? <ui.Image>[];
+ _session = null;
+ _catchupGap = 0;
+ _justifiedCatchup.value = 0;
+ _items = [];
+ _settling = false;
+ _committing = false;
+ _density.stop();
+ _opacity.stop();
+ _hold?.cancel();
+ _hold = null;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ for (final image in images) {
+ image.dispose();
+ }
+ });
+ }
+
+ @override
+ void dispose() {
+ _warmupTimer?.cancel();
+ _clear();
+ _density.dispose();
+ _opacity.dispose();
+ _justifiedCatchup.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final session = _session;
+ final background = GalleryAppBarWidget.backgroundColor(context);
+ return GalleryThumbnailSnapshotScope(
+ snapshots: _snapshots,
+ child: GalleryPinchDetector(
+ enabled: widget.enabled && !_settling,
+ onStart: _start,
+ onUpdate: _update,
+ onEnd: (cancelled) => unawaited(_end(cancelled)),
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ AbsorbPointer(absorbing: session != null, child: widget.child),
+ if (session != null)
+ Positioned.fill(
+ top: session.clipTop,
+ child: IgnorePointer(
+ child: ExcludeSemantics(
+ child: FadeTransition(
+ opacity: _opacity,
+ child: ColoredBox(
+ color: background,
+ child: Flow(
+ key: const ValueKey("gallery-grid-zoom-overlay"),
+ delegate: _ZoomFlowDelegate(
+ density: _density,
+ lower: _lower,
+ items: _items,
+ clipTop: session.clipTop,
+ tileExtent:
+ session.layouts[photoGridSizeMin]!.tileExtent,
+ headerExtent: widget.groups.groupHeaderExtent,
+ ),
+ children: [
+ for (final item in _items)
+ if (item.file case final file?)
+ RepaintBoundary(
+ key: item.key,
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(1),
+ child: GalleryZoomImage(
+ animation: _density,
+ lower: _lower,
+ from: item.from,
+ to: item.to,
+ image: session.images[file],
+ child: session.images[file] != null
+ ? const SizedBox.expand()
+ : widget.thumbnailBuilder?.call(
+ file,
+ ) ??
+ ThumbnailWidget(
+ file,
+ rawThumbnail: true,
+ thumbnailSize:
+ session.initialColumns <=
+ 3
+ ? thumbnailLargeSize
+ : thumbnailSmallSize,
+ useCachedThumbnailAsPlaceholder:
+ true,
+ ),
+ ),
+ ),
+ )
+ else
+ RepaintBoundary(
+ key: item.key,
+ child: ColoredBox(
+ color: background,
+ child: GroupHeaderWidget(
+ title: item.header!.title(context),
+ gridSize: session.initialColumns,
+ filesInGroup: const [],
+ selectedFiles: null,
+ showSelectAll: widget.showSelectAll,
+ showGalleryLayoutSettingCTA:
+ item.headerActions &&
+ widget.showGallerySettingsCTA,
+ action: item.headerActions
+ ? widget.groupHeaderAction
+ : null,
+ height: widget.groups.groupHeaderExtent,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+class _ZoomSession {
+ _ZoomSession({
+ required this.initialColumns,
+ required this.layouts,
+ required this.scrollOffsets,
+ required this.origins,
+ required this.size,
+ required this.clipTop,
+ required this.images,
+ });
+ final int initialColumns;
+ final Map<int, GalleryGridZoomLayout> layouts;
+ final Map<int, double> scrollOffsets;
+ final Map<int, double> origins;
+ final Size size;
+ final double clipTop;
+ final Map<EnteFile, ui.Image> images;
+ Future<void>? justifiedReady;
+}
+
+class _ZoomItem {
+ const _ZoomItem({
+ required this.key,
+ required this.from,
+ required this.to,
+ required this.fromOpacity,
+ required this.toOpacity,
+ this.file,
+ this.header,
+ this.pinnedFrom = false,
+ this.pinnedTo = false,
+ this.headerActions = false,
+ this.fadeDuringReflow = false,
+ });
+ final Key key;
+ final Rect from;
+ final Rect to;
+ final double fromOpacity;
+ final double toOpacity;
+ final EnteFile? file;
+ final GalleryGridZoomHeader? header;
+ final bool pinnedFrom;
+ final bool pinnedTo;
+ final bool headerActions;
+ final bool fadeDuringReflow;
+}
+
+class _ZoomFlowDelegate extends FlowDelegate {
+ _ZoomFlowDelegate({
+ required this.density,
+ required this.lower,
+ required this.items,
+ required this.clipTop,
+ required this.tileExtent,
+ required this.headerExtent,
+ }) : super(repaint: density);
+ final Animation<double> density;
+ final int lower;
+ final List<_ZoomItem> items;
+ final double clipTop;
+ final double tileExtent;
+ final double headerExtent;
+
+ @override
+ BoxConstraints getConstraintsForChild(int i, BoxConstraints constraints) =>
+ BoxConstraints.tight(
+ Size(
+ items[i].file != null ? tileExtent : constraints.maxWidth,
+ items[i].file != null ? tileExtent : headerExtent,
+ ),
+ );
+
+ @override
+ void paintChildren(FlowPaintingContext context) {
+ final progress = (density.value - lower).clamp(0.0, 1.0);
+ int? pinnedIndex;
+ void paint(int index) {
+ final item = items[index];
+ final rect = Rect.lerp(item.from, item.to, progress)!;
+ final size = context.getChildSize(index)!;
+ var opacity = ui.lerpDouble(item.fromOpacity, item.toOpacity, progress)!;
+ if (item.fadeDuringReflow) {
+ opacity *= 1 - 0.35 * 4 * progress * (1 - progress);
+ }
+ if (opacity == 0 ||
+ rect.bottom < clipTop ||
+ rect.top > context.size.height + clipTop) {
+ return;
+ }
+ context.paintChild(
+ index,
+ transform: Matrix4.identity()
+ ..translateByDouble(rect.left, rect.top - clipTop, 0, 1)
+ ..scaleByDouble(
+ rect.width / size.width,
+ rect.height / size.height,
+ 1,
+ 1,
+ ),
+ opacity: opacity,
+ );
+ }
+
+ for (var index = 0; index < items.length; index++) {
+ final item = items[index];
+ if (progress < 0.5 ? item.pinnedFrom : item.pinnedTo) {
+ pinnedIndex = index;
+ } else {
+ paint(index);
+ }
+ }
+ if (pinnedIndex != null) paint(pinnedIndex);
+ }
+
+ @override
+ bool shouldRepaint(_ZoomFlowDelegate oldDelegate) =>
+ oldDelegate.items != items || oldDelegate.lower != lower;
+
+ @override
+ bool shouldRelayout(_ZoomFlowDelegate oldDelegate) =>
+ oldDelegate.items != items ||
+ oldDelegate.tileExtent != tileExtent ||
+ oldDelegate.headerExtent != headerExtent;
+}
diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/gallery_pinch_detector.dart b/mobile/apps/photos/lib/ui/viewer/gallery/gallery_pinch_detector.dart
new file mode 100644
index 0000000000..563d948811
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/viewer/gallery/gallery_pinch_detector.dart
@@ -0,0 +1,179 @@
+import "package:flutter/gestures.dart";
+import "package:flutter/widgets.dart";
+
+class GalleryPinchDetector extends StatefulWidget {
+ final Widget child;
+ final bool enabled;
+ final ValueChanged<Offset> onStart;
+ final void Function(double scale, Offset localFocalPoint) onUpdate;
+ final ValueChanged<bool> onEnd;
+
+ const GalleryPinchDetector({
+ required this.child,
+ required this.enabled,
+ required this.onStart,
+ required this.onUpdate,
+ required this.onEnd,
+ super.key,
+ });
+
+ @override
+ State<GalleryPinchDetector> createState() => _GalleryPinchDetectorState();
+}
+
+class _GalleryPinchDetectorState extends State<GalleryPinchDetector> {
+ _GalleryPinchGestureRecognizer? _recognizer;
+
+ @override
+ void didUpdateWidget(covariant GalleryPinchDetector oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (oldWidget.enabled && !widget.enabled) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && !widget.enabled) _recognizer?.cancel();
+ });
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return RawGestureDetector(
+ behavior: HitTestBehavior.translucent,
+ gestures: {
+ _GalleryPinchGestureRecognizer:
+ GestureRecognizerFactoryWithHandlers<
+ _GalleryPinchGestureRecognizer
+ >(
+ () => _recognizer = _GalleryPinchGestureRecognizer(
+ debugOwner: this,
+ ),
+ (recognizer) => recognizer
+ ..enabled = widget.enabled
+ ..onStart = widget.onStart
+ ..onUpdate = widget.onUpdate
+ ..onEnd = widget.onEnd,
+ ),
+ },
+ child: widget.child,
+ );
+ }
+}
+
+class _GalleryPinchGestureRecognizer extends OneSequenceGestureRecognizer {
+ bool enabled = true;
+ ValueChanged<Offset>? onStart;
+ void Function(double scale, Offset localFocalPoint)? onUpdate;
+ ValueChanged<bool>? onEnd;
+
+ final _positions = <int, Offset>{};
+ final _accepted = <int>{};
+ (int, int)? _pair;
+ double _initialSpan = 0;
+ bool _active = false;
+ bool _blocked = false;
+ bool _finished = false;
+
+ _GalleryPinchGestureRecognizer({super.debugOwner})
+ : super(supportedDevices: {PointerDeviceKind.touch});
+
+ @override
+ bool isPointerAllowed(PointerDownEvent event) =>
+ enabled && super.isPointerAllowed(event);
+
+ @override
+ void addAllowedPointer(PointerDownEvent event) {
+ super.addAllowedPointer(event);
+ _positions[event.pointer] = event.localPosition;
+ if (_blocked) {
+ resolvePointer(event.pointer, GestureDisposition.rejected);
+ } else if (_finished || _active) {
+ resolvePointer(event.pointer, GestureDisposition.accepted);
+ } else if (_positions.length == 2) {
+ _pair = (_positions.keys.first, _positions.keys.last);
+ resolve(GestureDisposition.accepted);
+ }
+ }
+
+ @override
+ void acceptGesture(int pointer) {
+ _accepted.add(pointer);
+ final pair = _pair;
+ if (!_active &&
+ !_blocked &&
+ !_finished &&
+ pair != null &&
+ _accepted.contains(pair.$1) &&
+ _accepted.contains(pair.$2)) {
+ final first = _positions[pair.$1]!;
+ final second = _positions[pair.$2]!;
+ _initialSpan = (first - second).distance;
+ _active = true;
+ invokeCallback("onStart", () => onStart?.call((first + second) / 2));
+ }
+ }
+
+ @override
+ void rejectGesture(int pointer) {
+ _blocked = true;
+ _end(cancelled: true);
+ resolve(GestureDisposition.rejected);
+ }
+
+ @override
+ void handleEvent(PointerEvent event) {
+ if (!enabled) cancel();
+ if (event is PointerMoveEvent) {
+ _positions[event.pointer] = event.localPosition;
+ final pair = _pair;
+ if (_active &&
+ pair != null &&
+ (event.pointer == pair.$1 || event.pointer == pair.$2)) {
+ final first = _positions[pair.$1]!;
+ final second = _positions[pair.$2]!;
+ final span = (first - second).distance;
+ if (_initialSpan == 0) _initialSpan = span;
+ final scale = _initialSpan == 0 ? 1.0 : span / _initialSpan;
+ invokeCallback(
+ "onUpdate",
+ () => onUpdate?.call(scale, (first + second) / 2),
+ );
+ }
+ } else if (event is PointerUpEvent || event is PointerCancelEvent) {
+ final pair = _pair;
+ if (event is PointerCancelEvent ||
+ event.pointer == pair?.$1 ||
+ event.pointer == pair?.$2) {
+ _end(cancelled: event is PointerCancelEvent);
+ }
+ _positions.remove(event.pointer);
+ _accepted.remove(event.pointer);
+ resolvePointer(event.pointer, GestureDisposition.rejected);
+ stopTrackingPointer(event.pointer);
+ }
+ }
+
+ void cancel() {
+ _blocked = _positions.isNotEmpty;
+ _end(cancelled: true);
+ resolve(GestureDisposition.rejected);
+ }
+
+ void _end({required bool cancelled}) {
+ if (!_active) return;
+ _active = false;
+ _finished = true;
+ invokeCallback("onEnd", () => onEnd?.call(cancelled));
+ }
+
+ @override
+ void didStopTrackingLastPointer(int pointer) {
+ _positions.clear();
+ _accepted.clear();
+ _pair = null;
+ _active = false;
+ _blocked = false;
+ _finished = false;
+ }
+
+ @override
+ String get debugDescription => "gallery pinch";
+}
diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/gallery_thumbnail_snapshot.dart b/mobile/apps/photos/lib/ui/viewer/gallery/gallery_thumbnail_snapshot.dart
new file mode 100644
index 0000000000..d6f7cd1884
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/viewer/gallery/gallery_thumbnail_snapshot.dart
@@ -0,0 +1,44 @@
+import "dart:ui" as ui;
+
+import "package:flutter/widgets.dart";
+import "package:photos/models/file/file.dart";
+import "package:photos/ui/viewer/file/hero_image.dart";
+
+class GalleryThumbnailSnapshots {
+ final _tiles = Map<EnteFile, BuildContext>.identity();
+
+ void register(EnteFile file, BuildContext context) => _tiles[file] = context;
+
+ void unregister(EnteFile file, BuildContext context) {
+ if (_tiles[file] == context) _tiles.remove(file);
+ }
+
+ Map<EnteFile, ui.Image> capture() {
+ final images = Map<EnteFile, ui.Image>.identity();
+ for (final entry in _tiles.entries) {
+ if (entry.value.mounted) {
+ final image = imageFromHero(entry.value);
+ if (image != null) images[entry.key] = image.clone();
+ }
+ }
+ return images;
+ }
+}
+
+class GalleryThumbnailSnapshotScope extends InheritedWidget {
+ const GalleryThumbnailSnapshotScope({
+ required this.snapshots,
+ required super.child,
+ super.key,
+ });
+
+ final GalleryThumbnailSnapshots snapshots;
+
+ static GalleryThumbnailSnapshots? of(BuildContext context) => context
+ .dependOnInheritedWidgetOfExactType<GalleryThumbnailSnapshotScope>()
+ ?.snapshots;
+
+ @override
+ bool updateShouldNotify(GalleryThumbnailSnapshotScope oldWidget) =>
+ snapshots != oldWidget.snapshots;
+}
diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/gallery_zoom_image.dart b/mobile/apps/photos/lib/ui/viewer/gallery/gallery_zoom_image.dart
new file mode 100644
index 0000000000..1de1496613
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/viewer/gallery/gallery_zoom_image.dart
@@ -0,0 +1,116 @@
+import "dart:ui" as ui;
+
+import "package:flutter/foundation.dart";
+import "package:flutter/rendering.dart";
+import "package:flutter/widgets.dart";
+
+class GalleryZoomImage extends SingleChildRenderObjectWidget {
+ const GalleryZoomImage({
+ required this.animation,
+ required this.lower,
+ required this.from,
+ required this.to,
+ required this.image,
+ required super.child,
+ super.key,
+ });
+
+ final Animation<double> animation;
+ final int lower;
+ final Rect from;
+ final Rect to;
+ final ui.Image? image;
+
+ @override
+ RenderObject createRenderObject(BuildContext context) =>
+ RenderGalleryZoomImage(animation, lower, from, to, image);
+
+ @override
+ void updateRenderObject(
+ BuildContext context,
+ RenderGalleryZoomImage renderObject,
+ ) {
+ renderObject
+ ..lower = lower
+ ..from = from
+ ..to = to
+ ..image = image
+ ..markNeedsPaint();
+ }
+}
+
+class RenderGalleryZoomImage extends RenderProxyBox {
+ RenderGalleryZoomImage(
+ this.animation,
+ this.lower,
+ this.from,
+ this.to,
+ this.image,
+ );
+
+ final Animation<double> animation;
+ int lower;
+ Rect from;
+ Rect to;
+ ui.Image? image;
+
+ @override
+ void attach(PipelineOwner owner) {
+ super.attach(owner);
+ animation.addListener(_onProgress);
+ }
+
+ @override
+ void detach() {
+ animation.removeListener(_onProgress);
+ super.detach();
+ }
+
+ void _onProgress() {
+ if ((from.width / from.height - to.width / to.height).abs() >
+ precisionErrorTolerance) {
+ markNeedsPaint();
+ }
+ }
+
+ @override
+ void paint(PaintingContext context, Offset offset) {
+ var thumbnail = image;
+ if (thumbnail == null) {
+ void visit(RenderObject object) {
+ if (object is RenderImage && object.image != null) {
+ thumbnail ??= object.image;
+ } else if (thumbnail == null) {
+ object.visitChildren(visit);
+ }
+ }
+
+ child?.visitChildren(visit);
+ if (child is RenderImage) visit(child!);
+ }
+ if (thumbnail == null) {
+ super.paint(context, offset);
+ return;
+ }
+ final rect = Rect.lerp(
+ from,
+ to,
+ (animation.value - lower).clamp(0.0, 1.0),
+ )!;
+ final imageSize = Size(
+ thumbnail!.width.toDouble(),
+ thumbnail!.height.toDouble(),
+ );
+ final fit = applyBoxFit(BoxFit.cover, imageSize, rect.size);
+ final source = Alignment.center.inscribe(
+ fit.source,
+ Offset.zero & imageSize,
+ );
+ context.canvas.drawImageRect(
+ thumbnail!,
+ source,
+ offset & size,
+ Paint()..filterQuality = FilterQuality.low,
+ );
+ }
+}
diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/swipe_selection_wrapper.dart b/mobile/apps/photos/lib/ui/viewer/gallery/swipe_selection_wrapper.dart
index ad0851e168..a89bb99fa4 100644
--- a/mobile/apps/photos/lib/ui/viewer/gallery/swipe_selection_wrapper.dart
+++ b/mobile/apps/photos/lib/ui/viewer/gallery/swipe_selection_wrapper.dart
@@ -41,6 +41,8 @@ class _SwipeSelectionWrapperState extends State<SwipeSelectionWrapper>
double _currentPointerY = 0;
double _currentPointerX = 0;
int? _activePointer;
+ final _pointers = <int>{};
+ bool _multiplePointers = false;
double? _cachedScreenHeight;
double _accumulatedScrollDelta = 0;
@@ -89,6 +91,12 @@ class _SwipeSelectionWrapperState extends State<SwipeSelectionWrapper>
swipeActiveNotifier: widget.swipeActiveNotifier,
child: Listener(
onPointerDown: (event) {
+ _pointers.add(event.pointer);
+ if (_pointers.length > 1) {
+ _multiplePointers = true;
+ _endPointerSelection();
+ }
+ if (_multiplePointers) return;
_currentPointerX = event.position.dx;
_currentPointerY = event.position.dy;
_activePointer = event.pointer;
@@ -97,6 +105,7 @@ class _SwipeSelectionWrapperState extends State<SwipeSelectionWrapper>
widget.selectedFiles?.files.isEmpty ?? false;
},
onPointerMove: (event) {
+ if (_multiplePointers) return;
_currentPointerX = event.position.dx;
_currentPointerY = event.position.dy;
_activePointer = event.pointer;
@@ -132,25 +141,27 @@ class _SwipeSelectionWrapperState extends State<SwipeSelectionWrapper>
_checkAndHandleAutoScroll(boundariesProvider);
}
},
- onPointerUp: (_) {
- _stopAutoScroll();
- widget.swipeHelper?.endSelection();
- widget.swipeActiveNotifier.value = false;
- _initialMovementWasHorizontal = null;
- _activePointer = null;
- },
- onPointerCancel: (_) {
- _stopAutoScroll();
- widget.swipeHelper?.endSelection();
- widget.swipeActiveNotifier.value = false;
- _initialMovementWasHorizontal = null;
- _activePointer = null;
- },
+ onPointerUp: (event) => _pointerEnded(event.pointer),
+ onPointerCancel: (event) => _pointerEnded(event.pointer),
child: widget.child,
),
);
}
+ void _pointerEnded(int pointer) {
+ _pointers.remove(pointer);
+ if (_pointers.isEmpty) _multiplePointers = false;
+ _endPointerSelection();
+ }
+
+ void _endPointerSelection() {
+ _stopAutoScroll();
+ widget.swipeHelper?.endSelection();
+ widget.swipeActiveNotifier.value = false;
+ _initialMovementWasHorizontal = null;
+ _activePointer = null;
+ }
+
double _calculateScrollSpeed(
double distanceFromBoundary,
double boundaryPosition,
diff --git a/mobile/apps/photos/test/models/gallery/gallery_grid_zoom_layout_test.dart b/mobile/apps/photos/test/models/gallery/gallery_grid_zoom_layout_test.dart
new file mode 100644
index 0000000000..3ddf9cb349
--- /dev/null
+++ b/mobile/apps/photos/test/models/gallery/gallery_grid_zoom_layout_test.dart
@@ -0,0 +1,436 @@
+import "dart:collection";
+
+import "package:dio/dio.dart";
+import "package:flutter/widgets.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:package_info_plus/package_info_plus.dart";
+import "package:photos/core/configuration.dart";
+import "package:photos/models/file/dummy_file.dart";
+import "package:photos/models/file/file.dart";
+import "package:photos/models/file/file_type.dart";
+import "package:photos/models/gallery/fixed_extent_section_layout.dart";
+import "package:photos/models/gallery/gallery_grid_zoom_layout.dart";
+import "package:photos/models/gallery/gallery_groups.dart";
+import "package:photos/models/gallery/justified_layout.dart";
+import "package:photos/models/metadata/file_magic.dart";
+import "package:photos/service_locator.dart";
+import "package:photos/settings/local_settings.dart";
+import "package:photos/ui/viewer/gallery/component/group/type.dart";
+import "package:shared_preferences/shared_preferences.dart";
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ setUpAll(() async {
+ SharedPreferences.setMockInitialValues({});
+ final preferences = await SharedPreferences.getInstance();
+ ServiceLocator.instance.init(
+ preferences,
+ Dio(),
+ Dio(),
+ Dio(),
+ PackageInfo(
+ appName: "Photos",
+ packageName: "photos",
+ version: "1.0.0",
+ buildNumber: "1",
+ ),
+ );
+ try {
+ await Configuration.instance.init(preferences);
+ } catch (_) {}
+ await localSettings.setGalleryLayoutType(GalleryLayoutType.grid);
+ });
+
+ test(
+ "previews match settled rows, padding and headers at both densities",
+ () async {
+ final files = <EnteFile>[];
+ for (final (day, count) in [(14, 5), (13, 61), (12, 2), (11, 7)]) {
+ for (var index = 0; index < count; index++) {
+ files.add(_file(files.length, day: day));
+ }
+ }
+ final source = _groups(files, GroupType.day, 48);
+ final headerIDs = <List<String>>[];
+ for (final columns in [3, 6]) {
+ final headerExtent = columns == 6 ? 52.0 : 48.0;
+ final preview = source.gridZoomLayout(
+ columns: columns,
+ headerExtent: headerExtent,
+ );
+ await localSettings.setPhotoGridSize(columns);
+ final settled = _groups(files, GroupType.day, headerExtent);
+ _expectMatchesSettled(preview, settled);
+ final headers = preview.headersInViewport(
+ Rect.fromLTWH(0, 0, preview.width, preview.totalExtent),
+ );
+ headerIDs.add(headers.map((header) => header.id).toList());
+ expect(headers.map((header) => header.firstFile), [
+ files[0],
+ files[5],
+ files[66],
+ files[68],
+ ]);
+ for (final header in headers) {
+ expect(preview.headerAtOffset(header.rect.top)!.id, header.id);
+ expect(preview.tileAt(header.rect.center), isNull);
+ }
+ expect(
+ preview.tilesInViewport(
+ Rect.fromLTWH(0, 0, preview.width, preview.totalExtent),
+ ),
+ hasLength(files.length),
+ );
+ }
+ expect(headerIDs.first, headerIDs.last);
+ },
+ );
+
+ test("ungrouped previews match density-dependent chunk boundaries", () async {
+ final files = List.generate(127, _file);
+ final source = _groups(files, GroupType.none, GalleryGroups.spacing);
+ for (final columns in [3, 6]) {
+ final preview = source.gridZoomLayout(
+ columns: columns,
+ headerExtent: GalleryGroups.spacing,
+ );
+ await localSettings.setPhotoGridSize(columns);
+ final settled = _groups(files, GroupType.none, GalleryGroups.spacing);
+ _expectMatchesSettled(preview, settled);
+ expect(preview.headerAtOffset(preview.totalExtent / 2), isNull);
+ expect(
+ preview.headersInViewport(
+ Rect.fromLTWH(0, 0, preview.width, preview.totalExtent),
+ ),
+ isEmpty,
+ );
+ }
+ });
+
+ test("focal lookups reject gaps and dummies and preserve file identity", () {
+ final files = List.generate(5, _file);
+ final groups = _groups(files, GroupType.day, 48);
+ for (final columns in [3, 6]) {
+ final layout = groups.gridZoomLayout(columns: columns, headerExtent: 48);
+ for (var index = 0; index < files.length; index++) {
+ final tile = layout.tileForIndex(index)!;
+ final focalPoint =
+ tile.rect.topLeft +
+ Offset(tile.rect.width * 0.27, tile.rect.height * 0.73);
+ expect(layout.tileAt(focalPoint)!.index, index);
+ expect(layout.tileAt(focalPoint)!.file, same(files[index]));
+ }
+ final firstTile = layout.tileForIndex(0)!;
+ expect(
+ layout.tileAt(
+ Offset(firstTile.rect.right + 0.5, firstTile.rect.center.dy),
+ ),
+ isNull,
+ );
+ final lastTile = layout.tileForIndex(files.length - 1)!;
+ expect(
+ layout.tileAt(
+ Offset(layout.width - layout.tileExtent / 2, lastTile.rect.center.dy),
+ ),
+ isNull,
+ );
+ expect(layout.tileAt(Offset(-1, firstTile.rect.center.dy)), isNull);
+ expect(layout.tileAt(Offset(1, layout.totalExtent)), isNull);
+ expect(layout.tileForIndex(files.length), isNull);
+ }
+ final empty = _groups(
+ [],
+ GroupType.none,
+ GalleryGroups.spacing,
+ ).gridZoomLayout(columns: 3, headerExtent: GalleryGroups.spacing);
+ expect(empty.totalExtent, 0);
+ expect(empty.tileAt(Offset.zero), isNull);
+ expect(empty.tilesInViewport(const Rect.fromLTWH(0, 0, 390, 800)), isEmpty);
+ });
+
+ test(
+ "Justified endpoints reuse production rows and retain header identity",
+ () async {
+ final files = _CountingFiles(
+ List.generate(79, (index) {
+ final (width, height) = switch (index % 3) {
+ 0 => (400, 100),
+ 1 => (100, 400),
+ _ => (200, 200),
+ };
+ return _file(index, day: 14 - index ~/ 27)
+ ..pubMagicMetadata = PubMagicMetadata(w: width, h: height);
+ }),
+ );
+ for (final grouping in [GroupType.day, GroupType.none]) {
+ final headerExtent = grouping == GroupType.none
+ ? GalleryGroups.spacing
+ : 48.0;
+ final square = _groups(files, grouping, headerExtent);
+ final justified = _groups(
+ files,
+ grouping,
+ headerExtent,
+ layoutType: GalleryLayoutType.justified,
+ );
+ expect(
+ square.cachedGridZoomLayout(columns: 2, headerExtent: headerExtent),
+ isNull,
+ );
+ final preparation = square.prepareJustifiedZoomLayout(
+ headerExtent: headerExtent,
+ );
+ expect(
+ square.prepareJustifiedZoomLayout(headerExtent: headerExtent),
+ same(preparation),
+ );
+ final fromSquare = await preparation;
+ _expectMatchesJustified(fromSquare, justified);
+ for (final file in files.cast<_DimensionCountingFile>()) {
+ file.dimensionReads = 0;
+ }
+ final committed = _groups(
+ files,
+ grouping,
+ headerExtent,
+ layoutType: GalleryLayoutType.justified,
+ reuseLayoutFrom: square,
+ );
+ expect(
+ files.cast<_DimensionCountingFile>().every(
+ (file) => file.dimensionReads == 0,
+ ),
+ isTrue,
+ );
+ _expectMatchesJustified(fromSquare, committed);
+ final nextSquare = _groups(
+ files,
+ grouping,
+ headerExtent,
+ reuseLayoutFrom: committed,
+ );
+ expect(
+ nextSquare.cachedGridZoomLayout(
+ columns: 2,
+ headerExtent: headerExtent,
+ ),
+ isNotNull,
+ );
+ final nextJustified = _groups(
+ files,
+ grouping,
+ headerExtent,
+ layoutType: GalleryLayoutType.justified,
+ reuseLayoutFrom: nextSquare,
+ );
+ for (var index = 0; index < committed.groupLayouts.length; index++) {
+ expect(
+ (nextJustified.groupLayouts[index] as JustifiedSectionLayout).rows,
+ same(
+ (committed.groupLayouts[index] as JustifiedSectionLayout).rows,
+ ),
+ );
+ }
+ files.readCount = 0;
+ expect(
+ square.cachedGridZoomLayout(columns: 2, headerExtent: headerExtent),
+ same(fromSquare),
+ );
+ expect(files.readCount, 0);
+ final fromJustified = justified.cachedGridZoomLayout(
+ columns: 2,
+ headerExtent: headerExtent,
+ )!;
+ expect(files.readCount, 0);
+ _expectMatchesJustified(fromJustified, justified);
+ final squareEndpoint = justified.gridZoomLayout(
+ columns: 3,
+ headerExtent: headerExtent,
+ );
+ final allHeaders = Rect.fromLTWH(
+ 0,
+ 0,
+ 390,
+ fromJustified.totalExtent + squareEndpoint.totalExtent,
+ );
+ expect(
+ fromJustified
+ .headersInViewport(allHeaders)
+ .map((header) => header.id),
+ squareEndpoint
+ .headersInViewport(allHeaders)
+ .map((header) => header.id),
+ );
+ }
+ },
+ );
+
+ test("deep viewport enumeration reads only intersecting tiles", () async {
+ final files = _CountingFiles(List.generate(60000, _file));
+ final groups = _groups(files, GroupType.none, GalleryGroups.spacing);
+ for (final columns in [2, 6]) {
+ final layout = columns == 2
+ ? await groups.prepareJustifiedZoomLayout(
+ headerExtent: GalleryGroups.spacing,
+ )
+ : groups.gridZoomLayout(
+ columns: columns,
+ headerExtent: GalleryGroups.spacing,
+ );
+ final viewport = Rect.fromLTWH(0, layout.totalExtent * 0.8, 390, 800);
+ files.readCount = 0;
+ final tiles = layout.tilesInViewport(viewport);
+ expect(tiles, isNotEmpty);
+ expect(tiles.first.index, greaterThan(45000));
+ expect(tiles, hasLength(lessThan(100)));
+ expect(tiles.every((tile) => tile.rect.overlaps(viewport)), isTrue);
+ expect(files.readCount, lessThan(200));
+ files.readCount = 0;
+ expect(layout.tileForIndex(tiles.first.index)!.rect, tiles.first.rect);
+ expect(files.readCount, lessThan(4));
+ }
+ });
+}
+
+void _expectMatchesJustified(
+ GalleryGridZoomLayout preview,
+ GalleryGroups settled,
+) {
+ expect(
+ preview.totalExtent,
+ closeTo(settled.groupLayouts.last.maxOffset, 1e-8),
+ );
+ var rawIndex = 0;
+ for (
+ var groupIndex = 0;
+ groupIndex < settled.groupLayouts.length;
+ groupIndex++
+ ) {
+ final section = settled.groupLayouts[groupIndex] as JustifiedSectionLayout;
+ final files = settled.groupIDToFilesMap[settled.groupIDs[groupIndex]]!;
+ for (final row in section.rows) {
+ var left = 0.0;
+ for (var column = 0; column < row.itemWidths.length; column++) {
+ final tile = preview.tileForIndex(rawIndex++)!;
+ expect(tile.file, same(files[row.firstIndex + column]));
+ expect(tile.rect.left, closeTo(left, 1e-8));
+ expect(
+ tile.rect.top,
+ closeTo(section.bodyMinOffset + row.minOffset, 1e-8),
+ );
+ expect(tile.rect.width, closeTo(row.itemWidths[column], 1e-8));
+ expect(tile.rect.height, closeTo(row.height, 1e-8));
+ expect(preview.tileAt(tile.rect.center)!.index, tile.index);
+ left += row.itemWidths[column] + GalleryGroups.spacing;
+ }
+ }
+ }
+ expect(
+ preview
+ .tilesInViewport(Rect.fromLTWH(0, 0, 390, preview.totalExtent))
+ .map((tile) => tile.index),
+ orderedEquals(List.generate(rawIndex, (index) => index)),
+ );
+}
+
+void _expectMatchesSettled(
+ GalleryGridZoomLayout preview,
+ GalleryGroups settled,
+) {
+ expect(
+ preview.totalExtent,
+ closeTo(settled.groupLayouts.last.maxOffset, 1e-8),
+ );
+ var rawIndex = 0;
+ for (
+ var groupIndex = 0;
+ groupIndex < settled.groupLayouts.length;
+ groupIndex++
+ ) {
+ final section =
+ settled.groupLayouts[groupIndex] as FixedExtentSectionLayout;
+ final files = settled.groupIDToFilesMap[settled.groupIDs[groupIndex]]!;
+ for (var fileIndex = 0; fileIndex < files.length; fileIndex++) {
+ if (files[fileIndex] is DummyFile) continue;
+ final tile = preview.tileForIndex(rawIndex++)!;
+ expect(tile.file, same(files[fileIndex]));
+ expect(
+ tile.rect.left,
+ closeTo((fileIndex % preview.columns) * section.mainAxisStride, 1e-8),
+ );
+ expect(
+ tile.rect.top,
+ closeTo(
+ section.bodyMinOffset +
+ (fileIndex ~/ preview.columns) * section.mainAxisStride,
+ 1e-8,
+ ),
+ );
+ expect(tile.rect.width, closeTo(section.tileHeight, 1e-8));
+ expect(tile.rect.height, closeTo(section.tileHeight, 1e-8));
+ }
+ }
+}
+
+GalleryGroups _groups(
+ List<EnteFile> files,
+ GroupType groupType,
+ double headerExtent, {
+ GalleryLayoutType layoutType = GalleryLayoutType.grid,
+ GalleryGroups? reuseLayoutFrom,
+}) => GalleryGroups(
+ allFiles: files,
+ groupType: groupType,
+ sortOrderAsc: false,
+ widthAvailable: 390,
+ selectedFiles: null,
+ tagPrefix: "zoom_test_",
+ groupHeaderExtent: headerExtent,
+ showSelectAll: false,
+ layoutTypeOverride: layoutType,
+ reuseLayoutFrom: reuseLayoutFrom,
+);
+
+EnteFile _file(int index, {int day = 14}) => _DimensionCountingFile()
+ ..generatedID = index + 1
+ ..creationTime = DateTime(2026, 10, day).microsecondsSinceEpoch
+ ..fileType = FileType.image;
+
+class _DimensionCountingFile extends EnteFile {
+ var dimensionReads = 0;
+
+ @override
+ int get width {
+ dimensionReads++;
+ return super.width;
+ }
+
+ @override
+ int get height {
+ dimensionReads++;
+ return super.height;
+ }
+}
+
+class _CountingFiles extends ListBase<EnteFile> {
+ _CountingFiles(this.files);
+
+ final List<EnteFile> files;
+ var readCount = 0;
+
+ @override
+ int get length => files.length;
+
+ @override
+ set length(int value) => files.length = value;
+
+ @override
+ EnteFile operator [](int index) {
+ readCount++;
+ return files[index];
+ }
+
+ @override
+ void operator []=(int index, EnteFile file) => files[index] = file;
+}
diff --git a/mobile/apps/photos/test/ui/viewer/gallery/gallery_grid_zoom_test.dart b/mobile/apps/photos/test/ui/viewer/gallery/gallery_grid_zoom_test.dart
new file mode 100644
index 0000000000..60fa19a732
--- /dev/null
+++ b/mobile/apps/photos/test/ui/viewer/gallery/gallery_grid_zoom_test.dart
@@ -0,0 +1,584 @@
+import "dart:async";
+
+import "package:dio/dio.dart";
+import "package:ente_strings/ente_strings.dart";
+import "package:flutter/material.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:package_info_plus/package_info_plus.dart";
+import "package:photos/core/configuration.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/gallery/gallery_groups.dart";
+import "package:photos/models/metadata/file_magic.dart";
+import "package:photos/service_locator.dart";
+import "package:photos/settings/local_settings.dart";
+import "package:photos/ui/viewer/gallery/component/group/type.dart";
+import "package:photos/ui/viewer/gallery/gallery_grid_zoom.dart";
+import "package:shared_preferences/shared_preferences.dart";
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ setUpAll(() async {
+ SharedPreferences.setMockInitialValues({});
+ final preferences = await SharedPreferences.getInstance();
+ ServiceLocator.instance.init(
+ preferences,
+ Dio(),
+ Dio(),
+ Dio(),
+ PackageInfo(
+ appName: "Photos",
+ packageName: "photos",
+ version: "1.0.0",
+ buildNumber: "1",
+ ),
+ );
+ try {
+ await Configuration.instance.init(preferences);
+ } catch (_) {}
+ });
+
+ setUp(() async {
+ await localSettings.setGalleryLayoutType(GalleryLayoutType.grid);
+ await localSettings.setPhotoGridSize(4);
+ });
+
+ testWidgets(
+ "morphs during a pinch and commits the deep focal anchor only on release",
+ (tester) async {
+ final fixture = _ZoomFixture();
+ addTearDown(fixture.controller.dispose);
+ await fixture.mount(tester);
+ const anchorIndex = 806;
+ const fraction = 0.3;
+ const focalY = 300.0;
+ final source = fixture.groups.gridZoomLayout(
+ columns: 4,
+ headerExtent: GalleryGroups.spacing,
+ );
+ final sourceTile = source.tileForIndex(anchorIndex)!;
+ final scrollOffset =
+ _ZoomFixture.contentTop +
+ sourceTile.rect.top +
+ sourceTile.rect.height * fraction -
+ focalY;
+ fixture.controller.jumpTo(scrollOffset);
+ await tester.pump();
+ final focalX = sourceTile.rect.center.dx;
+ final first = await tester.startGesture(
+ Offset(focalX - 80, focalY),
+ pointer: 1,
+ );
+ final second = await tester.startGesture(
+ Offset(focalX + 80, focalY),
+ pointer: 2,
+ );
+ await tester.pump();
+ expect(_overlay, findsOneWidget);
+ final tileFinder = find.byKey(
+ const ValueKey(("gallery-grid-zoom-tile", anchorIndex)),
+ );
+ final startRect = tester.getRect(tileFinder);
+ expect(startRect.width, closeTo(source.tileExtent, 0.001));
+ expect(
+ startRect.top + startRect.height * fraction,
+ closeTo(focalY, 0.001),
+ );
+
+ await first.moveTo(Offset(focalX - 64, focalY));
+ await second.moveTo(Offset(focalX + 64, focalY));
+ await tester.pump();
+ final intermediate = tester.getRect(tileFinder);
+ final target = fixture.groups.gridZoomLayout(
+ columns: 5,
+ headerExtent: GalleryGroups.spacing,
+ );
+ expect(
+ intermediate.width,
+ closeTo((startRect.width + target.tileExtent) / 2, 0.001),
+ );
+ expect(
+ intermediate.top + intermediate.height * fraction,
+ closeTo(focalY, 0.001),
+ );
+ expect(fixture.commits, isEmpty);
+ expect(fixture.controller.offset, scrollOffset);
+
+ await first.moveTo(Offset(focalX - 50, focalY));
+ await second.moveTo(Offset(focalX + 50, focalY));
+ await tester.pump();
+ expect(fixture.commits, isEmpty);
+ await first.up();
+ await second.up();
+ await tester.pumpAndSettle();
+ final targetTile = target.tileForIndex(anchorIndex)!;
+ final targetOffset =
+ _ZoomFixture.contentTop +
+ targetTile.rect.top +
+ targetTile.rect.height * fraction -
+ focalY;
+ expect(fixture.commits, hasLength(1));
+ expect(fixture.commits.single.$1, 5);
+ expect(fixture.commits.single.$2, closeTo(targetOffset, 0.001));
+ expect(fixture.controller.offset, closeTo(targetOffset, 0.001));
+ expect(fixture.groups.crossAxisCount, 5);
+ expect(_overlay, findsNothing);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pump();
+ },
+ );
+
+ testWidgets("a cancelled morph restores the gallery without committing", (
+ tester,
+ ) async {
+ final fixture = _ZoomFixture();
+ addTearDown(fixture.controller.dispose);
+ await fixture.mount(tester);
+ fixture.controller.jumpTo(700);
+ await tester.pump();
+ final first = await tester.startGesture(const Offset(170, 280), pointer: 1);
+ final second = await tester.startGesture(
+ const Offset(330, 280),
+ pointer: 2,
+ );
+ await first.moveTo(const Offset(195, 280));
+ await second.moveTo(const Offset(305, 280));
+ await tester.pump();
+ expect(_overlay, findsOneWidget);
+ await first.cancel();
+ await second.up();
+ await tester.pumpAndSettle();
+ expect(_overlay, findsNothing);
+ expect(fixture.commits, isEmpty);
+ expect(fixture.controller.offset, 700);
+ expect(fixture.groups.crossAxisCount, 4);
+
+ await tester.drag(
+ find.byKey(const ValueKey("gallery-scroll")),
+ const Offset(0, -100),
+ );
+ await tester.pumpAndSettle();
+ expect(fixture.controller.offset, greaterThan(700));
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pump();
+ });
+
+ testWidgets("morphs into the justified layout and back to three columns", (
+ tester,
+ ) async {
+ await localSettings.setPhotoGridSize(3);
+ final fixture = _ZoomFixture();
+ addTearDown(fixture.controller.dispose);
+ await fixture.mount(tester);
+ const anchorIndex = 31;
+ const fraction = 0.5;
+ const focalY = 300.0;
+ final source = fixture.groups.gridZoomLayout(
+ columns: 3,
+ headerExtent: GalleryGroups.spacing,
+ );
+ final sourceTile = source.tileForIndex(anchorIndex)!;
+ final target = fixture.groups.gridZoomLayout(
+ columns: 2,
+ headerExtent: GalleryGroups.spacing,
+ );
+ final targetTile = target.tileForIndex(anchorIndex)!;
+ final initialOffset =
+ _ZoomFixture.contentTop + sourceTile.rect.center.dy - focalY;
+ fixture.controller.jumpTo(initialOffset);
+ await tester.pump();
+ final focalX = sourceTile.rect.center.dx;
+ final first = await tester.startGesture(
+ Offset(focalX - 50, focalY),
+ pointer: 1,
+ );
+ final second = await tester.startGesture(
+ Offset(focalX + 50, focalY),
+ pointer: 2,
+ );
+ await first.moveTo(Offset(focalX - 60, focalY));
+ await second.moveTo(Offset(focalX + 60, focalY));
+ await tester.pump();
+ final tileFinder = find.byKey(
+ const ValueKey(("gallery-grid-zoom-tile", anchorIndex)),
+ );
+ final intermediate = tester.getRect(tileFinder);
+ expect(
+ intermediate.width,
+ closeTo((sourceTile.rect.width * 3 + targetTile.rect.width) / 4, 0.001),
+ );
+ expect(
+ intermediate.height,
+ closeTo((sourceTile.rect.height * 3 + targetTile.rect.height) / 4, 0.001),
+ );
+ expect(intermediate.center.dy, closeTo(focalY, 0.001));
+ expect(fixture.commits, isEmpty);
+ await first.moveTo(Offset(focalX - 100, focalY));
+ await second.moveTo(Offset(focalX + 100, focalY));
+ await first.up();
+ await second.up();
+ await tester.pumpAndSettle();
+ expect(fixture.commits.single.$1, 2);
+ expect(fixture.groups.layoutType, GalleryLayoutType.justified);
+ expect(
+ fixture.controller.offset,
+ closeTo(
+ _ZoomFixture.contentTop +
+ targetTile.rect.top +
+ targetTile.rect.height * fraction -
+ focalY,
+ 0.001,
+ ),
+ );
+ expect(_overlay, findsNothing);
+
+ final justified = fixture.groups.gridZoomLayout(
+ columns: 2,
+ headerExtent: GalleryGroups.spacing,
+ );
+ final anchor = justified.tileForIndex(anchorIndex)!;
+ final nextFocalX = anchor.rect.center.dx;
+ final halfSpan =
+ (nextFocalX < 200 ? nextFocalX : 400 - nextFocalX).clamp(0, 40) * 0.8;
+ final third = await tester.startGesture(
+ Offset(nextFocalX - halfSpan, focalY),
+ pointer: 3,
+ );
+ final fourth = await tester.startGesture(
+ Offset(nextFocalX + halfSpan, focalY),
+ pointer: 4,
+ );
+ await third.moveTo(Offset(nextFocalX - halfSpan * 0.65, focalY));
+ await fourth.moveTo(Offset(nextFocalX + halfSpan * 0.65, focalY));
+ await tester.pump();
+ expect(_overlay, findsOneWidget);
+ await third.up();
+ await fourth.up();
+ await tester.pumpAndSettle();
+ expect(fixture.commits.map((commit) => commit.$1), [2, 3]);
+ expect(fixture.groups.layoutType, GalleryLayoutType.grid);
+ expect(fixture.groups.crossAxisCount, 3);
+ expect(_overlay, findsNothing);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pump();
+ });
+
+ testWidgets("clamps an enlarged short album to its new scroll extent", (
+ tester,
+ ) async {
+ await localSettings.setPhotoGridSize(3);
+ final fixture = _ZoomFixture(fileCount: 8, leadingExtent: 56);
+ addTearDown(fixture.controller.dispose);
+ await fixture.mount(tester);
+ expect(fixture.controller.position.maxScrollExtent, 0);
+ final source = fixture.groups.gridZoomLayout(
+ columns: 3,
+ headerExtent: GalleryGroups.spacing,
+ );
+ final target = fixture.groups.gridZoomLayout(
+ columns: 2,
+ headerExtent: GalleryGroups.spacing,
+ );
+ final sourceTile = source.tileForIndex(5)!;
+ final focalPoint = Offset(
+ sourceTile.rect.center.dx,
+ fixture.leadingExtent +
+ sourceTile.rect.top +
+ sourceTile.rect.height * 0.75,
+ );
+ final expectedMaximum = fixture.leadingExtent + target.totalExtent - 600;
+ expect(expectedMaximum, greaterThan(0));
+ final first = await tester.startGesture(
+ focalPoint - const Offset(50, 0),
+ pointer: 1,
+ );
+ final second = await tester.startGesture(
+ focalPoint + const Offset(50, 0),
+ pointer: 2,
+ );
+ await first.moveTo(focalPoint - const Offset(150, 0));
+ await second.moveTo(focalPoint + const Offset(150, 0));
+ await first.up();
+ await second.up();
+ await tester.pumpAndSettle();
+ expect(fixture.commits.single.$1, 2);
+ expect(fixture.commits.single.$2, closeTo(expectedMaximum, 0.001));
+ expect(fixture.controller.offset, closeTo(expectedMaximum, 0.001));
+ expect(_overlay, findsNothing);
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pump();
+ });
+
+ testWidgets("a file refresh invalidates an overlay while commit is pending", (
+ tester,
+ ) async {
+ final fixture = _ZoomFixture()..commitGate = Completer<void>();
+ addTearDown(fixture.controller.dispose);
+ await fixture.mount(tester);
+ fixture.controller.jumpTo(700);
+ await tester.pump();
+ final first = await tester.startGesture(const Offset(170, 280), pointer: 1);
+ final second = await tester.startGesture(
+ const Offset(330, 280),
+ pointer: 2,
+ );
+ await first.moveTo(const Offset(186, 280));
+ await second.moveTo(const Offset(314, 280));
+ await first.up();
+ await second.up();
+ await tester.pumpAndSettle();
+ expect(fixture.commits, hasLength(1));
+ expect(_overlay, findsOneWidget);
+
+ fixture.rebuild(() {
+ fixture.files = fixture.files.skip(1).toList();
+ fixture.groups = fixture._groups();
+ });
+ await tester.pump();
+ expect(_overlay, findsNothing);
+ fixture.commitGate!.complete();
+ await tester.pumpAndSettle();
+ expect(_overlay, findsNothing);
+ expect(fixture.commits, hasLength(1));
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pump();
+ });
+
+ testWidgets(
+ "a cold pinch remembers justified when released before preparation",
+ (tester) async {
+ await localSettings.setPhotoGridSize(3);
+ final fixture = _ZoomFixture();
+ addTearDown(fixture.controller.dispose);
+ await fixture.mount(tester, prewarm: false);
+ final sourceGroups = fixture.groups;
+ late Future<void> prepared;
+ await tester.runAsync(() async {
+ prepared = sourceGroups
+ .prepareJustifiedZoomLayout(headerExtent: GalleryGroups.spacing)
+ .then((_) {});
+ });
+ expect(
+ sourceGroups.cachedGridZoomLayout(
+ columns: 2,
+ headerExtent: GalleryGroups.spacing,
+ ),
+ isNull,
+ );
+ fixture.controller.jumpTo(700);
+ await tester.pump();
+ final first = await tester.startGesture(
+ const Offset(200, 280),
+ pointer: 1,
+ );
+ final second = await tester.startGesture(
+ const Offset(300, 280),
+ pointer: 2,
+ );
+ await first.moveTo(const Offset(150, 280));
+ await second.moveTo(const Offset(350, 280));
+ await first.up();
+ await second.up();
+ expect(fixture.commits, isEmpty);
+ expect(
+ sourceGroups.cachedGridZoomLayout(
+ columns: 2,
+ headerExtent: GalleryGroups.spacing,
+ ),
+ isNull,
+ );
+ await tester.runAsync(() => prepared);
+ await tester.pumpAndSettle();
+ expect(fixture.commits, hasLength(1));
+ expect(fixture.commits.single.$1, 2);
+ expect(fixture.groups.layoutType, GalleryLayoutType.justified);
+ expect(_overlay, findsNothing);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pump();
+ },
+ );
+
+ testWidgets("cold geometry catches up continuously during an active pinch", (
+ tester,
+ ) async {
+ await localSettings.setPhotoGridSize(3);
+ final fixture = _ZoomFixture();
+ addTearDown(fixture.controller.dispose);
+ await fixture.mount(tester, prewarm: false);
+ final sourceGroups = fixture.groups;
+ late Future<void> prepared;
+ await tester.runAsync(() async {
+ prepared = sourceGroups
+ .prepareJustifiedZoomLayout(headerExtent: GalleryGroups.spacing)
+ .then((_) {});
+ });
+ const anchorIndex = 31;
+ const focalY = 300.0;
+ final sourceTile = sourceGroups
+ .gridZoomLayout(columns: 3, headerExtent: GalleryGroups.spacing)
+ .tileForIndex(anchorIndex)!;
+ fixture.controller.jumpTo(
+ _ZoomFixture.contentTop + sourceTile.rect.center.dy - focalY,
+ );
+ await tester.pump();
+ final focalX = sourceTile.rect.center.dx;
+ final first = await tester.startGesture(
+ Offset(focalX - 50, focalY),
+ pointer: 1,
+ );
+ final second = await tester.startGesture(
+ Offset(focalX + 50, focalY),
+ pointer: 2,
+ );
+ await first.moveTo(Offset(focalX - 150, focalY));
+ await second.moveTo(Offset(focalX + 150, focalY));
+ await tester.pump();
+ final tileFinder = find.byKey(
+ const ValueKey(("gallery-grid-zoom-tile", anchorIndex)),
+ );
+ final heldRect = tester.getRect(tileFinder);
+ expect(heldRect.size, sourceTile.rect.size);
+ expect(
+ sourceGroups.cachedGridZoomLayout(
+ columns: 2,
+ headerExtent: GalleryGroups.spacing,
+ ),
+ isNull,
+ );
+
+ await tester.runAsync(() => prepared);
+ await tester.pump();
+ expect(tester.getRect(tileFinder), heldRect);
+ final targetTile = sourceGroups
+ .gridZoomLayout(columns: 2, headerExtent: GalleryGroups.spacing)
+ .tileForIndex(anchorIndex)!;
+ await tester.pump(const Duration(milliseconds: 45));
+ final intermediate = tester.getRect(tileFinder);
+ final progress =
+ (intermediate.height - heldRect.height) /
+ (targetTile.rect.height - heldRect.height);
+ expect(progress, greaterThan(0));
+ expect(progress, lessThan(1));
+ expect(intermediate.center.dy, closeTo(focalY, 0.001));
+ expect(fixture.commits, isEmpty);
+ await tester.pump(const Duration(milliseconds: 45));
+ expect(tester.getRect(tileFinder).size, targetTile.rect.size);
+ expect(fixture.commits, isEmpty);
+ await first.up();
+ await second.up();
+ await tester.pumpAndSettle();
+ expect(fixture.commits, hasLength(1));
+ expect(fixture.commits.single.$1, 2);
+ expect(_overlay, findsNothing);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pump();
+ });
+}
+
+Finder get _overlay => find.byKey(const ValueKey("gallery-grid-zoom-overlay"));
+
+class _ZoomFixture {
+ _ZoomFixture({int fileCount = 1200, this.leadingExtent = contentTop})
+ : files = List<EnteFile>.generate(
+ fileCount,
+ (index) => EnteFile()
+ ..generatedID = index + 1
+ ..creationTime = DateTime(2026, 8, 19).microsecondsSinceEpoch
+ ..fileType = FileType.image
+ ..pubMagicMetadata = PubMagicMetadata(
+ w: index.isEven ? 1600 : 900,
+ h: index.isEven ? 900 : 1600,
+ ),
+ );
+
+ static const contentTop = 112.0;
+ final double leadingExtent;
+ final controller = ScrollController();
+ final commits = <(int, double)>[];
+ List<EnteFile> files;
+ Completer<void>? commitGate;
+ late GalleryGroups groups;
+ late StateSetter rebuild;
+
+ GalleryGroups _groups() => GalleryGroups(
+ allFiles: files,
+ groupType: GroupType.none,
+ widthAvailable: 400,
+ selectedFiles: null,
+ tagPrefix: "zoom_test_",
+ groupHeaderExtent: GalleryGroups.spacing,
+ showSelectAll: false,
+ );
+
+ Future<void> mount(WidgetTester tester, {bool prewarm = true}) async {
+ groups = _groups();
+ if (prewarm) {
+ await tester.runAsync(
+ () => groups.prepareJustifiedZoomLayout(
+ headerExtent: GalleryGroups.spacing,
+ ),
+ );
+ }
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: lightThemeData,
+ localizationsDelegates: StringsLocalizations.localizationsDelegates,
+ supportedLocales: StringsLocalizations.supportedLocales,
+ home: Align(
+ alignment: Alignment.topLeft,
+ child: SizedBox(
+ width: 400,
+ height: 600,
+ child: StatefulBuilder(
+ builder: (context, setState) {
+ rebuild = setState;
+ return GalleryGridZoom(
+ groups: groups,
+ scrollController: controller,
+ sectionOrigin: () => leadingExtent - controller.offset,
+ appBarHeight: 56,
+ pinHeaders: false,
+ enabled: true,
+ onCommit: (columns, scrollOffset) async {
+ commits.add((columns, scrollOffset));
+ await commitGate?.future;
+ await localSettings.setGalleryLayoutType(
+ columns == 2
+ ? GalleryLayoutType.justified
+ : GalleryLayoutType.grid,
+ );
+ if (columns != 2) {
+ await localSettings.setPhotoGridSize(columns);
+ }
+ rebuild(() => groups = _groups());
+ await WidgetsBinding.instance.endOfFrame;
+ controller.jumpTo(scrollOffset);
+ },
+ thumbnailBuilder: (_) => const ColoredBox(color: Colors.blue),
+ child: SingleChildScrollView(
+ key: const ValueKey("gallery-scroll"),
+ controller: controller,
+ child: SizedBox(
+ height:
+ leadingExtent + groups.groupLayouts.last.maxOffset,
+ child: const ColoredBox(color: Colors.black),
+ ),
+ ),
+ );
+ },
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+}
diff --git a/mobile/apps/photos/test/ui/viewer/gallery/gallery_pinch_detector_test.dart b/mobile/apps/photos/test/ui/viewer/gallery/gallery_pinch_detector_test.dart
new file mode 100644
index 0000000000..939ddcab7e
--- /dev/null
+++ b/mobile/apps/photos/test/ui/viewer/gallery/gallery_pinch_detector_test.dart
@@ -0,0 +1,192 @@
+import "package:flutter/material.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:photos/ui/viewer/gallery/gallery_pinch_detector.dart";
+
+void main() {
+ testWidgets("leaves taps and established one-finger scrolling unchanged", (
+ tester,
+ ) async {
+ final controller = ScrollController();
+ addTearDown(controller.dispose);
+ var taps = 0;
+ var starts = 0;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: GalleryPinchDetector(
+ enabled: true,
+ onStart: (_) => starts++,
+ onUpdate: (_, _) {},
+ onEnd: (_) {},
+ child: ListView.builder(
+ controller: controller,
+ itemCount: 100,
+ itemBuilder: (_, _) => GestureDetector(
+ onTap: () => taps++,
+ behavior: HitTestBehavior.opaque,
+ child: const SizedBox(height: 80),
+ ),
+ ),
+ ),
+ ),
+ );
+
+ await tester.tapAt(const Offset(100, 100));
+ expect(taps, 1);
+ final first = await tester.startGesture(const Offset(100, 300), pointer: 1);
+ await first.moveTo(const Offset(100, 200));
+ await first.moveTo(const Offset(100, 150));
+ await tester.pump();
+ expect(controller.offset, greaterThan(0));
+ final second = await tester.startGesture(
+ const Offset(200, 150),
+ pointer: 2,
+ );
+ await second.moveTo(const Offset(240, 150));
+ await second.up();
+ await first.up();
+ await tester.pumpAndSettle();
+ expect(starts, 0);
+ expect(taps, 1);
+ });
+
+ testWidgets(
+ "starts on the second finger, keeps its pair and consumes trailing taps",
+ (tester) async {
+ final starts = <Offset>[];
+ final updates = <(double, Offset)>[];
+ final ends = <bool>[];
+ var taps = 0;
+ const detectorKey = ValueKey("pinch");
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Padding(
+ padding: const EdgeInsets.only(left: 20, top: 30),
+ child: GalleryPinchDetector(
+ key: detectorKey,
+ enabled: true,
+ onStart: starts.add,
+ onUpdate: (scale, focalPoint) => updates.add((scale, focalPoint)),
+ onEnd: ends.add,
+ child: GestureDetector(
+ onTap: () => taps++,
+ behavior: HitTestBehavior.opaque,
+ child: const SizedBox.expand(),
+ ),
+ ),
+ ),
+ ),
+ );
+ final origin = tester.getTopLeft(find.byKey(detectorKey));
+ final first = await tester.startGesture(
+ origin + const Offset(70, 140),
+ pointer: 1,
+ );
+ expect(starts, isEmpty);
+ final second = await tester.startGesture(
+ origin + const Offset(170, 140),
+ pointer: 2,
+ );
+ expect(starts, [const Offset(120, 140)]);
+ await first.moveTo(origin + const Offset(50, 140));
+ await second.moveTo(origin + const Offset(190, 140));
+ expect(updates.last.$1, closeTo(1.4, 0.0001));
+ expect(updates.last.$2, const Offset(120, 140));
+
+ final updateCount = updates.length;
+ final third = await tester.startGesture(
+ origin + const Offset(300, 300),
+ pointer: 3,
+ );
+ await third.moveTo(origin + const Offset(350, 350));
+ expect(updates.length, updateCount);
+ expect(starts, hasLength(1));
+ await first.up();
+ expect(ends, [false]);
+ await second.moveTo(origin + const Offset(220, 140));
+ await third.up();
+ await second.up();
+ expect(updates.length, updateCount);
+ expect(ends, [false]);
+ expect(taps, 0);
+
+ await tester.tapAt(origin + const Offset(100, 100));
+ expect(taps, 1);
+ },
+ );
+
+ testWidgets("pointer cancellation and disabling cancel exactly once", (
+ tester,
+ ) async {
+ var enabled = true;
+ late StateSetter rebuild;
+ final ends = <bool>[];
+ var starts = 0;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: StatefulBuilder(
+ builder: (context, setState) {
+ rebuild = setState;
+ return GalleryPinchDetector(
+ enabled: enabled,
+ onStart: (_) => starts++,
+ onUpdate: (_, _) {},
+ onEnd: ends.add,
+ child: const SizedBox.expand(),
+ );
+ },
+ ),
+ ),
+ );
+
+ for (final disable in [false, true]) {
+ final first = await tester.startGesture(
+ const Offset(100, 100),
+ pointer: 1,
+ );
+ final second = await tester.startGesture(
+ const Offset(200, 100),
+ pointer: 2,
+ );
+ if (disable) {
+ rebuild(() => enabled = false);
+ await tester.pump();
+ await first.up();
+ } else {
+ await first.cancel();
+ }
+ await second.up();
+ expect(ends, everyElement(isTrue));
+ expect(ends.length, starts);
+ }
+ expect(starts, 2);
+ expect(ends, [true, true]);
+
+ final first = await tester.startGesture(const Offset(100, 100), pointer: 1);
+ final second = await tester.startGesture(
+ const Offset(200, 100),
+ pointer: 2,
+ );
+ await first.moveTo(const Offset(70, 100));
+ await second.up();
+ await first.up();
+ expect(starts, 2);
+ expect(ends, [true, true]);
+ for (final nextEnabled in [true, false, true]) {
+ rebuild(() => enabled = nextEnabled);
+ await tester.pump();
+ }
+ final resumedFirst = await tester.startGesture(
+ const Offset(100, 100),
+ pointer: 3,
+ );
+ final resumedSecond = await tester.startGesture(
+ const Offset(200, 100),
+ pointer: 4,
+ );
+ await resumedFirst.up();
+ await resumedSecond.up();
+ expect(starts, 3);
+ expect(ends, [true, true, false]);
+ expect(tester.takeException(), isNull);
+ });
+}
diff --git a/mobile/apps/photos/test/ui/viewer/gallery/gallery_zoom_image_test.dart b/mobile/apps/photos/test/ui/viewer/gallery/gallery_zoom_image_test.dart
new file mode 100644
index 0000000000..c06c56b306
--- /dev/null
+++ b/mobile/apps/photos/test/ui/viewer/gallery/gallery_zoom_image_test.dart
@@ -0,0 +1,49 @@
+import "package:flutter/widgets.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:photos/ui/viewer/gallery/gallery_zoom_image.dart";
+
+void main() {
+ testWidgets(
+ "repaints thumbnail cropping only when its aspect ratio changes",
+ (tester) async {
+ final density = AnimationController.unbounded(vsync: tester, value: 3);
+ addTearDown(density.dispose);
+
+ Widget thumbnail(Rect to) => Directionality(
+ textDirection: TextDirection.ltr,
+ child: Center(
+ child: SizedBox(
+ width: 100,
+ height: 100,
+ child: RepaintBoundary(
+ child: GalleryZoomImage(
+ animation: density,
+ lower: 3,
+ from: const Rect.fromLTWH(0, 0, 100, 100),
+ to: to,
+ image: null,
+ child: const ColoredBox(color: Color(0xffabcdef)),
+ ),
+ ),
+ ),
+ ),
+ );
+
+ await tester.pumpWidget(thumbnail(const Rect.fromLTWH(50, 50, 75, 75)));
+ final render = tester.renderObject<RenderGalleryZoomImage>(
+ find.byType(GalleryZoomImage),
+ );
+ expect(render.debugNeedsPaint, isFalse);
+ density.value = 3.5;
+ expect(render.debugNeedsPaint, isFalse);
+
+ await tester.pumpWidget(thumbnail(const Rect.fromLTWH(50, 50, 75, 150)));
+ expect(render.debugNeedsPaint, isFalse);
+ density.value = 3.75;
+ expect(render.debugNeedsPaint, isTrue);
+ await tester.pump();
+ expect(render.debugNeedsPaint, isFalse);
+ await tester.pumpWidget(const SizedBox.shrink());
+ },
+ );
+}
diff --git a/mobile/apps/photos/test/ui/viewer/gallery/swipe_selection_pinch_test.dart b/mobile/apps/photos/test/ui/viewer/gallery/swipe_selection_pinch_test.dart
new file mode 100644
index 0000000000..136ae47865
--- /dev/null
+++ b/mobile/apps/photos/test/ui/viewer/gallery/swipe_selection_pinch_test.dart
@@ -0,0 +1,121 @@
+import "package:flutter/material.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:photos/models/file/file.dart";
+import "package:photos/models/selected_files.dart";
+import "package:photos/ui/viewer/gallery/component/swipe_selectable_file_widget.dart";
+import "package:photos/ui/viewer/gallery/state/gallery_boundaries_provider.dart";
+import "package:photos/ui/viewer/gallery/swipe_selection_wrapper.dart";
+import "package:photos/ui/viewer/gallery/swipe_to_select_helper.dart";
+
+void main() {
+ testWidgets("pinch stops selection and autoscroll until every finger lifts", (
+ tester,
+ ) async {
+ final files = List.generate(
+ 5,
+ (index) => EnteFile()..generatedID = index + 1,
+ );
+ final selectedFiles = SelectedFiles()..selectAll({files.first});
+ final helper = SwipeToSelectHelper(
+ allFiles: files,
+ selectedFiles: selectedFiles,
+ );
+ final swipeActive = ValueNotifier(false);
+ final controller = ScrollController();
+ final boundaries = GlobalKey<GalleryBoundariesProviderState>();
+ addTearDown(() async {
+ await tester.pumpWidget(const SizedBox.shrink());
+ helper.dispose();
+ selectedFiles.dispose();
+ swipeActive.dispose();
+ controller.dispose();
+ });
+ await tester.pumpWidget(
+ MaterialApp(
+ home: GalleryBoundariesProvider(
+ key: boundaries,
+ child: SwipeSelectionWrapper(
+ swipeHelper: helper,
+ selectedFiles: selectedFiles,
+ isEnabled: true,
+ swipeActiveNotifier: swipeActive,
+ scrollController: controller,
+ child: SingleChildScrollView(
+ controller: controller,
+ physics: const NeverScrollableScrollPhysics(),
+ child: Column(
+ children: [
+ const SizedBox(height: 520),
+ Row(
+ children: [
+ for (final file in files)
+ SwipeSelectableFileWidget(
+ file: file,
+ selectedFiles: selectedFiles,
+ child: const SizedBox(
+ width: 100,
+ height: 80,
+ child: ColoredBox(color: Colors.blue),
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 2000),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ boundaries.currentState!
+ ..setScrollController(controller, swipeActiveNotifier: swipeActive)
+ ..setTopBoundary(0)
+ ..setBottomBoundary(500);
+
+ final first = await tester.startGesture(const Offset(150, 550), pointer: 1);
+ await first.moveBy(const Offset(20, 0));
+ expect(swipeActive.value, isTrue);
+ expect(helper.isActive, isTrue);
+ expect(selectedFiles.files, unorderedEquals([files.first, files[1]]));
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 32));
+ expect(controller.offset, greaterThan(0));
+
+ final beforePinch = selectedFiles.files.toSet();
+ final second = await tester.startGesture(
+ const Offset(350, 550),
+ pointer: 2,
+ );
+ expect(swipeActive.value, isFalse);
+ expect(helper.isActive, isFalse);
+ expect(selectedFiles.files, unorderedEquals(beforePinch));
+ final stoppedOffset = controller.offset;
+ await first.moveTo(const Offset(250, 550));
+ await second.moveTo(const Offset(450, 550));
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(controller.offset, stoppedOffset);
+ expect(swipeActive.value, isFalse);
+ expect(helper.isActive, isFalse);
+ expect(selectedFiles.files, unorderedEquals(beforePinch));
+
+ await first.up();
+ await second.moveTo(const Offset(150, 550));
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(controller.offset, stoppedOffset);
+ expect(swipeActive.value, isFalse);
+ expect(helper.isActive, isFalse);
+ expect(selectedFiles.files, unorderedEquals(beforePinch));
+ await second.up();
+
+ final next = await tester.startGesture(const Offset(250, 550), pointer: 3);
+ await next.moveBy(const Offset(20, 0));
+ expect(swipeActive.value, isTrue);
+ expect(helper.isActive, isTrue);
+ await next.moveTo(const Offset(350, 550));
+ expect(selectedFiles.files, unorderedEquals(files.take(4)));
+ await next.up();
+ expect(swipeActive.value, isFalse);
+ expect(helper.isActive, isFalse);
+ });
+}