π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mob][photos] Refine memories viewer visuals
ashilkne4ad6f89027f
diff --git a/mobile/apps/photos/changes/memory-viewer-backdrop.md b/mobile/apps/photos/changes/memory-viewer-backdrop.mdnew file mode 100644index 0000000000..0a4b2db48c--- /dev/null+++ b/mobile/apps/photos/changes/memory-viewer-backdrop.md@@ -0,0 +1 @@+- Improved the memories viewer with a full-screen blurred backdrop and evenly sized progress indicators.diff --git a/mobile/apps/photos/lib/services/memories_cache_service.dart b/mobile/apps/photos/lib/services/memories_cache_service.dartindex 20d0685563..75dfb7dc31 100644--- a/mobile/apps/photos/lib/services/memories_cache_service.dart+++ b/mobile/apps/photos/lib/services/memories_cache_service.dart@@ -6,6 +6,7 @@ import "package:flutter/cupertino.dart";import "package:flutter/foundation.dart" show kDebugMode;import "package:logging/logging.dart";import "package:path_provider/path_provider.dart";+import "package:photos/core/configuration.dart";import "package:photos/core/event_bus.dart";import "package:photos/db/files_db.dart";import "package:photos/db/memories_db.dart";@@ -50,6 +51,12 @@ class MemoriesCacheService {static const _shouldUpdateCacheKey = "memories.shouldUpdateCache";static const _tripMemoryCarryForwardLimit = kTripSurfaceSlots;+ // TEMP(memory-viewer-verification): remove before merge.+ static const _kTempLibraryMemories = bool.fromEnvironment(+ "debugSocialMemoriesMix",+ defaultValue: false,+ );+/// Delay is for cache update to be done not during app init, during which a/// lot of other things are happening.static const _kCacheUpdateDelay = Duration(seconds: 20);@@ -62,6 +69,11 @@ class MemoriesCacheService {: MemoriesDB.instance;List<SmartMemory>? _cachedMemories;+ List<SmartMemory>? _debugLibraryMemories;+ List<SmartMemory>? _debugLibraryMemoriesSource;+ int? _debugLibraryMemoriesUserID;+ String? _debugLibraryMemoriesInputSignature;+ bool _debugLibraryMemoriesAttempted = false;List<SmartMemory>? get currentMemoriesSync => _cachedMemories;bool _shouldUpdate = false;bool _pendingInitialOfflineCacheUpgrade = false;@@ -72,6 +84,7 @@ class MemoriesCacheService {final _memoriesUpdateLock = Lock();final _memoriesGetLock = Lock();+ final _debugLibraryMemoriesLock = Lock();MemoriesCacheService(this._prefs) {_logger.info("MemoriesCacheService constructor");@@ -616,82 +629,223 @@ class MemoriesCacheService {_logger.info('Showing memories is disabled in settings, showing none');return [];}- return _memoriesGetLock.synchronized(() async {- if (_cachedMemories != null && _cachedMemories!.isNotEmpty) {- final currentMemories = _cachedMemories!- .where((memory) => memory.shouldShowNow())- .toList();- if (currentMemories.isNotEmpty) {- _logger.info("Found memories in memory cache");- return currentMemories;- }- _logger.info(- "In-memory memories not valid for current window, refreshing cache",- );- } else if (onlyUseCache) {- _logger.info("Only using cache, no memories found");- return [];- }- try {- if (!enableSmartMemories) {- await _calculateRegularFillers();- return _cachedMemories!;- }- final cacheFileExists = await _cacheFileExists();- _cachedMemories = await _getMemoriesFromCache();- if (_cachedMemories == null || _cachedMemories!.isEmpty) {- final shouldRefreshEmptyCache =- _cachedMemories == null ||- _shouldUpdate ||- _timeToUpdateCache() ||- lastMemoriesCacheUpdateTime == 0;- if (onlyUseCache) {- _logger.info("Only using cache, no memories found");- return [];+ final memories = await _memoriesGetLock.synchronized<List<SmartMemory>>(+ () async {+ if (_cachedMemories != null && _cachedMemories!.isNotEmpty) {+ final currentMemories = _cachedMemories!+ .where((memory) => memory.shouldShowNow())+ .toList();+ if (currentMemories.isNotEmpty) {+ _logger.info("Found memories in memory cache");+ return currentMemories;}- if (!shouldRefreshEmptyCache) {- _logger.info("Found fresh empty memories cache");- return [];+ _logger.info(+ "In-memory memories not valid for current window, refreshing cache",+ );+ } else if (onlyUseCache) {+ _logger.info("Only using cache, no memories found");+ return [];+ }+ try {+ if (!enableSmartMemories) {+ await _calculateRegularFillers();+ return _cachedMemories!;}- if (!cacheFileExists) {- _logger.info(- "No disk cache (fresh install): serving simple memories, "- "smart memories will upgrade in background",- );- _cachedMemories = await smartMemoriesService.calcSimpleMemories();- if (_shouldDeferInitialOfflineCacheUpgrade()) {- _pendingInitialOfflineCacheUpgrade = true;+ final cacheFileExists = await _cacheFileExists();+ _cachedMemories = await _getMemoriesFromCache();+ if (_cachedMemories == null || _cachedMemories!.isEmpty) {+ final shouldRefreshEmptyCache =+ _cachedMemories == null ||+ _shouldUpdate ||+ _timeToUpdateCache() ||+ lastMemoriesCacheUpdateTime == 0;+ if (onlyUseCache) {+ _logger.info("Only using cache, no memories found");+ return [];+ }+ if (!shouldRefreshEmptyCache) {+ _logger.info("Found fresh empty memories cache");+ return [];+ }+ if (!cacheFileExists) {_logger.info(- "Deferring initial offline memories cache upgrade until first import metadata is ready",- );- } else {- unawaited(- updateCache(- forced: true,- ).whenComplete(() => Bus.instance.fire(MemoriesChangedEvent())),+ "No disk cache (fresh install): serving simple memories, "+ "smart memories will upgrade in background",);+ _cachedMemories = await smartMemoriesService.calcSimpleMemories();+ if (_shouldDeferInitialOfflineCacheUpgrade()) {+ _pendingInitialOfflineCacheUpgrade = true;+ _logger.info(+ "Deferring initial offline memories cache upgrade until first import metadata is ready",+ );+ } else {+ unawaited(+ updateCache(forced: true).whenComplete(+ () => Bus.instance.fire(MemoriesChangedEvent()),+ ),+ );+ }+ return _cachedMemories!;}- return _cachedMemories!;+ _logger.warning(+ "No memories found in cache, force updating cache. Possible severe caching issue",+ );+ await updateCache(forced: true);+ } else {+ _logger.info("Found memories in cache");}- _logger.warning(- "No memories found in cache, force updating cache. Possible severe caching issue",- );- await updateCache(forced: true);- } else {- _logger.info("Found memories in cache");- }- if (_cachedMemories == null || _cachedMemories!.isEmpty) {- _logger.severe(- "No memories found in (computed) cache, getting fillers",- );- await _calculateRegularFillers();+ if (_cachedMemories == null || _cachedMemories!.isEmpty) {+ _logger.severe(+ "No memories found in (computed) cache, getting fillers",+ );+ await _calculateRegularFillers();+ }+ return _cachedMemories!;+ } catch (e, s) {+ _logger.severe("Error in getMemories", e, s);+ return [];}- return _cachedMemories!;- } catch (e, s) {- _logger.severe("Error in getMemories", e, s);- return [];+ },+ );+ return _debugBuildLibraryMemories(memories);+ }++ // TEMP(memory-viewer-verification): remove before merge. This exposes a+ // broad sample of the account library as several memory cards so that the+ // viewer can be exercised with varied media and sharing states.+ Future<List<SmartMemory>> _debugBuildLibraryMemories(+ List<SmartMemory> memories,+ ) async {+ if (!_kTempLibraryMemories || isLocalGalleryMode || memories.isEmpty) {+ return memories;+ }+ return _debugLibraryMemoriesLock.synchronized(+ () => _debugBuildLibraryMemoriesLocked(memories),+ );+ }++ Future<List<SmartMemory>> _debugBuildLibraryMemoriesLocked(+ List<SmartMemory> memories,+ ) async {+ final source = _cachedMemories ?? memories;+ final userID = Configuration.instance.getUserID();+ final inputSignature = memories+ .map((memory) => "${memory.id}:${memory.memories.length}")+ .join("|");+ final sameContext =+ identical(_debugLibraryMemoriesSource, source) &&+ _debugLibraryMemoriesUserID == userID &&+ _debugLibraryMemoriesInputSignature == inputSignature;+ if (!sameContext) {+ _debugLibraryMemories = null;+ _debugLibraryMemoriesAttempted = false;+ _debugLibraryMemoriesSource = source;+ _debugLibraryMemoriesUserID = userID;+ _debugLibraryMemoriesInputSignature = inputSignature;+ }+ if (_debugLibraryMemoriesAttempted) {+ return _debugLibraryMemories ?? memories;+ }+ _debugLibraryMemoriesAttempted = true;++ final searchFiles = await SearchService.instance.getAllFilesForSearch();+ final localOnlyFiles = await FilesDB.instance.getUnUploadedLocalFiles();+ final uniqueFiles = <String, EnteFile>{};+ String debugFileID(EnteFile file) {+ final uploadedFileID = file.uploadedFileID;+ if (uploadedFileID != null && uploadedFileID != -1) {+ return "uploaded:$uploadedFileID";}- });+ final localID = file.localID;+ if (localID != null && localID.isNotEmpty) {+ return "local:$localID";+ }+ final generatedID = file.generatedID;+ return generatedID != null+ ? "generated:$generatedID"+ : "object:${identityHashCode(file)}";+ }++ void addFiles(Iterable<EnteFile> files) {+ for (final file in files) {+ if (file.creationTime == null) continue;+ uniqueFiles.putIfAbsent(debugFileID(file), () => file);+ }+ }++ addFiles(searchFiles);+ addFiles(localOnlyFiles);+ if (uniqueFiles.isEmpty) {+ _logger.warning("TEMP library memories unavailable: no usable files");+ return memories;+ }++ final sortedFiles = uniqueFiles.values.toList()+ ..sort((first, second) {+ final creationOrder = second.creationTime!.compareTo(+ first.creationTime!,+ );+ if (creationOrder != 0) return creationOrder;+ return (second.generatedID ?? -1).compareTo(first.generatedID ?? -1);+ });+ const maxFiles = 600;+ const targetFilesPerMemory = 20;+ const maxMemoryGroups = 12;+ final selectedFiles = sortedFiles.take(maxFiles).toList();+ var groupCount =+ (selectedFiles.length + targetFilesPerMemory - 1) ~/+ targetFilesPerMemory;+ if (groupCount > maxMemoryGroups) groupCount = maxMemoryGroups;++ final now = DateTime.now().microsecondsSinceEpoch;+ final firstDateToShow = now - const Duration(days: 1).inMicroseconds;+ final lastDateToShow = now + const Duration(days: 1).inMicroseconds;+ final languageCode = (await getLocale())?.languageCode ?? "en";+ final seenTimes = await _memoriesDB.getSeenTimes();+ final filesPerGroup = selectedFiles.length ~/ groupCount;+ final groupsWithExtraFile = selectedFiles.length % groupCount;+ final debugMemories = <SmartMemory>[];+ var offset = 0;+ for (var groupIndex = 0; groupIndex < groupCount; groupIndex++) {+ final groupSize =+ filesPerGroup + (groupIndex < groupsWithExtraFile ? 1 : 0);+ final groupFiles = selectedFiles.sublist(offset, offset + groupSize);+ offset += groupSize;+ final newestCreationTime = groupFiles.first.creationTime!;+ final oldestCreationTime = groupFiles.last.creationTime!;+ final newestDate = SmartMemoriesService.getDateFormatted(+ creationTime: newestCreationTime,+ languageCode: languageCode,+ );+ final oldestDate = SmartMemoriesService.getDateFormatted(+ creationTime: oldestCreationTime,+ languageCode: languageCode,+ );+ final title = oldestDate == newestDate+ ? newestDate+ : "$oldestDate β $newestDate";+ debugMemories.add(+ SmartMemory(+ Memory.fromFiles(groupFiles, seenTimes),+ MemoryType.filler,+ title,+ firstDateToShow,+ lastDateToShow,+ id: "debug-library-$userID-$groupIndex",+ firstCreationTime: oldestCreationTime,+ lastCreationTime: newestCreationTime,+ ),+ );+ }++ _debugLibraryMemories = debugMemories;+ _logger.info(+ "TEMP library memories enabled: ${selectedFiles.length} of "+ "${uniqueFiles.length} files across ${debugMemories.length} memories "+ "(${searchFiles.length} search files, "+ "${localOnlyFiles.length} local-only files)",+ );+ return debugMemories;}Future<void> _calculateRegularFillers() async {diff --git a/mobile/apps/photos/lib/ui/home/memories/full_screen_memory.dart b/mobile/apps/photos/lib/ui/home/memories/full_screen_memory.dartindex 1c07c80570..c32584753e 100644--- a/mobile/apps/photos/lib/ui/home/memories/full_screen_memory.dart+++ b/mobile/apps/photos/lib/ui/home/memories/full_screen_memory.dart@@ -37,6 +37,7 @@ import "package:photos/ui/home/memories/memory_progress_indicator.dart";import "package:photos/ui/home/memories/memory_video_prefetcher.dart";import "package:photos/ui/social/widgets/file_social_overlay.dart";import "package:photos/ui/viewer/file/file_widget.dart";+import "package:photos/ui/viewer/file/thumbnail_widget.dart";import "package:photos/ui/viewer/file_details/favorite_widget.dart";import "package:photos/ui/viewer/gallery/jump_to_date_gallery.dart";import "package:photos/utils/dialog_util.dart";@@ -605,6 +606,7 @@ class _FullScreenMemoryState extends State<FullScreenMemory> {body: Stack(fit: StackFit.expand,children: [+ const _MemoryBlur(),ValueListenableBuilder<int>(valueListenable: inheritedData.indexNotifier,builder: (context, index, _) {@@ -681,7 +683,7 @@ class _FullScreenMemoryState extends State<FullScreenMemory> {autoPlay: false,tagPrefix: "memories",backgroundDecoration: const BoxDecoration(- color: Colors.black,+ color: Colors.transparent,),isFromMemories: true,playbackCallback: (shouldEnable, _) {@@ -1081,22 +1083,17 @@ class _MemoryViewerScrims extends StatelessWidget {child: SizedBox(width: double.infinity,height: topHeight,- child: ClipRect(- child: BackdropFilter(- filter: ImageFilter.blur(sigmaX: 18, sigmaY: 18),- child: const DecoratedBox(- decoration: BoxDecoration(- gradient: LinearGradient(- begin: Alignment.topCenter,- end: Alignment.bottomCenter,- colors: [- Color(0xB8000000),- Color(0x70000000),- Colors.transparent,- ],- stops: [0, 0.6, 1],- ),- ),+ child: const DecoratedBox(+ decoration: BoxDecoration(+ gradient: LinearGradient(+ begin: Alignment.topCenter,+ end: Alignment.bottomCenter,+ colors: [+ Color(0xB8000000),+ Color(0x70000000),+ Colors.transparent,+ ],+ stops: [0, 0.6, 1],),),),@@ -1129,6 +1126,56 @@ class _MemoryViewerScrims extends StatelessWidget {}}+class _MemoryBlur extends StatelessWidget {+ const _MemoryBlur();++ @override+ Widget build(BuildContext context) {+ final inheritedData = FullScreenMemoryData.of(context);+ if (inheritedData == null || inheritedData.memories.isEmpty) {+ return const SizedBox.shrink();+ }+ return ValueListenableBuilder<int>(+ valueListenable: inheritedData.indexNotifier,+ builder: (context, index, _) {+ final safeIndex = _clampedMemoryIndex(+ index,+ inheritedData.memories.length,+ );+ if (safeIndex == null) return const SizedBox.shrink();+ final currentFile = inheritedData.memories[safeIndex].file;+ if (currentFile.fileType == FileType.video) {+ return const SizedBox.shrink();+ }+ return AnimatedSwitcher(+ duration: const Duration(milliseconds: 750),+ switchInCurve: Curves.easeOutExpo,+ switchOutCurve: Curves.easeInExpo,+ layoutBuilder: (currentChild, previousChildren) {+ return Stack(+ fit: StackFit.expand,+ children: [...previousChildren, ?currentChild],+ );+ },+ child: ImageFiltered(+ key: ValueKey(+ "memory-blur-${currentFile.uploadedFileID ?? currentFile.localID ?? safeIndex}",+ ),+ imageFilter: ImageFilter.blur(sigmaX: 100, sigmaY: 100),+ child: ThumbnailWidget(+ currentFile,+ placeholderColor: Colors.black,+ shouldShowSyncStatus: false,+ shouldShowFavoriteIcon: false,+ shouldShowVideoOverlayIcon: false,+ ),+ ),+ );+ },+ );+ }+}+class MemoriesZoomWidget extends StatefulWidget {final Widget child;final bool isVideo;diff --git a/mobile/apps/photos/lib/ui/home/memories/memory_progress_indicator.dart b/mobile/apps/photos/lib/ui/home/memories/memory_progress_indicator.dartindex 2a6ece5a57..b85d4bf793 100644--- a/mobile/apps/photos/lib/ui/home/memories/memory_progress_indicator.dart+++ b/mobile/apps/photos/lib/ui/home/memories/memory_progress_indicator.dart@@ -1,47 +1,40 @@import "package:flutter/material.dart";-const double kMemoryProgressSegmentWidth = 8.0;const double kMemoryProgressGap = 10.0;const double kMemoryProgressHeight = 4.0;-const double kMemoryProgressMinimumCurrentWidth = 24.0;+const double kMemoryProgressMinSegmentWidth = 8.0;-int memoryProgressCapacityForWidth(- double availableWidth, {- double segmentWidth = kMemoryProgressSegmentWidth,+double memoryProgressSegmentWidthForLayout({+ required int totalSteps,+ required double availableWidth,double gap = kMemoryProgressGap,- double minimumCurrentWidth = kMemoryProgressMinimumCurrentWidth,}) {- if (!availableWidth.isFinite ||+ if (totalSteps <= 0 ||+ !availableWidth.isFinite ||availableWidth <= 0 ||- !segmentWidth.isFinite ||- segmentWidth <= 0 ||!gap.isFinite ||- gap < 0 ||- !minimumCurrentWidth.isFinite ||- minimumCurrentWidth <= 0) {- return 1;+ gap < 0) {+ return 0;}- final capacity =- 1 +- ((availableWidth - minimumCurrentWidth) / (segmentWidth + gap)).floor();- return capacity < 1 ? 1 : capacity;+ final availableSegmentWidth = availableWidth - ((totalSteps - 1) * gap);+ if (availableSegmentWidth <= 0) return 0;++ return availableSegmentWidth / totalSteps;}bool memoryProgressUsesContinuousTrack({required int totalSteps,required double availableWidth,- double segmentWidth = kMemoryProgressSegmentWidth,double gap = kMemoryProgressGap,- double minimumCurrentWidth = kMemoryProgressMinimumCurrentWidth,}) =>- totalSteps >- memoryProgressCapacityForWidth(- availableWidth,- segmentWidth: segmentWidth,- gap: gap,- minimumCurrentWidth: minimumCurrentWidth,- );+ totalSteps > 1 &&+ memoryProgressSegmentWidthForLayout(+ totalSteps: totalSteps,+ availableWidth: availableWidth,+ gap: gap,+ ) <+ kMemoryProgressMinSegmentWidth;class MemoryProgressIndicator extends StatefulWidget {final int totalSteps;@@ -168,9 +161,10 @@ class _MemoryProgressIndicatorState extends State<MemoryProgressIndicator>);segments.add(- index == widget.currentIndex- ? Expanded(child: segment)- : SizedBox(width: kMemoryProgressSegmentWidth, child: segment),+ Expanded(+ key: ValueKey("memory-progress-segment-$index"),+ child: segment,+ ),);}return Row(children: segments);diff --git a/mobile/apps/photos/test/ui/home/memories/memory_progress_indicator_test.dart b/mobile/apps/photos/test/ui/home/memories/memory_progress_indicator_test.dartindex 5a2f185cd5..ac604be905 100644--- a/mobile/apps/photos/test/ui/home/memories/memory_progress_indicator_test.dart+++ b/mobile/apps/photos/test/ui/home/memories/memory_progress_indicator_test.dart@@ -3,50 +3,101 @@ import "package:flutter_test/flutter_test.dart";import "package:photos/ui/home/memories/memory_progress_indicator.dart";void main() {- group("memory progress capacity", () {- test("derives phone and tablet capacity from the available width", () {- expect(memoryProgressCapacityForWidth(375), 20);- expect(memoryProgressCapacityForWidth(343), 18);- expect(memoryProgressCapacityForWidth(736), 40);- expect(memoryProgressCapacityForWidth(329), 17);- expect(memoryProgressCapacityForWidth(330), 18);- });-- test("switches to a continuous track only after capacity", () {- expect(- memoryProgressUsesContinuousTrack(totalSteps: 18, availableWidth: 343),- isFalse,- );+ group("memory progress layout", () {+ test("derives equal segment widths from the available width", () {expect(- memoryProgressUsesContinuousTrack(totalSteps: 19, availableWidth: 343),- isTrue,+ memoryProgressSegmentWidthForLayout(totalSteps: 6, availableWidth: 343),+ closeTo(48.833333, 0.000001),);expect(- memoryProgressUsesContinuousTrack(totalSteps: 41, availableWidth: 736),- isTrue,+ memoryProgressSegmentWidthForLayout(+ totalSteps: 18,+ availableWidth: 343,+ ),+ closeTo(9.611111, 0.000001),);});- });- testWidgets("keeps the current phone segment flexible at capacity", (- tester,- ) async {- await tester.pumpWidget(- const MaterialApp(- home: Center(- child: SizedBox(- width: 343,- child: MemoryProgressIndicator(totalSteps: 18, currentIndex: 7),+ test(+ "switches when equal chunks would be narrower than the legibility limit",+ () {+ expect(+ memoryProgressUsesContinuousTrack(+ totalSteps: 19,+ availableWidth: 343,),- ),- ),+ isFalse,+ );+ expect(+ memoryProgressUsesContinuousTrack(+ totalSteps: 20,+ availableWidth: 343,+ ),+ isTrue,+ );+ expect(+ memoryProgressUsesContinuousTrack(+ totalSteps: 41,+ availableWidth: 736,+ ),+ isFalse,+ );+ expect(+ memoryProgressUsesContinuousTrack(+ totalSteps: 42,+ availableWidth: 736,+ ),+ isTrue,+ );+ },);-- expect(find.byType(Row), findsOneWidget);- expect(tester.getSize(find.byType(LinearProgressIndicator)).width, 37);});- testWidgets("uses the full track when the phone capacity overflows", (+ for (final availableWidth in [343.0, 736.0]) {+ for (final totalSteps in [6, 18]) {+ testWidgets("fills ${availableWidth}px with $totalSteps equal chunks", (+ tester,+ ) async {+ final currentIndex = totalSteps ~/ 2;++ await tester.pumpWidget(+ MaterialApp(+ home: Center(+ child: SizedBox(+ width: availableWidth,+ child: MemoryProgressIndicator(+ totalSteps: totalSteps,+ currentIndex: currentIndex,+ ),+ ),+ ),+ ),+ );++ expect(find.byType(Row), findsOneWidget);+ final widths = [+ for (var index = 0; index < totalSteps; index++)+ tester+ .getSize(find.byKey(ValueKey("memory-progress-segment-$index")))+ .width,+ ];+ final segmentWidth = widths.first;+ final currentWidth = widths[currentIndex];++ expect(currentWidth / segmentWidth, closeTo(1.0, 0.000001));+ for (final width in widths) {+ expect(width, closeTo(segmentWidth, 0.000001));+ }+ expect(+ widths.reduce((left, right) => left + right) ++ ((totalSteps - 1) * kMemoryProgressGap),+ closeTo(availableWidth, 0.000001),+ );+ });+ }+ }++ testWidgets("uses the full track when segmented chunks become too narrow", (tester,) async {await tester.pumpWidget(@@ -54,7 +105,7 @@ void main() {home: Center(child: SizedBox(width: 343,- child: MemoryProgressIndicator(totalSteps: 19, currentIndex: 7),+ child: MemoryProgressIndicator(totalSteps: 20, currentIndex: 7),),),),