π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mob][photos] Add justified layout tuning controls
ashil-pilota20d84b5dbf7
diff --git a/mobile/apps/photos/changes/justified-layout-tuning.md b/mobile/apps/photos/changes/justified-layout-tuning.mdnew file mode 100644index 0000000000..a1b4cba917--- /dev/null+++ b/mobile/apps/photos/changes/justified-layout-tuning.md@@ -0,0 +1 @@+- (i) Added tuning controls and improved the experimental justified gallery layouts.diff --git a/mobile/apps/photos/lib/models/gallery/flex_layout.dart b/mobile/apps/photos/lib/models/gallery/flex_layout.dartindex c8d0c86cd8..f402c9e8f5 100644--- a/mobile/apps/photos/lib/models/gallery/flex_layout.dart+++ b/mobile/apps/photos/lib/models/gallery/flex_layout.dart@@ -7,8 +7,9 @@ import "package:photos/models/gallery/justified_layout.dart";// Selects the minimum-cost sequence from candidate row breaks across the group.class FlexLayoutCalculator {static const double _minimumTappableExtent = 48;- static const double _maximumRowHeightFactor = 1.6;+ static const double _defaultMaximumRowHeightFactor = 1.6;static const double _preferredTileWidthFactor = 0.6;+ static const double _cropPenaltyWeight = 4;const FlexLayoutCalculator._();@@ -17,6 +18,7 @@ class FlexLayoutCalculator {required double availableWidth,required double targetRowHeight,required double spacing,+ double maximumRowHeightFactor = _defaultMaximumRowHeightFactor,}) {if (!availableWidth.isFinite || availableWidth <= 0) {throw ArgumentError.value(availableWidth, "availableWidth");@@ -27,6 +29,12 @@ class FlexLayoutCalculator {if (!spacing.isFinite || spacing < 0) {throw ArgumentError.value(spacing, "spacing");}+ if (!maximumRowHeightFactor.isFinite || maximumRowHeightFactor < 1) {+ throw ArgumentError.value(+ maximumRowHeightFactor,+ "maximumRowHeightFactor",+ );+ }final ratios = Float64List.fromList(aspectRatios.toList(growable: false));if (ratios.isEmpty) return const [];@@ -40,24 +48,12 @@ class FlexLayoutCalculator {final count = ratios.length;final costs = Float64List(count + 1)..fillRange(0, count, double.infinity);final nextBreak = Uint32List(count);- final maximumHeight = targetRowHeight * _maximumRowHeightFactor;+ final maximumHeight = math.max(+ _minimumTappableExtent,+ targetRowHeight * maximumRowHeightFactor,+ );final preferredTileWidth = targetRowHeight * _preferredTileWidthFactor;- double rowHeight(double fittedHeight, double minimumRatio, bool isTail) {- if (!isTail && fittedHeight <= maximumHeight) return fittedHeight;- // Allow sparse tails to leave unused width while preserving tap extents.- return math.min(- fittedHeight,- math.max(- targetRowHeight,- math.max(- _minimumTappableExtent,- _minimumTappableExtent / minimumRatio,- ),- ),- );- }-for (var start = count - 1; start >= 0; start--) {var ratioSum = 0.0;var minimumRatio = double.infinity;@@ -66,43 +62,37 @@ class FlexLayoutCalculator {minimumRatio = math.min(minimumRatio, ratios[end]);final itemCount = end - start + 1;final contentWidth = availableWidth - spacing * (itemCount - 1);- if (contentWidth <= 0) break;- final fittedHeight = contentWidth / ratioSum;- // Adding items only shrinks these extents, so no later candidate can- // restore the minimum tap target.- if (itemCount > 1 &&- (fittedHeight < _minimumTappableExtent ||- fittedHeight * minimumRatio < _minimumTappableExtent)) {- break;- }- final isTail = end == count - 1;- if (!isTail && itemCount > 1 && fittedHeight > maximumHeight) continue;+ if (contentWidth < itemCount * _minimumTappableExtent) break;- final height = rowHeight(fittedHeight, minimumRatio, isTail);- final heightDeviation = math.log(height / targetRowHeight);+ final isTail = end == count - 1;+ // Product decision: a singleton is only allowed at the group tail.+ if (!isTail && itemCount == 1) continue;+ final geometry = _rowGeometry(+ ratios: ratios,+ start: start,+ end: end + 1,+ ratioSum: ratioSum,+ minimumRatio: minimumRatio,+ contentWidth: contentWidth,+ maximumHeight: maximumHeight,+ isTail: isTail,+ );+ final heightDeviation = math.log(geometry.height / targetRowHeight);final narrowness = math.max(0.0,- preferredTileWidth / (height * minimumRatio) - 1,+ preferredTileWidth / geometry.minimumWidth - 1,);final unusedWidthFraction = math.max(0.0,- 1 - height * ratioSum / contentWidth,+ 1 - geometry.occupiedWidth / contentWidth,);- // Log error treats shrinking and stretching symmetrically. Weighting by- // item count prevents extra rows from diluting the cost; the small- // per-row cost discourages fragmentation without excluding panoramas.- final singletonPenalty = itemCount == 1 && count > 1- ? isTail- ? 0.15- : ratios[start] < 2- ? 0.2- : 0.0- : 0.0;+ final singletonPenalty = itemCount == 1 && count > 1 ? 0.15 : 0.0;final rowCost =itemCount *(heightDeviation * heightDeviation +2 * narrowness * narrowness) +unusedWidthFraction * unusedWidthFraction ++ _cropPenaltyWeight * geometry.cropCost +0.08 +singletonPenalty;final cost = rowCost + costs[end + 1];@@ -111,6 +101,11 @@ class FlexLayoutCalculator {nextBreak[start] = end + 1;}}++ if (nextBreak[start] == 0) {+ nextBreak[start] = start + 1;+ costs[start] = costs[start + 1];+ }}final rows = <JustifiedRowLayout>[];@@ -124,31 +119,216 @@ class FlexLayoutCalculator {minimumRatio = math.min(minimumRatio, ratios[i]);}final contentWidth = availableWidth - spacing * (end - start - 1);- final fittedHeight = contentWidth / ratioSum;- final height = rowHeight(fittedHeight, minimumRatio, end == count);- final widths = List<double>.generate(- end - start,- (i) => ratios[start + i] * height,- growable: false,+ final geometry = _rowGeometry(+ ratios: ratios,+ start: start,+ end: end,+ ratioSum: ratioSum,+ minimumRatio: minimumRatio,+ contentWidth: contentWidth,+ maximumHeight: maximumHeight,+ isTail: end == count,);- if (height == fittedHeight) {- final precedingWidth = widths- .take(widths.length - 1)- .fold<double>(0, (a, b) => a + b);- widths[widths.length - 1] = math.max(0, contentWidth - precedingWidth);- }rows.add(JustifiedRowLayout(firstIndex: start,lastIndex: end - 1,minOffset: offset,- height: height,- itemWidths: UnmodifiableListView(widths),+ height: geometry.height,+ itemWidths: UnmodifiableListView(+ _itemWidths(+ ratios: ratios,+ start: start,+ end: end,+ contentWidth: contentWidth,+ geometry: geometry,+ ),+ ),),);- offset += height + spacing;+ offset += geometry.height + spacing;start = end;}return UnmodifiableListView(rows);}++ static _FlexRowGeometry _rowGeometry({+ required Float64List ratios,+ required int start,+ required int end,+ required double ratioSum,+ required double minimumRatio,+ required double contentWidth,+ required double maximumHeight,+ required bool isTail,+ }) {+ final naturalHeight = contentWidth / ratioSum;+ final height = naturalHeight.clamp(_minimumTappableExtent, maximumHeight);+ if (isTail && naturalHeight > maximumHeight) {+ final minimumWidth = minimumRatio * height;+ if (minimumWidth >= _minimumTappableExtent) {+ return _FlexRowGeometry(+ height: height,+ scale: 1,+ pinnedRatioCeiling: 0,+ fillsWidth: false,+ occupiedWidth: ratioSum * height,+ minimumWidth: minimumWidth,+ cropCost: 0,+ );+ }+ var occupiedWidth = 0.0;+ var croppedMinimumWidth = double.infinity;+ var cropCost = 0.0;+ for (var i = start; i < end; i++) {+ final naturalWidth = ratios[i] * height;+ final width = math.max(_minimumTappableExtent, naturalWidth);+ occupiedWidth += width;+ croppedMinimumWidth = math.min(croppedMinimumWidth, width);+ final ratioDeviation = math.log(width / height / ratios[i]);+ cropCost += ratioDeviation * ratioDeviation;+ }+ if (occupiedWidth <= contentWidth) {+ return _FlexRowGeometry(+ height: height,+ scale: 1,+ pinnedRatioCeiling: _minimumTappableExtent / height,+ fillsWidth: false,+ occupiedWidth: occupiedWidth,+ minimumWidth: croppedMinimumWidth,+ cropCost: cropCost,+ );+ }+ }++ return _filledRowGeometry(+ ratios: ratios,+ start: start,+ end: end,+ ratioSum: ratioSum,+ minimumRatio: minimumRatio,+ contentWidth: contentWidth,+ height: height,+ );+ }++ static _FlexRowGeometry _filledRowGeometry({+ required Float64List ratios,+ required int start,+ required int end,+ required double ratioSum,+ required double minimumRatio,+ required double contentWidth,+ required double height,+ }) {+ final uncroppedScale = contentWidth / (height * ratioSum);+ final uncroppedMinimumWidth = minimumRatio * height * uncroppedScale;+ if (uncroppedMinimumWidth >= _minimumTappableExtent) {+ final ratioDeviation = math.log(uncroppedScale);+ return _FlexRowGeometry(+ height: height,+ scale: uncroppedScale,+ pinnedRatioCeiling: 0,+ fillsWidth: true,+ occupiedWidth: contentWidth,+ minimumWidth: uncroppedMinimumWidth,+ cropCost: (end - start) * ratioDeviation * ratioDeviation,+ );+ }++ var pinnedRatioCeiling = 0.0;+ var pinnedCount = 0;+ var activeRatioSum = ratioSum;+ var remainingWidth = contentWidth;+ var scale = remainingWidth / (height * activeRatioSum);++ // Pin undersized slots, then redistribute the remaining row width.+ while (pinnedCount < end - start) {+ final nextPinnedRatioCeiling = _minimumTappableExtent / (height * scale);+ var newlyPinnedCount = 0;+ var newlyPinnedRatioSum = 0.0;+ for (var i = start; i < end; i++) {+ final ratio = ratios[i];+ if (ratio >= pinnedRatioCeiling && ratio < nextPinnedRatioCeiling) {+ newlyPinnedCount++;+ newlyPinnedRatioSum += ratio;+ }+ }+ if (newlyPinnedCount == 0) break;+ pinnedRatioCeiling = nextPinnedRatioCeiling;+ pinnedCount += newlyPinnedCount;+ activeRatioSum -= newlyPinnedRatioSum;+ remainingWidth -= newlyPinnedCount * _minimumTappableExtent;+ if (activeRatioSum <= 0) {+ scale = 0;+ break;+ }+ scale = remainingWidth / (height * activeRatioSum);+ }++ var minimumWidth = double.infinity;+ var cropCost = 0.0;+ for (var i = start; i < end; i++) {+ final width = ratios[i] < pinnedRatioCeiling+ ? _minimumTappableExtent+ : ratios[i] * height * scale;+ minimumWidth = math.min(minimumWidth, width);+ final ratioDeviation = math.log(width / height / ratios[i]);+ cropCost += ratioDeviation * ratioDeviation;+ }+ return _FlexRowGeometry(+ height: height,+ scale: scale,+ pinnedRatioCeiling: pinnedRatioCeiling,+ fillsWidth: true,+ occupiedWidth: contentWidth,+ minimumWidth: minimumWidth,+ cropCost: cropCost,+ );+ }++ static List<double> _itemWidths({+ required Float64List ratios,+ required int start,+ required int end,+ required double contentWidth,+ required _FlexRowGeometry geometry,+ }) {+ final widths = List<double>.generate(end - start, (index) {+ final ratio = ratios[start + index];+ return ratio < geometry.pinnedRatioCeiling+ ? _minimumTappableExtent+ : ratio * geometry.height * geometry.scale;+ }, growable: false);+ if (geometry.fillsWidth && widths.isNotEmpty) {+ final precedingWidth = widths+ .take(widths.length - 1)+ .fold<double>(0, (sum, width) => sum + width);+ widths[widths.length - 1] = math.max(+ _minimumTappableExtent,+ contentWidth - precedingWidth,+ );+ }+ return widths;+ }+}++class _FlexRowGeometry {+ final double height;+ final double scale;+ final double pinnedRatioCeiling;+ final bool fillsWidth;+ final double occupiedWidth;+ final double minimumWidth;+ final double cropCost;++ const _FlexRowGeometry({+ required this.height,+ required this.scale,+ required this.pinnedRatioCeiling,+ required this.fillsWidth,+ required this.occupiedWidth,+ required this.minimumWidth,+ required this.cropCost,+ });}diff --git a/mobile/apps/photos/lib/models/gallery/gallery_groups.dart b/mobile/apps/photos/lib/models/gallery/gallery_groups.dartindex 8926d57893..ba2346eb44 100644--- a/mobile/apps/photos/lib/models/gallery/gallery_groups.dart+++ b/mobile/apps/photos/lib/models/gallery/gallery_groups.dart@@ -14,6 +14,7 @@ import "package:photos/models/gallery/gallery_layout_config.dart";import "package:photos/models/gallery/justified_grid_row.dart";import "package:photos/models/gallery/justified_layout.dart";import "package:photos/models/gallery/justified_layout_strategy.dart";+import "package:photos/models/gallery/justified_layout_tuning.dart";import "package:photos/models/gallery/section_layout.dart";import "package:photos/models/selected_files.dart";import "package:photos/service_locator.dart";@@ -446,32 +447,65 @@ class GalleryGroups {List<SectionLayout> _computeJustifiedGroupLayouts() {final stopwatch = Stopwatch()..start();+ final strategy = localSettings.getJustifiedLayoutStrategy();+ final flexTuning = strategy == JustifiedLayoutStrategy.flex+ ? localSettings.getFlexLayoutTuning()+ : FlexLayoutTuning.defaults;+ final comfortLargeTuning = strategy == JustifiedLayoutStrategy.comfortLarge+ ? localSettings.getComfortLargeLayoutTuning()+ : ComfortLargeLayoutTuning.defaults;final gridTargetRowHeight =(widthAvailable - (crossAxisCount - 1) * spacing) / crossAxisCount;- final targetRowHeight = gridTargetRowHeight.isFinite+ final baseTargetRowHeight = gridTargetRowHeight.isFinite? math.min(gridTargetRowHeight, _maximumJustifiedTargetRowHeight): gridTargetRowHeight;- final computeRows = switch (localSettings.getJustifiedLayoutStrategy()) {- JustifiedLayoutStrategy.comfort => JustifiedLayoutCalculator.computeRows,- JustifiedLayoutStrategy.flex => FlexLayoutCalculator.computeRows,+ final targetHeightScale = switch (strategy) {+ JustifiedLayoutStrategy.comfort => 1.0,+ JustifiedLayoutStrategy.comfortLarge =>+ comfortLargeTuning.targetHeightScale,+ JustifiedLayoutStrategy.flex => flexTuning.targetHeightScale,};+ final targetRowHeight = baseTargetRowHeight * targetHeightScale;final groupLayouts = <SectionLayout>[];var currentIndex = 0;var currentOffset = 0.0;for (final groupID in _groupIdToFilesMap.keys) {final filesInGroup = _groupIdToFilesMap[groupID]!;- final rows = computeRows(- aspectRatios: filesInGroup.map(- (file) => JustifiedLayoutCalculator.aspectRatioForDimensions(- file.width,- file.height,- ),+ final aspectRatios = filesInGroup.map(+ (file) => JustifiedLayoutCalculator.aspectRatioForDimensions(+ file.width,+ file.height,),- availableWidth: widthAvailable,- targetRowHeight: targetRowHeight,- spacing: spacing,);+ final rows = switch (strategy) {+ JustifiedLayoutStrategy.comfort =>+ JustifiedLayoutCalculator.computeRows(+ aspectRatios: aspectRatios,+ availableWidth: widthAvailable,+ targetRowHeight: targetRowHeight,+ spacing: spacing,+ ),+ JustifiedLayoutStrategy.comfortLarge =>+ JustifiedLayoutCalculator.computeRows(+ aspectRatios: aspectRatios,+ availableWidth: widthAvailable,+ targetRowHeight: targetRowHeight,+ spacing: spacing,+ maximumRowHeightFactor: comfortLargeTuning.maximumHeightFactor,+ wideFinalMaximumRowHeightFactor:+ comfortLargeTuning.wideFinalMaximumHeightFactor,+ minimumLandscapeRowHeightFactor:+ comfortLargeTuning.minimumLandscapeHeightFactor,+ ),+ JustifiedLayoutStrategy.flex => FlexLayoutCalculator.computeRows(+ aspectRatios: aspectRatios,+ availableWidth: widthAvailable,+ targetRowHeight: targetRowHeight,+ spacing: spacing,+ maximumRowHeightFactor: flexTuning.maximumHeightFactor,+ ),+ };final firstIndex = currentIndex == 0 ? currentIndex : currentIndex + 1;final lastIndex = firstIndex + rows.length;final minOffset = currentOffset;diff --git a/mobile/apps/photos/lib/models/gallery/justified_layout.dart b/mobile/apps/photos/lib/models/gallery/justified_layout.dartindex 8b51494380..1653ed91af 100644--- a/mobile/apps/photos/lib/models/gallery/justified_layout.dart+++ b/mobile/apps/photos/lib/models/gallery/justified_layout.dart@@ -133,6 +133,9 @@ class JustifiedLayoutCalculator {required double availableWidth,required double targetRowHeight,required double spacing,+ double maximumRowHeightFactor = _maximumRowHeightFactor,+ double wideFinalMaximumRowHeightFactor = _maximumWideFinalRowHeightFactor,+ double minimumLandscapeRowHeightFactor = _minimumLandscapeRowHeightFactor,}) {if (aspectRatios.isEmpty) return const [];if (!availableWidth.isFinite || availableWidth <= 0) {@@ -144,18 +147,37 @@ class JustifiedLayoutCalculator {if (!spacing.isFinite || spacing < 0) {throw ArgumentError.value(spacing, "spacing");}+ if (!maximumRowHeightFactor.isFinite || maximumRowHeightFactor < 1) {+ throw ArgumentError.value(+ maximumRowHeightFactor,+ "maximumRowHeightFactor",+ );+ }+ if (!wideFinalMaximumRowHeightFactor.isFinite ||+ wideFinalMaximumRowHeightFactor < 1) {+ throw ArgumentError.value(+ wideFinalMaximumRowHeightFactor,+ "wideFinalMaximumRowHeightFactor",+ );+ }+ if (!minimumLandscapeRowHeightFactor.isFinite ||+ minimumLandscapeRowHeightFactor <= 0) {+ throw ArgumentError.value(+ minimumLandscapeRowHeightFactor,+ "minimumLandscapeRowHeightFactor",+ );+ }final rows = <JustifiedRowLayout>[];final pendingRatios = <double>[];- final maximumRowHeight = targetRowHeight * _maximumRowHeightFactor;+ final maximumRowHeight = targetRowHeight * maximumRowHeightFactor;final maximumItemsPerRow = _maximumItemsPerRowFor(availableWidth);- // Product decision: on wider galleries, prefer a partial final row over- // enlarging its items by more than 25%. Compact layouts retain their- // existing tail treatment.+ // On wider galleries, prefer a partial final row once its configured+ // growth limit is reached. Compact layouts retain their tail treatment.final limitsFinalRowGrowth = availableWidth >= _mediumWidthBreakpoint;final maximumFinalRowHeightFactor = limitsFinalRowGrowth- ? _maximumWideFinalRowHeightFactor- : _maximumRowHeightFactor;+ ? wideFinalMaximumRowHeightFactor+ : maximumRowHeightFactor;final maximumFinalRowHeight = targetRowHeight * maximumFinalRowHeightFactor;final lastCommittedRatios = <double>[];var pendingRatioSum = 0.0;@@ -229,7 +251,7 @@ class JustifiedLayoutCalculator {return ratios.length < _minimumLandscapeDensityItemCount ||ratios.any((ratio) => ratio < 1) ||- height >= targetRowHeight * _minimumLandscapeRowHeightFactor;+ height >= targetRowHeight * minimumLandscapeRowHeightFactor;}void replacePendingRatios(Iterable<double> ratios) {@@ -278,8 +300,7 @@ class JustifiedLayoutCalculator {candidateCount >= _minimumLandscapeDensityItemCount &&pendingMinimumRatio >= 1 &&ratio >= 1 &&- candidateHeight <- targetRowHeight * _minimumLandscapeRowHeightFactor;+ candidateHeight < targetRowHeight * minimumLandscapeRowHeightFactor;if (violatesTapTarget || violatesLandscapeDensity) {final leaveSingletonRagged = pendingRatios.length == 1;@@ -336,7 +357,7 @@ class JustifiedLayoutCalculator {final shouldJustifyFinalRow = canJustifyFinalRow(pendingRatios);final singletonHeightFactor =pendingRatios.length == 1 && pendingRatios.single < 1- ? math.min(_maximumRowHeightFactor, 1 / pendingRatios.single)+ ? math.min(maximumRowHeightFactor, 1 / pendingRatios.single): 1.0;final finalRowHeightFactor = pendingRatios.length == 1? math.min(singletonHeightFactor, maximumFinalRowHeightFactor)@@ -346,7 +367,7 @@ class JustifiedLayoutCalculator {addPendingRow(fillWidth: pendingRatios.length > 1 && shouldJustifyFinalRow,// Give compact portrait singletons roughly one target-width column;- // wider tails also obey their 25% growth limit.+ // wider tails also obey their configured growth limit.raggedHeightFactor: finalRowHeightFactor,);}diff --git a/mobile/apps/photos/lib/models/gallery/justified_layout_strategy.dart b/mobile/apps/photos/lib/models/gallery/justified_layout_strategy.dartindex eebf97f2ec..0e6f053a44 100644--- a/mobile/apps/photos/lib/models/gallery/justified_layout_strategy.dart+++ b/mobile/apps/photos/lib/models/gallery/justified_layout_strategy.dart@@ -1 +1 @@-enum JustifiedLayoutStrategy { comfort, flex }+enum JustifiedLayoutStrategy { comfort, comfortLarge, flex }diff --git a/mobile/apps/photos/lib/models/gallery/justified_layout_tuning.dart b/mobile/apps/photos/lib/models/gallery/justified_layout_tuning.dartnew file mode 100644index 0000000000..fa53f14caa--- /dev/null+++ b/mobile/apps/photos/lib/models/gallery/justified_layout_tuning.dart@@ -0,0 +1,84 @@+enum FlexLayoutTuningField { targetHeightScale, maximumHeightFactor }++enum ComfortLargeLayoutTuningField {+ targetHeightScale,+ maximumHeightFactor,+ wideFinalMaximumHeightFactor,+ minimumLandscapeHeightFactor,+}++class FlexLayoutTuning {+ static const defaults = FlexLayoutTuning();++ final double targetHeightScale;+ final double maximumHeightFactor;++ const FlexLayoutTuning({+ this.targetHeightScale = 1.12,+ this.maximumHeightFactor = 1.6,+ });++ double valueFor(FlexLayoutTuningField field) {+ return switch (field) {+ FlexLayoutTuningField.targetHeightScale => targetHeightScale,+ FlexLayoutTuningField.maximumHeightFactor => maximumHeightFactor,+ };+ }+}++extension FlexLayoutTuningFieldValue on FlexLayoutTuningField {+ double get defaultValue => FlexLayoutTuning.defaults.valueFor(this);++ double get maximumValue => 10;++ double get minimumValue => switch (this) {+ FlexLayoutTuningField.targetHeightScale => 0.1,+ FlexLayoutTuningField.maximumHeightFactor => 1,+ };++ bool isValid(double value) =>+ value.isFinite && value >= minimumValue && value <= maximumValue;+}++class ComfortLargeLayoutTuning {+ static const defaults = ComfortLargeLayoutTuning();++ final double targetHeightScale;+ final double maximumHeightFactor;+ final double wideFinalMaximumHeightFactor;+ final double minimumLandscapeHeightFactor;++ const ComfortLargeLayoutTuning({+ this.targetHeightScale = 1.12,+ this.maximumHeightFactor = 2.4,+ this.wideFinalMaximumHeightFactor = 1.25,+ this.minimumLandscapeHeightFactor = 0.88,+ });++ double valueFor(ComfortLargeLayoutTuningField field) {+ return switch (field) {+ ComfortLargeLayoutTuningField.targetHeightScale => targetHeightScale,+ ComfortLargeLayoutTuningField.maximumHeightFactor => maximumHeightFactor,+ ComfortLargeLayoutTuningField.wideFinalMaximumHeightFactor =>+ wideFinalMaximumHeightFactor,+ ComfortLargeLayoutTuningField.minimumLandscapeHeightFactor =>+ minimumLandscapeHeightFactor,+ };+ }+}++extension ComfortLargeLayoutTuningFieldValue on ComfortLargeLayoutTuningField {+ double get defaultValue => ComfortLargeLayoutTuning.defaults.valueFor(this);++ double get maximumValue => 10;++ double get minimumValue => switch (this) {+ ComfortLargeLayoutTuningField.targetHeightScale ||+ ComfortLargeLayoutTuningField.minimumLandscapeHeightFactor => 0.1,+ ComfortLargeLayoutTuningField.maximumHeightFactor ||+ ComfortLargeLayoutTuningField.wideFinalMaximumHeightFactor => 1,+ };++ bool isValid(double value) =>+ value.isFinite && value >= minimumValue && value <= maximumValue;+}diff --git a/mobile/apps/photos/lib/settings/local_settings.dart b/mobile/apps/photos/lib/settings/local_settings.dartindex 9ee733bef3..f23de445f4 100644--- a/mobile/apps/photos/lib/settings/local_settings.dart+++ b/mobile/apps/photos/lib/settings/local_settings.dart@@ -4,6 +4,7 @@ import 'package:home_widget/home_widget.dart' as hw;import 'package:photos/app_mode.dart';import 'package:photos/core/constants.dart';import 'package:photos/models/gallery/justified_layout_strategy.dart';+import 'package:photos/models/gallery/justified_layout_tuning.dart';import 'package:photos/ui/viewer/gallery/component/group/type.dart';import "package:photos/utils/ram_check_util.dart";import 'package:shared_preferences/shared_preferences.dart';@@ -59,6 +60,18 @@ class LocalSettings {static const kGalleryGroupType = "gallery_group_type";static const kGalleryLayoutType = "gallery_layout_type";static const kJustifiedLayoutStrategy = "justified_layout_strategy";+ static const kFlexLayoutTuningTargetHeightScale =+ "gallery.justified.flex.target_height_scale";+ static const kFlexLayoutTuningMaximumHeightFactor =+ "gallery.justified.flex.maximum_height_factor";+ static const kComfortLargeLayoutTuningTargetHeightScale =+ "gallery.justified.comfort_large.target_height_scale";+ static const kComfortLargeLayoutTuningMaximumHeightFactor =+ "gallery.justified.comfort_large.maximum_height_factor";+ static const kComfortLargeLayoutTuningWideFinalMaximumHeightFactor =+ "gallery.justified.comfort_large.wide_final_maximum_height_factor";+ static const kComfortLargeLayoutTuningMinimumLandscapeHeightFactor =+ "gallery.justified.comfort_large.minimum_landscape_height_factor";static const kPhotoGridSize = "photo_grid_size";static const _kisMLLocalIndexingEnabled = "ls.ml_local_indexing";static const _kLocalGalleryMLLocalIndexingEnabled =@@ -283,6 +296,7 @@ class LocalSettings {JustifiedLayoutStrategy getJustifiedLayoutStrategy() {return switch (_prefs.getString(kJustifiedLayoutStrategy)) {+ "comfortLarge" => JustifiedLayoutStrategy.comfortLarge,"flex" => JustifiedLayoutStrategy.flex,_ => JustifiedLayoutStrategy.comfort,};@@ -294,6 +308,125 @@ class LocalSettings {await _prefs.setString(kJustifiedLayoutStrategy, strategy.name);}+ FlexLayoutTuning getFlexLayoutTuning() {+ return FlexLayoutTuning(+ targetHeightScale: _validDoubleOrDefault(+ kFlexLayoutTuningTargetHeightScale,+ FlexLayoutTuningField.targetHeightScale.defaultValue,+ FlexLayoutTuningField.targetHeightScale.isValid,+ ),+ maximumHeightFactor: _validDoubleOrDefault(+ kFlexLayoutTuningMaximumHeightFactor,+ FlexLayoutTuningField.maximumHeightFactor.defaultValue,+ FlexLayoutTuningField.maximumHeightFactor.isValid,+ ),+ );+ }++ Future<void> setFlexLayoutTuningValue(+ FlexLayoutTuningField field,+ double value,+ ) async {+ if (!field.isValid(value)) {+ throw ArgumentError.value(value, field.name);+ }+ await _prefs.setDouble(_flexLayoutTuningKey(field), value);+ }++ Future<void> resetFlexLayoutTuningValue(FlexLayoutTuningField field) async {+ await _prefs.remove(_flexLayoutTuningKey(field));+ }++ Future<void> resetFlexLayoutTuning() async {+ await Future.wait(+ FlexLayoutTuningField.values.map(resetFlexLayoutTuningValue),+ );+ }++ ComfortLargeLayoutTuning getComfortLargeLayoutTuning() {+ return ComfortLargeLayoutTuning(+ targetHeightScale: _validDoubleOrDefault(+ kComfortLargeLayoutTuningTargetHeightScale,+ ComfortLargeLayoutTuningField.targetHeightScale.defaultValue,+ ComfortLargeLayoutTuningField.targetHeightScale.isValid,+ ),+ maximumHeightFactor: _validDoubleOrDefault(+ kComfortLargeLayoutTuningMaximumHeightFactor,+ ComfortLargeLayoutTuningField.maximumHeightFactor.defaultValue,+ ComfortLargeLayoutTuningField.maximumHeightFactor.isValid,+ ),+ wideFinalMaximumHeightFactor: _validDoubleOrDefault(+ kComfortLargeLayoutTuningWideFinalMaximumHeightFactor,+ ComfortLargeLayoutTuningField.wideFinalMaximumHeightFactor.defaultValue,+ ComfortLargeLayoutTuningField.wideFinalMaximumHeightFactor.isValid,+ ),+ minimumLandscapeHeightFactor: _validDoubleOrDefault(+ kComfortLargeLayoutTuningMinimumLandscapeHeightFactor,+ ComfortLargeLayoutTuningField.minimumLandscapeHeightFactor.defaultValue,+ ComfortLargeLayoutTuningField.minimumLandscapeHeightFactor.isValid,+ ),+ );+ }++ Future<void> setComfortLargeLayoutTuningValue(+ ComfortLargeLayoutTuningField field,+ double value,+ ) async {+ if (!field.isValid(value)) {+ throw ArgumentError.value(value, field.name);+ }+ await _prefs.setDouble(_comfortLargeLayoutTuningKey(field), value);+ }++ Future<void> resetComfortLargeLayoutTuningValue(+ ComfortLargeLayoutTuningField field,+ ) async {+ await _prefs.remove(_comfortLargeLayoutTuningKey(field));+ }++ Future<void> resetComfortLargeLayoutTuning() async {+ await Future.wait(+ ComfortLargeLayoutTuningField.values.map(+ resetComfortLargeLayoutTuningValue,+ ),+ );+ }++ double _validDoubleOrDefault(+ String key,+ double fallback,+ bool Function(double) isValid,+ ) {+ final storedValue = _prefs.get(key);+ if (storedValue is! num) return fallback;+ final value = storedValue.toDouble();+ return isValid(value) ? value : fallback;+ }++ static String _flexLayoutTuningKey(FlexLayoutTuningField field) {+ return switch (field) {+ FlexLayoutTuningField.targetHeightScale =>+ kFlexLayoutTuningTargetHeightScale,+ FlexLayoutTuningField.maximumHeightFactor =>+ kFlexLayoutTuningMaximumHeightFactor,+ };+ }++ static String _comfortLargeLayoutTuningKey(+ ComfortLargeLayoutTuningField field,+ ) {+ return switch (field) {+ ComfortLargeLayoutTuningField.targetHeightScale =>+ kComfortLargeLayoutTuningTargetHeightScale,+ ComfortLargeLayoutTuningField.maximumHeightFactor =>+ kComfortLargeLayoutTuningMaximumHeightFactor,+ ComfortLargeLayoutTuningField.wideFinalMaximumHeightFactor =>+ kComfortLargeLayoutTuningWideFinalMaximumHeightFactor,+ ComfortLargeLayoutTuningField.minimumLandscapeHeightFactor =>+ kComfortLargeLayoutTuningMinimumLandscapeHeightFactor,+ };+ }+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.dartindex 249beda1df..2b3600efb5 100644--- a/mobile/apps/photos/lib/ui/settings/gallery_settings_screen.dart+++ b/mobile/apps/photos/lib/ui/settings/gallery_settings_screen.dart@@ -9,6 +9,7 @@ import "package:photos/models/gallery/gallery_layout_config.dart";import "package:photos/models/gallery/justified_layout_strategy.dart";import "package:photos/service_locator.dart";import "package:photos/settings/local_settings.dart";+import "package:photos/ui/settings/justified_layout_tuning_screen.dart";import "package:photos/ui/viewer/gallery/component/group/type.dart";import "package:photos/ui/viewer/gallery/justified_layout_strategy_label.dart";@@ -57,6 +58,17 @@ class _GallerySettingsScreenState extends State<GallerySettingsScreen> {onTap: () async => _showLayoutTypeSheet(context),),const SizedBox(height: 8),+ SettingsItem(+ title: "Justified layout tuning",+ onTap: () async {+ await Navigator.of(context).push(+ MaterialPageRoute<void>(+ builder: (_) => const JustifiedLayoutTuningScreen(),+ ),+ );+ },+ ),+ const SizedBox(height: 8),],SettingsItem(title: l10n.photoGridSize,diff --git a/mobile/apps/photos/lib/ui/settings/justified_layout_tuning_screen.dart b/mobile/apps/photos/lib/ui/settings/justified_layout_tuning_screen.dartnew file mode 100644index 0000000000..68becb9e62--- /dev/null+++ b/mobile/apps/photos/lib/ui/settings/justified_layout_tuning_screen.dart@@ -0,0 +1,278 @@+import "package:ente_components/ente_components.dart";+import "package:ente_strings/ente_strings.dart";+import "package:flutter/material.dart";+import "package:photos/core/event_bus.dart";+import "package:photos/events/gallery_layout_changed_event.dart";+import "package:photos/models/gallery/justified_layout_tuning.dart";+import "package:photos/service_locator.dart";+import "package:photos/ui/components/menu_section_title.dart";++class JustifiedLayoutTuningScreen extends StatefulWidget {+ const JustifiedLayoutTuningScreen({super.key});++ @override+ State<JustifiedLayoutTuningScreen> createState() =>+ _JustifiedLayoutTuningScreenState();+}++class _JustifiedLayoutTuningScreenState+ extends State<JustifiedLayoutTuningScreen> {+ @override+ Widget build(BuildContext context) {+ final flexTuning = localSettings.getFlexLayoutTuning();+ final comfortLargeTuning = localSettings.getComfortLargeLayoutTuning();++ return SettingsPageScaffold(+ title: "Justified layout tuning",+ children: [+ Text(+ "Values are multipliers of the responsive target row height.",+ style: TextStyles.mini.copyWith(+ color: context.componentColors.textLight,+ ),+ ),+ const SizedBox(height: 16),+ const MenuSectionTitle(title: "Flex"),+ MenuGroupComponent(+ items: [+ for (final field in FlexLayoutTuningField.values)+ SettingsItem(+ title: _flexFieldLabel(field),+ trailing: _valueLabel(context, flexTuning.valueFor(field)),+ onTap: () => _editFlexValue(field),+ ),+ SettingsItem(+ title: "Reset all",+ showChevron: false,+ onTap: _resetFlexValues,+ ),+ ],+ ),+ const SizedBox(height: 24),+ const MenuSectionTitle(title: "Comfort Large"),+ MenuGroupComponent(+ items: [+ for (final field in ComfortLargeLayoutTuningField.values)+ SettingsItem(+ title: _comfortLargeFieldLabel(field),+ trailing: _valueLabel(+ context,+ comfortLargeTuning.valueFor(field),+ ),+ onTap: () => _editComfortLargeValue(field),+ ),+ SettingsItem(+ title: "Reset all",+ showChevron: false,+ onTap: _resetComfortLargeValues,+ ),+ ],+ ),+ ],+ );+ }++ Widget _valueLabel(BuildContext context, double value) {+ return Text(+ _formatValue(value),+ style: TextStyles.mini.copyWith(color: context.componentColors.textLight),+ );+ }++ Future<void> _editFlexValue(FlexLayoutTuningField field) async {+ final tuning = localSettings.getFlexLayoutTuning();+ await _showValueSheet(+ title: _flexFieldLabel(field),+ initialValue: tuning.valueFor(field),+ defaultValue: field.defaultValue,+ isValid: field.isValid,+ validRange: (field.minimumValue, field.maximumValue),+ onSave: (value) async {+ await localSettings.setFlexLayoutTuningValue(field, value);+ _refreshGallery();+ },+ onReset: () async {+ await localSettings.resetFlexLayoutTuningValue(field);+ _refreshGallery();+ },+ );+ }++ Future<void> _editComfortLargeValue(+ ComfortLargeLayoutTuningField field,+ ) async {+ final tuning = localSettings.getComfortLargeLayoutTuning();+ await _showValueSheet(+ title: _comfortLargeFieldLabel(field),+ initialValue: tuning.valueFor(field),+ defaultValue: field.defaultValue,+ isValid: field.isValid,+ validRange: (field.minimumValue, field.maximumValue),+ onSave: (value) async {+ await localSettings.setComfortLargeLayoutTuningValue(field, value);+ _refreshGallery();+ },+ onReset: () async {+ await localSettings.resetComfortLargeLayoutTuningValue(field);+ _refreshGallery();+ },+ );+ }++ Future<void> _showValueSheet({+ required String title,+ required double initialValue,+ required double defaultValue,+ required bool Function(double) isValid,+ required (double, double) validRange,+ required Future<void> Function(double) onSave,+ required Future<void> Function() onReset,+ }) async {+ await showBottomSheetComponent<void>(+ context: context,+ builder: (_) => _TuningValueSheet(+ title: title,+ initialValue: initialValue,+ defaultValue: defaultValue,+ isValid: isValid,+ validRange: validRange,+ onSave: onSave,+ onReset: onReset,+ ),+ );+ }++ Future<void> _resetFlexValues() async {+ await localSettings.resetFlexLayoutTuning();+ _refreshGallery();+ }++ Future<void> _resetComfortLargeValues() async {+ await localSettings.resetComfortLargeLayoutTuning();+ _refreshGallery();+ }++ void _refreshGallery() {+ if (mounted) setState(() {});+ Bus.instance.fire(GalleryLayoutChangedEvent());+ }+}++class _TuningValueSheet extends StatefulWidget {+ const _TuningValueSheet({+ required this.title,+ required this.initialValue,+ required this.defaultValue,+ required this.isValid,+ required this.validRange,+ required this.onSave,+ required this.onReset,+ });++ final String title;+ final double initialValue;+ final double defaultValue;+ final bool Function(double) isValid;+ final (double, double) validRange;+ final Future<void> Function(double) onSave;+ final Future<void> Function() onReset;++ @override+ State<_TuningValueSheet> createState() => _TuningValueSheetState();+}++class _TuningValueSheetState extends State<_TuningValueSheet> {+ late final TextEditingController _controller;+ late bool _isValid;++ @override+ void initState() {+ super.initState();+ final text = _formatValue(widget.initialValue);+ _controller = TextEditingController(text: text);+ _controller.selection = TextSelection(+ baseOffset: 0,+ extentOffset: text.length,+ );+ _isValid = _validate(text) != null;+ }++ @override+ void dispose() {+ _controller.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ return BottomSheetComponent(+ title: widget.title,+ isKeyboardAware: true,+ content: TextInputComponent(+ controller: _controller,+ autofocus: true,+ keyboardType: const TextInputType.numberWithOptions(decimal: true),+ textInputAction: TextInputAction.done,+ message: _isValid+ ? "Default: ${_formatValue(widget.defaultValue)}"+ : "Enter a value from ${_formatValue(widget.validRange.$1)} "+ "to ${_formatValue(widget.validRange.$2)}",+ messageType: _isValid+ ? TextInputComponentMessageType.helper+ : TextInputComponentMessageType.error,+ onChanged: (value) {+ final isValid = _validate(value) != null;+ if (_isValid != isValid) setState(() => _isValid = isValid);+ },+ onSubmit: (_) => _save(),+ ),+ actions: [+ ButtonComponent(+ label: context.strings.save,+ isDisabled: !_isValid,+ onTap: _save,+ ),+ ButtonComponent(+ label: context.strings.resetToDefault,+ variant: ButtonComponentVariant.secondary,+ onTap: _reset,+ ),+ ],+ );+ }++ double? _validate(String text) {+ final value = double.tryParse(text.trim());+ return value != null && widget.isValid(value) ? value : null;+ }++ Future<void> _save() async {+ final value = _validate(_controller.text);+ if (value == null) return;+ await widget.onSave(value);+ if (mounted) Navigator.of(context).pop();+ }++ Future<void> _reset() async {+ await widget.onReset();+ if (mounted) Navigator.of(context).pop();+ }+}++String _flexFieldLabel(FlexLayoutTuningField field) => switch (field) {+ FlexLayoutTuningField.targetHeightScale => "Target height scale",+ FlexLayoutTuningField.maximumHeightFactor => "Maximum height factor",+};++String _comfortLargeFieldLabel(ComfortLargeLayoutTuningField field) =>+ switch (field) {+ ComfortLargeLayoutTuningField.targetHeightScale => "Target height scale",+ ComfortLargeLayoutTuningField.maximumHeightFactor =>+ "Maximum height factor",+ ComfortLargeLayoutTuningField.wideFinalMaximumHeightFactor =>+ "Wide final maximum height factor",+ ComfortLargeLayoutTuningField.minimumLandscapeHeightFactor =>+ "Minimum landscape height factor",+ };++String _formatValue(double value) => value.toString();diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/justified_layout_strategy_label.dart b/mobile/apps/photos/lib/ui/viewer/gallery/justified_layout_strategy_label.dartindex 3252a1e816..3b82a586ed 100644--- a/mobile/apps/photos/lib/ui/viewer/gallery/justified_layout_strategy_label.dart+++ b/mobile/apps/photos/lib/ui/viewer/gallery/justified_layout_strategy_label.dart@@ -5,6 +5,8 @@ import "package:photos/models/gallery/justified_layout_strategy.dart";extension JustifiedLayoutStrategyLabel on JustifiedLayoutStrategy {String label(BuildContext context) => switch (this) {JustifiedLayoutStrategy.comfort => context.strings.layoutJustifiedComfort,+ JustifiedLayoutStrategy.comfortLarge =>+ "${context.strings.layoutJustifiedComfort} Large",JustifiedLayoutStrategy.flex => context.strings.layoutJustifiedFlex,};}diff --git a/mobile/apps/photos/test/models/flex_layout_test.dart b/mobile/apps/photos/test/models/flex_layout_test.dartindex 578b40ef67..b37c82c9b4 100644--- a/mobile/apps/photos/test/models/flex_layout_test.dart+++ b/mobile/apps/photos/test/models/flex_layout_test.dart@@ -1,105 +1,136 @@import "package:flutter_test/flutter_test.dart";import "package:photos/models/gallery/flex_layout.dart";+import "package:photos/models/gallery/justified_layout.dart";void main() {- test("considers later photos when choosing an earlier row break", () {- List<int> rowCounts(List<double> ratios) =>- FlexLayoutCalculator.computeRows(- aspectRatios: ratios,- availableWidth: 402,- targetRowHeight: 200,- spacing: 2,- ).map((row) => row.itemWidths.length).toList();-- expect(rowCounts([1.5, 0.5, 0.5]), [1, 2]);- expect(rowCounts([1.5, 0.5, 0.5, 0.5, 0.5]), [2, 3]);+ test("never creates a singleton before the final row", () {+ for (final width in [393.0, 744.0, 1024.0, 1366.0]) {+ for (final ratios in <List<double>>[+ [1.5, 0.5, 0.5],+ [4, 1 / 3, 1, 1],+ [1 / 3, 4, 1 / 3, 4, 1],+ List.filled(9, 9 / 16),+ ]) {+ final rows = _rows(ratios, width: width);++ expect(+ rows.take(rows.length - 1).map((row) => row.itemWidths.length),+ everyElement(greaterThanOrEqualTo(2)),+ reason: "width $width, ratios $ratios",+ );+ expect(rows.last.lastIndex, ratios.length - 1);+ }+ }});- test("can exceed Comfort's item cap to avoid a portrait orphan", () {- final rows = FlexLayoutCalculator.computeRows(- aspectRatios: List.filled(4, 9 / 16),- availableWidth: 402,- targetRowHeight: 200,- spacing: 2,+ test("uses adaptive cropping only when a row cannot remain tappable", () {+ final rows = _rows([4, 1 / 3, 1, 1]);+ final extremeRow = rows.first;++ expect(extremeRow.itemWidths, hasLength(2));+ expect(_occupiedWidth(extremeRow), closeTo(402, 1e-9));+ expect(extremeRow.itemWidths, everyElement(greaterThanOrEqualTo(48)));+ expect(+ extremeRow.itemWidths[1] / extremeRow.height,+ isNot(closeTo(1 / 3, 1e-9)),);- expect(rows, hasLength(1));- expect(rows.single.itemWidths, hasLength(4));++ final naturalRow = _rows([1, 1]).single;expect(- rows.single.itemWidths.reduce((a, b) => a + b) + 6,- closeTo(402, 1e-9),+ naturalRow.itemWidths.map((width) => width / naturalRow.height),+ everyElement(closeTo(1, 1e-9)),);});- test("keeps dense portraits balanced and sparse tablet tails restrained", () {- final portraits = FlexLayoutCalculator.computeRows(- aspectRatios: List.filled(9, 9 / 16),- availableWidth: 402,- targetRowHeight: 200,- spacing: 2,- );- expect(portraits.map((row) => row.itemWidths.length), [3, 3, 3]);- final tail = FlexLayoutCalculator.computeRows(- aspectRatios: const [0.75, 0.75],- availableWidth: 1024,- targetRowHeight: 320,- spacing: 2,+ test("conserves width at an adaptive-crop pinning threshold", () {+ final row = _rows([3.12, 0.4, 0.48], width: 404, targetHeight: 80).single;++ expect(row.itemWidths, everyElement(greaterThanOrEqualTo(48)));+ expect(_occupiedWidth(row), closeTo(404, 1e-9));+ });++ test("can exceed Comfort's item cap to avoid a portrait orphan", () {+ final rows = _rows(List.filled(4, 9 / 16));++ expect(rows, hasLength(1));+ expect(rows.single.itemWidths, hasLength(4));+ expect(_occupiedWidth(rows.single), closeTo(402, 1e-9));+ });++ test("fills a final row until its configurable maximum height", () {+ final fitted = _rows([0.75, 0.75], targetHeight: 200).single;+ expect(fitted.height, closeTo(400 / 1.5, 1e-9));+ expect(_occupiedWidth(fitted), closeTo(402, 1e-9));++ final capped = _rows([0.75, 0.75], width: 1024, targetHeight: 320).single;+ expect(capped.height, 512);+ expect(_occupiedWidth(capped), lessThan(1024));++ final relaxed = _rows(+ [0.75, 0.75],+ width: 1024,+ targetHeight: 320,+ maximumHeightFactor: 2,).single;- expect(tail.height, 320);- expect(tail.itemWidths.reduce((a, b) => a + b) + 2, lessThan(1024));+ expect(relaxed.height, 640);+ expect(relaxed.height, greaterThan(capped.height));});- test("preserves file order, ratios and tap extents across screen sizes", () {- const ratios = [1 / 3, 4.0, 0.85, 4.0, 1.0, 0.75, 1.5, 0.5, 1.0];- for (final width in [393.0, 744.0, 1024.0, 1366.0]) {- final rows = FlexLayoutCalculator.computeRows(- aspectRatios: ratios,- availableWidth: width,- targetRowHeight: width < 600 ? 195.5 : 320,- spacing: 2,- );- var fileIndex = 0;- var offset = 0.0;- for (final row in rows) {- expect(row.firstIndex, fileIndex);- expect(row.minOffset, closeTo(offset, 1e-9));- expect(row.height, greaterThanOrEqualTo(48));- expect(row.itemWidths, everyElement(greaterThanOrEqualTo(48 - 1e-9)));- for (final tileWidth in row.itemWidths) {- expect(tileWidth / row.height, closeTo(ratios[fileIndex++], 1e-9));+ test(+ "preserves order, offsets and tappable geometry across screen sizes",+ () {+ const ratios = [1 / 3, 4.0, 0.85, 4.0, 1.0, 0.75, 1.5, 0.5, 1.0];+ for (final width in [393.0, 744.0, 1024.0, 1366.0]) {+ final rows = _rows(ratios, width: width);+ var fileIndex = 0;+ var offset = 0.0;+ for (final row in rows) {+ expect(row.firstIndex, fileIndex);+ expect(row.minOffset, closeTo(offset, 1e-9));+ expect(row.height, inInclusiveRange(48, 320 * 1.6));+ expect(row.itemWidths, everyElement(greaterThanOrEqualTo(48 - 1e-9)));+ fileIndex += row.itemWidths.length;+ expect(row.lastIndex, fileIndex - 1);+ expect(_occupiedWidth(row), lessThanOrEqualTo(width + 1e-7));+ offset = row.maxOffset + 2;}- expect(row.lastIndex, fileIndex - 1);- expect(- row.itemWidths.reduce((a, b) => a + b) +- 2 * (row.itemWidths.length - 1),- lessThanOrEqualTo(width + 1e-9),- );- offset = row.maxOffset + 2;+ expect(fileIndex, ratios.length);}- expect(fileIndex, ratios.length);- }- });+ },+ );- test("normalizes missing and extreme ratios and handles empty groups", () {- final rows = FlexLayoutCalculator.computeRows(- aspectRatios: [0, double.nan, double.infinity, 0.01, 100],- availableWidth: 744,- targetRowHeight: 320,- spacing: 2,- );- expect(- rows.expand((row) => row.itemWidths.map((width) => width / row.height)),- orderedEquals(- [1.0, 1.0, 1.0, 1 / 3, 4.0].map((ratio) => closeTo(ratio, 1e-9)),- ),- );+ test("normalizes invalid ratios and handles empty groups", () {+ final rows = _rows([0, double.nan, double.infinity, 0.01, 100]);++ expect(rows.last.lastIndex, 4);expect(- FlexLayoutCalculator.computeRows(- aspectRatios: [],- availableWidth: 402,- targetRowHeight: 200,- spacing: 2,- ),- isEmpty,+ rows.expand((row) => row.itemWidths),+ everyElement(greaterThanOrEqualTo(48)),);+ expect(_rows([]), isEmpty);+ });++ test("rejects invalid height tuning", () {+ expect(() => _rows([1], maximumHeightFactor: 0.9), throwsArgumentError);});}++List<JustifiedRowLayout> _rows(+ List<double> ratios, {+ double width = 402,+ double? targetHeight,+ double maximumHeightFactor = 1.6,+}) {+ return FlexLayoutCalculator.computeRows(+ aspectRatios: ratios,+ availableWidth: width,+ targetRowHeight: targetHeight ?? (width < 600 ? 200 : 320),+ spacing: 2,+ maximumRowHeightFactor: maximumHeightFactor,+ );+}++double _occupiedWidth(JustifiedRowLayout row) {+ return row.itemWidths.fold<double>(0, (sum, width) => sum + width) ++ 2 * (row.itemWidths.length - 1);+}diff --git a/mobile/apps/photos/test/models/gallery_groups_justified_test.dart b/mobile/apps/photos/test/models/gallery_groups_justified_test.dartindex 750911ce57..65e23ef2c6 100644--- a/mobile/apps/photos/test/models/gallery_groups_justified_test.dart+++ b/mobile/apps/photos/test/models/gallery_groups_justified_test.dart@@ -13,6 +13,7 @@ import "package:photos/models/gallery/gallery_groups.dart";import "package:photos/models/gallery/justified_grid_row.dart";import "package:photos/models/gallery/justified_layout.dart";import "package:photos/models/gallery/justified_layout_strategy.dart";+import "package:photos/models/gallery/justified_layout_tuning.dart";import "package:photos/models/metadata/file_magic.dart";import "package:photos/service_locator.dart";import "package:photos/settings/local_settings.dart";@@ -51,6 +52,8 @@ void main() {await localSettings.setJustifiedLayoutStrategy(JustifiedLayoutStrategy.comfort,);+ await localSettings.resetFlexLayoutTuning();+ await localSettings.resetComfortLargeLayoutTuning();await localSettings.setPhotoGridSize(4);});@@ -159,6 +162,56 @@ void main() {expect(flex.rows.single.itemWidths, hasLength(4));});+ test("keeps layout tuning separate for Flex and Comfort Large", () async {+ final file = _file(+ index: 0,+ creationTime: DateTime(2026, 8, 19).microsecondsSinceEpoch,+ width: 1,+ height: 1,+ );+ await localSettings.setPhotoGridSize(2);+ double rowHeight() {+ final section =+ _galleryGroups(+ files: [file],+ groupType: GroupType.none,+ groupHeaderExtent: GalleryGroups.spacing,+ widthAvailable: 1024,+ ).groupLayouts.single+ as JustifiedSectionLayout;+ return section.rows.single.height;+ }++ expect(rowHeight(), 320);++ await localSettings.setJustifiedLayoutStrategy(+ JustifiedLayoutStrategy.comfortLarge,+ );+ expect(+ rowHeight(),+ 320 * ComfortLargeLayoutTuning.defaults.targetHeightScale,+ );+ await localSettings.setComfortLargeLayoutTuningValue(+ ComfortLargeLayoutTuningField.targetHeightScale,+ 1.5,+ );+ expect(rowHeight(), 480);++ await localSettings.setJustifiedLayoutStrategy(+ JustifiedLayoutStrategy.flex,+ );+ final defaultFlexHeight =+ 320 *+ FlexLayoutTuning.defaults.targetHeightScale *+ FlexLayoutTuning.defaults.maximumHeightFactor;+ expect(rowHeight(), defaultFlexHeight);+ await localSettings.setFlexLayoutTuningValue(+ FlexLayoutTuningField.maximumHeightFactor,+ 2,+ );+ expect(rowHeight(), 320 * FlexLayoutTuning.defaults.targetHeightScale * 2);+ });+test("headerless justified remains one continuous group past grid chunks",() {diff --git a/mobile/apps/photos/test/models/justified_layout_test.dart b/mobile/apps/photos/test/models/justified_layout_test.dartindex 1fb62c9ebe..080d63e7e4 100644--- a/mobile/apps/photos/test/models/justified_layout_test.dart+++ b/mobile/apps/photos/test/models/justified_layout_test.dart@@ -232,10 +232,11 @@ void main() {spacing: 2,);- expect(rows.map((row) => row.itemWidths.length), [- testCase.maximumItems,- testCase.maximumItems,- ], reason: "available width ${testCase.width}");+ expect(+ rows.map((row) => row.itemWidths.length),+ [testCase.maximumItems, testCase.maximumItems],+ reason: "available width ${testCase.width}",+ );expect(rows.first.height,closeTo(3 * targetHeight, 1e-9),@@ -283,6 +284,35 @@ void main() {}});+ test("applies configurable Comfort row-height policies", () {+ final wideTail = JustifiedLayoutCalculator.computeRows(+ aspectRatios: const [0.75, 0.75],+ availableWidth: 1024,+ targetRowHeight: 320,+ spacing: 2,+ wideFinalMaximumRowHeightFactor: 2,+ ).single;+ expect(wideTail.height, 640);++ final landscapes = JustifiedLayoutCalculator.computeRows(+ aspectRatios: const [4 / 3, 4 / 3, 4 / 3],+ availableWidth: 393,+ targetRowHeight: (393 - 4) / 3,+ spacing: 2,+ minimumLandscapeRowHeightFactor: 0.5,+ );+ expect(landscapes.single.itemWidths, hasLength(3));++ final portrait = JustifiedLayoutCalculator.computeRows(+ aspectRatios: const [1 / 3],+ availableWidth: 393,+ targetRowHeight: 130,+ spacing: 2,+ maximumRowHeightFactor: 3,+ ).single;+ expect(portrait.height, 390);+ });+test("merges a final portrait with a tappable two-item row", () {final rows = JustifiedLayoutCalculator.computeRows(aspectRatios: const [1.0, 1.0, 0.5],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.dartindex f057654070..51b414f25a 100644--- a/mobile/apps/photos/test/settings/local_settings_gallery_layout_test.dart+++ b/mobile/apps/photos/test/settings/local_settings_gallery_layout_test.dart@@ -1,5 +1,6 @@import "package:flutter_test/flutter_test.dart";import "package:photos/models/gallery/justified_layout_strategy.dart";+import "package:photos/models/gallery/justified_layout_tuning.dart";import "package:photos/settings/local_settings.dart";import "package:shared_preferences/shared_preferences.dart";@@ -27,18 +28,239 @@ void main() {);});- test("justified strategy defaults to Comfort and persists Flex", () async {- SharedPreferences.setMockInitialValues({});- final preferences = await SharedPreferences.getInstance();- final settings = LocalSettings(preferences);- expect(- settings.getJustifiedLayoutStrategy(),- JustifiedLayoutStrategy.comfort,- );- await settings.setJustifiedLayoutStrategy(JustifiedLayoutStrategy.flex);- expect(- LocalSettings(preferences).getJustifiedLayoutStrategy(),- JustifiedLayoutStrategy.flex,- );+ test(+ "justified strategy defaults to Comfort and persists alternatives",+ () async {+ SharedPreferences.setMockInitialValues({});+ final preferences = await SharedPreferences.getInstance();+ final settings = LocalSettings(preferences);+ expect(+ settings.getJustifiedLayoutStrategy(),+ JustifiedLayoutStrategy.comfort,+ );+ for (final strategy in [+ JustifiedLayoutStrategy.comfortLarge,+ JustifiedLayoutStrategy.flex,+ ]) {+ await settings.setJustifiedLayoutStrategy(strategy);+ expect(+ LocalSettings(preferences).getJustifiedLayoutStrategy(),+ strategy,+ );+ }+ },+ );++ group("justified layout tuning", () {+ test("uses defaults when tuning values are absent", () async {+ SharedPreferences.setMockInitialValues({});+ final settings = LocalSettings(await SharedPreferences.getInstance());++ final flex = settings.getFlexLayoutTuning();+ for (final field in FlexLayoutTuningField.values) {+ expect(flex.valueFor(field), FlexLayoutTuning.defaults.valueFor(field));+ }++ final comfortLarge = settings.getComfortLargeLayoutTuning();+ for (final field in ComfortLargeLayoutTuningField.values) {+ expect(+ comfortLarge.valueFor(field),+ ComfortLargeLayoutTuning.defaults.valueFor(field),+ );+ }+ });++ test("persists arbitrary valid decimal values", () async {+ SharedPreferences.setMockInitialValues({});+ final preferences = await SharedPreferences.getInstance();+ final settings = LocalSettings(preferences);+ const flexValues = <FlexLayoutTuningField, double>{+ FlexLayoutTuningField.targetHeightScale: 2.718281828,+ FlexLayoutTuningField.maximumHeightFactor: 9.125,+ };+ const comfortLargeValues = <ComfortLargeLayoutTuningField, double>{+ ComfortLargeLayoutTuningField.targetHeightScale: 0.123456789,+ ComfortLargeLayoutTuningField.maximumHeightFactor: 8.75,+ ComfortLargeLayoutTuningField.wideFinalMaximumHeightFactor: 3.14159,+ ComfortLargeLayoutTuningField.minimumLandscapeHeightFactor: 5.625,+ };++ for (final entry in flexValues.entries) {+ await settings.setFlexLayoutTuningValue(entry.key, entry.value);+ }+ for (final entry in comfortLargeValues.entries) {+ await settings.setComfortLargeLayoutTuningValue(entry.key, entry.value);+ }++ final reloadedSettings = LocalSettings(preferences);+ final flex = reloadedSettings.getFlexLayoutTuning();+ for (final entry in flexValues.entries) {+ expect(flex.valueFor(entry.key), entry.value);+ }+ final comfortLarge = reloadedSettings.getComfortLargeLayoutTuning();+ for (final entry in comfortLargeValues.entries) {+ expect(comfortLarge.valueFor(entry.key), entry.value);+ }+ });++ test("falls back independently for corrupt tuning values", () async {+ SharedPreferences.setMockInitialValues({+ LocalSettings.kFlexLayoutTuningTargetHeightScale: "invalid",+ LocalSettings.kFlexLayoutTuningMaximumHeightFactor: double.nan,+ LocalSettings.kComfortLargeLayoutTuningTargetHeightScale: 0.0,+ LocalSettings.kComfortLargeLayoutTuningMaximumHeightFactor: 0.99,+ LocalSettings.kComfortLargeLayoutTuningWideFinalMaximumHeightFactor:+ double.infinity,+ LocalSettings.kComfortLargeLayoutTuningMinimumLandscapeHeightFactor:+ 10.5,+ });+ final settings = LocalSettings(await SharedPreferences.getInstance());++ final flex = settings.getFlexLayoutTuning();+ for (final field in FlexLayoutTuningField.values) {+ expect(flex.valueFor(field), FlexLayoutTuning.defaults.valueFor(field));+ }+ final comfortLarge = settings.getComfortLargeLayoutTuning();+ for (final field in ComfortLargeLayoutTuningField.values) {+ expect(+ comfortLarge.valueFor(field),+ ComfortLargeLayoutTuning.defaults.valueFor(field),+ );+ }+ });++ test("keeps Flex and Comfort Large tuning isolated", () async {+ SharedPreferences.setMockInitialValues({});+ final settings = LocalSettings(await SharedPreferences.getInstance());++ await settings.setFlexLayoutTuningValue(+ FlexLayoutTuningField.targetHeightScale,+ 1.91,+ );+ expect(+ settings.getComfortLargeLayoutTuning().valueFor(+ ComfortLargeLayoutTuningField.targetHeightScale,+ ),+ ComfortLargeLayoutTuning.defaults.targetHeightScale,+ );++ await settings.setComfortLargeLayoutTuningValue(+ ComfortLargeLayoutTuningField.targetHeightScale,+ 2.73,+ );+ expect(+ settings.getFlexLayoutTuning().valueFor(+ FlexLayoutTuningField.targetHeightScale,+ ),+ 1.91,+ );+ });++ test("resets one field without changing its siblings", () async {+ SharedPreferences.setMockInitialValues({});+ final settings = LocalSettings(await SharedPreferences.getInstance());+ await settings.setFlexLayoutTuningValue(+ FlexLayoutTuningField.targetHeightScale,+ 1.91,+ );+ await settings.setFlexLayoutTuningValue(+ FlexLayoutTuningField.maximumHeightFactor,+ 2.73,+ );+ await settings.setComfortLargeLayoutTuningValue(+ ComfortLargeLayoutTuningField.targetHeightScale,+ 1.41,+ );+ await settings.setComfortLargeLayoutTuningValue(+ ComfortLargeLayoutTuningField.maximumHeightFactor,+ 3.41,+ );++ await settings.resetFlexLayoutTuningValue(+ FlexLayoutTuningField.targetHeightScale,+ );+ await settings.resetComfortLargeLayoutTuningValue(+ ComfortLargeLayoutTuningField.targetHeightScale,+ );++ final flex = settings.getFlexLayoutTuning();+ expect(+ flex.targetHeightScale,+ FlexLayoutTuning.defaults.targetHeightScale,+ );+ expect(flex.maximumHeightFactor, 2.73);+ final comfortLarge = settings.getComfortLargeLayoutTuning();+ expect(+ comfortLarge.targetHeightScale,+ ComfortLargeLayoutTuning.defaults.targetHeightScale,+ );+ expect(comfortLarge.maximumHeightFactor, 3.41);+ });++ test("reset all removes only the selected strategy keys", () async {+ SharedPreferences.setMockInitialValues({});+ final preferences = await SharedPreferences.getInstance();+ final settings = LocalSettings(preferences);+ for (final field in FlexLayoutTuningField.values) {+ await settings.setFlexLayoutTuningValue(+ field,+ field == FlexLayoutTuningField.maximumHeightFactor ? 2.0 : 1.5,+ );+ }+ for (final field in ComfortLargeLayoutTuningField.values) {+ await settings.setComfortLargeLayoutTuningValue(field, switch (field) {+ ComfortLargeLayoutTuningField.maximumHeightFactor ||+ ComfortLargeLayoutTuningField.wideFinalMaximumHeightFactor => 2.0,+ _ => 1.5,+ });+ }++ await settings.resetFlexLayoutTuning();++ expect(+ preferences.getKeys().where((key) => key.contains(".flex.")),+ isEmpty,+ );+ expect(+ preferences.getKeys().where((key) => key.contains(".comfort_large.")),+ isNotEmpty,+ );++ await settings.resetComfortLargeLayoutTuning();++ expect(+ preferences.getKeys().where((key) => key.contains(".comfort_large.")),+ isEmpty,+ );+ });++ test("rejects invalid values without persisting them", () async {+ SharedPreferences.setMockInitialValues({});+ final settings = LocalSettings(await SharedPreferences.getInstance());++ await expectLater(+ settings.setFlexLayoutTuningValue(+ FlexLayoutTuningField.targetHeightScale,+ 0,+ ),+ throwsArgumentError,+ );+ await expectLater(+ settings.setComfortLargeLayoutTuningValue(+ ComfortLargeLayoutTuningField.maximumHeightFactor,+ 0.999,+ ),+ throwsArgumentError,+ );++ expect(+ settings.getFlexLayoutTuning().targetHeightScale,+ FlexLayoutTuning.defaults.targetHeightScale,+ );+ expect(+ settings.getComfortLargeLayoutTuning().maximumHeightFactor,+ ComfortLargeLayoutTuning.defaults.maximumHeightFactor,+ );+ });});}diff --git a/mobile/apps/photos/test/ui/viewer/gallery/gallery_layout_changed_event_test.dart b/mobile/apps/photos/test/ui/viewer/gallery/gallery_layout_changed_event_test.dartindex a48c5c3113..13e307e65d 100644--- a/mobile/apps/photos/test/ui/viewer/gallery/gallery_layout_changed_event_test.dart+++ b/mobile/apps/photos/test/ui/viewer/gallery/gallery_layout_changed_event_test.dart@@ -13,10 +13,12 @@ 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/gallery/justified_layout_strategy.dart";+import "package:photos/models/gallery/justified_layout_tuning.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/settings/gallery_settings_screen.dart";+import "package:photos/ui/settings/justified_layout_tuning_screen.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.dart";@@ -61,6 +63,8 @@ void main() {await localSettings.setJustifiedLayoutStrategy(JustifiedLayoutStrategy.comfort,);+ await localSettings.resetFlexLayoutTuning();+ await localSettings.resetComfortLargeLayoutTuning();});tearDown(() async {@@ -127,6 +131,44 @@ void main() {},);+ testWidgets("Flex tuning accepts arbitrary decimals and resets one field", (+ tester,+ ) async {+ var events = 0;+ final subscription = Bus.instance.on<GalleryLayoutChangedEvent>().listen(+ (_) => events++,+ );+ addTearDown(subscription.cancel);+ await tester.pumpWidget(+ MaterialApp(+ theme: lightThemeData,+ localizationsDelegates: StringsLocalizations.localizationsDelegates,+ supportedLocales: StringsLocalizations.supportedLocales,+ home: const JustifiedLayoutTuningScreen(),+ ),+ );++ await tester.tap(find.text("Target height scale").first);+ await tester.pumpAndSettle();+ await tester.enterText(find.byType(TextField), "1.1375");+ await tester.tap(find.text("Save"));+ await tester.pumpAndSettle();++ expect(localSettings.getFlexLayoutTuning().targetHeightScale, 1.1375);+ expect(events, 1);++ await tester.tap(find.text("Target height scale").first);+ await tester.pumpAndSettle();+ await tester.tap(find.text("Reset to default"));+ await tester.pumpAndSettle();++ expect(+ localSettings.getFlexLayoutTuning().targetHeightScale,+ FlexLayoutTuning.defaults.targetHeightScale,+ );+ expect(events, 2);+ });+testWidgets("layout changes rebuild every mounted gallery without loading files",(tester) async {