Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mob][photos] Add mosaic gallery layout

ashil-pilot4d819a6f8b72
diff --git a/mobile/apps/photos/lib/events/gallery_layout_changed_event.dart b/mobile/apps/photos/lib/events/gallery_layout_changed_event.dart
new file mode 100644
index 0000000000..721ac9248c
--- /dev/null
+++ b/mobile/apps/photos/lib/events/gallery_layout_changed_event.dart
@@ -0,0 +1,3 @@
+import "package:photos/events/event.dart";
+
+class GalleryLayoutChangedEvent extends Event {}
diff --git a/mobile/apps/photos/lib/main.dart b/mobile/apps/photos/lib/main.dart
index 4f9e927793..ec39904f35 100644
--- a/mobile/apps/photos/lib/main.dart
+++ b/mobile/apps/photos/lib/main.dart
@@ -605,6 +605,7 @@ void logLocalSettings() {
'ML enabled': flagService.hasGrantedMLConsent,
'ML local indexing enabled': localSettings.isMLLocalIndexingEnabled,
'Multipart upload enabled': localSettings.userEnabledMultiplePart,
+ 'Gallery layout': localSettings.getGalleryLayoutType().name,
'Gallery grid size': localSettings.getPhotoGridSize(),
'Video streaming enabled':
VideoPreviewService.instance.isVideoStreamingEnabled,
diff --git a/mobile/apps/photos/lib/models/file/file.dart b/mobile/apps/photos/lib/models/file/file.dart
index 9e4e390c8b..d72aec7091 100644
--- a/mobile/apps/photos/lib/models/file/file.dart
+++ b/mobile/apps/photos/lib/models/file/file.dart
@@ -1,3 +1,5 @@
+import 'dart:convert';
+
import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';
import 'package:photo_manager/photo_manager.dart';
@@ -58,15 +60,28 @@ class EnteFile {
if (_pubMmdEncodedJson == value) return;
_pubMmdEncodedJson = value;
_pubMmd = null;
+ _dimensionsDecoded = false;
}
int pubMmdVersion = 0;
PubMagicMetadata? _pubMmd;
+ int _width = 0;
+ int _height = 0;
+ bool _dimensionsDecoded = false;
PubMagicMetadata? get pubMagicMetadata =>
_pubMmd ??= PubMagicMetadata.fromEncodedJson(pubMmdEncodedJson ?? '{}');
- set pubMagicMetadata(PubMagicMetadata? val) => _pubMmd = val;
+ set pubMagicMetadata(PubMagicMetadata? val) {
+ _pubMmd = val;
+ if (val == null) {
+ _dimensionsDecoded = false;
+ return;
+ }
+ _width = val.w ?? 0;
+ _height = val.h ?? 0;
+ _dimensionsDecoded = true;
+ }
// in Version 1, live photo hash is stored as zip's hash.
// in V2: LivePhoto hash is stored as imgHash:vidHash
@@ -195,11 +210,32 @@ class EnteFile {
}
int get height {
- return pubMagicMetadata?.h ?? 0;
+ _decodeDimensions();
+ return _height;
}
int get width {
- return pubMagicMetadata?.w ?? 0;
+ _decodeDimensions();
+ return _width;
+ }
+
+ void _decodeDimensions() {
+ if (_dimensionsDecoded) return;
+ if (_pubMmd != null) {
+ _width = _pubMmd!.w ?? 0;
+ _height = _pubMmd!.h ?? 0;
+ } else {
+ // Gallery layout only needs these two fields. Decode them without
+ // materializing and retaining PubMagicMetadata for every gallery file.
+ final metadata = jsonDecode(pubMmdEncodedJson ?? '{}');
+ if (metadata is Map<String, dynamic>) {
+ _width =
+ PubMagicMetadata.safeParseInt(metadata[widthKey], widthKey) ?? 0;
+ _height =
+ PubMagicMetadata.safeParseInt(metadata[heightKey], heightKey) ?? 0;
+ }
+ }
+ _dimensionsDecoded = true;
}
bool get hasDimensions {
diff --git a/mobile/apps/photos/lib/models/gallery/fixed_extent_section_layout.dart b/mobile/apps/photos/lib/models/gallery/fixed_extent_section_layout.dart
index 5a92858140..ecddeaac91 100644
--- a/mobile/apps/photos/lib/models/gallery/fixed_extent_section_layout.dart
+++ b/mobile/apps/photos/lib/models/gallery/fixed_extent_section_layout.dart
@@ -1,36 +1,28 @@
-import 'package:flutter/material.dart';
+import "package:photos/models/gallery/section_layout.dart";
-class FixedExtentSectionLayout {
- final double tileHeight, mainAxisStride;
- final int firstIndex, lastIndex, bodyFirstIndex;
- final double minOffset, maxOffset, bodyMinOffset;
- final double headerExtent, spacing;
- final IndexedWidgetBuilder builder;
+class FixedExtentSectionLayout extends SectionLayout {
+ final double tileHeight;
+ final double mainAxisStride;
const FixedExtentSectionLayout({
- required this.firstIndex,
- required this.lastIndex,
- required this.minOffset,
- required this.maxOffset,
- required this.headerExtent,
+ required super.firstIndex,
+ required super.lastIndex,
+ required super.minOffset,
+ required super.maxOffset,
+ required super.headerExtent,
required this.tileHeight,
- required this.spacing,
- required this.builder,
- }) : bodyFirstIndex = firstIndex + 1,
- bodyMinOffset = minOffset + headerExtent,
- mainAxisStride = tileHeight + spacing;
-
- bool hasChild(int index) => firstIndex <= index && index <= lastIndex;
-
- bool hasChildAtOffset(double scrollOffset) =>
- minOffset <= scrollOffset && scrollOffset <= maxOffset;
+ required super.spacing,
+ required super.builder,
+ }) : mainAxisStride = tileHeight + spacing;
+ @override
double indexToLayoutOffset(int index) {
index -= bodyFirstIndex;
if (index < 0) return minOffset;
return bodyMinOffset + index * mainAxisStride;
}
+ @override
int getMinChildIndexForScrollOffset(double scrollOffset) {
scrollOffset -= bodyMinOffset;
if (mainAxisStride == 0 || !scrollOffset.isFinite || scrollOffset < 0) {
@@ -40,6 +32,7 @@ class FixedExtentSectionLayout {
return bodyFirstIndex + scrollOffset ~/ mainAxisStride;
}
+ @override
int getMaxChildIndexForScrollOffset(double scrollOffset) {
scrollOffset -= bodyMinOffset;
if (mainAxisStride == 0 || !scrollOffset.isFinite || scrollOffset < 0) {
@@ -48,41 +41,3 @@ class FixedExtentSectionLayout {
return bodyFirstIndex + (scrollOffset / mainAxisStride).ceil() - 1;
}
}
-
-extension FixedExtentSectionLayoutList on List<FixedExtentSectionLayout> {
- FixedExtentSectionLayout? sectionForIndex(int index) {
- if (isEmpty) return null;
- int low = 0;
- int high = length - 1;
- while (low <= high) {
- final int mid = (low + high) >>> 1;
- final FixedExtentSectionLayout section = this[mid];
- if (index < section.firstIndex) {
- high = mid - 1;
- } else if (index > section.lastIndex) {
- low = mid + 1;
- } else {
- return section;
- }
- }
- return null;
- }
-
- FixedExtentSectionLayout? sectionForOffset(double scrollOffset) {
- if (isEmpty) return null;
- int low = 0;
- int high = length - 1;
- while (low <= high) {
- final int mid = (low + high) >>> 1;
- final FixedExtentSectionLayout section = this[mid];
- if (scrollOffset < section.minOffset) {
- high = mid - 1;
- } else if (scrollOffset > section.maxOffset) {
- low = mid + 1;
- } else {
- return section;
- }
- }
- return last;
- }
-}
diff --git a/mobile/apps/photos/lib/models/gallery/gallery_groups.dart b/mobile/apps/photos/lib/models/gallery/gallery_groups.dart
index 56e0441248..9e6c39b12e 100644
--- a/mobile/apps/photos/lib/models/gallery/gallery_groups.dart
+++ b/mobile/apps/photos/lib/models/gallery/gallery_groups.dart
@@ -3,12 +3,17 @@ import "dart:core";
import "package:flutter/material.dart";
import "package:logging/logging.dart";
import "package:photos/core/configuration.dart";
+import "package:photos/core/constants.dart";
import "package:photos/models/file/dummy_file.dart";
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/mosaic_grid_row.dart";
+import "package:photos/models/gallery/mosaic_layout.dart";
+import "package:photos/models/gallery/section_layout.dart";
import "package:photos/models/selected_files.dart";
import "package:photos/service_locator.dart";
+import "package:photos/settings/local_settings.dart";
import "package:photos/ui/viewer/gallery/component/dummy_file_widget.dart";
import "package:photos/ui/viewer/gallery/component/gallery_file_widget.dart";
import "package:photos/ui/viewer/gallery/component/group/group_header_widget.dart";
@@ -53,7 +58,8 @@ class GalleryGroups {
static const double spacing = 2.0;
late final int crossAxisCount;
- late final List<FixedExtentSectionLayout> _groupLayouts;
+ late final GalleryLayoutType layoutType;
+ late final List<SectionLayout> _groupLayouts;
final List<EnteFile> _allFilesWithDummies = [];
final List<String> _groupIds = [];
@@ -76,7 +82,7 @@ class GalleryGroups {
get groupIdToGroupDataMap => _groupIdToGroupDataMap;
Map<double, String> get scrollOffsetToGroupIdMap => _scrollOffsetToGroupIdMap;
Map<String, double> get groupIdToScrollOffsetMap => _groupIdToScrollOffsetMap;
- List<FixedExtentSectionLayout> get groupLayouts => _groupLayouts;
+ List<SectionLayout> get groupLayouts => _groupLayouts;
List<double> get groupScrollOffsets => _groupScrollOffsets;
List<({String groupID, String title})> get scrollbarDivisions =>
_scrollbarDivisions;
@@ -105,6 +111,105 @@ class GalleryGroups {
return scrollOffset;
}
+ EnteFile? getFileAtScrollOffset(double scrollOffset) {
+ if (_groupLayouts.isEmpty || !scrollOffset.isFinite) return null;
+ final section = _groupLayouts.sectionForOffset(scrollOffset);
+ if (section == null) return null;
+ final groupIndex = _groupLayouts.indexOf(section);
+ if (groupIndex < 0 || groupIndex >= _groupIds.length) return null;
+ final files = _groupIdToFilesMap[_groupIds[groupIndex]];
+ if (files == null || files.isEmpty) return null;
+
+ final childIndex = section.getMinChildIndexForScrollOffset(scrollOffset);
+ if (childIndex <= section.firstIndex) return files.first;
+ final rowIndex = childIndex - section.bodyFirstIndex;
+ final fileIndex = switch (section) {
+ FixedExtentSectionLayout() => rowIndex * crossAxisCount,
+ MosaicSectionLayout() => section.rows[rowIndex].firstIndex,
+ _ => 0,
+ };
+ return files[fileIndex.clamp(0, files.length - 1)];
+ }
+
+ ({double headerExtent, double rowOffset, double rowExtent})?
+ getGeometryOfFile(EnteFile file) {
+ final location = _findExactFileLocation(file);
+ if (location == null) return null;
+ final groupIndex = location.groupIndex;
+ final fileIndex = location.fileIndex;
+ final section = _groupLayouts[groupIndex];
+
+ return switch (section) {
+ FixedExtentSectionLayout() => (
+ headerExtent: section.headerExtent,
+ rowOffset:
+ section.bodyMinOffset +
+ (fileIndex ~/ crossAxisCount) * section.mainAxisStride,
+ rowExtent: section.tileHeight,
+ ),
+ MosaicSectionLayout() => () {
+ final row =
+ section.rows[_mosaicRowIndexForFile(section.rows, fileIndex)];
+ return (
+ headerExtent: section.headerExtent,
+ rowOffset: section.bodyMinOffset + row.minOffset,
+ rowExtent: row.height,
+ );
+ }(),
+ _ => null,
+ };
+ }
+
+ double? getOffsetOfFile(EnteFile file) => getGeometryOfFile(file)?.rowOffset;
+
+ ({int groupIndex, int fileIndex})? _findExactFileLocation(EnteFile file) {
+ ({int groupIndex, int fileIndex})? generatedIDLocation;
+ ({int groupIndex, int fileIndex})? uploadedFileIDLocation;
+ ({int groupIndex, int fileIndex})? localIDLocation;
+ for (var groupIndex = 0; groupIndex < _groupIds.length; groupIndex++) {
+ final files = _groupIdToFilesMap[_groupIds[groupIndex]]!;
+ for (var fileIndex = 0; fileIndex < files.length; fileIndex++) {
+ final candidate = files[fileIndex];
+ if (identical(candidate, file)) {
+ return (groupIndex: groupIndex, fileIndex: fileIndex);
+ }
+ if (candidate is DummyFile || file is DummyFile) continue;
+ final location = (groupIndex: groupIndex, fileIndex: fileIndex);
+ if (file.generatedID != null &&
+ candidate.generatedID == file.generatedID) {
+ generatedIDLocation ??= location;
+ }
+ if (file.uploadedFileID != null &&
+ candidate.uploadedFileID == file.uploadedFileID) {
+ uploadedFileIDLocation ??= location;
+ }
+ if (file.localID != null &&
+ file.localID!.isNotEmpty &&
+ candidate.localID == file.localID) {
+ localIDLocation ??= location;
+ }
+ }
+ }
+ return generatedIDLocation ?? uploadedFileIDLocation ?? localIDLocation;
+ }
+
+ int _mosaicRowIndexForFile(List<MosaicRowLayout> rows, int fileIndex) {
+ var low = 0;
+ var high = rows.length - 1;
+ while (low <= high) {
+ final mid = (low + high) >>> 1;
+ final row = rows[mid];
+ if (fileIndex < row.firstIndex) {
+ high = mid - 1;
+ } else if (fileIndex > row.lastIndex) {
+ low = mid + 1;
+ } else {
+ return mid;
+ }
+ }
+ return rows.length - 1;
+ }
+
String? _findGroupForCreationTime(int creationTime) {
if (_groupIds.isEmpty) {
_logger.warning(
@@ -153,9 +258,13 @@ class GalleryGroups {
void init() {
crossAxisCount = localSettings.getPhotoGridSize();
+ layoutType = localSettings.getGalleryLayoutType();
_buildGroups();
- _groupLayouts = _computeGroupLayouts();
+ _groupLayouts = switch (layoutType) {
+ GalleryLayoutType.grid => _computeFixedGroupLayouts(),
+ GalleryLayoutType.mosaic => _computeMosaicGroupLayouts(),
+ };
assert(groupIDs.length == _groupIdToFilesMap.length);
assert(groupIDs.length == _groupIdToGroupDataMap.length);
@@ -164,14 +273,14 @@ class GalleryGroups {
assert(groupIDs.length == _groupScrollOffsets.length);
}
- List<FixedExtentSectionLayout> _computeGroupLayouts() {
+ List<SectionLayout> _computeFixedGroupLayouts() {
final stopwatch = Stopwatch()..start();
final showGroupHeader = groupType.showGroupHeader();
int currentIndex = 0;
double currentOffset = 0.0;
final tileHeight =
(widthAvailable - (crossAxisCount - 1) * spacing) / crossAxisCount;
- final groupLayouts = <FixedExtentSectionLayout>[];
+ final groupLayouts = <SectionLayout>[];
final groupIDs = _groupIdToFilesMap.keys;
@@ -306,6 +415,121 @@ class GalleryGroups {
return groupLayouts;
}
+ List<SectionLayout> _computeMosaicGroupLayouts() {
+ final stopwatch = Stopwatch()..start();
+ final showGroupHeader = groupType.showGroupHeader();
+ final targetRowHeight =
+ (widthAvailable - (crossAxisCount - 1) * spacing) / crossAxisCount;
+ final largeThumbnailMinExtent =
+ (widthAvailable - (photoGridSizeDefault - 2) * spacing) /
+ (photoGridSizeDefault - 1) *
+ 0.9;
+ final groupLayouts = <SectionLayout>[];
+ var currentIndex = 0;
+ var currentOffset = 0.0;
+
+ for (final groupID in _groupIdToFilesMap.keys) {
+ final filesInGroup = _groupIdToFilesMap[groupID]!;
+ final rows = MosaicLayoutCalculator.computeRows(
+ aspectRatios: filesInGroup
+ .map(
+ (file) => MosaicLayoutCalculator.aspectRatioForDimensions(
+ file.width,
+ file.height,
+ ),
+ )
+ .toList(growable: false),
+ availableWidth: widthAvailable,
+ targetRowHeight: targetRowHeight,
+ spacing: spacing,
+ );
+ final firstIndex = currentIndex == 0 ? currentIndex : currentIndex + 1;
+ final lastIndex = firstIndex + rows.length;
+ final minOffset = currentOffset;
+ final maxOffset = minOffset + groupHeaderExtent + rows.last.maxOffset;
+ final bodyFirstIndex = firstIndex + 1;
+
+ groupLayouts.add(
+ MosaicSectionLayout(
+ firstIndex: firstIndex,
+ lastIndex: lastIndex,
+ minOffset: minOffset,
+ maxOffset: maxOffset,
+ headerExtent: groupHeaderExtent,
+ spacing: spacing,
+ rows: rows,
+ builder: (context, rowIndex) {
+ if (rowIndex == firstIndex) {
+ if (showGroupHeader) {
+ return GroupHeaderWidget(
+ title: _groupIdToGroupDataMap[groupID]!.groupType.getTitle(
+ context,
+ filesInGroup.first,
+ ),
+ gridSize: crossAxisCount,
+ filesInGroup: filesInGroup,
+ selectedFiles: selectedFiles,
+ showSelectAll: showSelectAll && !limitSelectionToOne,
+ showGalleryLayoutSettingCTA:
+ rowIndex == 0 && showGallerySettingsCTA,
+ );
+ }
+ return const SizedBox(height: spacing);
+ }
+
+ final row = rows[rowIndex - bodyFirstIndex];
+ final rowChildren = <Widget>[];
+ for (
+ var fileIndex = row.firstIndex;
+ fileIndex <= row.lastIndex;
+ fileIndex++
+ ) {
+ final file = filesInGroup[fileIndex];
+ final itemWidth = row.itemWidths[fileIndex - row.firstIndex];
+ rowChildren.add(
+ RepaintBoundary(
+ key: ValueKey(tagPrefix + file.tag),
+ child: GalleryFileWidget(
+ file: file,
+ selectedFiles: selectedFiles,
+ limitSelectionToOne: limitSelectionToOne,
+ tag: tagPrefix,
+ photoGridSize: crossAxisCount,
+ thumbnailSize: itemWidth >= largeThumbnailMinExtent
+ ? thumbnailLargeSize
+ : thumbnailSmallSize,
+ currentUserID: currentUserID,
+ ),
+ ),
+ );
+ }
+
+ return MosaicGridRow(
+ itemWidths: row.itemWidths,
+ height: row.height,
+ spacing: spacing,
+ textDirection: TextDirection.ltr,
+ children: rowChildren,
+ );
+ },
+ ),
+ );
+
+ _scrollOffsetToGroupIdMap[currentOffset] = groupID;
+ _groupIdToScrollOffsetMap[groupID] = currentOffset;
+ _groupScrollOffsets.add(currentOffset);
+
+ currentIndex = lastIndex;
+ currentOffset = maxOffset;
+ }
+
+ _logger.info(
+ "Built mosaic group layouts in ${stopwatch.elapsedMilliseconds} ms",
+ );
+ stopwatch.stop();
+ return groupLayouts;
+ }
+
void _buildGroups() {
final stopwatch = Stopwatch()..start();
@@ -317,6 +541,10 @@ class GalleryGroups {
_createNewGroup(_copyFilesInRange(start, end), yearsInGroups);
start = end;
}
+ } else if (layoutType == GalleryLayoutType.mosaic) {
+ if (allFiles.isNotEmpty) {
+ _createNewGroup(_copyFilesInRange(0, allFiles.length), yearsInGroups);
+ }
} else {
// Split allFiles into groups of max length 10 * crossAxisCount for
// better performance since SectionedSliverList is used.
@@ -365,7 +593,7 @@ class GalleryGroups {
final lastFile = groupFiles.last;
// Dummy files are used for gesture tracking in swipe-to-select
- if (!limitSelectionToOne) {
+ if (layoutType == GalleryLayoutType.grid && !limitSelectionToOne) {
final incompleteRowCount = groupFiles.length % crossAxisCount;
if (incompleteRowCount != 0) {
final dummiesNeeded = crossAxisCount - incompleteRowCount;
diff --git a/mobile/apps/photos/lib/models/gallery/mosaic_grid_row.dart b/mobile/apps/photos/lib/models/gallery/mosaic_grid_row.dart
new file mode 100644
index 0000000000..8c9615ee32
--- /dev/null
+++ b/mobile/apps/photos/lib/models/gallery/mosaic_grid_row.dart
@@ -0,0 +1,174 @@
+import "package:flutter/foundation.dart";
+import "package:flutter/material.dart";
+import "package:flutter/rendering.dart";
+
+class MosaicGridRow extends MultiChildRenderObjectWidget {
+ final List<double> itemWidths;
+ final double height;
+ final double spacing;
+ final TextDirection textDirection;
+
+ const MosaicGridRow({
+ super.key,
+ required this.itemWidths,
+ required this.height,
+ required this.spacing,
+ required this.textDirection,
+ required super.children,
+ });
+
+ @override
+ RenderObject createRenderObject(BuildContext context) {
+ return RenderMosaicGridRow(
+ itemWidths: itemWidths,
+ height: height,
+ spacing: spacing,
+ textDirection: textDirection,
+ );
+ }
+
+ @override
+ void updateRenderObject(
+ BuildContext context,
+ RenderMosaicGridRow renderObject,
+ ) {
+ renderObject
+ ..itemWidths = itemWidths
+ ..height = height
+ ..spacing = spacing
+ ..textDirection = textDirection;
+ }
+
+ @override
+ void debugFillProperties(DiagnosticPropertiesBuilder properties) {
+ super.debugFillProperties(properties);
+ properties.add(IterableProperty<double>("itemWidths", itemWidths));
+ properties.add(DoubleProperty("height", height));
+ properties.add(DoubleProperty("spacing", spacing));
+ properties.add(EnumProperty<TextDirection>("textDirection", textDirection));
+ }
+}
+
+class _MosaicGridRowParentData extends ContainerBoxParentData<RenderBox> {}
+
+class RenderMosaicGridRow extends RenderBox
+ with
+ ContainerRenderObjectMixin<RenderBox, _MosaicGridRowParentData>,
+ RenderBoxContainerDefaultsMixin<RenderBox, _MosaicGridRowParentData> {
+ RenderMosaicGridRow({
+ List<RenderBox>? children,
+ required List<double> itemWidths,
+ required double height,
+ required double spacing,
+ required TextDirection textDirection,
+ }) : _itemWidths = itemWidths,
+ _height = height,
+ _spacing = spacing,
+ _textDirection = textDirection {
+ addAll(children);
+ }
+
+ List<double> get itemWidths => _itemWidths;
+ List<double> _itemWidths;
+
+ set itemWidths(List<double> value) {
+ if (listEquals(_itemWidths, value)) return;
+ _itemWidths = value;
+ markNeedsLayout();
+ }
+
+ double get height => _height;
+ double _height;
+
+ set height(double value) {
+ if (_height == value) return;
+ _height = value;
+ markNeedsLayout();
+ }
+
+ double get spacing => _spacing;
+ double _spacing;
+
+ set spacing(double value) {
+ if (_spacing == value) return;
+ _spacing = value;
+ markNeedsLayout();
+ }
+
+ TextDirection get textDirection => _textDirection;
+ TextDirection _textDirection;
+
+ set textDirection(TextDirection value) {
+ if (_textDirection == value) return;
+ _textDirection = value;
+ markNeedsLayout();
+ }
+
+ @override
+ void setupParentData(RenderBox child) {
+ if (child.parentData is! _MosaicGridRowParentData) {
+ child.parentData = _MosaicGridRowParentData();
+ }
+ }
+
+ double get intrinsicWidth =>
+ itemWidths.fold<double>(0, (sum, width) => sum + width) +
+ spacing * (childCount > 0 ? childCount - 1 : 0);
+
+ @override
+ double computeMinIntrinsicWidth(double height) => intrinsicWidth;
+
+ @override
+ double computeMaxIntrinsicWidth(double height) => intrinsicWidth;
+
+ @override
+ double computeMinIntrinsicHeight(double width) => height;
+
+ @override
+ double computeMaxIntrinsicHeight(double width) => height;
+
+ @override
+ void performLayout() {
+ assert(
+ childCount == itemWidths.length,
+ "Each mosaic child must have one precomputed width",
+ );
+ final rowWidth = constraints.hasBoundedWidth
+ ? constraints.maxWidth
+ : intrinsicWidth;
+ size = constraints.constrain(Size(rowWidth, height));
+
+ var child = firstChild;
+ final flipMainAxis = textDirection == TextDirection.rtl;
+ var offsetX = flipMainAxis ? size.width : 0.0;
+ var index = 0;
+ while (child != null) {
+ final childWidth = index < itemWidths.length ? itemWidths[index] : 0.0;
+ child.layout(
+ BoxConstraints.tight(Size(childWidth, size.height)),
+ parentUsesSize: false,
+ );
+ final childParentData = child.parentData! as _MosaicGridRowParentData;
+ if (flipMainAxis) offsetX -= childWidth;
+ childParentData.offset = Offset(offsetX, 0);
+ offsetX += flipMainAxis ? -(spacing) : childWidth + spacing;
+ child = childParentData.nextSibling;
+ index++;
+ }
+ }
+
+ @override
+ double? computeDistanceToActualBaseline(TextBaseline baseline) {
+ return defaultComputeDistanceToHighestActualBaseline(baseline);
+ }
+
+ @override
+ bool hitTestChildren(BoxHitTestResult result, {required Offset position}) {
+ return defaultHitTestChildren(result, position: position);
+ }
+
+ @override
+ void paint(PaintingContext context, Offset offset) {
+ defaultPaint(context, offset);
+ }
+}
diff --git a/mobile/apps/photos/lib/models/gallery/mosaic_layout.dart b/mobile/apps/photos/lib/models/gallery/mosaic_layout.dart
new file mode 100644
index 0000000000..5a862ec70d
--- /dev/null
+++ b/mobile/apps/photos/lib/models/gallery/mosaic_layout.dart
@@ -0,0 +1,214 @@
+import "dart:math" as math;
+
+import "package:photos/models/gallery/section_layout.dart";
+
+class MosaicRowLayout {
+ final int firstIndex;
+ final int lastIndex;
+ final double minOffset;
+ final double height;
+ final List<double> itemWidths;
+
+ const MosaicRowLayout({
+ required this.firstIndex,
+ required this.lastIndex,
+ required this.minOffset,
+ required this.height,
+ required this.itemWidths,
+ });
+
+ double get maxOffset => minOffset + height;
+}
+
+class MosaicSectionLayout extends SectionLayout {
+ final List<MosaicRowLayout> rows;
+
+ const MosaicSectionLayout({
+ required super.firstIndex,
+ required super.lastIndex,
+ required super.minOffset,
+ required super.maxOffset,
+ required super.headerExtent,
+ required super.spacing,
+ required super.builder,
+ required this.rows,
+ });
+
+ @override
+ double indexToLayoutOffset(int index) {
+ index -= bodyFirstIndex;
+ if (index < 0) return minOffset;
+ if (index >= rows.length) return maxOffset + spacing;
+ return bodyMinOffset + rows[index].minOffset;
+ }
+
+ @override
+ int getMinChildIndexForScrollOffset(double scrollOffset) {
+ final bodyOffset = scrollOffset - bodyMinOffset;
+ if (bodyOffset < 0 || rows.isEmpty) return firstIndex;
+ return bodyFirstIndex + _lastRowStartingAtOrBefore(bodyOffset);
+ }
+
+ @override
+ int getMaxChildIndexForScrollOffset(double scrollOffset) {
+ final bodyOffset = scrollOffset - bodyMinOffset;
+ if (bodyOffset <= 0 || rows.isEmpty) return firstIndex;
+ return bodyFirstIndex + _lastRowStartingBefore(bodyOffset);
+ }
+
+ int _lastRowStartingAtOrBefore(double offset) {
+ if (!offset.isFinite) return rows.length - 1;
+ var low = 0;
+ var high = rows.length - 1;
+ var result = 0;
+ while (low <= high) {
+ final mid = (low + high) >>> 1;
+ if (rows[mid].minOffset <= offset) {
+ result = mid;
+ low = mid + 1;
+ } else {
+ high = mid - 1;
+ }
+ }
+ return result;
+ }
+
+ int _lastRowStartingBefore(double offset) {
+ if (!offset.isFinite) return rows.length - 1;
+ var low = 0;
+ var high = rows.length - 1;
+ var result = 0;
+ while (low <= high) {
+ final mid = (low + high) >>> 1;
+ if (rows[mid].minOffset < offset) {
+ result = mid;
+ low = mid + 1;
+ } else {
+ high = mid - 1;
+ }
+ }
+ return result;
+ }
+}
+
+class MosaicLayoutCalculator {
+ static const double _minimumAspectRatio = 0.25;
+ static const double _maximumAspectRatio = 4.0;
+ static const double _maximumRowHeightFactor = 2.4;
+ static const double _minimumTileExtentFactor = 0.62;
+ static const double _rowCompressionThreshold = 0.88;
+
+ const MosaicLayoutCalculator._();
+
+ static double aspectRatioForDimensions(int width, int height) {
+ if (width <= 0 || height <= 0) return 1;
+ return (width / height)
+ .clamp(_minimumAspectRatio, _maximumAspectRatio)
+ .toDouble();
+ }
+
+ static List<MosaicRowLayout> computeRows({
+ required List<double> aspectRatios,
+ required double availableWidth,
+ required double targetRowHeight,
+ required double spacing,
+ }) {
+ if (aspectRatios.isEmpty) return const [];
+ if (!availableWidth.isFinite || availableWidth <= 0) {
+ throw ArgumentError.value(availableWidth, "availableWidth");
+ }
+ if (!targetRowHeight.isFinite || targetRowHeight <= 0) {
+ throw ArgumentError.value(targetRowHeight, "targetRowHeight");
+ }
+ if (!spacing.isFinite || spacing < 0) {
+ throw ArgumentError.value(spacing, "spacing");
+ }
+
+ final normalizedRatios = aspectRatios
+ .map(
+ (ratio) => ratio.isFinite && ratio > 0
+ ? ratio.clamp(_minimumAspectRatio, _maximumAspectRatio).toDouble()
+ : 1.0,
+ )
+ .toList(growable: false);
+ final rows = <MosaicRowLayout>[];
+ final pendingRatios = <double>[];
+ final maximumRowHeight = targetRowHeight * _maximumRowHeightFactor;
+ final minimumTileExtent = targetRowHeight * _minimumTileExtentFactor;
+ var pendingRatioSum = 0.0;
+ var pendingMinimumRatio = double.infinity;
+ var pendingFirstIndex = 0;
+ var rowOffset = 0.0;
+
+ double widthWithoutGaps(int itemCount) =>
+ math.max(1, availableWidth - spacing * (itemCount - 1));
+
+ void addPendingRow({required bool fillWidth}) {
+ if (pendingRatios.isEmpty) return;
+ final contentWidth = widthWithoutGaps(pendingRatios.length);
+ final fittedHeight = contentWidth / pendingRatioSum;
+ final height = fillWidth
+ ? fittedHeight
+ : math.min(targetRowHeight, fittedHeight);
+ final widths = pendingRatios
+ .map((ratio) => ratio * height)
+ .toList(growable: false);
+
+ if (fillWidth && widths.isNotEmpty) {
+ final precedingWidth = widths
+ .take(widths.length - 1)
+ .fold<double>(0, (sum, width) => sum + width);
+ widths[widths.length - 1] = math.max(0, contentWidth - precedingWidth);
+ }
+
+ rows.add(
+ MosaicRowLayout(
+ firstIndex: pendingFirstIndex,
+ lastIndex: pendingFirstIndex + pendingRatios.length - 1,
+ minOffset: rowOffset,
+ height: height,
+ itemWidths: List.unmodifiable(widths),
+ ),
+ );
+ rowOffset += height + spacing;
+ pendingFirstIndex += pendingRatios.length;
+ pendingRatios.clear();
+ pendingRatioSum = 0;
+ pendingMinimumRatio = double.infinity;
+ }
+
+ for (final ratio in normalizedRatios) {
+ if (pendingRatios.isNotEmpty) {
+ final candidateCount = pendingRatios.length + 1;
+ final candidateRatioSum = pendingRatioSum + ratio;
+ final candidateHeight =
+ widthWithoutGaps(candidateCount) / candidateRatioSum;
+ final candidateMinimumWidth =
+ candidateHeight * math.min(pendingMinimumRatio, ratio);
+ final currentHeight =
+ widthWithoutGaps(pendingRatios.length) / pendingRatioSum;
+ final wouldOverCompress =
+ candidateHeight < targetRowHeight * _rowCompressionThreshold ||
+ candidateMinimumWidth < minimumTileExtent;
+
+ if (wouldOverCompress) {
+ addPendingRow(fillWidth: currentHeight <= maximumRowHeight);
+ }
+ }
+
+ pendingRatios.add(ratio);
+ pendingRatioSum += ratio;
+ pendingMinimumRatio = math.min(pendingMinimumRatio, ratio);
+
+ final naturalWidth =
+ pendingRatioSum * targetRowHeight +
+ spacing * (pendingRatios.length - 1);
+ if (naturalWidth >= availableWidth) {
+ addPendingRow(fillWidth: true);
+ }
+ }
+
+ addPendingRow(fillWidth: false);
+ return List.unmodifiable(rows);
+ }
+}
diff --git a/mobile/apps/photos/lib/models/gallery/section_layout.dart b/mobile/apps/photos/lib/models/gallery/section_layout.dart
new file mode 100644
index 0000000000..d64b2c2f28
--- /dev/null
+++ b/mobile/apps/photos/lib/models/gallery/section_layout.dart
@@ -0,0 +1,78 @@
+import "package:flutter/material.dart";
+
+abstract class SectionLayout {
+ final int firstIndex;
+ final int lastIndex;
+ final int bodyFirstIndex;
+ final double minOffset;
+ final double maxOffset;
+ final double bodyMinOffset;
+ final double headerExtent;
+ final double spacing;
+ final IndexedWidgetBuilder builder;
+
+ const SectionLayout({
+ required this.firstIndex,
+ required this.lastIndex,
+ required this.minOffset,
+ required this.maxOffset,
+ required this.headerExtent,
+ required this.spacing,
+ required this.builder,
+ }) : bodyFirstIndex = firstIndex + 1,
+ bodyMinOffset = minOffset + headerExtent;
+
+ bool hasChild(int index) => firstIndex <= index && index <= lastIndex;
+
+ bool hasChildAtOffset(double scrollOffset) =>
+ minOffset <= scrollOffset && scrollOffset <= maxOffset;
+
+ double indexToLayoutOffset(int index);
+
+ int getMinChildIndexForScrollOffset(double scrollOffset);
+
+ int getMaxChildIndexForScrollOffset(double scrollOffset);
+}
+
+extension SectionLayoutList<T extends SectionLayout> on List<T> {
+ T? sectionForIndex(int index) {
+ if (isEmpty) return null;
+ var low = 0;
+ var high = length - 1;
+ while (low <= high) {
+ final mid = (low + high) >>> 1;
+ final section = this[mid];
+ if (index < section.firstIndex) {
+ high = mid - 1;
+ } else if (index > section.lastIndex) {
+ low = mid + 1;
+ } else {
+ return section;
+ }
+ }
+ return null;
+ }
+
+ T? sectionForOffset(double scrollOffset) {
+ if (isEmpty) return null;
+ if (scrollOffset <= first.minOffset || scrollOffset.isNaN) return first;
+
+ // Sections are contiguous and share their boundary offset. Resolve an
+ // exact boundary to the section that starts there so callers do not
+ // anchor or lay out the final row of the preceding section.
+ var low = 0;
+ var high = length - 1;
+ var result = first;
+ while (low <= high) {
+ final mid = (low + high) >>> 1;
+ final section = this[mid];
+ if (section.minOffset <= scrollOffset) {
+ result = section;
+ low = mid + 1;
+ } else {
+ high = mid - 1;
+ }
+ }
+ return result;
+ }
+}
diff --git a/mobile/apps/photos/lib/settings/local_settings.dart b/mobile/apps/photos/lib/settings/local_settings.dart
index 7e98e37eaa..d0fe908526 100644
--- a/mobile/apps/photos/lib/settings/local_settings.dart
+++ b/mobile/apps/photos/lib/settings/local_settings.dart
@@ -14,6 +14,8 @@ enum AlbumSortDirection { ascending, descending }
enum AlbumViewType { grid, list }
+enum GalleryLayoutType { grid, mosaic }
+
enum PeopleSortKey { mostPhotos, name, lastUpdated }
// Stored as bit positions. Append only; never reorder or remove values.
@@ -55,6 +57,7 @@ enum DeletePreference {
class LocalSettings {
static const kCollectionSortPref = "collection_sort_pref";
static const kGalleryGroupType = "gallery_group_type";
+ static const kGalleryLayoutType = "gallery_layout_type";
static const kPhotoGridSize = "photo_grid_size";
static const _kisMLLocalIndexingEnabled = "ls.ml_local_indexing";
static const _kLocalGalleryMLLocalIndexingEnabled =
@@ -261,6 +264,17 @@ class LocalSettings {
await _prefs.setString(kGalleryGroupType, groupType.toString());
}
+ GalleryLayoutType getGalleryLayoutType() {
+ return switch (_prefs.getString(kGalleryLayoutType)) {
+ "mosaic" => GalleryLayoutType.mosaic,
+ _ => GalleryLayoutType.grid,
+ };
+ }
+
+ Future<void> setGalleryLayoutType(GalleryLayoutType layoutType) async {
+ await _prefs.setString(kGalleryLayoutType, layoutType.name);
+ }
+
int getPhotoGridSize() {
if (_prefs.containsKey(kPhotoGridSize)) {
return _prefs.getInt(kPhotoGridSize)!;
diff --git a/mobile/apps/photos/lib/ui/settings/gallery_settings_screen.dart b/mobile/apps/photos/lib/ui/settings/gallery_settings_screen.dart
index 8f283c2c3d..2f6aa6b91d 100644
--- a/mobile/apps/photos/lib/ui/settings/gallery_settings_screen.dart
+++ b/mobile/apps/photos/lib/ui/settings/gallery_settings_screen.dart
@@ -3,9 +3,10 @@ import "package:ente_strings/ente_strings.dart";
import "package:flutter/material.dart";
import "package:photos/core/constants.dart";
import "package:photos/core/event_bus.dart";
-import "package:photos/events/force_reload_home_gallery_event.dart";
+import "package:photos/events/gallery_layout_changed_event.dart";
import "package:photos/events/hide_shared_items_from_home_gallery_event.dart";
import "package:photos/service_locator.dart";
+import "package:photos/settings/local_settings.dart";
import "package:photos/ui/viewer/gallery/component/group/type.dart";
class GallerySettingsScreen extends StatefulWidget {
@@ -20,12 +21,14 @@ class GallerySettingsScreen extends StatefulWidget {
}
class _GallerySettingsScreenState extends State<GallerySettingsScreen> {
+ late GalleryLayoutType _layoutType;
late int _photoGridSize;
late GroupType _groupType;
@override
void initState() {
super.initState();
+ _layoutType = localSettings.getGalleryLayoutType();
_photoGridSize = localSettings.getPhotoGridSize();
_groupType = localSettings.getGalleryGroupType();
}
@@ -37,6 +40,15 @@ class _GallerySettingsScreenState extends State<GallerySettingsScreen> {
return SettingsPageScaffold(
title: l10n.gallery,
children: [
+ SettingsItem(
+ title: l10n.layout,
+ trailing: _trailingLabel(
+ context,
+ _layoutTypeLabel(context, _layoutType),
+ ),
+ onTap: () async => _showLayoutTypeSheet(context),
+ ),
+ const SizedBox(height: 8),
SettingsItem(
title: l10n.photoGridSize,
trailing: _trailingLabel(context, _photoGridSize.toString()),
@@ -84,6 +96,55 @@ class _GallerySettingsScreenState extends State<GallerySettingsScreen> {
);
}
+ String _layoutTypeLabel(BuildContext context, GalleryLayoutType layoutType) {
+ return switch (layoutType) {
+ GalleryLayoutType.grid => context.strings.grid,
+ GalleryLayoutType.mosaic => context.strings.layoutMasonry,
+ };
+ }
+
+ Future<void> _showLayoutTypeSheet(BuildContext context) async {
+ final l10n = context.strings;
+ await showBottomSheetComponent<void>(
+ context: context,
+ builder: (sheetContext) => BottomSheetComponent(
+ title: l10n.layout,
+ content: MenuGroupComponent(
+ items: [
+ for (final layoutType in GalleryLayoutType.values)
+ MenuComponent(
+ key: ValueKey(layoutType),
+ title: _layoutTypeLabel(sheetContext, layoutType),
+ trailing: _layoutType == layoutType
+ ? Icon(
+ Icons.check,
+ color: sheetContext.componentColors.primary,
+ )
+ : null,
+ onTap: () async {
+ await _setLayoutType(layoutType);
+ if (sheetContext.mounted) {
+ Navigator.of(sheetContext).pop();
+ }
+ },
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Future<void> _setLayoutType(GalleryLayoutType layoutType) async {
+ if (localSettings.getGalleryLayoutType() == layoutType) return;
+ await localSettings.setGalleryLayoutType(layoutType);
+ if (mounted) {
+ setState(() {
+ _layoutType = layoutType;
+ });
+ }
+ Bus.instance.fire(GalleryLayoutChangedEvent());
+ }
+
Future<void> _showPhotoGridSizeSheet(BuildContext context) async {
final l10n = context.strings;
await showBottomSheetComponent<void>(
@@ -120,13 +181,14 @@ class _GallerySettingsScreenState extends State<GallerySettingsScreen> {
}
Future<void> _setPhotoGridSize(int gridSize) async {
+ if (localSettings.getPhotoGridSize() == gridSize) return;
await localSettings.setPhotoGridSize(gridSize);
if (mounted) {
setState(() {
_photoGridSize = gridSize;
});
}
- Bus.instance.fire(ForceReloadHomeGalleryEvent("grid size changed"));
+ Bus.instance.fire(GalleryLayoutChangedEvent());
}
Future<void> _showGroupTypeSheet(BuildContext context) async {
@@ -167,12 +229,13 @@ class _GallerySettingsScreenState extends State<GallerySettingsScreen> {
}
Future<void> _setGroupType(GroupType groupType) async {
+ if (localSettings.getGalleryGroupType() == groupType) return;
await localSettings.setGalleryGroupType(groupType);
if (mounted) {
setState(() {
_groupType = groupType;
});
}
- Bus.instance.fire(ForceReloadHomeGalleryEvent("group type changed"));
+ Bus.instance.fire(GalleryLayoutChangedEvent());
}
}
diff --git a/mobile/apps/photos/lib/ui/settings/search/settings_search_registry.dart b/mobile/apps/photos/lib/ui/settings/search/settings_search_registry.dart
index 0392d15212..66c1182d84 100644
--- a/mobile/apps/photos/lib/ui/settings/search/settings_search_registry.dart
+++ b/mobile/apps/photos/lib/ui/settings/search/settings_search_registry.dart
@@ -315,7 +315,20 @@ class SettingsSearchRegistry {
routeBuilder: (_) =>
const GallerySettingsScreen(fromGalleryLayoutSettingsCTA: false),
isSubPage: true,
- keywords: ["grid size", "group by", "layout"],
+ keywords: ["grid size", "group by", "layout", "masonry", "mosaic"],
+ ),
+ );
+
+ items.add(
+ SettingsSearchItem(
+ title: l10n.layout,
+ subtitle: l10n.gallery,
+ sectionPath: "${l10n.appearance} > ${l10n.gallery}",
+ icon: HugeIcons.strokeRoundedDashboardSquare02,
+ routeBuilder: (_) =>
+ const GallerySettingsScreen(fromGalleryLayoutSettingsCTA: false),
+ isSubPage: true,
+ keywords: ["layout", "grid", "masonry", "mosaic", "justified"],
),
);
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 547fab91cd..ced133b00d 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
@@ -31,6 +31,7 @@ class GalleryFileWidget extends StatefulWidget {
final bool limitSelectionToOne;
final String tag;
final int photoGridSize;
+ final int? thumbnailSize;
final int? currentUserID;
const GalleryFileWidget({
required this.file,
@@ -38,6 +39,7 @@ class GalleryFileWidget extends StatefulWidget {
required this.limitSelectionToOne,
required this.tag,
required this.photoGridSize,
+ this.thumbnailSize,
required this.currentUserID,
super.key,
});
@@ -113,15 +115,20 @@ class _GalleryFileWidgetState extends State<GalleryFileWidget> {
selectionColor = getUserAvatarColor(context, owner);
}
final String heroTag = widget.tag + widget.file.tag;
+ final effectiveThumbnailSize =
+ widget.thumbnailSize ??
+ (widget.photoGridSize < photoGridSizeDefault
+ ? thumbnailLargeSize
+ : thumbnailSmallSize);
final Widget thumbnailWidget = ThumbnailWidget(
widget.file,
diskLoadDeferDuration: galleryThumbnailDiskLoadDeferDuration,
serverLoadDeferDuration: galleryThumbnailServerLoadDeferDuration,
shouldShowLivePhotoOverlay: true,
- key: Key(heroTag),
- thumbnailSize: widget.photoGridSize < photoGridSizeDefault
- ? thumbnailLargeSize
- : thumbnailSmallSize,
+ // Recreate the loader when a mosaic tile crosses thumbnail tiers.
+ key: ValueKey((heroTag, effectiveThumbnailSize)),
+ thumbnailSize: effectiveThumbnailSize,
+ useRequestedThumbnailSizeForLocalCache: widget.thumbnailSize != null,
shouldShowOwnerAvatar: !_isFileSelected,
ownerAvatarType: widget.photoGridSize < photoGridSizeMax
? AvatarType.small
diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/component/sectioned_sliver_list.dart b/mobile/apps/photos/lib/ui/viewer/gallery/component/sectioned_sliver_list.dart
index 29e745ebd6..abcda3c7b5 100644
--- a/mobile/apps/photos/lib/ui/viewer/gallery/component/sectioned_sliver_list.dart
+++ b/mobile/apps/photos/lib/ui/viewer/gallery/component/sectioned_sliver_list.dart
@@ -3,7 +3,7 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
-import "package:photos/models/gallery/fixed_extent_section_layout.dart";
+import "package:photos/models/gallery/section_layout.dart";
// Based on code from https://github.com/deckerst/aves
// Copyright (c) 2020-2023 Thibault Deckers and contributors
@@ -18,7 +18,7 @@ import "package:photos/models/gallery/fixed_extent_section_layout.dart";
// https://github.com/flutter/flutter/issues/95028
class SectionedListSliver<T> extends StatelessWidget {
- final List<FixedExtentSectionLayout> sectionLayouts;
+ final List<SectionLayout> sectionLayouts;
const SectionedListSliver({super.key, required this.sectionLayouts});
@override
@@ -43,7 +43,7 @@ class SectionedListSliver<T> extends StatelessWidget {
}
class _SliverKnownExtentList extends SliverMultiBoxAdaptorWidget {
- final List<FixedExtentSectionLayout> sectionLayouts;
+ final List<SectionLayout> sectionLayouts;
const _SliverKnownExtentList({
required super.delegate,
@@ -69,11 +69,11 @@ class _SliverKnownExtentList extends SliverMultiBoxAdaptorWidget {
}
class _RenderSliverKnownExtentBoxAdaptor extends RenderSliverMultiBoxAdaptor {
- List<FixedExtentSectionLayout> _sectionLayouts;
+ List<SectionLayout> _sectionLayouts;
- List<FixedExtentSectionLayout> get sectionLayouts => _sectionLayouts;
+ List<SectionLayout> get sectionLayouts => _sectionLayouts;
- set sectionLayouts(List<FixedExtentSectionLayout> value) {
+ set sectionLayouts(List<SectionLayout> value) {
if (_sectionLayouts == value) return;
_sectionLayouts = value;
markNeedsLayout();
@@ -81,13 +81,13 @@ class _RenderSliverKnownExtentBoxAdaptor extends RenderSliverMultiBoxAdaptor {
_RenderSliverKnownExtentBoxAdaptor({
required super.childManager,
- required List<FixedExtentSectionLayout> sectionLayouts,
+ required List<SectionLayout> sectionLayouts,
}) : _sectionLayouts = sectionLayouts;
- FixedExtentSectionLayout? sectionAtIndex(int index) =>
+ SectionLayout? sectionAtIndex(int index) =>
sectionLayouts.sectionForIndex(index);
- FixedExtentSectionLayout? sectionAtOffset(double scrollOffset) =>
+ SectionLayout? sectionAtOffset(double scrollOffset) =>
sectionLayouts.sectionForOffset(scrollOffset);
double indexToLayoutOffset(int index) {
diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/gallery.dart b/mobile/apps/photos/lib/ui/viewer/gallery/gallery.dart
index 7e3f958a20..09da06d34d 100644
--- a/mobile/apps/photos/lib/ui/viewer/gallery/gallery.dart
+++ b/mobile/apps/photos/lib/ui/viewer/gallery/gallery.dart
@@ -12,6 +12,7 @@ import 'package:photos/core/constants.dart';
import 'package:photos/core/event_bus.dart';
import 'package:photos/events/event.dart';
import 'package:photos/events/files_updated_event.dart';
+import "package:photos/events/gallery_layout_changed_event.dart";
import "package:photos/events/homepage_swipe_to_select_in_progress_event.dart";
import 'package:photos/events/local_photos_updated_event.dart';
import 'package:photos/events/tab_changed_event.dart';
@@ -49,6 +50,8 @@ typedef GalleryLoader =
bool? asc,
});
+typedef _LayoutScrollAnchor = ({EnteFile file, bool inHeader, double progress});
+
typedef SortAscFn = bool Function();
typedef NewLocalFilesResolver =
@@ -150,10 +153,12 @@ class GalleryState extends State<Gallery> {
bool _allFilesLoaded = false;
bool _completedJumpToDate = false;
StreamSubscription<FilesUpdatedEvent>? _reloadEventSubscription;
+ StreamSubscription<GalleryLayoutChangedEvent>? _layoutChangeSubscription;
StreamSubscription<TabDoubleTapEvent>? _tabDoubleTapEvent;
final _forceReloadEventSubscriptions = <StreamSubscription<Event>>[];
late String _logTag;
bool _sortOrderAsc = false;
+ int _layoutChangeGeneration = 0;
int _activeFileLoads = 0;
List<EnteFile> _allGalleryFiles = [];
final _scrollController = ScrollController();
@@ -197,6 +202,20 @@ class GalleryState extends State<Gallery> {
widget.priorityReloadDebounceTime,
leading: true,
);
+ _layoutChangeSubscription = Bus.instance
+ .on<GalleryLayoutChangedEvent>()
+ .listen((event) async {
+ if (!mounted) return;
+ final generation = ++_layoutChangeGeneration;
+ final scrollAnchor = _captureLayoutScrollAnchor();
+ _logger.info("Rebuilding gallery for ${event.reason}");
+ _setGroupType();
+ final measuredHeaderExtent = await _measureGroupHeaderExtent();
+ if (!mounted || generation != _layoutChangeGeneration) return;
+ groupHeaderExtent = measuredHeaderExtent;
+ _updateGalleryGroups();
+ _restoreLayoutScrollAnchor(scrollAnchor, generation);
+ });
_sortOrderAsc = widget.sortAsyncFn != null ? widget.sortAsyncFn!() : false;
if (widget.reloadEvent != null) {
_reloadEventSubscription = widget.reloadEvent!.listen((event) async {
@@ -288,19 +307,11 @@ class GalleryState extends State<Gallery> {
});
if (_groupType.showGroupHeader()) {
- getIntrinsicSizeOfWidget(
- GroupHeaderWidget(
- title: "Dummy title",
- gridSize: localSettings.getPhotoGridSize(),
- filesInGroup: const [],
- selectedFiles: null,
- showSelectAll: false,
- ),
- context,
- ).then((size) {
- if (!mounted) return;
+ final generation = _layoutChangeGeneration;
+ _measureGroupHeaderExtent().then((extent) {
+ if (!mounted || generation != _layoutChangeGeneration) return;
setState(() {
- groupHeaderExtent = size.height;
+ groupHeaderExtent = extent;
_updateGalleryGroups(callSetState: false);
});
});
@@ -392,6 +403,78 @@ class GalleryState extends State<Gallery> {
}
}
+ _LayoutScrollAnchor? _captureLayoutScrollAnchor() {
+ final groups = galleryGroups;
+ if (groups == null || _scrollController.positions.length != 1) return null;
+ final appBarCollapseExtent =
+ widget.appBar?.resolveGeometry(context).collapseExtent ?? 0;
+ final sectionScrollOffset =
+ _scrollController.offset - appBarCollapseExtent - _headerHeight;
+ if (sectionScrollOffset < 0) return null;
+ final file = groups.getFileAtScrollOffset(sectionScrollOffset);
+ if (file == null) return null;
+ final geometry = groups.getGeometryOfFile(file);
+ if (geometry == null) return null;
+
+ final inHeader = sectionScrollOffset < geometry.rowOffset;
+ final offset = inHeader
+ ? geometry.rowOffset - sectionScrollOffset
+ : sectionScrollOffset - geometry.rowOffset;
+ final extent = inHeader ? geometry.headerExtent : geometry.rowExtent;
+ final progress = extent > 0 && extent.isFinite
+ ? (offset / extent).clamp(0.0, 1.0).toDouble()
+ : 0.0;
+ return (file: file, inHeader: inHeader, progress: progress);
+ }
+
+ void _restoreLayoutScrollAnchor(_LayoutScrollAnchor? anchor, int generation) {
+ if (anchor == null) return;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted ||
+ generation != _layoutChangeGeneration ||
+ _scrollController.positions.length != 1) {
+ return;
+ }
+ final geometry = galleryGroups?.getGeometryOfFile(anchor.file);
+ if (geometry == null) return;
+ final appBarCollapseExtent =
+ widget.appBar?.resolveGeometry(context).collapseExtent ?? 0;
+ final maxRowPenetration = geometry.rowExtent > precisionErrorTolerance
+ ? geometry.rowExtent - precisionErrorTolerance
+ : 0.0;
+ final rowPenetration = (geometry.rowExtent * anchor.progress)
+ .clamp(0.0, maxRowPenetration)
+ .toDouble();
+ final sectionOffset = anchor.inHeader
+ ? geometry.rowOffset - geometry.headerExtent * anchor.progress
+ : geometry.rowOffset + rowPenetration;
+ final targetOffset =
+ _scrollOffsetForSectionOffset(
+ sectionOffset,
+ appBarCollapseExtent,
+ ).clamp(
+ _scrollController.position.minScrollExtent,
+ _scrollController.position.maxScrollExtent,
+ );
+ _scrollController.jumpTo(targetOffset);
+ });
+ }
+
+ Future<double> _measureGroupHeaderExtent() async {
+ if (!_groupType.showGroupHeader()) return GalleryGroups.spacing;
+ final size = await getIntrinsicSizeOfWidget(
+ GroupHeaderWidget(
+ title: "Dummy title",
+ gridSize: localSettings.getPhotoGridSize(),
+ filesInGroup: const [],
+ selectedFiles: null,
+ showSelectAll: false,
+ ),
+ context,
+ );
+ return size.height;
+ }
+
void _selectedFilesListener() {
final bottomInset = MediaQuery.paddingOf(context).bottom;
final extra = widget.galleryType == GalleryType.homepage ? 76.0 : 0.0;
@@ -639,6 +722,7 @@ class GalleryState extends State<Gallery> {
_boundariesProvider?.setScrollController(null);
_reloadEventSubscription?.cancel();
+ _layoutChangeSubscription?.cancel();
_tabDoubleTapEvent?.cancel();
for (final subscription in _forceReloadEventSubscriptions) {
subscription.cancel();
@@ -1187,7 +1271,7 @@ class _PinnedGroupHeaderState extends State<PinnedGroupHeader>
.groupIDToFilesMap[currentGroupId]!
.first,
),
- gridSize: localSettings.getPhotoGridSize(),
+ gridSize: widget.galleryGroups.crossAxisCount,
height: widget.galleryGroups.groupHeaderExtent,
filesInGroup: widget
.galleryGroups
diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/layout_settings.dart b/mobile/apps/photos/lib/ui/viewer/gallery/layout_settings.dart
index c0e290d82b..288fee6020 100644
--- a/mobile/apps/photos/lib/ui/viewer/gallery/layout_settings.dart
+++ b/mobile/apps/photos/lib/ui/viewer/gallery/layout_settings.dart
@@ -5,8 +5,9 @@ import "package:ente_pure_utils/ente_pure_utils.dart";
import "package:ente_strings/ente_strings.dart";
import "package:flutter/material.dart";
import "package:photos/core/event_bus.dart";
-import "package:photos/events/force_reload_home_gallery_event.dart";
+import "package:photos/events/gallery_layout_changed_event.dart";
import "package:photos/service_locator.dart";
+import "package:photos/settings/local_settings.dart";
import "package:photos/ui/settings/gallery_settings_screen.dart";
import "package:photos/ui/viewer/gallery/component/group/type.dart";
@@ -19,21 +20,29 @@ class GalleryLayoutSettings extends StatefulWidget {
class _GalleryLayoutSettingsState extends State<GalleryLayoutSettings> {
bool isDayLayout =
+ localSettings.getGalleryLayoutType() == GalleryLayoutType.grid &&
localSettings.getGalleryGroupType() == GroupType.day &&
localSettings.getPhotoGridSize() == 3;
bool isMonthLayout =
+ localSettings.getGalleryLayoutType() == GalleryLayoutType.grid &&
localSettings.getGalleryGroupType() == GroupType.month &&
localSettings.getPhotoGridSize() == 5;
+ bool isMosaicLayout =
+ localSettings.getGalleryLayoutType() == GalleryLayoutType.mosaic;
void _reloadWithLatestSetting() {
if (!mounted) return;
setState(() {
isDayLayout =
+ localSettings.getGalleryLayoutType() == GalleryLayoutType.grid &&
localSettings.getGalleryGroupType() == GroupType.day &&
localSettings.getPhotoGridSize() == 3;
isMonthLayout =
+ localSettings.getGalleryLayoutType() == GalleryLayoutType.grid &&
localSettings.getGalleryGroupType() == GroupType.month &&
localSettings.getPhotoGridSize() == 5;
+ isMosaicLayout =
+ localSettings.getGalleryLayoutType() == GalleryLayoutType.mosaic;
});
}
@@ -62,12 +71,21 @@ class _GalleryLayoutSettingsState extends State<GalleryLayoutSettings> {
showOnlyLoadingState: true,
onTap: () => _applyLayout(GroupType.month, 5),
),
+ MenuComponent(
+ title: context.strings.layoutMasonry,
+ leading: const Icon(Icons.view_quilt_outlined),
+ trailing: isMosaicLayout
+ ? Icon(Icons.check, color: colors.primary)
+ : null,
+ showOnlyLoadingState: true,
+ onTap: _applyMosaicLayout,
+ ),
MenuComponent(
title: context.strings.custom,
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
- if (!isDayLayout && !isMonthLayout) ...[
+ if (!isDayLayout && !isMonthLayout && !isMosaicLayout) ...[
Icon(Icons.check, color: colors.primary),
const SizedBox(width: 8),
],
@@ -90,11 +108,28 @@ class _GalleryLayoutSettingsState extends State<GalleryLayoutSettings> {
}
Future<void> _applyLayout(GroupType groupType, int gridSize) async {
- await Future.wait([
- localSettings.setGalleryGroupType(groupType),
- localSettings.setPhotoGridSize(gridSize),
- ]);
- Bus.instance.fire(ForceReloadHomeGalleryEvent("Gallery layout changed"));
+ final alreadyApplied =
+ localSettings.getGalleryLayoutType() == GalleryLayoutType.grid &&
+ localSettings.getGalleryGroupType() == groupType &&
+ localSettings.getPhotoGridSize() == gridSize;
+ if (!alreadyApplied) {
+ await Future.wait([
+ localSettings.setGalleryLayoutType(GalleryLayoutType.grid),
+ localSettings.setGalleryGroupType(groupType),
+ localSettings.setPhotoGridSize(gridSize),
+ ]);
+ Bus.instance.fire(GalleryLayoutChangedEvent());
+ }
+
+ if (!mounted) return;
+ Navigator.pop(context);
+ }
+
+ Future<void> _applyMosaicLayout() async {
+ if (localSettings.getGalleryLayoutType() != GalleryLayoutType.mosaic) {
+ await localSettings.setGalleryLayoutType(GalleryLayoutType.mosaic);
+ Bus.instance.fire(GalleryLayoutChangedEvent());
+ }
if (!mounted) return;
Navigator.pop(context);
diff --git a/mobile/apps/photos/test/models/ente_file_dimensions_test.dart b/mobile/apps/photos/test/models/ente_file_dimensions_test.dart
new file mode 100644
index 0000000000..41d8cbda1e
--- /dev/null
+++ b/mobile/apps/photos/test/models/ente_file_dimensions_test.dart
@@ -0,0 +1,35 @@
+import "package:flutter_test/flutter_test.dart";
+import "package:photos/models/file/file.dart";
+import "package:photos/models/metadata/file_magic.dart";
+
+void main() {
+ test("dimensions are decoded directly from public metadata", () {
+ final file = EnteFile()
+ ..pubMmdEncodedJson = '{"caption":"hello","w":4032,"h":"3024"}';
+
+ expect(file.width, 4032);
+ expect(file.height, 3024);
+ expect(file.pubMmdEncodedJson, contains('"caption":"hello"'));
+ });
+
+ test("dimension cache is invalidated when encoded metadata changes", () {
+ final file = EnteFile()..pubMmdEncodedJson = '{"w":10,"h":20}';
+ expect((file.width, file.height), (10, 20));
+
+ file.pubMmdEncodedJson = '{"w":30,"h":40}';
+ expect((file.width, file.height), (30, 40));
+ });
+
+ test("decoded public metadata supplies and updates dimensions", () {
+ final file = EnteFile()..pubMagicMetadata = PubMagicMetadata(w: 50, h: 60);
+ expect((file.width, file.height), (50, 60));
+
+ file.pubMagicMetadata = PubMagicMetadata(w: 70, h: 80);
+ expect((file.width, file.height), (70, 80));
+ });
+
+ test("missing dimensions use zero", () {
+ final file = EnteFile()..pubMmdEncodedJson = '{"caption":"hello"}';
+ expect((file.width, file.height), (0, 0));
+ });
+}
diff --git a/mobile/apps/photos/test/models/gallery_groups_mosaic_test.dart b/mobile/apps/photos/test/models/gallery_groups_mosaic_test.dart
new file mode 100644
index 0000000000..d951e71c2e
--- /dev/null
+++ b/mobile/apps/photos/test/models/gallery_groups_mosaic_test.dart
@@ -0,0 +1,242 @@
+import "package:dio/dio.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/gallery_groups.dart";
+import "package:photos/models/gallery/mosaic_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",
+ ),
+ );
+
+ // GalleryGroups only reads Configuration's preferences-backed user ID.
+ // The remaining plugin initialization is unavailable in unit tests.
+ try {
+ await Configuration.instance.init(preferences);
+ } catch (_) {}
+ });
+
+ setUp(() async {
+ await localSettings.setGalleryLayoutType(GalleryLayoutType.mosaic);
+ await localSettings.setPhotoGridSize(4);
+ });
+
+ test("day grouping creates independent, contiguous mosaic sections", () {
+ for (final sortOrderAsc in [false, true]) {
+ final days = sortOrderAsc ? [17, 18, 19] : [19, 18, 17];
+ final expectedGroups = <List<EnteFile>>[];
+ final files = <EnteFile>[];
+ var fileIndex = 0;
+ for (final day in days) {
+ final filesForDay = List<EnteFile>.generate(5, (index) {
+ final isPortrait = index.isEven;
+ return _file(
+ index: fileIndex++,
+ creationTime: DateTime(2026, 8, day).microsecondsSinceEpoch,
+ width: isPortrait ? 100 : 400,
+ height: isPortrait ? 400 : 100,
+ );
+ }, growable: false);
+ expectedGroups.add(filesForDay);
+ files.addAll(filesForDay);
+ }
+
+ final groups = _galleryGroups(
+ files: files,
+ groupType: GroupType.day,
+ groupHeaderExtent: 48,
+ sortOrderAsc: sortOrderAsc,
+ );
+
+ expect(groups.groupIDs, hasLength(expectedGroups.length));
+ expect(groups.groupLayouts, hasLength(expectedGroups.length));
+ var expectedFirstChildIndex = 0;
+ var expectedSectionOffset = 0.0;
+
+ for (
+ var groupIndex = 0;
+ groupIndex < expectedGroups.length;
+ groupIndex++
+ ) {
+ final expectedFiles = expectedGroups[groupIndex];
+ final groupID = groups.groupIDs[groupIndex];
+ final section = groups.groupLayouts[groupIndex];
+
+ expect(section, isA<MosaicSectionLayout>());
+ final mosaicSection = section as MosaicSectionLayout;
+ expect(groups.groupIDToFilesMap[groupID], orderedEquals(expectedFiles));
+ expect(mosaicSection.firstIndex, expectedFirstChildIndex);
+ expect(mosaicSection.minOffset, closeTo(expectedSectionOffset, 1e-9));
+ expect(mosaicSection.headerExtent, 48);
+ _expectRowsCoverFiles(mosaicSection, expectedFiles.length);
+ expect(
+ groups.getFileAtScrollOffset(mosaicSection.minOffset),
+ same(expectedFiles.first),
+ reason: "a shared section boundary belongs to the next section",
+ );
+ if (groupIndex > 0) {
+ expect(
+ groups.groupLayouts[groupIndex - 1].maxOffset,
+ mosaicSection.minOffset,
+ );
+ }
+
+ for (final file in expectedFiles) {
+ final fileOffset = groups.getOffsetOfFile(file);
+ expect(fileOffset, isNotNull);
+ expect(groups.getFileAtScrollOffset(fileOffset!), same(file));
+ expect(
+ groups.getOffsetOfGroupContainingFile(file),
+ closeTo(mosaicSection.minOffset, 1e-9),
+ );
+ }
+
+ expectedFirstChildIndex = mosaicSection.lastIndex + 1;
+ expectedSectionOffset = mosaicSection.maxOffset;
+ }
+ }
+ });
+
+ test("headerless mosaic remains one continuous group past grid chunks", () {
+ const fileCount = 100;
+ final files = List<EnteFile>.generate(
+ fileCount,
+ (index) => _file(
+ index: index,
+ creationTime: DateTime(2026, 8, 19).microsecondsSinceEpoch,
+ width: 3,
+ height: 2,
+ ),
+ growable: false,
+ );
+
+ final groups = _galleryGroups(
+ files: files,
+ groupType: GroupType.none,
+ groupHeaderExtent: GalleryGroups.spacing,
+ );
+
+ expect(groups.groupIDs, hasLength(1));
+ expect(groups.groupLayouts, hasLength(1));
+ expect(groups.groupIDToFilesMap.values.single, orderedEquals(files));
+ expect(groups.allFilesWithDummies, hasLength(fileCount));
+ for (var index = 0; index < fileCount; index++) {
+ expect(groups.allFilesWithDummies[index], same(files[index]));
+ expect(groups.allFilesWithDummies[index], isNot(isA<DummyFile>()));
+ }
+
+ final section = groups.groupLayouts.single as MosaicSectionLayout;
+ expect(section.headerExtent, GalleryGroups.spacing);
+ expect(section.bodyMinOffset, GalleryGroups.spacing);
+ _expectRowsCoverFiles(section, fileCount);
+
+ final rowAcrossLegacyBoundary = section.rows.singleWhere(
+ (row) => row.firstIndex <= 39 && row.lastIndex >= 40,
+ );
+ expect(rowAcrossLegacyBoundary.firstIndex, 39);
+ expect(rowAcrossLegacyBoundary.lastIndex, 41);
+
+ for (final index in [75, fileCount - 1]) {
+ final fileOffset = groups.getOffsetOfFile(files[index]);
+ expect(fileOffset, isNotNull);
+ expect(groups.getFileAtScrollOffset(fileOffset!), same(files[index]));
+ }
+ expect(groups.getFileAtScrollOffset(section.maxOffset), same(files.last));
+ });
+
+ test("file geometry survives replacement with the same stable identity", () {
+ final files = List<EnteFile>.generate(
+ 20,
+ (index) => _file(
+ index: index,
+ creationTime: DateTime(2026, 8, 19).microsecondsSinceEpoch,
+ width: 3,
+ height: 2,
+ ),
+ growable: false,
+ );
+ final original = files[13]..localID = "local-13";
+ final groups = _galleryGroups(
+ files: files,
+ groupType: GroupType.none,
+ groupHeaderExtent: GalleryGroups.spacing,
+ );
+ final originalGeometry = groups.getGeometryOfFile(original);
+
+ final replacement = EnteFile.from(original)..uploadedFileID = 1013;
+ expect(replacement, isNot(same(original)));
+ expect(replacement == original, isFalse);
+ expect(groups.getGeometryOfFile(replacement), originalGeometry);
+ expect(groups.getOffsetOfFile(replacement), originalGeometry?.rowOffset);
+ });
+}
+
+GalleryGroups _galleryGroups({
+ required List<EnteFile> files,
+ required GroupType groupType,
+ required double groupHeaderExtent,
+ bool sortOrderAsc = false,
+}) {
+ return GalleryGroups(
+ allFiles: files,
+ groupType: groupType,
+ sortOrderAsc: sortOrderAsc,
+ widthAvailable: 430,
+ selectedFiles: null,
+ tagPrefix: "test_",
+ groupHeaderExtent: groupHeaderExtent,
+ showSelectAll: false,
+ );
+}
+
+EnteFile _file({
+ required int index,
+ required int creationTime,
+ required int width,
+ required int height,
+}) {
+ return EnteFile()
+ ..generatedID = index + 1
+ ..creationTime = creationTime
+ ..fileType = FileType.image
+ ..pubMagicMetadata = PubMagicMetadata(w: width, h: height);
+}
+
+void _expectRowsCoverFiles(MosaicSectionLayout section, int fileCount) {
+ expect(section.rows, isNotEmpty);
+ var expectedFirstFileIndex = 0;
+ var expectedRowOffset = 0.0;
+ for (final row in section.rows) {
+ expect(row.firstIndex, expectedFirstFileIndex);
+ expect(row.lastIndex, greaterThanOrEqualTo(row.firstIndex));
+ expect(row.itemWidths, hasLength(row.lastIndex - row.firstIndex + 1));
+ expect(row.minOffset, closeTo(expectedRowOffset, 1e-9));
+ expectedFirstFileIndex = row.lastIndex + 1;
+ expectedRowOffset = row.maxOffset + GalleryGroups.spacing;
+ }
+ expect(expectedFirstFileIndex, fileCount);
+ expect(section.rows.last.lastIndex, fileCount - 1);
+}
diff --git a/mobile/apps/photos/test/models/mosaic_grid_row_test.dart b/mobile/apps/photos/test/models/mosaic_grid_row_test.dart
new file mode 100644
index 0000000000..319d1a3973
--- /dev/null
+++ b/mobile/apps/photos/test/models/mosaic_grid_row_test.dart
@@ -0,0 +1,96 @@
+import "package:flutter/material.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:photos/models/gallery/mosaic_grid_row.dart";
+
+void main() {
+ testWidgets(
+ "MosaicGridRow gives children their precomputed sizes and offsets",
+ (tester) async {
+ const rowKey = ValueKey("row");
+ const firstKey = ValueKey("first");
+ const secondKey = ValueKey("second");
+ const thirdKey = ValueKey("third");
+
+ await tester.pumpWidget(
+ const MaterialApp(
+ home: Scaffold(
+ body: Align(
+ alignment: Alignment.topLeft,
+ child: SizedBox(
+ width: 300,
+ child: MosaicGridRow(
+ key: rowKey,
+ itemWidths: [60, 90, 146],
+ height: 80,
+ spacing: 2,
+ textDirection: TextDirection.ltr,
+ children: [
+ ColoredBox(key: firstKey, color: Colors.red),
+ ColoredBox(key: secondKey, color: Colors.green),
+ ColoredBox(key: thirdKey, color: Colors.blue),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+
+ final rowFinder = find.byKey(rowKey);
+ final rowOrigin = tester.getTopLeft(rowFinder);
+ expect(tester.getSize(rowFinder), const Size(300, 80));
+ expect(tester.getSize(find.byKey(firstKey)), const Size(60, 80));
+ expect(tester.getSize(find.byKey(secondKey)), const Size(90, 80));
+ expect(tester.getSize(find.byKey(thirdKey)), const Size(146, 80));
+ expect(tester.getTopLeft(find.byKey(firstKey)), rowOrigin);
+ expect(
+ tester.getTopLeft(find.byKey(secondKey)),
+ rowOrigin + const Offset(62, 0),
+ );
+ expect(
+ tester.getTopLeft(find.byKey(thirdKey)),
+ rowOrigin + const Offset(154, 0),
+ );
+ },
+ );
+
+ testWidgets("MosaicGridRow mirrors child offsets in RTL", (tester) async {
+ const rowKey = ValueKey("rtl-row");
+ const firstKey = ValueKey("rtl-first");
+ const secondKey = ValueKey("rtl-second");
+
+ await tester.pumpWidget(
+ const MaterialApp(
+ home: Scaffold(
+ body: Align(
+ alignment: Alignment.topLeft,
+ child: SizedBox(
+ width: 200,
+ child: MosaicGridRow(
+ key: rowKey,
+ itemWidths: [60, 100],
+ height: 50,
+ spacing: 4,
+ textDirection: TextDirection.rtl,
+ children: [
+ ColoredBox(key: firstKey, color: Colors.red),
+ ColoredBox(key: secondKey, color: Colors.green),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+
+ final rowOrigin = tester.getTopLeft(find.byKey(rowKey));
+ expect(
+ tester.getTopLeft(find.byKey(firstKey)),
+ rowOrigin + const Offset(140, 0),
+ );
+ expect(
+ tester.getTopLeft(find.byKey(secondKey)),
+ rowOrigin + const Offset(36, 0),
+ );
+ });
+}
diff --git a/mobile/apps/photos/test/models/mosaic_layout_test.dart b/mobile/apps/photos/test/models/mosaic_layout_test.dart
new file mode 100644
index 0000000000..194fb9bc0d
--- /dev/null
+++ b/mobile/apps/photos/test/models/mosaic_layout_test.dart
@@ -0,0 +1,266 @@
+import "package:flutter/widgets.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:photos/models/gallery/mosaic_layout.dart";
+
+void main() {
+ group("MosaicLayoutCalculator", () {
+ test("uses a square fallback for missing or invalid dimensions", () {
+ expect(MosaicLayoutCalculator.aspectRatioForDimensions(0, 0), 1);
+ expect(MosaicLayoutCalculator.aspectRatioForDimensions(0, 100), 1);
+ expect(MosaicLayoutCalculator.aspectRatioForDimensions(100, 0), 1);
+ expect(MosaicLayoutCalculator.aspectRatioForDimensions(-100, 50), 1);
+ expect(MosaicLayoutCalculator.aspectRatioForDimensions(100, -50), 1);
+ });
+
+ test("preserves normal ratios and clamps extreme dimensions", () {
+ expect(MosaicLayoutCalculator.aspectRatioForDimensions(4, 3), 4 / 3);
+ expect(MosaicLayoutCalculator.aspectRatioForDimensions(1, 100), 0.25);
+ expect(MosaicLayoutCalculator.aspectRatioForDimensions(100, 1), 4);
+ });
+
+ test("normalizes invalid and extreme input ratios", () {
+ final rows = MosaicLayoutCalculator.computeRows(
+ aspectRatios: [
+ double.nan,
+ double.infinity,
+ double.negativeInfinity,
+ -1,
+ 0,
+ 1e-9,
+ 1e9,
+ ],
+ availableWidth: 400,
+ targetRowHeight: 100,
+ spacing: 2,
+ );
+
+ expect(rows.first.firstIndex, 0);
+ expect(rows.last.lastIndex, 6);
+ for (final row in rows) {
+ expect(row.height.isFinite, isTrue);
+ expect(row.height, greaterThan(0));
+ for (final width in row.itemWidths) {
+ expect(width.isFinite, isTrue);
+ expect(width, greaterThan(0));
+ }
+ }
+ });
+
+ test("justified rows conserve the full available width", () {
+ const availableWidth = 400.0;
+ const spacing = 2.0;
+ final rows = MosaicLayoutCalculator.computeRows(
+ aspectRatios: const [1, 1, 1, 1],
+ availableWidth: availableWidth,
+ targetRowHeight: 100,
+ spacing: spacing,
+ );
+
+ expect(rows, hasLength(1));
+ final row = rows.single;
+ final occupiedWidth =
+ row.itemWidths.fold<double>(0, (sum, width) => sum + width) +
+ spacing * (row.itemWidths.length - 1);
+ expect(occupiedWidth, closeTo(availableWidth, 1e-9));
+ expect(row.itemWidths, everyElement(closeTo(98.5, 1e-9)));
+ });
+
+ test("the final incomplete row does not grow past the target height", () {
+ const availableWidth = 400.0;
+ const targetRowHeight = 100.0;
+ const spacing = 2.0;
+ final rows = MosaicLayoutCalculator.computeRows(
+ aspectRatios: const [1, 1],
+ availableWidth: availableWidth,
+ targetRowHeight: targetRowHeight,
+ spacing: spacing,
+ );
+
+ expect(rows, hasLength(1));
+ final row = rows.single;
+ expect(row.height, targetRowHeight);
+ expect(row.itemWidths, everyElement(row.height));
+ final occupiedWidth =
+ row.itemWidths.fold<double>(0, (sum, width) => sum + width) + spacing;
+ expect(occupiedWidth, lessThanOrEqualTo(availableWidth));
+ });
+
+ test("a sparse portrait final row remains ragged at target height", () {
+ const availableWidth = 400.0;
+ const targetRowHeight = 100.0;
+ final rows = MosaicLayoutCalculator.computeRows(
+ aspectRatios: const [0.25],
+ availableWidth: availableWidth,
+ targetRowHeight: targetRowHeight,
+ spacing: 2,
+ );
+
+ expect(rows, hasLength(1));
+ final row = rows.single;
+ expect(row.height, targetRowHeight);
+ expect(row.itemWidths.single / row.height, closeTo(0.25, 1e-9));
+ expect(row.itemWidths.single, lessThan(availableWidth));
+ });
+
+ test("does not squeeze an extreme item into a mixed row", () {
+ for (final ratios in const [
+ [0.25, 4.0],
+ [4.0, 0.25],
+ ]) {
+ final rows = MosaicLayoutCalculator.computeRows(
+ aspectRatios: ratios,
+ availableWidth: 430,
+ targetRowHeight: 106,
+ spacing: 2,
+ );
+
+ expect(rows, hasLength(2));
+ expect(rows.first.lastIndex, 0);
+ expect(rows.last.firstIndex, 1);
+ }
+ });
+
+ test("lays out 100k ratios quickly and deterministically", () {
+ final ratios = List<double>.generate(100000, (index) {
+ return switch (index % 8) {
+ 0 => 0.25,
+ 1 => 0.5,
+ 2 => 0.75,
+ 3 => 1,
+ 4 => 4 / 3,
+ 5 => 1.5,
+ 6 => 2,
+ _ => 4,
+ };
+ }, growable: false);
+
+ final stopwatch = Stopwatch()..start();
+ final first = MosaicLayoutCalculator.computeRows(
+ aspectRatios: ratios,
+ availableWidth: 430,
+ targetRowHeight: 105,
+ spacing: 2,
+ );
+ stopwatch.stop();
+
+ expect(stopwatch.elapsed, lessThan(const Duration(seconds: 5)));
+ expect(first, isNotEmpty);
+ expect(first.first.firstIndex, 0);
+ expect(first.last.lastIndex, ratios.length - 1);
+ _expectValidRows(first, itemCount: ratios.length, spacing: 2);
+
+ final second = MosaicLayoutCalculator.computeRows(
+ aspectRatios: ratios,
+ availableWidth: 430,
+ targetRowHeight: 105,
+ spacing: 2,
+ );
+ _expectSameRows(first, second);
+ });
+ });
+
+ group("MosaicSectionLayout", () {
+ const rows = [
+ MosaicRowLayout(
+ firstIndex: 0,
+ lastIndex: 1,
+ minOffset: 0,
+ height: 10,
+ itemWidths: [40, 40],
+ ),
+ MosaicRowLayout(
+ firstIndex: 2,
+ lastIndex: 2,
+ minOffset: 12,
+ height: 20,
+ itemWidths: [80],
+ ),
+ MosaicRowLayout(
+ firstIndex: 3,
+ lastIndex: 4,
+ minOffset: 34,
+ height: 30,
+ itemWidths: [30, 50],
+ ),
+ ];
+ final section = MosaicSectionLayout(
+ firstIndex: 10,
+ lastIndex: 13,
+ minOffset: 100,
+ maxOffset: 169,
+ headerExtent: 5,
+ spacing: 2,
+ rows: rows,
+ builder: (context, index) => const SizedBox.shrink(),
+ );
+
+ test("maps header and row indices to exact layout offsets", () {
+ expect(section.indexToLayoutOffset(10), 100);
+ expect(section.indexToLayoutOffset(11), 105);
+ expect(section.indexToLayoutOffset(12), 117);
+ expect(section.indexToLayoutOffset(13), 139);
+ expect(section.indexToLayoutOffset(14), 171);
+ });
+
+ test("finds the first child at row and spacing boundaries", () {
+ expect(section.getMinChildIndexForScrollOffset(100), 10);
+ expect(section.getMinChildIndexForScrollOffset(104.999), 10);
+ expect(section.getMinChildIndexForScrollOffset(105), 11);
+ expect(section.getMinChildIndexForScrollOffset(115), 11);
+ expect(section.getMinChildIndexForScrollOffset(116.999), 11);
+ expect(section.getMinChildIndexForScrollOffset(117), 12);
+ expect(section.getMinChildIndexForScrollOffset(139), 13);
+ expect(section.getMinChildIndexForScrollOffset(169), 13);
+ });
+
+ test(
+ "finds the last child without including a row at its leading edge",
+ () {
+ expect(section.getMaxChildIndexForScrollOffset(100), 10);
+ expect(section.getMaxChildIndexForScrollOffset(105), 10);
+ expect(section.getMaxChildIndexForScrollOffset(105.001), 11);
+ expect(section.getMaxChildIndexForScrollOffset(117), 11);
+ expect(section.getMaxChildIndexForScrollOffset(117.001), 12);
+ expect(section.getMaxChildIndexForScrollOffset(139), 12);
+ expect(section.getMaxChildIndexForScrollOffset(139.001), 13);
+ expect(section.getMaxChildIndexForScrollOffset(169), 13);
+ },
+ );
+ });
+}
+
+void _expectValidRows(
+ List<MosaicRowLayout> rows, {
+ required int itemCount,
+ required double spacing,
+}) {
+ var expectedFirstIndex = 0;
+ var expectedOffset = 0.0;
+ for (final row in rows) {
+ expect(row.firstIndex, expectedFirstIndex);
+ expect(row.lastIndex, greaterThanOrEqualTo(row.firstIndex));
+ expect(row.itemWidths, hasLength(row.lastIndex - row.firstIndex + 1));
+ expect(row.minOffset, closeTo(expectedOffset, 1e-9));
+ expect(row.height.isFinite, isTrue);
+ expect(row.height, greaterThan(0));
+ expectedFirstIndex = row.lastIndex + 1;
+ expectedOffset = row.maxOffset + spacing;
+ }
+ expect(expectedFirstIndex, itemCount);
+}
+
+void _expectSameRows(
+ List<MosaicRowLayout> first,
+ List<MosaicRowLayout> second,
+) {
+ expect(second, hasLength(first.length));
+ for (var index = 0; index < first.length; index++) {
+ final firstRow = first[index];
+ final secondRow = second[index];
+ expect(secondRow.firstIndex, firstRow.firstIndex, reason: "row $index");
+ expect(secondRow.lastIndex, firstRow.lastIndex, reason: "row $index");
+ expect(secondRow.minOffset, firstRow.minOffset, reason: "row $index");
+ expect(secondRow.height, firstRow.height, reason: "row $index");
+ expect(secondRow.itemWidths, firstRow.itemWidths, reason: "row $index");
+ }
+}
diff --git a/mobile/apps/photos/test/settings/local_settings_gallery_layout_test.dart b/mobile/apps/photos/test/settings/local_settings_gallery_layout_test.dart
new file mode 100644
index 0000000000..93b95b614d
--- /dev/null
+++ b/mobile/apps/photos/test/settings/local_settings_gallery_layout_test.dart
@@ -0,0 +1,37 @@
+import "package:flutter_test/flutter_test.dart";
+import "package:photos/settings/local_settings.dart";
+import "package:shared_preferences/shared_preferences.dart";
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ test("gallery layout defaults to grid", () async {
+ SharedPreferences.setMockInitialValues({});
+ final settings = LocalSettings(await SharedPreferences.getInstance());
+
+ expect(settings.getGalleryLayoutType(), GalleryLayoutType.grid);
+ });
+
+ test("gallery layout persists mosaic", () async {
+ SharedPreferences.setMockInitialValues({});
+ final preferences = await SharedPreferences.getInstance();
+ final settings = LocalSettings(preferences);
+
+ await settings.setGalleryLayoutType(GalleryLayoutType.mosaic);
+
+ expect(settings.getGalleryLayoutType(), GalleryLayoutType.mosaic);
+ expect(
+ preferences.getString(LocalSettings.kGalleryLayoutType),
+ GalleryLayoutType.mosaic.name,
+ );
+ });
+
+ test("unknown persisted gallery layout falls back to grid", () async {
+ SharedPreferences.setMockInitialValues({
+ LocalSettings.kGalleryLayoutType: "future-layout",
+ });
+ final settings = LocalSettings(await SharedPreferences.getInstance());
+
+ expect(settings.getGalleryLayoutType(), GalleryLayoutType.grid);
+ });
+}
diff --git a/mobile/apps/photos/test/ui/viewer/gallery/component/gallery_file_widget_test.dart b/mobile/apps/photos/test/ui/viewer/gallery/component/gallery_file_widget_test.dart
new file mode 100644
index 0000000000..cfefe18a02
--- /dev/null
+++ b/mobile/apps/photos/test/ui/viewer/gallery/component/gallery_file_widget_test.dart
@@ -0,0 +1,238 @@
+import "dart:typed_data";
+
+import "package:dio/dio.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/cache/thumbnail_in_memory_cache.dart";
+import "package:photos/core/constants.dart";
+import "package:photos/models/file/file.dart";
+import "package:photos/models/file/file_type.dart";
+import "package:photos/service_locator.dart";
+import "package:photos/ui/viewer/file/thumbnail_widget.dart";
+import "package:photos/ui/viewer/gallery/component/gallery_file_widget.dart";
+import "package:photos/ui/viewer/gallery/state/gallery_context_state.dart";
+import "package:shared_preferences/shared_preferences.dart";
+
+// A minimal valid 1x1 RGBA PNG.
+const _tinyImage = <int>[
+ 0x89,
+ 0x50,
+ 0x4e,
+ 0x47,
+ 0x0d,
+ 0x0a,
+ 0x1a,
+ 0x0a,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x0d,
+ 0x49,
+ 0x48,
+ 0x44,
+ 0x52,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x01,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x01,
+ 0x08,
+ 0x06,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x1f,
+ 0x15,
+ 0xc4,
+ 0x89,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x0d,
+ 0x49,
+ 0x44,
+ 0x41,
+ 0x54,
+ 0x08,
+ 0xd7,
+ 0x63,
+ 0xf8,
+ 0xcf,
+ 0xc0,
+ 0xf0,
+ 0x1f,
+ 0x00,
+ 0x05,
+ 0x00,
+ 0x01,
+ 0xff,
+ 0x89,
+ 0x99,
+ 0xd1,
+ 0x8d,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x49,
+ 0x45,
+ 0x4e,
+ 0x44,
+ 0xae,
+ 0x42,
+ 0x60,
+ 0x82,
+];
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ setUpAll(() async {
+ SharedPreferences.setMockInitialValues({});
+ ServiceLocator.instance.init(
+ await SharedPreferences.getInstance(),
+ Dio(),
+ Dio(),
+ Dio(),
+ PackageInfo(
+ appName: "Photos",
+ packageName: "photos",
+ version: "1.0.0",
+ buildNumber: "1",
+ ),
+ );
+ });
+
+ testWidgets("a thumbnail tier change recreates the thumbnail loader", (
+ tester,
+ ) async {
+ final file = EnteFile()
+ ..generatedID = 1
+ ..fileType = FileType.image
+ ..title = "photo.jpg";
+
+ Widget buildGalleryTile(int thumbnailSize) {
+ return MaterialApp(
+ home: GalleryContextState(
+ sortOrderAsc: false,
+ child: SizedBox(
+ width: 200,
+ height: 200,
+ child: GalleryFileWidget(
+ key: const ValueKey("gallery-tile"),
+ file: file,
+ selectedFiles: null,
+ limitSelectionToOne: true,
+ tag: "gallery_",
+ photoGridSize: photoGridSizeDefault,
+ thumbnailSize: thumbnailSize,
+ currentUserID: null,
+ ),
+ ),
+ ),
+ );
+ }
+
+ await tester.pumpWidget(buildGalleryTile(thumbnailSmallSize));
+ final smallThumbnailState = tester.state<State<ThumbnailWidget>>(
+ find.byType(ThumbnailWidget),
+ );
+ expect(
+ tester
+ .widget<ThumbnailWidget>(find.byType(ThumbnailWidget))
+ .thumbnailSize,
+ thumbnailSmallSize,
+ );
+
+ await tester.pumpWidget(buildGalleryTile(thumbnailLargeSize));
+ final largeThumbnailState = tester.state<State<ThumbnailWidget>>(
+ find.byType(ThumbnailWidget),
+ );
+ expect(
+ tester
+ .widget<ThumbnailWidget>(find.byType(ThumbnailWidget))
+ .thumbnailSize,
+ thumbnailLargeSize,
+ );
+ expect(largeThumbnailState, isNot(same(smallThumbnailState)));
+
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pump(const Duration(milliseconds: 100));
+ });
+
+ testWidgets(
+ "a requested large mosaic thumbnail bypasses the cached small tier",
+ (tester) async {
+ final file = EnteFile()
+ ..generatedID = 2
+ ..localID = "local-photo"
+ ..fileType = FileType.image
+ ..title = "local-photo.jpg";
+ ThumbnailInMemoryLruCache.put(
+ file,
+ Uint8List.fromList(_tinyImage),
+ thumbnailSmallSize,
+ );
+ addTearDown(() => ThumbnailInMemoryLruCache.clearCache(file));
+
+ Widget buildGalleryTile({required bool mosaic}) {
+ return MaterialApp(
+ home: GalleryContextState(
+ sortOrderAsc: false,
+ child: SizedBox(
+ width: 200,
+ height: 200,
+ child: GalleryFileWidget(
+ file: file,
+ selectedFiles: null,
+ limitSelectionToOne: true,
+ tag: mosaic ? "mosaic_" : "grid_",
+ // A dense-grid size that preserves the legacy large-render /
+ // small-local-cache behavior when no mosaic override exists.
+ photoGridSize: photoGridSizeDefault - 1,
+ thumbnailSize: mosaic ? thumbnailLargeSize : null,
+ currentUserID: null,
+ ),
+ ),
+ ),
+ );
+ }
+
+ await tester.pumpWidget(buildGalleryTile(mosaic: true));
+ final mosaicThumbnail = tester.widget<ThumbnailWidget>(
+ find.byType(ThumbnailWidget),
+ );
+ expect(mosaicThumbnail.thumbnailSize, thumbnailLargeSize);
+ expect(mosaicThumbnail.useRequestedThumbnailSizeForLocalCache, isTrue);
+ expect(
+ find.descendant(
+ of: find.byType(ThumbnailWidget),
+ matching: find.byType(Image),
+ ),
+ findsNothing,
+ );
+
+ await tester.pumpWidget(buildGalleryTile(mosaic: false));
+ await tester.pump();
+ final gridThumbnail = tester.widget<ThumbnailWidget>(
+ find.byType(ThumbnailWidget),
+ );
+ expect(gridThumbnail.thumbnailSize, thumbnailLargeSize);
+ expect(gridThumbnail.useRequestedThumbnailSizeForLocalCache, isFalse);
+ expect(
+ find.descendant(
+ of: find.byType(ThumbnailWidget),
+ matching: find.byType(Image),
+ ),
+ findsOneWidget,
+ );
+
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pump(const Duration(milliseconds: 100));
+ },
+ );
+}
diff --git a/mobile/apps/photos/test/ui/viewer/gallery/component/sectioned_sliver_list_test.dart b/mobile/apps/photos/test/ui/viewer/gallery/component/sectioned_sliver_list_test.dart
new file mode 100644
index 0000000000..73136c3ffd
--- /dev/null
+++ b/mobile/apps/photos/test/ui/viewer/gallery/component/sectioned_sliver_list_test.dart
@@ -0,0 +1,92 @@
+import "package:flutter/material.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:photos/models/gallery/mosaic_layout.dart";
+import "package:photos/ui/viewer/gallery/component/sectioned_sliver_list.dart";
+
+void main() {
+ testWidgets(
+ "a deep mosaic jump builds only the nearby viewport and cache rows",
+ (tester) async {
+ const rowCount = 100000;
+ const rowHeight = 50.0;
+ const headerHeight = 20.0;
+ const spacing = 2.0;
+ const rowStride = rowHeight + spacing;
+ const deepRowIndex = 80000;
+ const deepChildIndex = deepRowIndex + 1;
+ final builtIndices = <int>[];
+ final rows = List<MosaicRowLayout>.generate(
+ rowCount,
+ (index) => MosaicRowLayout(
+ firstIndex: index,
+ lastIndex: index,
+ minOffset: index * rowStride,
+ height: rowHeight,
+ itemWidths: const [400],
+ ),
+ growable: false,
+ );
+ final section = MosaicSectionLayout(
+ firstIndex: 0,
+ lastIndex: rowCount,
+ minOffset: 0,
+ maxOffset: headerHeight + rows.last.maxOffset,
+ headerExtent: headerHeight,
+ spacing: spacing,
+ rows: rows,
+ builder: (context, index) {
+ builtIndices.add(index);
+ return SizedBox(
+ key: ValueKey(index),
+ height: index == 0 ? headerHeight : rowHeight,
+ );
+ },
+ );
+ final controller = ScrollController();
+ addTearDown(controller.dispose);
+
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Align(
+ alignment: Alignment.topLeft,
+ child: SizedBox(
+ width: 400,
+ height: 300,
+ child: CustomScrollView(
+ controller: controller,
+ cacheExtent: 100,
+ slivers: [
+ SectionedListSliver<void>(sectionLayouts: [section]),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+
+ expect(builtIndices, contains(0));
+ expect(builtIndices.length, lessThan(50));
+ builtIndices.clear();
+
+ final deepOffset = headerHeight + rows[deepRowIndex].minOffset;
+ controller.jumpTo(deepOffset);
+ await tester.pump();
+
+ expect(controller.offset, deepOffset);
+ expect(builtIndices, contains(deepChildIndex));
+ expect(builtIndices.length, lessThan(50));
+ expect(
+ builtIndices,
+ everyElement(
+ inInclusiveRange(deepChildIndex - 20, deepChildIndex + 20),
+ ),
+ );
+
+ final scrollViewOrigin = tester.getTopLeft(find.byType(CustomScrollView));
+ final deepRowOrigin = tester.getTopLeft(
+ find.byKey(const ValueKey(80001)),
+ );
+ expect(deepRowOrigin, scrollViewOrigin);
+ },
+ );
+}
diff --git a/mobile/apps/photos/test/ui/viewer/gallery/gallery_layout_changed_event_test.dart b/mobile/apps/photos/test/ui/viewer/gallery/gallery_layout_changed_event_test.dart
new file mode 100644
index 0000000000..4420a8a0db
--- /dev/null
+++ b/mobile/apps/photos/test/ui/viewer/gallery/gallery_layout_changed_event_test.dart
@@ -0,0 +1,247 @@
+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/core/event_bus.dart";
+import "package:photos/ente_theme_data.dart";
+import "package:photos/events/gallery_layout_changed_event.dart";
+import "package:photos/models/file/dummy_file.dart";
+import "package:photos/models/file/file.dart";
+import "package:photos/models/file/file_type.dart";
+import "package:photos/models/file_load_result.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/gallery.dart";
+import "package:photos/ui/viewer/gallery/state/gallery_boundaries_provider.dart";
+import "package:photos/ui/viewer/gallery/state/gallery_files_inherited_widget.dart";
+import "package:shared_preferences/shared_preferences.dart";
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ 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",
+ ),
+ );
+
+ // GalleryGroups only needs Configuration's preferences-backed user ID.
+ // Plugin initialization is unavailable in a widget-test process.
+ try {
+ await Configuration.instance.init(preferences);
+ } catch (_) {}
+ });
+
+ testWidgets(
+ "layout changes rebuild every mounted gallery without loading files",
+ (tester) async {
+ await localSettings.setPhotoGridSize(4);
+ final firstKey = GlobalKey<GalleryState>();
+ final secondKey = GlobalKey<GalleryState>();
+ var firstLoadCount = 0;
+ var secondLoadCount = 0;
+ final firstFile = _dummyFile("first");
+ final secondFile = _dummyFile("second");
+
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: lightThemeData,
+ localizationsDelegates: StringsLocalizations.localizationsDelegates,
+ supportedLocales: StringsLocalizations.supportedLocales,
+ home: Column(
+ children: [
+ Expanded(
+ child: _galleryHost(
+ Gallery(
+ key: firstKey,
+ asyncLoader: (start, end, {limit, asc}) async {
+ firstLoadCount++;
+ return FileLoadResult([firstFile], false);
+ },
+ tagPrefix: "first_",
+ limitSelectionToOne: true,
+ showSelectAll: false,
+ ),
+ ),
+ ),
+ Expanded(
+ child: _galleryHost(
+ Gallery(
+ key: secondKey,
+ asyncLoader: (start, end, {limit, asc}) async {
+ secondLoadCount++;
+ return FileLoadResult([secondFile], false);
+ },
+ tagPrefix: "second_",
+ limitSelectionToOne: true,
+ showSelectAll: false,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.pump(const Duration(milliseconds: 750));
+ await tester.pump();
+
+ final firstGroups = firstKey.currentState!.galleryGroups!;
+ final secondGroups = secondKey.currentState!.galleryGroups!;
+ final oldHeaderExtent = firstGroups.groupHeaderExtent;
+ expect(firstGroups.crossAxisCount, 4);
+ expect(secondGroups.crossAxisCount, 4);
+ expect(firstLoadCount, 1);
+ expect(secondLoadCount, 1);
+
+ await localSettings.setPhotoGridSize(6);
+ Bus.instance.fire(GalleryLayoutChangedEvent());
+ await tester.pumpAndSettle();
+
+ final updatedFirstGroups = firstKey.currentState!.galleryGroups!;
+ final updatedSecondGroups = secondKey.currentState!.galleryGroups!;
+ expect(updatedFirstGroups, isNot(same(firstGroups)));
+ expect(updatedSecondGroups, isNot(same(secondGroups)));
+ expect(updatedFirstGroups.crossAxisCount, 6);
+ expect(updatedSecondGroups.crossAxisCount, 6);
+ expect(
+ updatedFirstGroups.groupHeaderExtent,
+ greaterThan(oldHeaderExtent),
+ );
+ expect(
+ updatedSecondGroups.groupHeaderExtent,
+ greaterThan(oldHeaderExtent),
+ );
+ expect(updatedFirstGroups.allFiles.single, same(firstFile));
+ expect(updatedSecondGroups.allFiles.single, same(secondFile));
+ expect(firstLoadCount, 1);
+ expect(secondLoadCount, 1);
+
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pump();
+ },
+ );
+
+ testWidgets("a deep layout change preserves partial-row progress", (
+ tester,
+ ) async {
+ await localSettings.setGalleryLayoutType(GalleryLayoutType.grid);
+ await localSettings.setPhotoGridSize(2);
+ final galleryKey = GlobalKey<GalleryState>();
+ final files = List<EnteFile>.generate(1000, _mosaicTestFile);
+
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: lightThemeData,
+ home: Scaffold(
+ body: _galleryHost(
+ Gallery(
+ key: galleryKey,
+ asyncLoader: (start, end, {limit, asc}) async =>
+ FileLoadResult(files, false),
+ tagPrefix: "anchor_",
+ enableFileGrouping: false,
+ limitSelectionToOne: true,
+ showSelectAll: false,
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.pump(const Duration(milliseconds: 750));
+ await tester.pump();
+
+ final oldGroups = galleryKey.currentState!.galleryGroups!;
+ final anchorFile = files[800];
+ final oldGeometry = oldGroups.getGeometryOfFile(anchorFile)!;
+ const rowProgress = 0.72;
+ final oldAnchorOffset =
+ oldGeometry.rowOffset + oldGeometry.rowExtent * rowProgress;
+ final scrollableFinder = find.descendant(
+ of: find.byType(CustomScrollView),
+ matching: find.byType(Scrollable),
+ );
+ expect(scrollableFinder, findsOneWidget);
+ final scrollPosition = tester
+ .state<ScrollableState>(scrollableFinder)
+ .position;
+ scrollPosition.jumpTo(oldAnchorOffset);
+ await tester.pump();
+ expect(
+ oldGroups.getFileAtScrollOffset(scrollPosition.pixels),
+ same(anchorFile),
+ );
+
+ await Future.wait([
+ localSettings.setGalleryLayoutType(GalleryLayoutType.mosaic),
+ localSettings.setPhotoGridSize(6),
+ ]);
+ Bus.instance.fire(GalleryLayoutChangedEvent());
+ await tester.pump();
+ await tester.pump();
+ await tester.pump();
+
+ final mosaicGroups = galleryKey.currentState!.galleryGroups!;
+ expect(mosaicGroups.layoutType, GalleryLayoutType.mosaic);
+ final newGeometry = mosaicGroups.getGeometryOfFile(anchorFile)!;
+ expect(newGeometry.rowExtent, lessThan(oldGeometry.rowExtent));
+ final expectedAnchorOffset =
+ newGeometry.rowOffset + newGeometry.rowExtent * rowProgress;
+ expect(
+ (newGeometry.rowOffset - oldGeometry.rowOffset).abs(),
+ greaterThan(500),
+ reason: "the two layouts should have meaningfully different geometry",
+ );
+ expect(scrollPosition.pixels, closeTo(expectedAnchorOffset, 0.001));
+ expect(
+ find.byWidgetPredicate(
+ (widget) =>
+ widget is RepaintBoundary &&
+ widget.key == ValueKey("anchor_${anchorFile.tag}"),
+ ),
+ findsOneWidget,
+ );
+
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pump(const Duration(milliseconds: 100));
+ await localSettings.setGalleryLayoutType(GalleryLayoutType.grid);
+ await localSettings.setPhotoGridSize(4);
+ });
+}
+
+Widget _galleryHost(Gallery gallery) {
+ return GalleryBoundariesProvider(child: GalleryFilesState(child: gallery));
+}
+
+DummyFile _dummyFile(String groupID) {
+ return DummyFile(groupID: groupID, index: 0)
+ ..creationTime = DateTime(2026, 8, 19).microsecondsSinceEpoch;
+}
+
+DummyFile _mosaicTestFile(int index) {
+ final dimensions = switch (index % 4) {
+ 0 => (w: 1600, h: 900),
+ 1 => (w: 900, h: 1600),
+ 2 => (w: 1200, h: 1200),
+ _ => (w: 2400, h: 1000),
+ };
+ return DummyFile(groupID: "anchor", index: index)
+ // Real libraries commonly contain many files with the same EXIF second.
+ ..creationTime = DateTime(2026, 8, 19).microsecondsSinceEpoch
+ ..fileType = FileType.image
+ ..pubMagicMetadata = PubMagicMetadata(w: dimensions.w, h: dimensions.h);
+}