Skip to content

armgit / ente

Public Imported from GitHub
0

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

Rename isOfflineMode to isLocalGalleryMode

laurenspriemd0f6b3b0e228
diff --git a/mobile/apps/photos/lib/app_mode.dart b/mobile/apps/photos/lib/app_mode.dart
index 8a760360e5..b74f496299 100644
--- a/mobile/apps/photos/lib/app_mode.dart
+++ b/mobile/apps/photos/lib/app_mode.dart
@@ -1,4 +1 @@
-enum AppMode {
- online,
- offline,
-}
+enum AppMode { enteGallery, localGallery }
diff --git a/mobile/apps/photos/lib/core/configuration.dart b/mobile/apps/photos/lib/core/configuration.dart
index 8fd74d2504..afce88d7a7 100644
--- a/mobile/apps/photos/lib/core/configuration.dart
+++ b/mobile/apps/photos/lib/core/configuration.dart
@@ -125,15 +125,11 @@ class Configuration {
_logger.info(
"(for debugging) Token found, loading secure storage data",
);
- _key = await _secureStorage.read(
- key: keyKey,
- );
+ _key = await _secureStorage.read(key: keyKey);
_logger.info(
"(for debugging) Key loaded from secure storage, is null: ${_key == null}",
);
- _secretKey = await _secureStorage.read(
- key: secretKeyKey,
- );
+ _secretKey = await _secureStorage.read(key: secretKeyKey);
_logger.info(
"(for debugging) Secret Key loaded from secure storage, is null: ${_secretKey == null}",
);
@@ -210,9 +206,9 @@ class Configuration {
if (SyncService.instance.isSyncInProgress()) {
SyncService.instance.stopSync();
try {
- await SyncService.instance
- .existingSync()
- .timeout(const Duration(seconds: 5));
+ await SyncService.instance.existingSync().timeout(
+ const Duration(seconds: 5),
+ );
} catch (e) {
// ignore
}
@@ -554,7 +550,7 @@ class Configuration {
Future<void> setToken(String token) async {
_cachedToken = token;
await _preferences.setString(tokenKey, token);
- await localSettings.setAppMode(AppMode.online);
+ await localSettings.setAppMode(AppMode.enteGallery);
Bus.instance.fire(AppModeChangedEvent());
Bus.instance.fire(SignedInEvent());
}
diff --git a/mobile/apps/photos/lib/core/user_config.dart b/mobile/apps/photos/lib/core/user_config.dart
index 1c50d32ed9..8d4f9c7df1 100644
--- a/mobile/apps/photos/lib/core/user_config.dart
+++ b/mobile/apps/photos/lib/core/user_config.dart
@@ -4,7 +4,7 @@ import "package:photos/service_locator.dart";
extension UserConfig on Configuration {
int getUserIDV2() {
final int? userID = getUserID();
- if (userID == null && !isOfflineMode) {
+ if (userID == null && !isLocalGalleryMode) {
throw StateError("Missing user ID in online mode");
}
return userID ?? -1;
diff --git a/mobile/apps/photos/lib/main.dart b/mobile/apps/photos/lib/main.dart
index 4ad91a2286..e8a8d46c0e 100644
--- a/mobile/apps/photos/lib/main.dart
+++ b/mobile/apps/photos/lib/main.dart
@@ -190,8 +190,9 @@ Future<void> _runMinimally(String taskId, TimeLogger tlog) async {
// App LifeCycle
AppLifecycleService.instance.init(prefs);
- AppLifecycleService.instance
- .onAppInBackground('init via: WorkManager $tlog');
+ AppLifecycleService.instance.onAppInBackground(
+ 'init via: WorkManager $tlog',
+ );
// Crypto rel.
await Computer.shared().turnOn(workersCount: 4);
@@ -244,7 +245,7 @@ Future<void> _runMinimally(String taskId, TimeLogger tlog) async {
_logger.info("[BG TASK] home widget sync");
await _homeWidgetSync(true);
- if ((isOfflineMode || flagService.enableMLInBackground) &&
+ if ((isLocalGalleryMode || flagService.enableMLInBackground) &&
hasGrantedMLConsent) {
await controller.init();
final canRunML = controller.requestCompute(ml: true);
@@ -418,10 +419,7 @@ Future<void> _ensureRustInitialized({required String via}) async {
return;
}
- final initFuture = Future.wait([
- EntePhotosRust.init(),
- EnteRust.init(),
- ]);
+ final initFuture = Future.wait([EntePhotosRust.init(), EnteRust.init()]);
_rustInitFuture = initFuture;
try {
await initFuture;
diff --git a/mobile/apps/photos/lib/service_locator.dart b/mobile/apps/photos/lib/service_locator.dart
index 491c02e0fc..da4f8595ae 100644
--- a/mobile/apps/photos/lib/service_locator.dart
+++ b/mobile/apps/photos/lib/service_locator.dart
@@ -91,33 +91,33 @@ LocalSettings get localSettings {
return _localSettings!;
}
-bool get isOfflineMode => localSettings.appMode == AppMode.offline;
+bool get isLocalGalleryMode => localSettings.appMode == AppMode.localGallery;
bool get hasGrantedMLConsent {
- if (isOfflineMode) {
- return localSettings.offlineMLConsent;
+ if (isLocalGalleryMode) {
+ return localSettings.localGalleryMLConsent;
}
return flagService.hasGrantedMLConsent;
}
Future<void> setMLConsent(bool enabled) async {
- if (isOfflineMode) {
- await localSettings.setOfflineMLConsent(enabled);
+ if (isLocalGalleryMode) {
+ await localSettings.setLocalGalleryMLConsent(enabled);
return;
}
await flagService.setMLConsent(enabled);
}
bool get mapEnabled {
- if (isOfflineMode) {
- return localSettings.offlineMapEnabled;
+ if (isLocalGalleryMode) {
+ return localSettings.localGalleryMapEnabled;
}
return flagService.mapEnabled;
}
Future<void> setMapEnabled(bool enabled) async {
- if (isOfflineMode) {
- await localSettings.setOfflineMapEnabled(enabled);
+ if (isLocalGalleryMode) {
+ await localSettings.setLocalGalleryMapEnabled(enabled);
return;
}
await flagService.setMapEnabled(enabled);
@@ -178,17 +178,13 @@ LocationService get locationService {
MagicCacheService? _magicCacheService;
MagicCacheService get magicCacheService {
- _magicCacheService ??= MagicCacheService(
- ServiceLocator.instance.prefs,
- );
+ _magicCacheService ??= MagicCacheService(ServiceLocator.instance.prefs);
return _magicCacheService!;
}
MemoriesCacheService? _memoriesCacheService;
MemoriesCacheService get memoriesCacheService {
- _memoriesCacheService ??= MemoriesCacheService(
- ServiceLocator.instance.prefs,
- );
+ _memoriesCacheService ??= MemoriesCacheService(ServiceLocator.instance.prefs);
return _memoriesCacheService!;
}
@@ -239,9 +235,7 @@ FileDataService get fileDataService {
DownloadManager? _downloadManager;
DownloadManager get downloadManager {
- _downloadManager ??= DownloadManager(
- ServiceLocator.instance.nonEnteDio,
- );
+ _downloadManager ??= DownloadManager(ServiceLocator.instance.nonEnteDio);
return _downloadManager!;
}
@@ -332,15 +326,17 @@ TrashGateway get trashGateway {
CollectionFilesGateway? _collectionFilesGateway;
CollectionFilesGateway get collectionFilesGateway {
- _collectionFilesGateway ??=
- CollectionFilesGateway(ServiceLocator.instance.enteDio);
+ _collectionFilesGateway ??= CollectionFilesGateway(
+ ServiceLocator.instance.enteDio,
+ );
return _collectionFilesGateway!;
}
CollectionShareGateway? _collectionShareGateway;
CollectionShareGateway get collectionShareGateway {
- _collectionShareGateway ??=
- CollectionShareGateway(ServiceLocator.instance.enteDio);
+ _collectionShareGateway ??= CollectionShareGateway(
+ ServiceLocator.instance.enteDio,
+ );
return _collectionShareGateway!;
}
diff --git a/mobile/apps/photos/lib/services/account/user_service.dart b/mobile/apps/photos/lib/services/account/user_service.dart
index a0474551f8..08b746e3be 100644
--- a/mobile/apps/photos/lib/services/account/user_service.dart
+++ b/mobile/apps/photos/lib/services/account/user_service.dart
@@ -62,8 +62,9 @@ class UserService {
static const kIsEmailMFAEnabled = "is_email_mfa_enabled";
final SRP6GroupParameters kDefaultSrpGroup = SRP6StandardGroups.rfc5054_4096;
- final _emailToPubKeyCache =
- TimedCache<String, String>(duration: const Duration(seconds: 10));
+ final _emailToPubKeyCache = TimedCache<String, String>(
+ duration: const Duration(seconds: 10),
+ );
final _logger = Logger((UserService).toString());
final _config = Configuration.instance;
@@ -73,8 +74,9 @@ class UserService {
UsersGateway get _gateway => usersGateway;
- final ValueNotifier<String?> emailValueNotifier =
- ValueNotifier<String?>(null);
+ final ValueNotifier<String?> emailValueNotifier = ValueNotifier<String?>(
+ null,
+ );
UserService._privateConstructor();
@@ -85,8 +87,9 @@ class UserService {
if (_loggedOutEventSubscription != null) {
await _loggedOutEventSubscription!.cancel();
}
- _loggedOutEventSubscription =
- Bus.instance.on<UserLoggedOutEvent>().listen((_) {
+ _loggedOutEventSubscription = Bus.instance.on<UserLoggedOutEvent>().listen((
+ _,
+ ) {
emailValueNotifier.value = null;
});
if (_signedInEventSubscription != null) {
@@ -96,7 +99,7 @@ class UserService {
emailValueNotifier.value = Configuration.instance.getEmail();
});
_preferences = await SharedPreferences.getInstance();
- if (Configuration.instance.isLoggedIn() && !isOfflineMode) {
+ if (Configuration.instance.isLoggedIn() && !isLocalGalleryMode) {
// add artificial delay in refreshing 2FA status
Future.delayed(
const Duration(seconds: 5),
@@ -113,8 +116,10 @@ class UserService {
bool isResetPasswordScreen = false,
String? purpose,
}) async {
- final dialog =
- createProgressDialog(context, AppLocalizations.of(context).pleaseWait);
+ final dialog = createProgressDialog(
+ context,
+ AppLocalizations.of(context).pleaseWait,
+ );
await dialog.show();
try {
await _gateway.sendOtt(
@@ -184,9 +189,7 @@ class UserService {
} catch (e, s) {
await dialog.hide();
_logger.severe(e, s);
- unawaited(
- showGenericErrorBottomSheet(context: context, error: e),
- );
+ unawaited(showGenericErrorBottomSheet(context: context, error: e));
}
}
@@ -233,10 +236,7 @@ class UserService {
if (userDetails.profileData != null) {
final bool currentEmailMFAStatus =
userDetails.profileData!.isEmailMFAEnabled;
- await _preferences.setBool(
- kIsEmailMFAEnabled,
- currentEmailMFAStatus,
- );
+ await _preferences.setBool(kIsEmailMFAEnabled, currentEmailMFAStatus);
hasSecurityStatusChanged = hasSecurityStatusChanged ||
previousEmailMFAStatus != currentEmailMFAStatus;
final bool currentTwoFactorStatus =
@@ -351,8 +351,10 @@ class UserService {
}
Future<void> onPassKeyVerified(BuildContext context, Map response) async {
- final ProgressDialog dialog =
- createProgressDialog(context, context.l10n.pleaseWait);
+ final ProgressDialog dialog = createProgressDialog(
+ context,
+ context.l10n.pleaseWait,
+ );
await dialog.show();
try {
final userPassword = Configuration.instance.getVolatilePassword();
@@ -394,8 +396,10 @@ class UserService {
String ott, {
bool isResettingPasswordScreen = false,
}) async {
- final dialog =
- createProgressDialog(context, AppLocalizations.of(context).pleaseWait);
+ final dialog = createProgressDialog(
+ context,
+ AppLocalizations.of(context).pleaseWait,
+ );
await dialog.show();
try {
final responseData = await _gateway.verifyEmail(
@@ -430,9 +434,7 @@ class UserService {
page = const PasswordReentryPage();
}
} else {
- page = const PasswordEntryPage(
- mode: PasswordEntryMode.set,
- );
+ page = const PasswordEntryPage(mode: PasswordEntryMode.set);
}
}
await Navigator.of(context).pushAndRemoveUntil(
@@ -459,8 +461,9 @@ class UserService {
showAlertBottomSheet(
context,
title: AppLocalizations.of(context).incorrectCode,
- message:
- AppLocalizations.of(context).sorryTheCodeYouveEnteredIsIncorrect,
+ message: AppLocalizations.of(
+ context,
+ ).sorryTheCodeYouveEnteredIsIncorrect,
assetPath: 'assets/warning-green.png',
);
}
@@ -495,8 +498,10 @@ class UserService {
String email,
String ott,
) async {
- final dialog =
- createProgressDialog(context, AppLocalizations.of(context).pleaseWait);
+ final dialog = createProgressDialog(
+ context,
+ AppLocalizations.of(context).pleaseWait,
+ );
await dialog.show();
try {
await _gateway.changeEmail(email: email, ott: ott);
@@ -523,8 +528,9 @@ class UserService {
showAlertBottomSheet(
context,
title: AppLocalizations.of(context).incorrectCode,
- message:
- AppLocalizations.of(context).authenticationFailedPleaseTryAgain,
+ message: AppLocalizations.of(
+ context,
+ ).authenticationFailedPleaseTryAgain,
assetPath: 'assets/warning-green.png',
);
}
@@ -590,8 +596,9 @@ class UserService {
isUpdate: false,
);
final setupSRPResponse = await _gateway.setupSrp(request);
- final serverB =
- SRP6Util.decodeBigInt(base64Decode(setupSRPResponse.srpB));
+ final serverB = SRP6Util.decodeBigInt(
+ base64Decode(setupSRPResponse.srpB),
+ );
// ignore: unused_local_variable, need to calculate secret to get M1
final clientS = client.calculateSecret(serverB);
final clientM = client.calculateClientEvidenceMessage();
@@ -811,8 +818,9 @@ class UserService {
showAlertBottomSheet(
context,
title: AppLocalizations.of(context).incorrectCode,
- message:
- AppLocalizations.of(context).authenticationFailedPleaseTryAgain,
+ message: AppLocalizations.of(
+ context,
+ ).authenticationFailedPleaseTryAgain,
assetPath: 'assets/warning-green.png',
);
}
@@ -823,8 +831,9 @@ class UserService {
showAlertBottomSheet(
context,
title: AppLocalizations.of(context).oops,
- message:
- AppLocalizations.of(context).authenticationFailedPleaseTryAgain,
+ message: AppLocalizations.of(
+ context,
+ ).authenticationFailedPleaseTryAgain,
assetPath: 'assets/warning-green.png',
);
}
@@ -835,8 +844,10 @@ class UserService {
String sessionID,
TwoFactorType type,
) async {
- final dialog =
- createProgressDialog(context, AppLocalizations.of(context).pleaseWait);
+ final dialog = createProgressDialog(
+ context,
+ AppLocalizations.of(context).pleaseWait,
+ );
await dialog.show();
try {
_logger.info("recovering two factor");
@@ -879,8 +890,9 @@ class UserService {
showAlertBottomSheet(
context,
title: AppLocalizations.of(context).oops,
- message:
- AppLocalizations.of(context).somethingWentWrongPleaseTryAgain,
+ message: AppLocalizations.of(
+ context,
+ ).somethingWentWrongPleaseTryAgain,
assetPath: 'assets/warning-green.png',
);
}
@@ -908,8 +920,10 @@ class UserService {
String encryptedSecret,
String secretDecryptionNonce,
) async {
- final dialog =
- createProgressDialog(context, AppLocalizations.of(context).pleaseWait);
+ final dialog = createProgressDialog(
+ context,
+ AppLocalizations.of(context).pleaseWait,
+ );
await dialog.show();
String secret;
try {
@@ -933,8 +947,9 @@ class UserService {
await showAlertBottomSheet(
context,
title: AppLocalizations.of(context).incorrectRecoveryKey,
- message:
- AppLocalizations.of(context).theRecoveryKeyYouEnteredIsIncorrect,
+ message: AppLocalizations.of(
+ context,
+ ).theRecoveryKeyYouEnteredIsIncorrect,
assetPath: 'assets/warning-green.png',
);
return;
@@ -979,8 +994,9 @@ class UserService {
showAlertBottomSheet(
context,
title: AppLocalizations.of(context).oops,
- message:
- AppLocalizations.of(context).somethingWentWrongPleaseTryAgain,
+ message: AppLocalizations.of(
+ context,
+ ).somethingWentWrongPleaseTryAgain,
assetPath: 'assets/warning-green.png',
);
}
@@ -1001,8 +1017,10 @@ class UserService {
}
Future<void> setupTwoFactor(BuildContext context, Completer completer) async {
- final dialog =
- createProgressDialog(context, AppLocalizations.of(context).pleaseWait);
+ final dialog = createProgressDialog(
+ context,
+ AppLocalizations.of(context).pleaseWait,
+ );
await dialog.show();
try {
final responseData = await _gateway.setupTwoFactor();
@@ -1037,18 +1055,24 @@ class UserService {
await showGenericErrorBottomSheet(context: context, error: e);
return false;
}
- final dialog =
- createProgressDialog(context, AppLocalizations.of(context).verifying);
+ final dialog = createProgressDialog(
+ context,
+ AppLocalizations.of(context).verifying,
+ );
await dialog.show();
- final encryptionResult =
- CryptoUtil.encryptSync(CryptoUtil.base642bin(secret), recoveryKey);
+ final encryptionResult = CryptoUtil.encryptSync(
+ CryptoUtil.base642bin(secret),
+ recoveryKey,
+ );
try {
await _gateway.enableTwoFactor(
code: code,
- encryptedTwoFactorSecret:
- CryptoUtil.bin2base64(encryptionResult.encryptedData!),
- twoFactorSecretDecryptionNonce:
- CryptoUtil.bin2base64(encryptionResult.nonce!),
+ encryptedTwoFactorSecret: CryptoUtil.bin2base64(
+ encryptionResult.encryptedData!,
+ ),
+ twoFactorSecretDecryptionNonce: CryptoUtil.bin2base64(
+ encryptionResult.nonce!,
+ ),
);
await setTwoFactor(value: true);
await dialog.hide();
@@ -1064,8 +1088,9 @@ class UserService {
showAlertBottomSheet(
context,
title: AppLocalizations.of(context).incorrectCode,
- message:
- AppLocalizations.of(context).pleaseVerifyTheCodeYouHaveEntered,
+ message: AppLocalizations.of(
+ context,
+ ).pleaseVerifyTheCodeYouHaveEntered,
assetPath: 'assets/warning-green.png',
);
return false;
@@ -1075,8 +1100,9 @@ class UserService {
showAlertBottomSheet(
context,
title: AppLocalizations.of(context).somethingWentWrong,
- message: AppLocalizations.of(context)
- .pleaseContactSupportIfTheProblemPersists,
+ message: AppLocalizations.of(
+ context,
+ ).pleaseContactSupportIfTheProblemPersists,
assetPath: 'assets/warning-green.png',
);
}
@@ -1104,8 +1130,9 @@ class UserService {
await showAlertBottomSheet(
context,
title: AppLocalizations.of(context).somethingWentWrong,
- message: AppLocalizations.of(context)
- .pleaseContactSupportIfTheProblemPersists,
+ message: AppLocalizations.of(
+ context,
+ ).pleaseContactSupportIfTheProblemPersists,
assetPath: 'assets/warning-green.png',
);
}
@@ -1167,8 +1194,9 @@ class UserService {
await Configuration.instance.setUserID(responseData["id"]);
if (responseData["encryptedToken"] != null) {
- await Configuration.instance
- .setEncryptedToken(responseData["encryptedToken"]);
+ await Configuration.instance.setEncryptedToken(
+ responseData["encryptedToken"],
+ );
await Configuration.instance.setKeyAttributes(
KeyAttributes.fromMap(responseData["keyAttributes"]),
);
diff --git a/mobile/apps/photos/lib/services/album_home_widget_service.dart b/mobile/apps/photos/lib/services/album_home_widget_service.dart
index b73a5fab17..a066fa63d7 100644
--- a/mobile/apps/photos/lib/services/album_home_widget_service.dart
+++ b/mobile/apps/photos/lib/services/album_home_widget_service.dart
@@ -51,7 +51,7 @@ class AlbumHomeWidgetService {
void _listenToLocalPhotoUpdates() {
Bus.instance.on<LocalPhotosUpdatedEvent>().listen((event) async {
if (event.type != EventType.hide ||
- isOfflineMode ||
+ isLocalGalleryMode ||
!Configuration.instance.hasConfiguredAccount()) {
return;
}
@@ -195,12 +195,10 @@ class AlbumHomeWidgetService {
return albums;
}
- Future<void> onLaunchFromWidget(
- int fileId,
- int collectionId,
- ) async {
- final collection =
- CollectionsService.instance.getCollectionByID(collectionId);
+ Future<void> onLaunchFromWidget(int fileId, int collectionId) async {
+ final collection = CollectionsService.instance.getCollectionByID(
+ collectionId,
+ );
if (collection == null) {
_logger.warning(
"Cannot launch widget: collection with ID $collectionId not found",
@@ -212,13 +210,12 @@ class AlbumHomeWidgetService {
final thumbnail = await CollectionsService.instance.getCover(collection);
AppNavigationService.instance
.pushPage(
- CollectionPage(
- CollectionWithThumbnail(collection, thumbnail),
- ),
+ CollectionPage(CollectionWithThumbnail(collection, thumbnail)),
)
.ignore();
- final getAllFilesCollection =
- await FilesDB.instance.getAllFilesCollection(collection.id);
+ final getAllFilesCollection = await FilesDB.instance.getAllFilesCollection(
+ collection.id,
+ );
// Then open the specific file
final file = await FilesDB.instance.getFile(fileId);
@@ -335,9 +332,7 @@ class AlbumHomeWidgetService {
return decoded;
}
if (decoded is Map) {
- return decoded.map(
- (key, value) => MapEntry(key.toString(), value),
- );
+ return decoded.map((key, value) => MapEntry(key.toString(), value));
}
return null;
}
@@ -347,9 +342,7 @@ class AlbumHomeWidgetService {
}
if (data is Map) {
- return data.map(
- (key, value) => MapEntry(key.toString(), value),
- );
+ return data.map((key, value) => MapEntry(key.toString(), value));
}
return null;
@@ -448,15 +441,18 @@ class AlbumHomeWidgetService {
for (final albumId in selectedAlbumIds) {
final collection = CollectionsService.instance.getCollectionByID(albumId);
if (collection != null) {
- final allFiles =
- await FilesDB.instance.getAllFilesCollection(collection.id);
+ final allFiles = await FilesDB.instance.getAllFilesCollection(
+ collection.id,
+ );
final files = allFiles.where((file) {
final uploadedID = file.uploadedFileID;
return uploadedID == null || !hiddenUploadIDs.contains(uploadedID);
}).toList();
if (files.isNotEmpty) {
- albumsWithFiles[collection.id] =
- (collection.decryptedName ?? "Album", files);
+ albumsWithFiles[collection.id] = (
+ collection.decryptedName ?? "Album",
+ files,
+ );
}
}
}
@@ -565,9 +561,7 @@ class AlbumHomeWidgetService {
// Show update toast after first item is rendered
if (renderedCount == 1) {
- await _refreshWidget(
- message: "First album fetched, updating widget",
- );
+ await _refreshWidget(message: "First album fetched, updating widget");
await updateAlbumsStatus(WidgetStatus.syncedPartially);
}
diff --git a/mobile/apps/photos/lib/services/filedata/filedata_service.dart b/mobile/apps/photos/lib/services/filedata/filedata_service.dart
index f300e42d7c..33f700dfb8 100644
--- a/mobile/apps/photos/lib/services/filedata/filedata_service.dart
+++ b/mobile/apps/photos/lib/services/filedata/filedata_service.dart
@@ -34,10 +34,7 @@ class FileDataService {
/// preview ids
void appendPreview(int id, String objectId, int objectSize) {
if (previewIds.containsKey(id)) return;
- previewIds[id] = PreviewInfo(
- objectId: objectId,
- objectSize: objectSize,
- );
+ previewIds[id] = PreviewInfo(objectId: objectId, objectSize: objectSize);
}
Future<void> putFileData(EnteFile file, FileDataEntity data) async {
@@ -81,8 +78,9 @@ class FileDataService {
return FileDataResponse(
fileIdToDataMap,
fetchErrorFileIDs: Set<int>.from(errFileIds.map((x) => x as int)),
- pendingIndexFileIDs:
- Set<int>.from(pendingIndexFiles.map((x) => x as int)),
+ pendingIndexFileIDs: Set<int>.from(
+ pendingIndexFiles.map((x) => x as int),
+ ),
);
} catch (e, s) {
_logger.severe("Failed to get embeddings", e, s);
@@ -98,8 +96,9 @@ class FileDataService {
return result;
}
final inputs = <_DecoderInput>[];
- final fileMap = await FilesDB.instance
- .getFileIDToFileFromIDs(remoteData.map((e) => e.fileID).toList());
+ final fileMap = await FilesDB.instance.getFileIDToFileFromIDs(
+ remoteData.map((e) => e.fileID).toList(),
+ );
for (final data in remoteData) {
final file = fileMap[data.fileID];
if (file == null) {
@@ -111,9 +110,7 @@ class FileDataService {
}
return _computer.compute<Map<String, dynamic>, Map<int, FileDataEntity>>(
_decryptFileDataComputer,
- param: {
- "inputs": inputs,
- },
+ param: {"inputs": inputs},
);
}
@@ -133,7 +130,7 @@ class FileDataService {
}
Future<void> _syncFDStatusInternal() async {
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
_logger.fine("Skipping file data sync in offline mode");
return;
}
diff --git a/mobile/apps/photos/lib/services/machine_learning/face_ml/face_recognition_service.dart b/mobile/apps/photos/lib/services/machine_learning/face_ml/face_recognition_service.dart
index 714be89ea0..edec65cec9 100644
--- a/mobile/apps/photos/lib/services/machine_learning/face_ml/face_recognition_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/face_ml/face_recognition_service.dart
@@ -53,7 +53,7 @@ class FaceRecognitionService {
if (_isSyncing) {
return;
}
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
_logger.finest("Skipping person feedback sync in offline mode");
return;
}
@@ -154,12 +154,7 @@ class FaceRecognitionService {
// Add detected faces to the faceResults
for (var i = 0; i < faces.length; i++) {
- faceResults.add(
- FaceResult.fromFaceDetection(
- faces[i],
- fileID,
- ),
- );
+ faceResults.add(FaceResult.fromFaceDetection(faces[i], fileID));
}
return faces;
@@ -181,11 +176,7 @@ class FaceRecognitionService {
) async {
try {
final (alignedFaces, alignmentResults, _, blurValues, _) =
- await preprocessToMobileFaceNetFloat32List(
- dim,
- rawRgbaBytes,
- faces,
- );
+ await preprocessToMobileFaceNetFloat32List(dim, rawRgbaBytes, faces);
// Store the results
if (alignmentResults.length != faces.length) {
diff --git a/mobile/apps/photos/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart b/mobile/apps/photos/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart
index d5c94398a6..4eac07fea5 100644
--- a/mobile/apps/photos/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart
@@ -74,10 +74,10 @@ class ClusterFeedbackService<T> {
bool extremeFilesFirst = true,
}) async {
assert(
- !isOfflineMode,
+ !isLocalGalleryMode,
"Person suggestions are online-only and should not run in offline mode.",
);
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
_logger.info(
"Skipping getSuggestionForPerson in offline mode because person suggestions are online-only",
);
@@ -99,12 +99,11 @@ class ClusterFeedbackService<T> {
// Get the files for the suggestions
final suggestionClusterIDs = foundSuggestions.map((e) => e.$1).toSet();
- final Map<int, Set<String>> fileIdToClusterID =
- await mlDataDB.getFileIdToClusterIDSetForCluster(
+ final Map<int, Set<String>> fileIdToClusterID = await mlDataDB
+ .getFileIdToClusterIDSetForCluster(suggestionClusterIDs);
+ final clusterIdToFaceIDs = await mlDataDB.getClusterToFaceIDs(
suggestionClusterIDs,
);
- final clusterIdToFaceIDs =
- await mlDataDB.getClusterToFaceIDs(suggestionClusterIDs);
final Map<String, List<EnteFile>> clusterIDToFiles = {};
final allFiles = await SearchService.instance.getAllFilesForSearch();
for (final f in allFiles) {
@@ -209,9 +208,7 @@ class ClusterFeedbackService<T> {
final embeddings = await mlDataDB.getFaceEmbeddingMapForFaces(faceIDs);
if (embeddings.isEmpty) {
- _logger.severe(
- 'No embeddings found for faces $faceIDs',
- );
+ _logger.severe('No embeddings found for faces $faceIDs');
Bus.instance.fire(PeopleChangedEvent());
return;
}
@@ -244,8 +241,10 @@ class ClusterFeedbackService<T> {
await mlDataDB.bulkCaptureNotPersonFeedback(notClusterIdToPersonId);
// Update remote so new sync does not undo this change
- await PersonService.instance
- .removeFacesFromPerson(person: p, faceIDs: faceIDs.toSet());
+ await PersonService.instance.removeFacesFromPerson(
+ person: p,
+ faceIDs: faceIDs.toSet(),
+ );
if (manualAssignmentUpdate != null) {
await manualAssignmentUpdate;
@@ -273,8 +272,10 @@ class ClusterFeedbackService<T> {
await mlDataDB.bulkCaptureNotPersonFeedback(notClusterIdToPersonId);
// Update remote so new sync does not undo this change
- await PersonService.instance
- .removeFacesFromPerson(person: person, faceIDs: {faceID});
+ await PersonService.instance.removeFacesFromPerson(
+ person: person,
+ faceIDs: {faceID},
+ );
Bus.instance.fire(
PeopleChangedEvent(
@@ -446,8 +447,9 @@ class ClusterFeedbackService<T> {
for (final clusters in personToClusterIDs.values) {
assignedClustersToAnyPerson.addAll(clusters);
}
- final ignoredClustersForAverages =
- assignedClustersToAnyPerson.difference(selectedPersonClusters);
+ final ignoredClustersForAverages = assignedClustersToAnyPerson.difference(
+ selectedPersonClusters,
+ );
final clusterAvg = await _getUpdateClusterAvg(
allClusterIdsToCountMap,
@@ -524,8 +526,9 @@ class ClusterFeedbackService<T> {
if (queryVectorID == null) {
continue;
}
- final hasRawMatchesForQuery =
- rawMatchesByQueryVectorID.containsKey(queryVectorID);
+ final hasRawMatchesForQuery = rawMatchesByQueryVectorID.containsKey(
+ queryVectorID,
+ );
final rawMatches = rawMatchesByQueryVectorID[queryVectorID] ??
const <(int, double)>[];
if (!hasRawMatchesForQuery) {
@@ -551,8 +554,9 @@ class ClusterFeedbackService<T> {
);
}
- final selectedClusterToFaceIDs =
- await mlDataDB.getClusterToFaceIDs(selectedPersonClusters);
+ final selectedClusterToFaceIDs = await mlDataDB.getClusterToFaceIDs(
+ selectedPersonClusters,
+ );
final personIDToFileIDs = <String, Set<int>>{};
for (final entry in personIDToQueryClusters.entries) {
final fileIDs = <int>{};
@@ -755,8 +759,9 @@ class ClusterFeedbackService<T> {
return [];
}
- final candidateClusterToFaceIDs =
- await mlDataDB.getClusterToFaceIDs(allCandidateClusterIDs);
+ final candidateClusterToFaceIDs = await mlDataDB.getClusterToFaceIDs(
+ allCandidateClusterIDs,
+ );
final candidateClusterToFileIDs = <String, Set<int>>{};
for (final entry in candidateClusterToFaceIDs.entries) {
candidateClusterToFileIDs[entry.key] =
@@ -808,8 +813,11 @@ class ClusterFeedbackService<T> {
continue;
}
}
- bestSuggestionPerPerson[personID] =
- (candidateClusterID, meanDistance, true);
+ bestSuggestionPerPerson[personID] = (
+ candidateClusterID,
+ meanDistance,
+ true,
+ );
foundGoodMeanSuggestion = true;
break;
}
@@ -978,12 +986,8 @@ class ClusterFeedbackService<T> {
final rankedSuggestions = bestPersonPerCluster.entries
.map(
- (entry) => (
- entry.key,
- entry.value.$2,
- entry.value.$1,
- entry.value.$3,
- ),
+ (entry) =>
+ (entry.key, entry.value.$2, entry.value.$1, entry.value.$3),
)
.toList(growable: false)
..sort((a, b) => a.$2.compareTo(b.$2));
@@ -991,10 +995,8 @@ class ClusterFeedbackService<T> {
final suggestionClusterIDs =
rankedSuggestions.map((entry) => entry.$1).toSet();
- final fileIdToClusterID =
- await mlDataDB.getFileIdToClusterIDSetForCluster(
- suggestionClusterIDs,
- );
+ final fileIdToClusterID = await mlDataDB
+ .getFileIdToClusterIDSetForCluster(suggestionClusterIDs);
final clusterIdToFaceIDs = await mlDataDB.getClusterToFaceIDs(
suggestionClusterIDs,
);
@@ -1164,8 +1166,9 @@ class ClusterFeedbackService<T> {
final fileIdToClusterID = await mlDataDB.getFileIdToClusterIDSetForCluster(
suggestionClusterIDs,
);
- final clusterIdToFaceIDs =
- await mlDataDB.getClusterToFaceIDs(suggestionClusterIDs);
+ final clusterIdToFaceIDs = await mlDataDB.getClusterToFaceIDs(
+ suggestionClusterIDs,
+ );
final clusterIDToFiles = <String, List<EnteFile>>{};
final allFiles = await SearchService.instance.getAllFilesForSearch();
for (final file in allFiles) {
@@ -1267,8 +1270,9 @@ class ClusterFeedbackService<T> {
if (person.data.rejectedFaceIDs.isNotEmpty) {
final clusterFaceIDs = await mlDataDB.getFaceIDsForCluster(clusterID);
final rejectedLengthBefore = person.data.rejectedFaceIDs.length;
- person.data.rejectedFaceIDs
- .removeWhere((faceID) => clusterFaceIDs.contains(faceID));
+ person.data.rejectedFaceIDs.removeWhere(
+ (faceID) => clusterFaceIDs.contains(faceID),
+ );
final rejectedLengthAfter = person.data.rejectedFaceIDs.length;
if (rejectedLengthBefore != rejectedLengthAfter) {
_logger.info(
@@ -1293,8 +1297,11 @@ class ClusterFeedbackService<T> {
String clusterID, {
bool firePeopleChangedEvent = true,
}) async {
- final ignoredPerson = await PersonService.instance
- .addPerson(name: '', clusterID: clusterID, isHidden: true);
+ final ignoredPerson = await PersonService.instance.addPerson(
+ name: '',
+ clusterID: clusterID,
+ isHidden: true,
+ );
final merged = await checkAndDoAutomaticMerges(
ignoredPerson,
personClusterID: clusterID,
@@ -1341,8 +1348,10 @@ class ClusterFeedbackService<T> {
continue;
}
- final newClusterIdToCount =
- clusterResult.newClusterIdToFaceIds.map((key, value) {
+ final newClusterIdToCount = clusterResult.newClusterIdToFaceIds.map((
+ key,
+ value,
+ ) {
return MapEntry(key, value.length);
});
final amountOfNewClusters = newClusterIdToCount.length;
@@ -1368,8 +1377,9 @@ class ClusterFeedbackService<T> {
final secondBiggestRatio = secondBiggestSize / originalClusterSize;
if (biggestRatio < 0.5 || secondBiggestRatio > 0.2) {
- final faceIdsOfCluster =
- await mlDataDB.getFaceIDsForCluster(clusterID);
+ final faceIdsOfCluster = await mlDataDB.getFaceIDsForCluster(
+ clusterID,
+ );
final uniqueFileIDs =
faceIdsOfCluster.map(getFileIdFromFaceId<int>).toSet();
susClusters.add((clusterID, uniqueFileIDs.length));
@@ -1428,8 +1438,10 @@ class ClusterFeedbackService<T> {
return ClusteringResult.empty();
}
- final clusterIdToCount =
- clusterResult.newClusterIdToFaceIds.map((key, value) {
+ final clusterIdToCount = clusterResult.newClusterIdToFaceIds.map((
+ key,
+ value,
+ ) {
return MapEntry(key, value.length);
});
final amountOfNewClusters = clusterIdToCount.length;
@@ -1580,17 +1592,15 @@ class ClusterFeedbackService<T> {
onVectorDbFailed: () => canUseVectorDb = false,
);
if (moreSuggestionsMean.isEmpty) {
- _logger
- .info("No suggestions found using mean, even with higher threshold");
+ _logger.info(
+ "No suggestions found using mean, even with higher threshold",
+ );
return [];
}
moreSuggestionsMean.sort((a, b) => a.$2.compareTo(b.$2));
- final otherClusterIdsCandidates = moreSuggestionsMean
- .map(
- (e) => e.$1,
- )
- .toList(growable: false);
+ final otherClusterIdsCandidates =
+ moreSuggestionsMean.map((e) => e.$1).toList(growable: false);
_logger.info(
"Found potential suggestions from loose mean for median test: $otherClusterIdsCandidates",
);
@@ -1622,9 +1632,7 @@ class ClusterFeedbackService<T> {
double minMedianDistance = maxMedianDistance;
for (final otherClusterId in otherClusterIdsCandidates) {
final Iterable<Uint8List> otherEmbeddingsProto =
- await mlDataDB.getFaceEmbeddingsForCluster(
- otherClusterId,
- );
+ await mlDataDB.getFaceEmbeddingsForCluster(otherClusterId);
final sampledOtherEmbeddingsProto = _randomSampleWithoutReplacement(
otherEmbeddingsProto,
sampleSize,
@@ -1700,20 +1708,22 @@ class ClusterFeedbackService<T> {
Set<String>? extraIgnoredClusters,
}) async {
assert(
- !isOfflineMode,
+ !isLocalGalleryMode,
"Fast person suggestions are online-only and should not run in offline mode.",
);
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
_logger.info(
"Skipping _getFastSuggestions in offline mode because person suggestions are online-only",
);
return [];
}
final allClusterIdsToCountMap = (await mlDataDB.clusterIdToFaceCount());
- final personignoredClusters =
- await mlDataDB.getPersonIgnoredClusters(person.remoteID);
- final ignoredClusters =
- personignoredClusters.union(extraIgnoredClusters ?? {});
+ final personignoredClusters = await mlDataDB.getPersonIgnoredClusters(
+ person.remoteID,
+ );
+ final ignoredClusters = personignoredClusters.union(
+ extraIgnoredClusters ?? {},
+ );
final startTime = DateTime.now();
final Map<String, Vector> clusterAvg = await _getUpdateClusterAvg(
allClusterIdsToCountMap,
@@ -1761,9 +1771,7 @@ class ClusterFeedbackService<T> {
await mlDataDB.getAllClusterSummary(minClusterSize);
final Map<String, (Uint8List, int)> updatesForClusterSummary = {};
- w?.log(
- 'getUpdateClusterAvg database call for getAllClusterSummary',
- );
+ w?.log('getUpdateClusterAvg database call for getAllClusterSummary');
final serializationEmbeddings = await _computer.compute(
checkAndSerializeCurrentClusterMeans,
@@ -1785,9 +1793,7 @@ class ClusterFeedbackService<T> {
assert((avg.norm() - 1.0).abs() < 1e-5);
}
- w?.log(
- 'serialization of embeddings',
- );
+ w?.log('serialization of embeddings');
_logger.info(
'Ignored $ignoredClustersCnt clusters, already updated $alreadyUpdatedClustersCnt clusters, $smallerClustersCnt clusters are smaller than $minClusterSize',
);
@@ -1838,18 +1844,19 @@ class ClusterFeedbackService<T> {
for (final clusterID in clusterEmbeddings.keys) {
final Iterable<Uint8List> embeddings = clusterEmbeddings[clusterID]!;
final Iterable<Vector> vectors = embeddings.map(
- (e) => Vector.fromList(
- EVector.fromBuffer(e).values,
- dtype: DType.float32,
- ),
+ (e) =>
+ Vector.fromList(EVector.fromBuffer(e).values, dtype: DType.float32),
);
final avg = vectors.reduce((a, b) => a + b) / vectors.length;
final avgNormalized = avg / avg.norm();
if (shouldPersistClusterSummaryUpdates) {
- final avgEmbeddingBuffer =
- EVector(values: avgNormalized).writeToBuffer();
- updatesForClusterSummary[clusterID] =
- (avgEmbeddingBuffer, embeddings.length);
+ final avgEmbeddingBuffer = EVector(
+ values: avgNormalized,
+ ).writeToBuffer();
+ updatesForClusterSummary[clusterID] = (
+ avgEmbeddingBuffer,
+ embeddings.length,
+ );
}
// store the intermediate updates
indexedInCurrentRun++;
@@ -2007,8 +2014,10 @@ class ClusterFeedbackService<T> {
}
final previous = bestSuggestionPerCluster[suggestedClusterID];
if (previous == null || match.$2 < previous.$1) {
- bestSuggestionPerCluster[suggestedClusterID] =
- (match.$2, personClusterID);
+ bestSuggestionPerCluster[suggestedClusterID] = (
+ match.$2,
+ personClusterID,
+ );
}
}
}
@@ -2219,9 +2228,10 @@ class ClusterFeedbackService<T> {
// Logging the cluster summary for the cluster
if (logClusterSummary) {
- final summaryMap = await mlDataDB.getClusterToClusterSummary(
- [clusterID, biggestClusterID],
- );
+ final summaryMap = await mlDataDB.getClusterToClusterSummary([
+ clusterID,
+ biggestClusterID,
+ ]);
final summary = summaryMap[clusterID];
if (summary != null) {
_logger.info(
@@ -2256,11 +2266,11 @@ class ClusterFeedbackService<T> {
'Element differences between the two means are ${biggestMean - currentMean}',
);
final currentL2Norm = currentMean.norm();
- _logger.info(
- 'L2 norm of current mean: $currentL2Norm',
+ _logger.info('L2 norm of current mean: $currentL2Norm');
+ final trueDistance = biggestMean.distanceTo(
+ currentMean,
+ distance: Distance.cosine,
);
- final trueDistance =
- biggestMean.distanceTo(currentMean, distance: Distance.cosine);
_logger.info('True distance between the two means: $trueDistance');
// Median distance
@@ -2268,10 +2278,7 @@ class ClusterFeedbackService<T> {
final Iterable<Uint8List> biggestEmbeddings =
await mlDataDB.getFaceEmbeddingsForCluster(biggestClusterID);
final List<Uint8List> biggestSampledEmbeddingsProto =
- _randomSampleWithoutReplacement(
- biggestEmbeddings,
- sampleSize,
- );
+ _randomSampleWithoutReplacement(biggestEmbeddings, sampleSize);
final List<Vector> biggestSampledEmbeddings =
biggestSampledEmbeddingsProto
.map(
@@ -2285,10 +2292,7 @@ class ClusterFeedbackService<T> {
final Iterable<Uint8List> currentEmbeddings =
await mlDataDB.getFaceEmbeddingsForCluster(clusterID);
final List<Uint8List> currentSampledEmbeddingsProto =
- _randomSampleWithoutReplacement(
- currentEmbeddings,
- sampleSize,
- );
+ _randomSampleWithoutReplacement(currentEmbeddings, sampleSize);
final List<Vector> currentSampledEmbeddings =
currentSampledEmbeddingsProto
.map(
@@ -2365,8 +2369,9 @@ List<(String, double, String)> _calcSuggestionsMean(Map<String, dynamic> args) {
final w = (kDebugMode ? EnteWatch('getSuggestions') : null)?..start();
// ignore the clusters that belong to the person or is ignored
- Set<String> otherClusters =
- clusterAvg.keys.toSet().difference(personClusters);
+ Set<String> otherClusters = clusterAvg.keys.toSet().difference(
+ personClusters,
+ );
otherClusters = otherClusters.difference(ignoredClusters);
for (final otherClusterID in otherClusters) {
@@ -2384,8 +2389,9 @@ List<(String, double, String)> _calcSuggestionsMean(Map<String, dynamic> args) {
}
if (extraIgnoreCheck &&
personClusterToIgnoredClusters[personCluster] != null &&
- personClusterToIgnoredClusters[personCluster]!
- .contains(otherClusterID)) {
+ personClusterToIgnoredClusters[personCluster]!.contains(
+ otherClusterID,
+ )) {
continue;
}
final Vector avg = clusterAvg[personCluster]!;
@@ -2399,9 +2405,12 @@ List<(String, double, String)> _calcSuggestionsMean(Map<String, dynamic> args) {
}
}
if (nearestPersonCluster != null && minDistance != null) {
- suggestions
- .putIfAbsent(nearestPersonCluster, () => [])
- .add((otherClusterID, minDistance));
+ suggestions.putIfAbsent(nearestPersonCluster, () => []).add(
+ (
+ otherClusterID,
+ minDistance,
+ ),
+ );
suggestionCount++;
}
if (suggestionCount >= suggestionMax) {
@@ -2422,9 +2431,7 @@ List<(String, double, String)> _calcSuggestionsMean(Map<String, dynamic> args) {
),
);
}
- suggestClusterIds.sort(
- (a, b) => a.$2.compareTo(b.$2),
- ); // sort by distance
+ suggestClusterIds.sort((a, b) => a.$2.compareTo(b.$2)); // sort by distance
dev.log(
"Already found ${suggestClusterIds.length} good suggestions using mean",
@@ -2437,9 +2444,7 @@ List<(String, double, String)> _calcSuggestionsMean(Map<String, dynamic> args) {
}
Future<(Map<String, Vector>, Set<String>, int, int, int)>
- checkAndSerializeCurrentClusterMeans(
- Map args,
-) async {
+ checkAndSerializeCurrentClusterMeans(Map args) async {
final Map<String, int> allClusterIdsToCountMap =
args['allClusterIdsToCountMap'];
final int minClusterSize = args['minClusterSize'] ?? 1;
@@ -2476,6 +2481,6 @@ Future<(Map<String, Vector>, Set<String>, int, int, int)>
allClusterIds,
ignoredClustersCnt,
alreadyUpdatedClustersCnt,
- smallerClustersCnt
+ smallerClustersCnt,
);
}
diff --git a/mobile/apps/photos/lib/services/machine_learning/face_ml/person/person_service.dart b/mobile/apps/photos/lib/services/machine_learning/face_ml/person/person_service.dart
index ce47c72f21..c60fd40fce 100644
--- a/mobile/apps/photos/lib/services/machine_learning/face_ml/person/person_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/face_ml/person/person_service.dart
@@ -88,23 +88,19 @@ class PersonService {
final _ = await getPersons();
if (notifyListeners) {
Bus.instance.fire(
- PeopleChangedEvent(
- type: PeopleEventType.syncDone,
- source: source,
- ),
+ PeopleChangedEvent(type: PeopleEventType.syncDone, source: source),
);
}
}
Future<List<PersonEntity>> getCertainPersons(List<String> ids) async {
- final entities =
- await entityService.getCertainEntities(EntityType.cgroup, ids);
+ final entities = await entityService.getCertainEntities(
+ EntityType.cgroup,
+ ids,
+ );
return entities
.map(
- (e) => PersonEntity(
- e.id,
- PersonData.fromJson(json.decode(e.data)),
- ),
+ (e) => PersonEntity(e.id, PersonData.fromJson(json.decode(e.data))),
)
.toList();
}
@@ -143,16 +139,11 @@ class PersonService {
return persons;
}
- static List<PersonEntity> _decodePersonEntities(
- Map<String, dynamic> param,
- ) {
+ static List<PersonEntity> _decodePersonEntities(Map<String, dynamic> param) {
final entities = param["entity"] as List<LocalEntityData>;
return entities
.map(
- (e) => PersonEntity(
- e.id,
- PersonData.fromJson(json.decode(e.data)),
- ),
+ (e) => PersonEntity(e.id, PersonData.fromJson(json.decode(e.data))),
)
.toList();
}
@@ -162,10 +153,7 @@ class PersonService {
if (e == null) {
return null;
}
- return PersonEntity(
- e.id,
- PersonData.fromJson(json.decode(e.data)),
- );
+ return PersonEntity(e.id, PersonData.fromJson(json.decode(e.data)));
});
}
@@ -200,8 +188,10 @@ class PersonService {
final Map<String, Set<String>> dbPersonCluster =
dbPersonClusterInfo[personID]!;
final personData = person.data;
- final bool shouldUpdateAssigned =
- _shouldUpdateRemotePerson(personData, dbPersonCluster);
+ final bool shouldUpdateAssigned = _shouldUpdateRemotePerson(
+ personData,
+ dbPersonCluster,
+ );
bool shouldUpdateManualAssignments = false;
List<int>? updatedManualAssignments;
@@ -238,12 +228,7 @@ class PersonService {
if (shouldUpdateAssigned) {
personData.assigned = dbPersonCluster.entries
- .map(
- (e) => ClusterInfo(
- id: e.key,
- faces: e.value,
- ),
- )
+ .map((e) => ClusterInfo(id: e.key, faces: e.value))
.toList();
}
@@ -251,8 +236,11 @@ class PersonService {
personData.manuallyAssigned = updatedManualAssignments ?? <int>[];
}
- _addOrUpdateEntity(EntityType.cgroup, personData.toJson(), id: personID)
- .ignore();
+ _addOrUpdateEntity(
+ EntityType.cgroup,
+ personData.toJson(),
+ id: personID,
+ ).ignore();
personData.logStats();
}
if (orphanMappingsRemoved > 0) {
@@ -317,10 +305,7 @@ class PersonService {
final data = PersonData(
name: name,
assigned: <ClusterInfo>[
- ClusterInfo(
- id: clusterID,
- faces: faceIds.toSet(),
- ),
+ ClusterInfo(id: clusterID, faces: faceIds.toSet()),
],
isHidden: isHidden,
isPinned: isPinned,
@@ -328,10 +313,7 @@ class PersonService {
birthDate: birthdate,
email: email,
);
- final result = await _addOrUpdateEntity(
- EntityType.cgroup,
- data.toJson(),
- );
+ final result = await _addOrUpdateEntity(EntityType.cgroup, data.toJson());
await faceMLDataDB.assignClusterToPerson(
personID: result.id,
clusterID: clusterID,
@@ -391,8 +373,9 @@ class PersonService {
// Safety check to make sure we haven't created an empty cluster now, if so delete it
for (final emptyClusterID in emptiedClusters) {
- personData.assigned
- .removeWhere((element) => element.id == emptyClusterID);
+ personData.assigned.removeWhere(
+ (element) => element.id == emptyClusterID,
+ );
await faceMLDataDB.removeClusterToPerson(
personID: person.remoteID,
clusterID: emptyClusterID,
@@ -416,8 +399,10 @@ class PersonService {
if (entity == null) {
return;
}
- final PersonEntity justName =
- PersonEntity(personID, PersonData(name: entity.data.name));
+ final PersonEntity justName = PersonEntity(
+ personID,
+ PersonData(name: entity.data.name),
+ );
await _addOrUpdateEntity(
EntityType.cgroup,
justName.data.toJson(),
@@ -448,12 +433,13 @@ class PersonService {
Future<bool> fetchRemoteClusterFeedback({
bool skipClusterUpdateIfNoChange = true,
}) async {
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
logger.finest("Skip fetching remote clusters in offline mode");
return false;
}
- final int changedEntities =
- await entityService.syncEntity(EntityType.cgroup);
+ final int changedEntities = await entityService.syncEntity(
+ EntityType.cgroup,
+ );
final bool changed = changedEntities > 0;
if (changed == false && skipClusterUpdateIfNoChange) {
return false;
@@ -537,8 +523,9 @@ class PersonService {
final personFaceIDs =
personClustersToFaceIDs.values.expand((e) => e).toSet();
final rejectedFaceIDsSet = personData.rejectedFaceIDs.toSet();
- final assignedAndRejectedFaceIDs =
- rejectedFaceIDsSet.intersection(personFaceIDs);
+ final assignedAndRejectedFaceIDs = rejectedFaceIDsSet.intersection(
+ personFaceIDs,
+ );
if (assignedAndRejectedFaceIDs.isNotEmpty) {
// Check that we don't have any empty clusters now
@@ -632,9 +619,7 @@ class PersonService {
hideFromMemories != person.data.hideFromMemories) {
memoriesCacheService.queueUpdateCache();
if (hideFromMemories) {
- unawaited(
- memoriesCacheService.purgePersonFromMemoriesCache(id),
- );
+ unawaited(memoriesCacheService.purgePersonFromMemoriesCache(id));
}
}
return updatedPerson;
@@ -655,8 +640,9 @@ class PersonService {
alreadyAssignedFileIds: const <int>[],
);
}
- final existingClusterFileIds =
- await faceMLDataDB.getFileIdToClusterIDSet(personID);
+ final existingClusterFileIds = await faceMLDataDB.getFileIdToClusterIDSet(
+ personID,
+ );
final manualFileIDs = person.data.manuallyAssigned.toSet();
final addedFileIDs = <int>[];
final alreadyAssigned = <int>[];
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart b/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart
index 7ba4a39631..087aaabda0 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart
@@ -6,7 +6,8 @@ import "package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart"
show Uint64List;
import "package:logging/logging.dart";
import "package:photos/models/ml/vector.dart";
-import "package:photos/service_locator.dart" show flagService, isOfflineMode;
+import "package:photos/service_locator.dart"
+ show flagService, isLocalGalleryMode;
import "package:photos/services/machine_learning/ml_constants.dart";
import "package:photos/services/machine_learning/semantic_search/clip/clip_text_encoder.dart";
import "package:photos/services/machine_learning/semantic_search/query_result.dart";
@@ -36,7 +37,7 @@ class MLComputer extends SuperIsolate {
@override
bool get shouldAutomaticDispose => false;
- bool get _shouldUseRustMl => flagService.useRustForML || isOfflineMode;
+ bool get _shouldUseRustMl => flagService.useRustForML || isLocalGalleryMode;
// Singleton pattern
MLComputer._privateConstructor();
@@ -60,16 +61,12 @@ class MLComputer extends SuperIsolate {
}
Future<(Uint64List, List<Uint64List>, List<Float32List>)>
- bulkVectorSearchWithKeys(
- Uint64List potentialKeys,
- bool exact,
- ) async {
+ bulkVectorSearchWithKeys(Uint64List potentialKeys, bool exact) async {
try {
- final result =
- await runInIsolate(IsolateOperation.bulkVectorSearchWithKeys, {
- "potentialKeys": potentialKeys,
- "exact": exact,
- });
+ final result = await runInIsolate(
+ IsolateOperation.bulkVectorSearchWithKeys,
+ {"potentialKeys": potentialKeys, "exact": exact},
+ );
return result;
} catch (e, s) {
_logger.severe("Could not run bulk vector search in MLComputer", e, s);
@@ -134,8 +131,9 @@ class MLComputer extends SuperIsolate {
try {
if (_clipTextVocabPath == null) {
final tokenizerRemotePath = ClipTextEncoder.instance.vocabRemotePath;
- _clipTextVocabPath = await RemoteAssetsService.instance
- .getAssetPath(tokenizerRemotePath);
+ _clipTextVocabPath = await RemoteAssetsService.instance.getAssetPath(
+ tokenizerRemotePath,
+ );
}
if (useRustMl &&
@@ -151,10 +149,9 @@ class MLComputer extends SuperIsolate {
}
if (!useRustMl && !_isClipTokenizerInitialized) {
- await runInIsolate(
- IsolateOperation.initializeClipTokenizer,
- {'vocabPath': _clipTextVocabPath!},
- );
+ await runInIsolate(IsolateOperation.initializeClipTokenizer, {
+ 'vocabPath': _clipTextVocabPath!,
+ });
_isClipTokenizerInitialized = true;
}
@@ -170,13 +167,10 @@ class MLComputer extends SuperIsolate {
}
final String modelName = ClipTextEncoder.instance.modelName;
- final address = await runInIsolate(
- IsolateOperation.loadModel,
- {
- 'modelName': modelName,
- 'modelPath': downloadedModelPath,
- },
- ) as int;
+ final address = await runInIsolate(IsolateOperation.loadModel, {
+ 'modelName': modelName,
+ 'modelPath': downloadedModelPath,
+ }) as int;
ClipTextEncoder.instance.storeSessionAddress(address);
} catch (e, s) {
_logger.severe("Could not load clip text model in MLComputer", e, s);
@@ -232,13 +226,10 @@ class MLComputer extends SuperIsolate {
bool cacheRustExact = false,
}) async {
try {
- await runInIsolate(
- IsolateOperation.cacheImageEmbeddings,
- {
- 'embeddings': embeddings,
- 'cacheRustExact': cacheRustExact,
- },
- ) as bool;
+ await runInIsolate(IsolateOperation.cacheImageEmbeddings, {
+ 'embeddings': embeddings,
+ 'cacheRustExact': cacheRustExact,
+ }) as bool;
_logger.info(
'Cached ${embeddings.length} image embeddings inside MLComputer',
);
@@ -251,10 +242,9 @@ class MLComputer extends SuperIsolate {
Future<void> clearImageEmbeddingsCache() async {
try {
- await runInIsolate(
- IsolateOperation.clearIsolateCache,
- {'key': imageEmbeddingsKey},
- ) as bool;
+ await runInIsolate(IsolateOperation.clearIsolateCache, {
+ 'key': imageEmbeddingsKey,
+ }) as bool;
return;
} catch (e, s) {
_logger.severe(
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart b/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart
index 815ec538ed..27ed2609d9 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart
@@ -4,7 +4,7 @@ import "dart:io" show Platform;
import "package:flutter/foundation.dart" show debugPrint;
import "package:logging/logging.dart";
import "package:photos/service_locator.dart"
- show flagService, isOfflineMode, localSettings;
+ show flagService, isLocalGalleryMode, localSettings;
import 'package:photos/services/machine_learning/face_ml/face_detection/face_detection_service.dart';
import 'package:photos/services/machine_learning/face_ml/face_embedding/face_embedding_service.dart';
import "package:photos/services/machine_learning/ml_models_overview.dart";
@@ -33,7 +33,7 @@ class MLIndexingIsolate extends SuperIsolate {
@override
bool get shouldAutomaticDispose => true;
- bool get _shouldUseRustMl => flagService.useRustForML || isOfflineMode;
+ bool get _shouldUseRustMl => flagService.useRustForML || isLocalGalleryMode;
int _loadedModelsCount = 0;
int _deloadedModelsCount = 0;
@@ -128,8 +128,9 @@ class MLIndexingIsolate extends SuperIsolate {
}
return _rustRuntimeLock.synchronized(() async {
final rustRuntimeArgs = await _buildRustRuntimeArgs();
- final frozenRuntimeArgs =
- Map<String, dynamic>.unmodifiable(rustRuntimeArgs);
+ final frozenRuntimeArgs = Map<String, dynamic>.unmodifiable(
+ rustRuntimeArgs,
+ );
await runInIsolate(
IsolateOperation.prepareRustMlRuntime,
frozenRuntimeArgs,
@@ -187,7 +188,7 @@ class MLIndexingIsolate extends SuperIsolate {
if (areModelsDownloaded) {
return;
}
- final goodInternet = isOfflineMode || await canUseHighBandwidth();
+ final goodInternet = isLocalGalleryMode || await canUseHighBandwidth();
if (!goodInternet) {
_logger.info(
"Cannot download models because user is not connected to wifi and is in online mode",
@@ -243,8 +244,10 @@ class MLIndexingIsolate extends SuperIsolate {
_logger.info(
"Loaded models count: $_loadedModelsCount, deloaded models count: $_deloadedModelsCount",
);
- await MLIndexingIsolate.instance
- ._loadModels(loadFaces: shouldLoadFaces, loadClip: shouldLoadClip);
+ await MLIndexingIsolate.instance._loadModels(
+ loadFaces: shouldLoadFaces,
+ loadClip: shouldLoadClip,
+ );
_logger.info('Models loaded');
});
}
@@ -307,8 +310,9 @@ class MLIndexingIsolate extends SuperIsolate {
final modelName = modelInstance.modelName;
final modelPath = await modelInstance.downloadModelSafe();
if (modelPath == null) {
- _logger
- .warning("Could not download model '$modelName': WiFi unavailable");
+ _logger.warning(
+ "Could not download model '$modelName': WiFi unavailable",
+ );
return;
}
final address = await runInIsolate(IsolateOperation.loadModel, {
@@ -332,8 +336,9 @@ class MLIndexingIsolate extends SuperIsolate {
final mlModel = model.model;
remoteModelPaths.add(mlModel.modelRemotePath);
}
- await RemoteAssetsService.instance
- .cleanupSelectedModels(remoteModelPaths);
+ await RemoteAssetsService.instance.cleanupSelectedModels(
+ remoteModelPaths,
+ );
areModelsDownloaded = false;
}
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_model.dart b/mobile/apps/photos/lib/services/machine_learning/ml_model.dart
index a44b454aed..118cc173c7 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_model.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_model.dart
@@ -3,7 +3,7 @@ import "dart:io" show File, Platform;
import "package:logging/logging.dart";
import "package:onnx_dart/onnx_dart.dart";
import "package:onnxruntime/onnxruntime.dart";
-import "package:photos/service_locator.dart" show isOfflineMode;
+import "package:photos/service_locator.dart" show isLocalGalleryMode;
import "package:photos/services/machine_learning/onnx_env.dart";
import "package:photos/services/remote_assets_service.dart";
import "package:photos/utils/network_util.dart";
@@ -37,8 +37,9 @@ abstract class MlModel {
/// WARNING: If [downloadModel] was not first called, this method will download the model first using high bandwidth.
Future<(String, String)> getModelNameAndPath() async {
return _downloadModelLock.synchronized(() async {
- final path =
- await RemoteAssetsService.instance.getAssetPath(modelRemotePath);
+ final path = await RemoteAssetsService.instance.getAssetPath(
+ modelRemotePath,
+ );
return (modelName, path);
});
}
@@ -47,7 +48,7 @@ abstract class MlModel {
if (await RemoteAssetsService.instance.hasAsset(modelRemotePath)) {
return await RemoteAssetsService.instance.getAssetPath(modelRemotePath);
} else {
- if (isOfflineMode || await canUseHighBandwidth()) {
+ if (isLocalGalleryMode || await canUseHighBandwidth()) {
return await downloadModel();
} else {
logger.warning(
@@ -61,8 +62,9 @@ abstract class MlModel {
Future<String> downloadModel([bool forceRefresh = false]) async {
return _downloadModelLock.synchronized(() async {
if (forceRefresh) {
- final file = await RemoteAssetsService.instance
- .getAssetIfUpdated(modelRemotePath);
+ final file = await RemoteAssetsService.instance.getAssetIfUpdated(
+ modelRemotePath,
+ );
return file!.path;
} else {
return await RemoteAssetsService.instance.getAssetPath(modelRemotePath);
@@ -92,12 +94,10 @@ abstract class MlModel {
// Note: The platform plugin requires a dedicated isolate for loading the model to ensure thread safety and performance isolation.
// In contrast, the current FFI-based plugin leverages the session memory address for session management, which does not require a dedicated isolate.
- static Future<int> loadModel(
- String modelName,
- String modelPath,
- ) async {
- isolateLogger
- .info('Start loading $modelName (platformPlugin: $usePlatformPlugin)');
+ static Future<int> loadModel(String modelName, String modelPath) async {
+ isolateLogger.info(
+ 'Start loading $modelName (platformPlugin: $usePlatformPlugin)',
+ );
final time = DateTime.now();
try {
late int result;
@@ -145,9 +145,7 @@ abstract class MlModel {
final sessionOptions = OrtSessionOptions()
..setInterOpNumThreads(1)
..setIntraOpNumThreads(1)
- ..setSessionGraphOptimizationLevel(
- GraphOptimizationLevel.ortEnableAll,
- );
+ ..setSessionGraphOptimizationLevel(GraphOptimizationLevel.ortEnableAll);
final session = OrtSession.fromFile(File(modelPath), sessionOptions);
return session.address;
} catch (e, s) {
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
index c409eadda1..a0d5e1eb68 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
@@ -68,22 +68,23 @@ class MLService {
static const _kForceClusteringFaceCount = 8000;
static const _kForceClusteringFaceCountOffline = 100;
int _forceClusteringFaceCountForMode(MLMode mode) {
- return mode == MLMode.offline
+ return mode == MLMode.localGallery
? _kForceClusteringFaceCountOffline
: _kForceClusteringFaceCount;
}
MLDataDB get _mlDataDB =>
- isOfflineMode ? MLDataDB.offlineInstance : MLDataDB.instance;
+ isLocalGalleryMode ? MLDataDB.offlineInstance : MLDataDB.instance;
MLDataDB _dbForMode(MLMode mode) {
- return mode == MLMode.offline
+ return mode == MLMode.localGallery
? MLDataDB.offlineInstance
: MLDataDB.instance;
}
bool _hasModeChanged(MLMode mode) {
- return (isOfflineMode ? MLMode.offline : MLMode.online) != mode;
+ return (isLocalGalleryMode ? MLMode.localGallery : MLMode.enteGallery) !=
+ mode;
}
/// Only call this function once at app startup, after that you can directly call [runAllML]
@@ -183,7 +184,7 @@ class MLService {
if (_hasScheduledStartupOwnedRemoteHydration ||
isProcessBg ||
!hasGrantedMLConsent ||
- isOfflineMode ||
+ isLocalGalleryMode ||
!localSettings.remoteFetchEnabled) {
return;
}
@@ -192,7 +193,7 @@ class MLService {
}
Future<void> _runStartupOwnedRemoteHydration() async {
- if (!hasGrantedMLConsent || isOfflineMode) {
+ if (!hasGrantedMLConsent || isLocalGalleryMode) {
return;
}
try {
@@ -225,7 +226,7 @@ class MLService {
int? skipHydrationIfCandidateFileCountAtMost,
}) async {
if (isProcessBg ||
- isOfflineMode ||
+ isLocalGalleryMode ||
!hasGrantedMLConsent ||
!localSettings.remoteFetchEnabled) {
return;
@@ -351,7 +352,8 @@ class MLService {
return;
}
try {
- final MLMode mode = isOfflineMode ? MLMode.offline : MLMode.online;
+ final MLMode mode =
+ isLocalGalleryMode ? MLMode.localGallery : MLMode.enteGallery;
final mlDataDB = _dbForMode(mode);
if (force) {
_mlControllerStatus = true;
@@ -442,7 +444,7 @@ class MLService {
/// with the lastest faceMlVersion and stored on remote or local database. If so, it skips the image.
Future<void> fetchAndIndexAllImages({required MLMode mode}) async {
if (!_canRunMLFunction(function: "Indexing")) return;
- if (mode == MLMode.online && !isOfflineMode) {
+ if (mode == MLMode.enteGallery && !isLocalGalleryMode) {
await _waitForOwnedRemoteHydrationIfRunning();
}
if (!_canRunMLFunction(function: "Indexing")) return;
@@ -462,7 +464,8 @@ class MLService {
stream:
await for (final chunk in instructionStream) {
- if ((isOfflineMode ? MLMode.offline : MLMode.online) != mode) {
+ if ((isLocalGalleryMode ? MLMode.localGallery : MLMode.enteGallery) !=
+ mode) {
_logger.info(
"App mode changed during indexing, stopping current ML run",
);
@@ -475,14 +478,14 @@ class MLService {
}
await MLIndexingIsolate.instance.cleanupLocalIndexingModels();
continue;
- } else if (!(isOfflineMode || await canUseHighBandwidth())) {
+ } else if (!(isLocalGalleryMode || await canUseHighBandwidth())) {
_logger.info(
'stopping indexing because user is not connected to wifi and in online mode',
);
break stream;
} else {
await MLIndexingIsolate.instance.ensureDownloadedModels();
- if ((flagService.useRustForML || isOfflineMode) &&
+ if ((flagService.useRustForML || isLocalGalleryMode) &&
!rustRuntimePrepared) {
await MLIndexingIsolate.instance.prepareRustRuntime();
rustRuntimePrepared = true;
@@ -490,7 +493,8 @@ class MLService {
}
final futures = <Future<bool>>[];
for (final instruction in chunk) {
- if ((isOfflineMode ? MLMode.offline : MLMode.online) != mode) {
+ if ((isLocalGalleryMode ? MLMode.localGallery : MLMode.enteGallery) !=
+ mode) {
_logger.info(
"App mode changed during indexing, stopping current ML run",
);
@@ -543,7 +547,7 @@ class MLService {
final clusterAllImagesTime = DateTime.now();
final faceIdNotToCluster = <String, List<String>>{};
- if (!isOfflineMode) {
+ if (!isLocalGalleryMode) {
_logger.info('Pulling remote feedback before actually clustering');
await PersonService.instance.fetchRemoteClusterFeedback();
final persons = await PersonService.instance.getPersons();
@@ -562,7 +566,7 @@ class MLService {
try {
// Get a sense of the total number of faces in the database
final int totalFaces = await _mlDataDB.getTotalFaceCount();
- final fileIDToCreationTime = isOfflineMode
+ final fileIDToCreationTime = isLocalGalleryMode
? await _getOfflineFileIdToCreationTime()
: await FilesDB.instance.getFileIDToCreationTime();
final startEmbeddingFetch = DateTime.now();
@@ -584,8 +588,9 @@ class MLService {
}
// sort the embeddings based on file creation time, newest first
allFaceInfoForClustering.sort((b, a) {
- return fileIDToCreationTime[a.fileID]!
- .compareTo(fileIDToCreationTime[b.fileID]!);
+ return fileIDToCreationTime[a.fileID]!.compareTo(
+ fileIDToCreationTime[b.fileID]!,
+ );
});
_logger.info(
'Getting and sorting embeddings took ${DateTime.now().difference(startEmbeddingFetch).inMilliseconds} ms for ${allFaceInfoForClustering.length} embeddings'
@@ -653,10 +658,12 @@ class MLService {
return;
}
- await _mlDataDB
- .updateFaceIdToClusterId(clusteringResult.newFaceIdToCluster);
- await _mlDataDB
- .clusterSummaryUpdate(clusteringResult.newClusterSummaries);
+ await _mlDataDB.updateFaceIdToClusterId(
+ clusteringResult.newFaceIdToCluster,
+ );
+ await _mlDataDB.clusterSummaryUpdate(
+ clusteringResult.newClusterSummaries,
+ );
Bus.instance.fire(PeopleChangedEvent());
for (final faceInfo in faceInfoForClustering) {
faceInfo.clusterId ??=
@@ -698,16 +705,22 @@ class MLService {
_logger.info(
'Updating ${clusteringResult.newFaceIdToCluster.length} FaceIDs with clusterIDs in the DB',
);
- await _mlDataDB
- .updateFaceIdToClusterId(clusteringResult.newFaceIdToCluster);
- await _mlDataDB
- .clusterSummaryUpdate(clusteringResult.newClusterSummaries);
+ await _mlDataDB.updateFaceIdToClusterId(
+ clusteringResult.newFaceIdToCluster,
+ );
+ await _mlDataDB.clusterSummaryUpdate(
+ clusteringResult.newClusterSummaries,
+ );
Bus.instance.fire(PeopleChangedEvent());
- _logger.info('Done updating FaceIDs with clusterIDs in the DB, in '
- '${DateTime.now().difference(clusterDoneTime).inSeconds} seconds');
+ _logger.info(
+ 'Done updating FaceIDs with clusterIDs in the DB, in '
+ '${DateTime.now().difference(clusterDoneTime).inSeconds} seconds',
+ );
}
- _logger.info('clusterAllImages() finished, in '
- '${DateTime.now().difference(clusterAllImagesTime).inSeconds} seconds');
+ _logger.info(
+ 'clusterAllImages() finished, in '
+ '${DateTime.now().difference(clusterAllImagesTime).inSeconds} seconds',
+ );
} catch (e, s) {
_logger.severe("`clusterAllImages` failed", e, s);
} finally {
@@ -740,7 +753,7 @@ class MLService {
// Check anything actually ran
actuallyRanML = result.ranML;
if (!actuallyRanML) return actuallyRanML;
- final bool isOffline = instruction.isOffline;
+ final bool isOffline = instruction.isLocalGallery;
// Bitmask describing properties of this index (e.g. which runtime
// produced it), so remote indexes stay distinguishable between rust
// and legacy during and after the rust ML rollout.
@@ -798,10 +811,7 @@ class MLService {
}
if (!isOffline && (result.facesRan || result.clipRan)) {
// Storing results on remote
- await fileDataService.putFileData(
- instruction.file,
- dataEntity!,
- );
+ await fileDataService.putFileData(instruction.file, dataEntity!);
}
// Storing results locally
if (result.facesRan) await mlDataDB.bulkInsertFaces(faces);
@@ -841,10 +851,7 @@ class MLService {
);
}).toList();
await mlDataDB.bulkInsertPetFaces(dbPetFaces);
- await mlDataDB.storePetFaceEmbeddings(
- dbPetFaces,
- result.petFaces!,
- );
+ await mlDataDB.storePetFaceEmbeddings(dbPetFaces, result.petFaces!);
} else if (instruction.shouldRunPets) {
// No pet faces detected; insert empty marker so the file is
// considered pet-indexed (mirrors Face.empty for human faces).
@@ -876,10 +883,7 @@ class MLService {
);
}).toList();
await mlDataDB.bulkInsertPetBodies(dbPetBodies);
- await mlDataDB.storePetBodyEmbeddings(
- dbPetBodies,
- result.petBodies!,
- );
+ await mlDataDB.storePetBodyEmbeddings(dbPetBodies, result.petBodies!);
}
}
_logger.info("ML result for fileID ${result.fileId} stored remote+local");
@@ -895,13 +899,13 @@ class MLService {
);
final storedMarkers = <String>[];
if (instruction.shouldRunFaces) {
- await mlDataDB.bulkInsertFaces(
- [Face.empty(instruction.fileKey, error: true)],
- );
+ await mlDataDB.bulkInsertFaces([
+ Face.empty(instruction.fileKey, error: true),
+ ]);
storedMarkers.add("faces");
}
if (instruction.shouldRunClip) {
- if (instruction.isOffline) {
+ if (instruction.isLocalGallery) {
await mlDataDB.putClip([ClipEmbedding.empty(instruction.fileKey)]);
} else {
await SemanticSearchService.instance.storeEmptyClipImageResult(
@@ -912,9 +916,9 @@ class MLService {
}
if (instruction.shouldRunPets) {
await mlDataDB.deletePetDataForFiles([instruction.fileKey]);
- await mlDataDB.bulkInsertPetFaces(
- [DBPetFace.empty(instruction.fileKey, error: true)],
- );
+ await mlDataDB.bulkInsertPetFaces([
+ DBPetFace.empty(instruction.fileKey, error: true),
+ ]);
storedMarkers.add("pets");
}
_logger.info(
@@ -983,10 +987,8 @@ class MLService {
}
}
if (localIdToCreation.isEmpty) return {};
- final localIdToIntId =
- await OfflineFilesDB.instance.getLocalIntIdsForLocalIds(
- localIdToCreation.keys,
- );
+ final localIdToIntId = await OfflineFilesDB.instance
+ .getLocalIntIdsForLocalIds(localIdToCreation.keys);
final map = <int, int>{};
localIdToIntId.forEach((localId, localIntId) {
final creationTime = localIdToCreation[localId];
diff --git a/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart b/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
index 7d1041c32a..72d3c036a2 100644
--- a/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
@@ -33,9 +33,9 @@ class SemanticSearchService {
final LRUMap<String, List<double>> _queryEmbeddingCache = LRUMap(20);
static const kMinimumSimilarityThreshold = 0.175;
MLDataDB get _mlDataDB =>
- isOfflineMode ? MLDataDB.offlineInstance : MLDataDB.instance;
+ isLocalGalleryMode ? MLDataDB.offlineInstance : MLDataDB.instance;
ClipVectorDB get _vectorDB =>
- isOfflineMode ? ClipVectorDB.offlineInstance : ClipVectorDB.instance;
+ isLocalGalleryMode ? ClipVectorDB.offlineInstance : ClipVectorDB.instance;
bool _hasInitialized = false;
bool _textModelIsLoaded = false;
@@ -174,7 +174,7 @@ class SemanticSearchService {
return _cacheLock.synchronized(() async {
_resetInactivityTimer();
if (_imageEmbeddingsAreCached) {
- if (_cachedEmbeddingsOffline != isOfflineMode) {
+ if (_cachedEmbeddingsOffline != isLocalGalleryMode) {
await MLComputer.instance.clearImageEmbeddingsCache();
_imageEmbeddingsAreCached = false;
_cachedEmbeddingsOffline = null;
@@ -195,7 +195,7 @@ class SemanticSearchService {
cacheRustExact: _shouldUseRustExactSearch,
);
_imageEmbeddingsAreCached = true;
- _cachedEmbeddingsOffline = isOfflineMode;
+ _cachedEmbeddingsOffline = isLocalGalleryMode;
return;
});
}
@@ -236,7 +236,7 @@ class SemanticSearchService {
fileIDToScoreMap[result.id] = result.score;
}
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
return _getOfflineMatchingFiles(
queryResults,
fileIDToScoreMap,
@@ -244,8 +244,9 @@ class SemanticSearchService {
);
}
- final filesMap = await FilesDB.instance
- .getFileIDToFileFromIDs(queryResults.map((e) => e.id).toList());
+ final filesMap = await FilesDB.instance.getFileIDToFileFromIDs(
+ queryResults.map((e) => e.id).toList(),
+ );
final ignoredCollections =
CollectionsService.instance.getHiddenCollectionIds();
@@ -333,8 +334,9 @@ class SemanticSearchService {
final query = entry.key;
final score = entry.value;
// Use cache service instead of _getTextEmbedding
- final textEmbedding =
- await textEmbeddingsCacheService.getEmbedding(query);
+ final textEmbedding = await textEmbeddingsCacheService.getEmbedding(
+ query,
+ );
textEmbeddings[query] = textEmbedding;
minimumSimilarityMap[query] = score;
}
@@ -461,11 +463,9 @@ class SemanticSearchService {
}
final startTime = DateTime.now();
- final Map<String, List<QueryResult>> queryResults =
- await MLComputer.instance.computeBulkSimilarities(
- textQueryToEmbeddingMap,
- minimumSimilarityMap,
- );
+ final Map<String, List<QueryResult>> queryResults = await MLComputer
+ .instance
+ .computeBulkSimilarities(textQueryToEmbeddingMap, minimumSimilarityMap);
final endTime = DateTime.now();
_logger.info(
"computingSimilarities (dot-product) took for ${textQueryToEmbeddingMap.length} queries " +
diff --git a/mobile/apps/photos/lib/services/magic_cache_service.dart b/mobile/apps/photos/lib/services/magic_cache_service.dart
index 9f032c7308..da8dc3e450 100644
--- a/mobile/apps/photos/lib/services/magic_cache_service.dart
+++ b/mobile/apps/photos/lib/services/magic_cache_service.dart
@@ -34,11 +34,7 @@ class MagicCache {
final List<int>? fileLocalIntIDs;
Map<int, int>? _fileIdToPositionMap;
- MagicCache(
- this.title,
- this.fileUploadedIDs, {
- this.fileLocalIntIDs,
- });
+ MagicCache(this.title, this.fileUploadedIDs, {this.fileLocalIntIDs});
// Get map of uploadID to index in fileUploadedIDs
Map<int, int> get fileIdToPositionMap {
@@ -87,7 +83,7 @@ String getLocalizedTitle(BuildContext context, String title) {
case 'Screenshots':
return context.l10n.discover_screenshots;
case 'QR Codes':
- return context.l10n.discover_qr_codes;
+ return title;
case 'Receipts':
return context.l10n.discover_receipts;
case 'Notes':
@@ -251,7 +247,7 @@ class MagicCacheService {
});
}
- String get _lastMagicCacheUpdateKey => isOfflineMode
+ String get _lastMagicCacheUpdateKey => isLocalGalleryMode
? "${_lastMagicCacheUpdateTime}_offline"
: _lastMagicCacheUpdateTime;
@@ -289,7 +285,7 @@ class MagicCacheService {
}
Future<String> _getCachePath() async {
- final suffix = isOfflineMode ? "_offline" : "";
+ final suffix = isLocalGalleryMode ? "_offline" : "";
return (await getApplicationSupportDirectory()).path +
"/cache/magic_cache$suffix";
}
@@ -314,8 +310,9 @@ class MagicCacheService {
w?.start();
final magicPromptsData = await getPrompts();
w?.log("loadedPrompts");
- final List<MagicCache> magicCaches =
- await _nonEmptyMagicResults(magicPromptsData);
+ final List<MagicCache> magicCaches = await _nonEmptyMagicResults(
+ magicPromptsData,
+ );
w?.log("resultComputed");
_magicCacheFuture = Future.value(magicCaches);
await writeToJsonFile<List<MagicCache>>(
@@ -415,7 +412,7 @@ class MagicCacheService {
final List<EnteFile> files =
await SearchService.instance.getAllFilesForSearch();
- if (!isOfflineMode) {
+ if (!isLocalGalleryMode) {
final Map<String, List<EnteFile>> magicIdToFiles = {};
final Map<String, Map<int, int>> promptFileOrder = {};
for (final cache in magicCaches) {
@@ -458,8 +455,9 @@ class MagicCacheService {
}
}
if (localIntIds.isNotEmpty) {
- final localIdMap =
- await OfflineFilesDB.instance.getLocalIdsForIntIds(localIntIds);
+ final localIdMap = await OfflineFilesDB.instance.getLocalIdsForIntIds(
+ localIntIds,
+ );
final localIdToIntId = <String, int>{};
for (final entry in localIdMap.entries) {
localIdToIntId[entry.value] = entry.key;
@@ -543,8 +541,8 @@ class MagicCacheService {
results.add(
MagicCache(
prompt.title,
- isOfflineMode ? const <int>[] : matchedIds,
- fileLocalIntIDs: isOfflineMode ? matchedIds : null,
+ isLocalGalleryMode ? const <int>[] : matchedIds,
+ fileLocalIntIDs: isLocalGalleryMode ? matchedIds : null,
),
);
}
diff --git a/mobile/apps/photos/lib/services/memories/memories_computation_context.dart b/mobile/apps/photos/lib/services/memories/memories_computation_context.dart
index 138f767236..74b7b927ea 100644
--- a/mobile/apps/photos/lib/services/memories/memories_computation_context.dart
+++ b/mobile/apps/photos/lib/services/memories/memories_computation_context.dart
@@ -11,7 +11,7 @@ import "package:photos/services/location_service.dart";
class MemoriesComputationContext {
final Map<int, EnteFile> allFileIdsToFile;
final Set<int> collectionIDsToExclude;
- final bool isOfflineMode;
+ final bool isLocalGalleryMode;
final bool mlEnabled;
final DateTime now;
final MemoriesCache oldCache;
@@ -33,7 +33,7 @@ class MemoriesComputationContext {
const MemoriesComputationContext({
required this.allFileIdsToFile,
required this.collectionIDsToExclude,
- required this.isOfflineMode,
+ required this.isLocalGalleryMode,
required this.mlEnabled,
required this.now,
required this.oldCache,
@@ -62,7 +62,7 @@ class MemoriesComputationContext {
),
collectionIDsToExclude:
(args["collectionIDsToExclude"] as Set).cast<int>(),
- isOfflineMode: args["isOfflineMode"] ?? false,
+ isLocalGalleryMode: args["isLocalGalleryMode"] ?? false,
mlEnabled: args["mlEnabled"] ?? false,
now: args["now"] as DateTime,
oldCache: args["oldCache"] as MemoriesCache,
@@ -98,7 +98,7 @@ class MemoriesComputationContext {
return <String, dynamic>{
"allFileIdsToFile": allFileIdsToFile,
"collectionIDsToExclude": collectionIDsToExclude,
- "isOfflineMode": isOfflineMode,
+ "isLocalGalleryMode": isLocalGalleryMode,
"mlEnabled": mlEnabled,
"now": now,
"oldCache": oldCache,
diff --git a/mobile/apps/photos/lib/services/memories/photo_selector.dart b/mobile/apps/photos/lib/services/memories/photo_selector.dart
index e208f529de..97beb5cd13 100644
--- a/mobile/apps/photos/lib/services/memories/photo_selector.dart
+++ b/mobile/apps/photos/lib/services/memories/photo_selector.dart
@@ -52,7 +52,7 @@ enum SelectionSort {
/// All the parameters that control how [PhotoSelector.select] works.
class SelectionConfig {
final int targetSize;
- final bool isOfflineMode;
+ final bool isLocalGalleryMode;
final Map<int, EmbeddingVector> fileIDToImageEmbedding;
/// Pre-computed score per file-ID. Higher = better.
@@ -76,7 +76,7 @@ class SelectionConfig {
const SelectionConfig({
required this.targetSize,
- required this.isOfflineMode,
+ required this.isLocalGalleryMode,
required this.fileIDToImageEmbedding,
required this.scores,
required this.distribution,
@@ -138,10 +138,14 @@ class PhotoSelector {
final fileCount = memories.length;
// Sort by score descending.
memories.sort((a, b) {
- final aID =
- memoryFileIdFromMemory(a, isOfflineMode: config.isOfflineMode);
- final bID =
- memoryFileIdFromMemory(b, isOfflineMode: config.isOfflineMode);
+ final aID = memoryFileIdFromMemory(
+ a,
+ isLocalGalleryMode: config.isLocalGalleryMode,
+ );
+ final bID = memoryFileIdFromMemory(
+ b,
+ isLocalGalleryMode: config.isLocalGalleryMode,
+ );
return (config.scores[bID] ?? 0.0).compareTo(config.scores[aID] ?? 0.0);
});
@@ -197,13 +201,17 @@ class PhotoSelector {
// photos.
final int numBuckets = config.targetSize;
final int totalRange = maxCreationTime - minCreationTime + 1;
- final List<List<Memory>> buckets =
- List.generate(numBuckets, (_) => <Memory>[]);
+ final List<List<Memory>> buckets = List.generate(
+ numBuckets,
+ (_) => <Memory>[],
+ );
for (final mem in sorted) {
final creationTime = mem.file.creationTime!;
final bucketIndex =
- ((creationTime - minCreationTime) * numBuckets ~/ totalRange)
- .clamp(0, numBuckets - 1);
+ ((creationTime - minCreationTime) * numBuckets ~/ totalRange).clamp(
+ 0,
+ numBuckets - 1,
+ );
buckets[bucketIndex].add(mem);
}
@@ -212,29 +220,39 @@ class PhotoSelector {
// Score within bucket.
final bucketFileIDs = bucket
.map(
- (m) =>
- memoryFileIdFromMemory(m, isOfflineMode: config.isOfflineMode),
+ (m) => memoryFileIdFromMemory(
+ m,
+ isLocalGalleryMode: config.isLocalGalleryMode,
+ ),
)
.whereType<int>()
.toSet();
- final bucketVectors =
- getEmbeddingsForFileIDs(config.fileIDToImageEmbedding, bucketFileIDs);
+ final bucketVectors = getEmbeddingsForFileIDs(
+ config.fileIDToImageEmbedding,
+ bucketFileIDs,
+ );
final bool littleEmbeddings = bucketVectors.length < bucket.length * 0.5;
// Sort bucket by score descending.
bucket.sort((a, b) {
- final aID =
- memoryFileIdFromMemory(a, isOfflineMode: config.isOfflineMode);
- final bID =
- memoryFileIdFromMemory(b, isOfflineMode: config.isOfflineMode);
+ final aID = memoryFileIdFromMemory(
+ a,
+ isLocalGalleryMode: config.isLocalGalleryMode,
+ );
+ final bID = memoryFileIdFromMemory(
+ b,
+ isLocalGalleryMode: config.isLocalGalleryMode,
+ );
return (config.scores[bID] ?? 0.0).compareTo(config.scores[aID] ?? 0.0);
});
// Optionally narrow to top N%.
List<Memory> candidates;
if (!littleEmbeddings && config.preNarrowTopPercent != null) {
- final keep =
- max(bucket.length * config.preNarrowTopPercent!, 1).toInt();
+ final keep = max(
+ bucket.length * config.preNarrowTopPercent!,
+ 1,
+ ).toInt();
candidates = bucket.take(keep).toList();
} else {
candidates = bucket;
@@ -251,7 +269,7 @@ class PhotoSelector {
candidates,
finalSelection,
config.fileIDToImageEmbedding,
- isOfflineMode: config.isOfflineMode,
+ isLocalGalleryMode: config.isLocalGalleryMode,
);
if (filteredCandidates.isNotEmpty) {
candidates = filteredCandidates;
@@ -271,22 +289,32 @@ class PhotoSelector {
final selectedFileIDs = finalSelection
.map(
- (mem) =>
- memoryFileIdFromMemory(mem, isOfflineMode: config.isOfflineMode),
+ (mem) => memoryFileIdFromMemory(
+ mem,
+ isLocalGalleryMode: config.isLocalGalleryMode,
+ ),
)
.whereType<int>()
.toSet();
final remaining = sorted.where((mem) {
- final fileID =
- memoryFileIdFromMemory(mem, isOfflineMode: config.isOfflineMode);
+ final fileID = memoryFileIdFromMemory(
+ mem,
+ isLocalGalleryMode: config.isLocalGalleryMode,
+ );
return fileID == null || !selectedFileIDs.contains(fileID);
}).toList()
..sort((a, b) {
- final aID =
- memoryFileIdFromMemory(a, isOfflineMode: config.isOfflineMode);
- final bID =
- memoryFileIdFromMemory(b, isOfflineMode: config.isOfflineMode);
- return (config.scores[bID] ?? 0.0).compareTo(config.scores[aID] ?? 0.0);
+ final aID = memoryFileIdFromMemory(
+ a,
+ isLocalGalleryMode: config.isLocalGalleryMode,
+ );
+ final bID = memoryFileIdFromMemory(
+ b,
+ isLocalGalleryMode: config.isLocalGalleryMode,
+ );
+ return (config.scores[bID] ?? 0.0).compareTo(
+ config.scores[aID] ?? 0.0,
+ );
});
for (final candidate in remaining) {
@@ -295,7 +323,7 @@ class PhotoSelector {
[candidate],
finalSelection,
config.fileIDToImageEmbedding,
- isOfflineMode: config.isOfflineMode,
+ isLocalGalleryMode: config.isLocalGalleryMode,
);
if (filteredCandidates.isEmpty) continue;
final timeFiltered = excludeTooCloseInTime(
@@ -320,18 +348,23 @@ class PhotoSelector {
// Group by year.
final yearToFiles = <int, List<Memory>>{};
for (final mem in memories) {
- final year =
- DateTime.fromMicrosecondsSinceEpoch(mem.file.creationTime!).year;
+ final year = DateTime.fromMicrosecondsSinceEpoch(
+ mem.file.creationTime!,
+ ).year;
yearToFiles.putIfAbsent(year, () => []).add(mem);
}
// Sort each year's list by score descending.
for (final yearFiles in yearToFiles.values) {
yearFiles.sort((a, b) {
- final aID =
- memoryFileIdFromMemory(a, isOfflineMode: config.isOfflineMode);
- final bID =
- memoryFileIdFromMemory(b, isOfflineMode: config.isOfflineMode);
+ final aID = memoryFileIdFromMemory(
+ a,
+ isLocalGalleryMode: config.isLocalGalleryMode,
+ );
+ final bID = memoryFileIdFromMemory(
+ b,
+ isLocalGalleryMode: config.isLocalGalleryMode,
+ );
return (config.scores[bID] ?? 0.0).compareTo(config.scores[aID] ?? 0.0);
});
}
@@ -363,7 +396,7 @@ class PhotoSelector {
if (checkDuplicates && (fileCount - skipped) > config.targetSize) {
final candID = memoryFileIdFromMemory(
candidate,
- isOfflineMode: config.isOfflineMode,
+ isLocalGalleryMode: config.isLocalGalleryMode,
);
final clip =
candID == null ? null : config.fileIDToImageEmbedding[candID];
@@ -372,7 +405,7 @@ class PhotoSelector {
for (final sel in selected) {
final selID = memoryFileIdFromMemory(
sel,
- isOfflineMode: config.isOfflineMode,
+ isLocalGalleryMode: config.isLocalGalleryMode,
);
final selClip =
selID == null ? null : config.fileIDToImageEmbedding[selID];
@@ -431,8 +464,10 @@ class PhotoSelector {
if (selected.file.location == null || mem.file.location == null) {
continue;
}
- final distance =
- calculateDistance(mem.file.location!, selected.file.location!);
+ final distance = calculateDistance(
+ mem.file.location!,
+ selected.file.location!,
+ );
if (distance < minDistance) {
minDistance = distance;
}
@@ -463,14 +498,18 @@ class PhotoSelector {
if (isTooCloseInTime(creationTime, selectedCreationTimes)) {
return false;
}
- final memFileID =
- memoryFileIdFromMemory(mem, isOfflineMode: config.isOfflineMode);
+ final memFileID = memoryFileIdFromMemory(
+ mem,
+ isLocalGalleryMode: config.isLocalGalleryMode,
+ );
final clip =
memFileID == null ? null : config.fileIDToImageEmbedding[memFileID];
if (clip != null && (fileCount - skipped) > config.targetSize) {
for (final selMem in selected) {
- final selID =
- memoryFileIdFromMemory(selMem, isOfflineMode: config.isOfflineMode);
+ final selID = memoryFileIdFromMemory(
+ selMem,
+ isLocalGalleryMode: config.isLocalGalleryMode,
+ );
final selClip =
selID == null ? null : config.fileIDToImageEmbedding[selID];
if (selClip == null) continue;
@@ -504,7 +543,7 @@ class PhotoSelector {
static Future<List<Memory>> bestSelectionPeople(
List<Memory> memories, {
int? prefferedSize,
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
required Map<int, EmbeddingVector> fileIDToImageEmbedding,
required Vector clipPositiveTextVector,
}) async {
@@ -518,7 +557,7 @@ class PhotoSelector {
for (final mem in memories) {
final fileID = memoryFileIdFromMemory(
mem,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
);
if (fileID == null) continue;
@@ -532,7 +571,7 @@ class PhotoSelector {
memories,
SelectionConfig(
targetSize: targetSize,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
fileIDToImageEmbedding: fileIDToImageEmbedding,
scores: scores,
distribution: SelectionDistribution.timeBuckets,
@@ -563,7 +602,7 @@ class PhotoSelector {
List<Memory> memories, {
int? prefferedSize,
SelectionDistribution? distributionOverride,
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
required bool mlEnabled,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
required Map<String, String> faceIDsToPersonID,
@@ -578,7 +617,7 @@ class PhotoSelector {
return _bestSelectionNoMl(
memories,
targetSize: targetSize,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
distributionOverride: distributionOverride,
);
}
@@ -588,7 +627,10 @@ class PhotoSelector {
// CLIP secondary) as a single numeric score.
final Map<int, double> scores = {};
for (final mem in memories) {
- final fileID = memoryFileIdFromMemory(mem, isOfflineMode: isOfflineMode);
+ final fileID = memoryFileIdFromMemory(
+ mem,
+ isLocalGalleryMode: isLocalGalleryMode,
+ );
if (fileID == null) continue;
// CLIP score
@@ -618,7 +660,7 @@ class PhotoSelector {
memories,
SelectionConfig(
targetSize: targetSize,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
fileIDToImageEmbedding: fileIDToImageEmbedding,
scores: scores,
distribution: distributionOverride,
@@ -637,7 +679,7 @@ class PhotoSelector {
memories,
SelectionConfig(
targetSize: targetSize,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
fileIDToImageEmbedding: fileIDToImageEmbedding,
scores: scores,
distribution: SelectionDistribution.none,
@@ -656,7 +698,7 @@ class PhotoSelector {
memories,
SelectionConfig(
targetSize: targetSize,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
fileIDToImageEmbedding: fileIDToImageEmbedding,
scores: scores,
distribution: SelectionDistribution.yearRoundRobin,
@@ -680,7 +722,7 @@ class PhotoSelector {
static List<Memory> _bestSelectionNoMl(
List<Memory> memories, {
required int targetSize,
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
SelectionDistribution? distributionOverride,
}) {
final withCreationTime =
@@ -721,8 +763,9 @@ class PhotoSelector {
// year's list with fresh randomness.
final yearToFiles = <int, List<Memory>>{};
for (final mem in withCreationTime) {
- final year =
- DateTime.fromMicrosecondsSinceEpoch(mem.file.creationTime!).year;
+ final year = DateTime.fromMicrosecondsSinceEpoch(
+ mem.file.creationTime!,
+ ).year;
yearToFiles.putIfAbsent(year, () => []).add(mem);
}
for (final yearFiles in yearToFiles.values) {
@@ -755,8 +798,9 @@ class PhotoSelector {
}
}
- selected
- .sort((a, b) => a.file.creationTime!.compareTo(b.file.creationTime!));
+ selected.sort(
+ (a, b) => a.file.creationTime!.compareTo(b.file.creationTime!),
+ );
return selected;
}
@@ -775,13 +819,17 @@ class PhotoSelector {
}
final int numBuckets = targetSize;
final int totalRange = maxCreationTime - minCreationTime + 1;
- final List<List<Memory>> buckets =
- List.generate(numBuckets, (_) => <Memory>[]);
+ final List<List<Memory>> buckets = List.generate(
+ numBuckets,
+ (_) => <Memory>[],
+ );
for (final mem in sorted) {
final creationTime = mem.file.creationTime!;
final bucketIndex =
- ((creationTime - minCreationTime) * numBuckets ~/ totalRange)
- .clamp(0, numBuckets - 1);
+ ((creationTime - minCreationTime) * numBuckets ~/ totalRange).clamp(
+ 0,
+ numBuckets - 1,
+ );
buckets[bucketIndex].add(mem);
}
@@ -820,8 +868,9 @@ class PhotoSelector {
}
}
- selected
- .sort((a, b) => a.file.creationTime!.compareTo(b.file.creationTime!));
+ selected.sort(
+ (a, b) => a.file.creationTime!.compareTo(b.file.creationTime!),
+ );
return selected;
}
@@ -860,18 +909,15 @@ class PhotoSelector {
return false;
}
- static int? memoryFileId(
- EnteFile file, {
- required bool isOfflineMode,
- }) {
- return isOfflineMode ? file.generatedID : file.uploadedFileID;
+ static int? memoryFileId(EnteFile file, {required bool isLocalGalleryMode}) {
+ return isLocalGalleryMode ? file.generatedID : file.uploadedFileID;
}
static int? memoryFileIdFromMemory(
Memory memory, {
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
}) {
- return memoryFileId(memory.file, isOfflineMode: isOfflineMode);
+ return memoryFileId(memory.file, isLocalGalleryMode: isLocalGalleryMode);
}
static bool isTooCloseInTime(
@@ -893,7 +939,7 @@ class PhotoSelector {
List<Memory> memories,
Map<int, EmbeddingVector> fileIDToImageEmbedding, {
int? minKeep,
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
double similarityThreshold = clipSimilarImageThreshold,
}) {
if (memories.length < 2) return memories;
@@ -904,7 +950,7 @@ class PhotoSelector {
for (final mem in memories) {
final fileID = memoryFileIdFromMemory(
mem,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
);
final bool shouldSkip = fileID != null &&
isNearDuplicate(
@@ -930,7 +976,7 @@ class PhotoSelector {
List<Memory> candidates,
List<Memory> selected,
Map<int, EmbeddingVector> fileIDToImageEmbedding, {
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
double similarityThreshold = clipSimilarImageThreshold,
}) {
if (selected.isEmpty || candidates.isEmpty) return candidates;
@@ -938,7 +984,7 @@ class PhotoSelector {
.map(
(mem) => memoryFileIdFromMemory(
mem,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
),
)
.whereType<int>()
@@ -948,7 +994,7 @@ class PhotoSelector {
for (final candidate in candidates) {
final fileID = memoryFileIdFromMemory(
candidate,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
);
if (fileID == null ||
!isNearDuplicate(
diff --git a/mobile/apps/photos/lib/services/memories_cache_service.dart b/mobile/apps/photos/lib/services/memories_cache_service.dart
index 622bdc7f02..31be59af85 100644
--- a/mobile/apps/photos/lib/services/memories_cache_service.dart
+++ b/mobile/apps/photos/lib/services/memories_cache_service.dart
@@ -57,7 +57,7 @@ class MemoriesCacheService {
static final Logger _logger = Logger("MemoriesCacheService");
MemoriesDB get _memoriesDB =>
- isOfflineMode ? MemoriesDB.offlineInstance : MemoriesDB.instance;
+ isLocalGalleryMode ? MemoriesDB.offlineInstance : MemoriesDB.instance;
List<SmartMemory>? _cachedMemories;
List<SmartMemory>? get currentMemoriesSync => _cachedMemories;
@@ -97,7 +97,7 @@ class MemoriesCacheService {
Bus.instance.on<LocalPhotosUpdatedEvent>().listen((event) {
if (_pendingInitialOfflineCacheUpgrade &&
- isOfflineMode &&
+ isLocalGalleryMode &&
event.source == "offlineImportMetadata" &&
LocalSyncService.instance.hasCompletedFirstImport()) {
unawaited(
@@ -127,11 +127,11 @@ class MemoriesCacheService {
});
}
- String get _lastCacheUpdateKey => isOfflineMode
+ String get _lastCacheUpdateKey => isLocalGalleryMode
? "${_lastMemoriesCacheUpdateTimeKey}_offline"
: _lastMemoriesCacheUpdateTimeKey;
- String get _shouldUpdateKey => isOfflineMode
+ String get _shouldUpdateKey => isLocalGalleryMode
? "${_shouldUpdateCacheKey}_offline"
: _shouldUpdateCacheKey;
@@ -164,7 +164,7 @@ class MemoriesCacheService {
if (!_mlEnabled) return false;
try {
final mlDataDB =
- isOfflineMode ? MLDataDB.offlineInstance : MLDataDB.instance;
+ isLocalGalleryMode ? MLDataDB.offlineInstance : MLDataDB.instance;
final clipIndexed = await mlDataDB.getClipIndexedFileCount();
return clipIndexed >= SmartMemoriesService.minimumMemoryLength;
} catch (e, s) {
@@ -195,7 +195,7 @@ class MemoriesCacheService {
return true;
}
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
return type == EventType.deletedFromDevice;
}
@@ -205,7 +205,7 @@ class MemoriesCacheService {
Future markMemoryAsSeen(Memory memory, bool lastInList) async {
memory.markSeen();
int? seenTimeKey;
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
final localId = memory.file.localID;
if (localId != null && localId.isNotEmpty) {
seenTimeKey = _localIdToIntIdCache[localId];
@@ -223,7 +223,7 @@ class MemoriesCacheService {
seenTimeKey: seenTimeKey,
);
if (_cachedMemories != null) {
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
final localId = memory.file.localID;
if (localId != null && localId.isNotEmpty) {
final localIntId = _localIdToIntIdCache[localId] ??
@@ -312,7 +312,7 @@ class MemoriesCacheService {
}
Future<Set<int>> _deletedMemoryFileIds(List<EnteFile> deletedFiles) async {
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
final localIds = deletedFiles
.map((file) => file.localID)
.whereType<String>()
@@ -321,15 +321,16 @@ class MemoriesCacheService {
if (localIds.isEmpty) {
return {};
}
- final localIdToIntId =
- await OfflineFilesDB.instance.ensureLocalIntIds(localIds);
+ final localIdToIntId = await OfflineFilesDB.instance.ensureLocalIntIds(
+ localIds,
+ );
_localIdToIntIdCache.addAll(localIdToIntId);
return localIdToIntId.values.toSet();
}
return deletedFiles
.map(
- (file) => PhotoSelector.memoryFileId(file, isOfflineMode: false),
+ (file) => PhotoSelector.memoryFileId(file, isLocalGalleryMode: false),
)
.whereType<int>()
.toSet();
@@ -341,7 +342,7 @@ class MemoriesCacheService {
) {
final originalLength = memory.memories.length;
memory.memories.removeWhere((mem) {
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
final localId = mem.file.localID;
if (localId == null || localId.isEmpty) {
return false;
@@ -350,8 +351,10 @@ class MemoriesCacheService {
return localIntId != null && deletedMemoryFileIds.contains(localIntId);
}
- final uploadedFileId =
- PhotoSelector.memoryFileIdFromMemory(mem, isOfflineMode: false);
+ final uploadedFileId = PhotoSelector.memoryFileIdFromMemory(
+ mem,
+ isLocalGalleryMode: false,
+ );
return uploadedFileId != null &&
deletedMemoryFileIds.contains(uploadedFileId);
});
@@ -401,7 +404,7 @@ class MemoriesCacheService {
ToShowMemory memory,
Set<int> deletedMemoryFileIds,
) {
- if (isOfflineMode && memory.fileLocalIntIDs != null) {
+ if (isLocalGalleryMode && memory.fileLocalIntIDs != null) {
final originalLength = memory.fileLocalIntIDs!.length;
memory.fileLocalIntIDs!.removeWhere(deletedMemoryFileIds.contains);
return memory.fileLocalIntIDs!.length != originalLength;
@@ -413,14 +416,14 @@ class MemoriesCacheService {
}
bool _cacheMemoryHasFiles(ToShowMemory memory) {
- if (isOfflineMode && memory.fileLocalIntIDs != null) {
+ if (isLocalGalleryMode && memory.fileLocalIntIDs != null) {
return memory.fileLocalIntIDs!.isNotEmpty;
}
return memory.fileUploadedIDs.isNotEmpty;
}
bool _shouldDeferInitialOfflineCacheUpgrade() {
- return isOfflineMode &&
+ return isLocalGalleryMode &&
!LocalSyncService.instance.hasCompletedFirstImport();
}
@@ -429,7 +432,7 @@ class MemoriesCacheService {
}) async {
if (!_pendingInitialOfflineCacheUpgrade ||
_isRunningDeferredInitialOfflineCacheUpgrade ||
- !isOfflineMode) {
+ !isLocalGalleryMode) {
return;
}
@@ -705,7 +708,7 @@ class MemoriesCacheService {
_logger.info('Processing disk cache memories to smart memories');
final List<SmartMemory> memories = [];
final List<(ToShowMemory, SmartMemory)> typedMemories = [];
- final seenTimes = await (isOfflineMode
+ final seenTimes = await (isLocalGalleryMode
? MemoriesDB.offlineInstance
: MemoriesDB.instance)
.getSeenTimes();
@@ -855,7 +858,7 @@ class MemoriesCacheService {
mlEnabled: mlReady,
);
w?.log("calculated new memories");
- final localIdToIntId = isOfflineMode
+ final localIdToIntId = isLocalGalleryMode
? await _buildLocalIntIdMapForMemories([
...nowResult.memories,
...nextResult.memories,
@@ -1078,7 +1081,7 @@ class MemoriesCacheService {
}
Future<String> _getCachePath() async {
- final suffix = isOfflineMode ? "_offline" : "";
+ final suffix = isLocalGalleryMode ? "_offline" : "";
return (await getApplicationSupportDirectory()).path +
"/cache/memories_cache$suffix";
}
@@ -1259,13 +1262,7 @@ class MemoriesCacheService {
return;
}
await _routeToPage(
- DetailPage(
- DetailPageConfiguration(
- [file],
- 0,
- "memorywidget-fallback",
- ),
- ),
+ DetailPage(DetailPageConfiguration([file], 0, "memorywidget-fallback")),
context: context,
forceCustomPageRoute: true,
);
diff --git a/mobile/apps/photos/lib/services/people_home_widget_service.dart b/mobile/apps/photos/lib/services/people_home_widget_service.dart
index 5ac55332a6..92ffad872a 100644
--- a/mobile/apps/photos/lib/services/people_home_widget_service.dart
+++ b/mobile/apps/photos/lib/services/people_home_widget_service.dart
@@ -152,10 +152,7 @@ class PeopleHomeWidgetService {
);
}
- Future<void> onLaunchFromWidget(
- int fileId,
- String personId,
- ) async {
+ Future<void> onLaunchFromWidget(int fileId, String personId) async {
final file = await FilesDB.instance.getFile(fileId);
if (file == null) {
_logger.warning("Cannot launch widget: file with ID $fileId not found");
@@ -164,17 +161,15 @@ class PeopleHomeWidgetService {
final person = await PersonService.instance.getPerson(personId);
if (person == null) {
- _logger
- .warning("Cannot launch widget: person with ID $personId not found");
+ _logger.warning(
+ "Cannot launch widget: person with ID $personId not found",
+ );
return;
}
AppNavigationService.instance
.pushPage(
- PeoplePage(
- person: person,
- searchResult: null,
- ),
+ PeoplePage(person: person, searchResult: null),
forceCustomPageRoute: true,
)
.ignore();
@@ -187,11 +182,7 @@ class PeopleHomeWidgetService {
AppNavigationService.instance
.pushPage(
DetailPage(
- DetailPageConfiguration(
- files,
- files.indexOf(file),
- "peoplewidget",
- ),
+ DetailPageConfiguration(files, files.indexOf(file), "peoplewidget"),
),
forceCustomPageRoute: true,
)
@@ -232,7 +223,7 @@ class PeopleHomeWidgetService {
}
// Check ML consent
- if (isOfflineMode || !hasGrantedMLConsent) {
+ if (isLocalGalleryMode || !hasGrantedMLConsent) {
return true;
}
diff --git a/mobile/apps/photos/lib/services/remote_assets_service.dart b/mobile/apps/photos/lib/services/remote_assets_service.dart
index 3c832acc8e..daf921798b 100644
--- a/mobile/apps/photos/lib/services/remote_assets_service.dart
+++ b/mobile/apps/photos/lib/services/remote_assets_service.dart
@@ -7,7 +7,8 @@ import "package:flutter/foundation.dart";
import "package:logging/logging.dart";
import "package:path_provider/path_provider.dart";
import "package:photos/core/network/network.dart";
-import "package:photos/service_locator.dart" show flagService, isOfflineMode;
+import "package:photos/service_locator.dart"
+ show flagService, isLocalGalleryMode;
import "package:synchronized/synchronized.dart";
class RemoteAssetsService {
@@ -189,7 +190,7 @@ class RemoteAssetsService {
Dio get _dio => NetworkClient.instance.getDio();
bool get _resumableDownloadsEnabled =>
- isOfflineMode || flagService.internalUser;
+ isLocalGalleryMode || flagService.internalUser;
Lock _lockFor(String remotePath) =>
_assetLocks.putIfAbsent(remotePath, Lock.new);
@@ -212,10 +213,7 @@ class RemoteAssetsService {
try {
final response = await _dio.head<void>(url);
- final probe = _RemoteAssetProbe.fromHeaders(
- url,
- response.headers,
- );
+ final probe = _RemoteAssetProbe.fromHeaders(url, response.headers);
if (probe == null && _shouldLogProbeDiagnosticsFor(url)) {
final contentLength =
response.headers.value(HttpHeaders.contentLengthHeader) ??
@@ -250,10 +248,7 @@ class RemoteAssetsService {
_RemoteAssetProbe probe,
) async {
final tempFile = File(savePath);
- final existingBytes = await _prepareTempFileForResume(
- tempFile,
- probe,
- );
+ final existingBytes = await _prepareTempFileForResume(tempFile, probe);
if (existingBytes > 0 && _shouldLogProbeDiagnosticsFor(url)) {
_logger.info(
"Resuming download for $url from $existingBytes / ${probe.totalBytes} bytes",
@@ -518,10 +513,7 @@ class _RemoteAssetProbe {
required this.etag,
});
- static _RemoteAssetProbe? fromHeaders(
- String url,
- Headers headers,
- ) {
+ static _RemoteAssetProbe? fromHeaders(String url, Headers headers) {
final contentLength = headers.value(HttpHeaders.contentLengthHeader);
final totalBytes = int.tryParse(contentLength ?? "");
if (totalBytes == null || totalBytes <= 0) {
@@ -556,11 +548,7 @@ class _RemoteAssetProbe {
bool get canResume => acceptsRanges && ifRangeValidator != null;
Map<String, dynamic> toJson() {
- return {
- "url": url,
- "totalBytes": totalBytes,
- "etag": etag,
- };
+ return {"url": url, "totalBytes": totalBytes, "etag": etag};
}
bool matches(_RemoteAssetProbe other) {
diff --git a/mobile/apps/photos/lib/services/search_service.dart b/mobile/apps/photos/lib/services/search_service.dart
index 3a221c0e66..d00923f84e 100644
--- a/mobile/apps/photos/lib/services/search_service.dart
+++ b/mobile/apps/photos/lib/services/search_service.dart
@@ -192,12 +192,7 @@ class SearchService {
}
_cachedFilesForSearch = _cachedFilesFuture!.then((files) {
- return applyDBFilters(
- files,
- DBFilterOptions(
- dedupeUploadID: true,
- ),
- );
+ return applyDBFilters(files, DBFilterOptions(dedupeUploadID: true));
});
return _cachedFilesForSearch!;
@@ -220,10 +215,7 @@ class SearchService {
_cachedFilesForHierarchicalSearch = _cachedFilesFuture!.then((files) {
return applyDBFilters(
files,
- DBFilterOptions(
- dedupeUploadID: false,
- onlyUploadedFiles: true,
- ),
+ DBFilterOptions(dedupeUploadID: false, onlyUploadedFiles: true),
);
});
@@ -290,8 +282,9 @@ class SearchService {
_logger.info("Reading hidden files from db");
final hiddenCollections =
CollectionsService.instance.getHiddenCollectionIds();
- _cachedHiddenFilesFuture =
- FilesDB.instance.getAllFilesFromCollections(hiddenCollections);
+ _cachedHiddenFilesFuture = FilesDB.instance.getAllFilesFromCollections(
+ hiddenCollections,
+ );
return _cachedHiddenFilesFuture!;
}
@@ -310,7 +303,7 @@ class SearchService {
Future<List<AlbumSearchResult>> getCollectionSearchResults(
String query,
) async {
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
return <AlbumSearchResult>[];
}
final List<Collection> collections = _collectionService.getCollectionsForUI(
@@ -326,12 +319,11 @@ class SearchService {
if (!c.isHidden() &&
c.type != CollectionType.uncategorized &&
- c.displayName.toLowerCase().contains(
- query.toLowerCase(),
- )) {
+ c.displayName.toLowerCase().contains(query.toLowerCase())) {
final EnteFile? thumbnail = await _collectionService.getCover(c);
- collectionSearchResults
- .add(AlbumSearchResult(CollectionWithThumbnail(c, thumbnail)));
+ collectionSearchResults.add(
+ AlbumSearchResult(CollectionWithThumbnail(c, thumbnail)),
+ );
}
}
@@ -342,13 +334,11 @@ class SearchService {
int? limit,
) async {
try {
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
return <AlbumSearchResult>[];
}
final List<Collection> collections =
- _collectionService.getCollectionsForUI(
- includedShared: true,
- );
+ _collectionService.getCollectionsForUI(includedShared: true);
final List<AlbumSearchResult> collectionSearchResults = [];
@@ -359,8 +349,9 @@ class SearchService {
if (!c.isHidden() && c.type != CollectionType.uncategorized) {
final EnteFile? thumbnail = await _collectionService.getCover(c);
- collectionSearchResults
- .add(AlbumSearchResult(CollectionWithThumbnail(c, thumbnail)));
+ collectionSearchResults.add(
+ AlbumSearchResult(CollectionWithThumbnail(c, thumbnail)),
+ );
}
}
@@ -375,10 +366,8 @@ class SearchService {
String query,
) async {
try {
- final List<DeviceCollection> deviceCollections =
- await FilesDB.instance.getDeviceCollections(
- includeCoverThumbnail: true,
- );
+ final List<DeviceCollection> deviceCollections = await FilesDB.instance
+ .getDeviceCollections(includeCoverThumbnail: true);
final List<DeviceAlbumSearchResult> results = [];
@@ -405,8 +394,9 @@ class SearchService {
final List<GenericSearchResult> searchResults = [];
for (var yearData in YearsData.instance.yearsData) {
if (yearData.year.startsWith(yearFromQuery)) {
- final List<EnteFile> filesInYear =
- await _getFilesInYear(yearData.duration);
+ final List<EnteFile> filesInYear = await _getFilesInYear(
+ yearData.duration,
+ );
if (filesInYear.isNotEmpty) {
searchResults.add(
GenericSearchResult(
@@ -484,7 +474,10 @@ class SearchService {
if (holiday.name.toLowerCase().contains(query.toLowerCase())) {
final matchedFiles =
await FilesDB.instance.getFilesCreatedWithinDurations(
- _getDurationsForCalendarDateInEveryYear(holiday.day, holiday.month),
+ _getDurationsForCalendarDateInEveryYear(
+ holiday.day,
+ holiday.month,
+ ),
ignoreCollections(),
order: 'DESC',
);
@@ -908,10 +901,7 @@ class SearchService {
onResultTap: (ctx) {
routeToPage(
ctx,
- LocationScreenStateProvider(
- entry.key,
- const LocationScreen(),
- ),
+ LocationScreenStateProvider(entry.key, const LocationScreen()),
);
},
hierarchicalSearchFilter: LocationFilter(
@@ -1046,7 +1036,7 @@ class SearchService {
bool showIgnoredOnly = false,
}) async {
try {
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
final effectiveMinClusterSize = minClusterSize > 1 ? 1 : minClusterSize;
if (showIgnoredOnly) {
return [];
@@ -1059,8 +1049,9 @@ class SearchService {
return [];
}
final localIntIds = fileIdToClusterID.keys.toSet();
- final localIdMap =
- await OfflineFilesDB.instance.getLocalIdsForIntIds(localIntIds);
+ final localIdMap = await OfflineFilesDB.instance.getLocalIdsForIntIds(
+ localIntIds,
+ );
final allFiles = await getAllFilesForSearch();
final localIdToFile = <String, EnteFile>{};
for (final file in allFiles) {
@@ -1082,9 +1073,9 @@ class SearchService {
final List<GenericSearchResult> facesResult = [];
final sortedClusterIds = clusterIdToFiles.keys.toList()
..sort(
- (a, b) => clusterIdToFiles[b]!
- .length
- .compareTo(clusterIdToFiles[a]!.length),
+ (a, b) => clusterIdToFiles[b]!.length.compareTo(
+ clusterIdToFiles[a]!.length,
+ ),
);
for (final clusterId in sortedClusterIds) {
final files = clusterIdToFiles[clusterId]!;
@@ -1094,9 +1085,7 @@ class SearchService {
ResultType.faces,
"",
files,
- params: {
- kClusterParamId: clusterId,
- },
+ params: {kClusterParamId: clusterId},
onResultTap: (ctx) {
routeToPage(
ctx,
@@ -1164,11 +1153,15 @@ class SearchService {
final PersonEntity? p =
personIdToPerson[clusterIDToPersonID[cluster] ?? ""];
if (p != null) {
- final filesForPerson =
- personIdToFiles.putIfAbsent(p.remoteID, () => []);
+ final filesForPerson = personIdToFiles.putIfAbsent(
+ p.remoteID,
+ () => [],
+ );
filesForPerson.add(file);
- final fileIdsForPerson =
- personIdToFileIds.putIfAbsent(p.remoteID, () => <int>{});
+ final fileIdsForPerson = personIdToFileIds.putIfAbsent(
+ p.remoteID,
+ () => <int>{},
+ );
fileIdsForPerson.add(entry.key);
} else {
if (clusterIdToFiles.containsKey(cluster)) {
@@ -1185,8 +1178,10 @@ class SearchService {
final manualIDs = entry.value.data.manuallyAssigned.toSet();
if (manualIDs.isEmpty) continue;
- final filesForPerson =
- personIdToFiles.putIfAbsent(personID, () => <EnteFile>[]);
+ final filesForPerson = personIdToFiles.putIfAbsent(
+ personID,
+ () => <EnteFile>[],
+ );
final idSet = personIdToFileIds.putIfAbsent(personID, () => <int>{});
for (final manualID in manualIDs) {
@@ -1204,9 +1199,8 @@ class SearchService {
// get sorted personId by files count
final sortedPersonIds = personIdToFiles.keys.toList()
..sort(
- (a, b) => personIdToFiles[b]!.length.compareTo(
- personIdToFiles[a]!.length,
- ),
+ (a, b) =>
+ personIdToFiles[b]!.length.compareTo(personIdToFiles[a]!.length),
);
final pinnedPersonIds = <String>[];
final unpinnedPersonIds = <String>[];
@@ -1278,9 +1272,9 @@ class SearchService {
}
final sortedClusterIds = clusterIdToFiles.keys.toList()
..sort(
- (a, b) => clusterIdToFiles[b]!
- .length
- .compareTo(clusterIdToFiles[a]!.length),
+ (a, b) => clusterIdToFiles[b]!.length.compareTo(
+ clusterIdToFiles[a]!.length,
+ ),
);
if (!showIgnoredOnly) {
@@ -1468,8 +1462,10 @@ class SearchService {
// }
if (limit == null || tagSearchResults.length < limit) {
- final results =
- await locationService.getFilesInCity(filesWithNoLocTag, '');
+ final results = await locationService.getFilesInCity(
+ filesWithNoLocTag,
+ '',
+ );
final List<City> sortedByResultCount = results.keys.toList()
..sort((a, b) => results[b]!.length.compareTo(results[a]!.length));
for (final city in sortedByResultCount) {
@@ -1494,8 +1490,10 @@ class SearchService {
locationTag: LocationTag(
name: city.city,
radius: defaultCityRadius,
- centerPoint:
- Location(latitude: city.lat, longitude: city.lng),
+ centerPoint: Location(
+ latitude: city.lat,
+ longitude: city.lng,
+ ),
aSquare: a * a,
bSquare: b * b,
),
@@ -1676,8 +1674,9 @@ class SearchService {
);
locationService.baseLocations = memoriesResult.baseLocations;
for (final nowMemory in memoriesResult.memories) {
- cache.toShowMemories
- .add(ToShowMemory.fromSmartMemory(nowMemory, calcTime));
+ cache.toShowMemories.add(
+ ToShowMemory.fromSmartMemory(nowMemory, calcTime),
+ );
}
cache.baseLocations.addAll(memoriesResult.baseLocations);
// memories = memoriesResult.memories;
@@ -1688,20 +1687,14 @@ class SearchService {
cache,
MemoriesCache.encodeToJsonString,
);
- _logger.info(
- "Smart memories cache written to $tempCachePath",
- );
+ _logger.info("Smart memories cache written to $tempCachePath");
final decodedCache = await decodeJsonFile(
tempCachePath,
MemoriesCache.decodeFromJsonString,
);
- _logger.info(
- "Smart memories cache decoded from $tempCachePath",
- );
+ _logger.info("Smart memories cache decoded from $tempCachePath");
memories = await MemoriesCacheService.fromCacheToMemories(decodedCache!);
- _logger.info(
- "Smart memories cache converted to memories",
- );
+ _logger.info("Smart memories cache converted to memories");
}
final searchResults = <GenericSearchResult>[];
for (final memory in memories) {
@@ -1727,7 +1720,7 @@ class SearchService {
Future<List<GenericSearchResult>> getContactSearchResults(
String query,
) async {
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
return <GenericSearchResult>[];
}
await _warmContactsCacheIfNeeded();
@@ -1746,8 +1739,10 @@ class SearchService {
for (EnteFile file in allFiles) {
if (file.isOwner) continue;
- final fileOwner = CollectionsService.instance
- .getFileOwner(file.ownerID!, file.collectionID);
+ final fileOwner = CollectionsService.instance.getFileOwner(
+ file.ownerID!,
+ file.collectionID,
+ );
if (matchesResolvedContactQuery(fileOwner, lowerCaseQuery)) {
if (peopleToSharedFiles.containsKey(fileOwner)) {
@@ -1838,8 +1833,10 @@ class SearchService {
for (EnteFile file in allFiles) {
if (file.isOwner) continue;
- final fileOwner = CollectionsService.instance
- .getFileOwner(file.ownerID!, file.collectionID);
+ final fileOwner = CollectionsService.instance.getFileOwner(
+ file.ownerID!,
+ file.collectionID,
+ );
if (peopleToSharedFiles.containsKey(fileOwner)) {
peopleToSharedFiles[fileOwner]!.add(file);
} else {
diff --git a/mobile/apps/photos/lib/services/smart_memories_clip_calculator.dart b/mobile/apps/photos/lib/services/smart_memories_clip_calculator.dart
index 1d1d9633e9..75e5485a0f 100644
--- a/mobile/apps/photos/lib/services/smart_memories_clip_calculator.dart
+++ b/mobile/apps/photos/lib/services/smart_memories_clip_calculator.dart
@@ -6,7 +6,7 @@ class ClipMemoriesCalculator {
DateTime currentTime,
List<ClipShownLog> shownClip, {
bool surfaceAll = false,
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
required Map<int, int> seenTimes,
required Map<int, EmbeddingVector> fileIDToImageEmbedding,
required Map<ClipMemoryType, Vector> clipMemoryTypeVectors,
@@ -29,14 +29,12 @@ class ClipMemoriesCalculator {
for (final entry in fileIDToImageEmbedding.entries) {
similarities[entry.key] = entry.value.vector.dot(activityVector);
}
- w?.log(
- 'comparing embeddings for clipMemoryType $clipMemoryType',
- );
+ w?.log('comparing embeddings for clipMemoryType $clipMemoryType');
final List<EnteFile> clipFiles = [];
for (final file in allFiles) {
final memoryFileID = SmartMemoriesService._memoryFileId(
file,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
);
if (memoryFileID == null) continue;
final similarity = similarities[memoryFileID];
@@ -49,11 +47,11 @@ class ClipMemoriesCalculator {
clipFiles.sort((a, b) {
final int bFileID = SmartMemoriesService._memoryFileId(
b,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
)!;
final int aFileID = SmartMemoriesService._memoryFileId(
a,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
)!;
return similarities[bFileID]!.compareTo(similarities[aFileID]!);
});
@@ -68,7 +66,7 @@ class ClipMemoriesCalculator {
if (selected.length >= 10) break;
final fileID = SmartMemoriesService._memoryFileId(
file,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
);
if (fileID == null) continue;
final creationTime = file.creationTime;
@@ -97,11 +95,11 @@ class ClipMemoriesCalculator {
selected.sort((a, b) {
final int bFileID = SmartMemoriesService._memoryFileId(
b,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
)!;
final int aFileID = SmartMemoriesService._memoryFileId(
a,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
)!;
return similarities[bFileID]!.compareTo(similarities[aFileID]!);
});
@@ -129,8 +127,9 @@ class ClipMemoriesCalculator {
for (final clipMemoryType in rotationOrder) {
for (final shownLog in shownClip) {
if (shownLog.clipMemoryType != clipMemoryType) continue;
- final shownDate =
- DateTime.fromMicrosecondsSinceEpoch(shownLog.lastTimeShown);
+ final shownDate = DateTime.fromMicrosecondsSinceEpoch(
+ shownLog.lastTimeShown,
+ );
final bool seenRecently =
currentTime.difference(shownDate) < kClipShowTimeout;
if (seenRecently) continue clipMemoriesLoop;
diff --git a/mobile/apps/photos/lib/services/smart_memories_people_calculator.dart b/mobile/apps/photos/lib/services/smart_memories_people_calculator.dart
index 5967449086..64c15a2cef 100644
--- a/mobile/apps/photos/lib/services/smart_memories_people_calculator.dart
+++ b/mobile/apps/photos/lib/services/smart_memories_people_calculator.dart
@@ -8,7 +8,7 @@ class PeopleMemoriesCalculator {
bool surfaceAll = false,
required Map<int, int> seenTimes,
required List<PersonEntity> persons,
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
required bool canUseUnnamedFallback,
String? currentUserEmail,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
@@ -38,12 +38,13 @@ class PeopleMemoriesCalculator {
for (final cluster in person.data.assigned) {
if (cluster.faces.isEmpty) continue;
personIdToFaceIDs[personID]!.addAll(cluster.faces);
- personIdToFileIDs[personID]!
- .addAll(cluster.faces.map((faceID) => getFileIdFromFaceId(faceID)));
+ personIdToFileIDs[personID]!.addAll(
+ cluster.faces.map((faceID) => getFileIdFromFaceId(faceID)),
+ );
}
}
final List<String> orderedImportantPersonsID = persons
- .where((person) => !isOfflineMode && !person.data.isIgnored)
+ .where((person) => !isLocalGalleryMode && !person.data.isIgnored)
.map((p) => p.remoteID)
.toList();
orderedImportantPersonsID.shuffle(Random());
@@ -70,7 +71,7 @@ class PeopleMemoriesCalculator {
Future<List<Memory>> selectPeopleMemories(List<Memory> memories) {
return SmartMemoriesService._bestSelectionPeople(
memories,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
fileIDToImageEmbedding: fileIDToImageEmbedding,
clipPositiveTextVector: clipPositiveTextVector,
);
@@ -88,7 +89,7 @@ class PeopleMemoriesCalculator {
seenTimes: seenTimes,
nowInMicroseconds: nowInMicroseconds,
windowEnd: windowEnd,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
selectionBuilder: selectPeopleMemories,
);
final randomizedUnnamedClusterCandidates =
@@ -201,8 +202,9 @@ class PeopleMemoriesCalculator {
}
final Map<int, double> similarities = {};
for (final embedding in vectors) {
- similarities[embedding.fileID] =
- embedding.vector.dot(activityVector);
+ similarities[embedding.fileID] = embedding.vector.dot(
+ activityVector,
+ );
}
w?.log(
'comparing embeddings for doingSomethingTogether and $activity',
@@ -251,15 +253,17 @@ class PeopleMemoriesCalculator {
final file = allFileIdsToFile[fileID];
if (file != null && file.creationTime != null) {
final creationTime = file.creationTime!;
- final creationDateTime =
- DateTime.fromMicrosecondsSinceEpoch(creationTime);
+ final creationDateTime = DateTime.fromMicrosecondsSinceEpoch(
+ creationTime,
+ );
if (currentTime.difference(creationDateTime).inDays < 365) {
longAgo = false;
break;
}
if (creationTime > lastCreationTime - microSecondsInDay) {
- final lastDateTime =
- DateTime.fromMicrosecondsSinceEpoch(lastCreationTime);
+ final lastDateTime = DateTime.fromMicrosecondsSinceEpoch(
+ lastCreationTime,
+ );
if (creationDateTime.difference(lastDateTime).inHours > 24) {
lastTimeYouSawThemFiles.clear();
}
@@ -282,12 +286,10 @@ class PeopleMemoriesCalculator {
lastTimeMemories,
fileIDToImageEmbedding,
minKeep: 2,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
);
final spacedLastTimeMemories =
- SmartMemoriesService._filterByTimeSpacing(
- filteredLastTimeMemories,
- );
+ SmartMemoriesService._filterByTimeSpacing(filteredLastTimeMemories);
final lastTimeList =
personToCandidates.putIfAbsent(personID, () => {}).putIfAbsent(
PeopleMemoryType.lastTimeYouSawThem,
@@ -352,8 +354,11 @@ class PeopleMemoriesCalculator {
final birthdate = DateTime.tryParse(person.data.birthDate ?? "");
if (birthdate != null) {
- final thisBirthday =
- DateTime(currentTime.year, birthdate.month, birthdate.day);
+ final thisBirthday = DateTime(
+ currentTime.year,
+ birthdate.month,
+ birthdate.day,
+ );
final daysTillBirthday = thisBirthday.difference(currentTime).inDays;
if (daysTillBirthday < 6 && daysTillBirthday >= 0) {
final int newAge = currentTime.year - birthdate.year;
@@ -416,8 +421,9 @@ class PeopleMemoriesCalculator {
}
w?.log('relevancy setup');
- final shownPersonAndTypeTimeout =
- Duration(days: shownPersonTimeout.inDays * 2);
+ final shownPersonAndTypeTimeout = Duration(
+ days: shownPersonTimeout.inDays * 2,
+ );
bool addedFromRotation = false;
peopleRotationLoop:
for (final personID in orderedImportantPersonsID) {
@@ -428,8 +434,9 @@ class PeopleMemoriesCalculator {
}
for (final shownLog in shownPeople) {
if (shownLog.personID != personID) continue;
- final shownDate =
- DateTime.fromMicrosecondsSinceEpoch(shownLog.lastTimeShown);
+ final shownDate = DateTime.fromMicrosecondsSinceEpoch(
+ shownLog.lastTimeShown,
+ );
final bool seenPersonRecently =
currentTime.difference(shownDate) < shownPersonTimeout;
if (seenPersonRecently) continue peopleRotationLoop;
@@ -459,8 +466,9 @@ class PeopleMemoriesCalculator {
if (shownLog.peopleMemoryType != potentialCandidate.type) {
continue;
}
- final shownTypeDate =
- DateTime.fromMicrosecondsSinceEpoch(shownLog.lastTimeShown);
+ final shownTypeDate = DateTime.fromMicrosecondsSinceEpoch(
+ shownLog.lastTimeShown,
+ );
final bool seenPersonTypeRecently =
currentTime.difference(shownTypeDate) < shownPersonAndTypeTimeout;
if (manyMemoryTypes && seenPersonTypeRecently) {
diff --git a/mobile/apps/photos/lib/services/smart_memories_service.dart b/mobile/apps/photos/lib/services/smart_memories_service.dart
index 5fb3e779c2..777cd73962 100644
--- a/mobile/apps/photos/lib/services/smart_memories_service.dart
+++ b/mobile/apps/photos/lib/services/smart_memories_service.dart
@@ -60,7 +60,7 @@ class MemoriesResult {
class SmartMemoriesService {
final _logger = Logger("SmartMemoriesService");
MemoriesDB get _memoriesDB =>
- isOfflineMode ? MemoriesDB.offlineInstance : MemoriesDB.instance;
+ isLocalGalleryMode ? MemoriesDB.offlineInstance : MemoriesDB.instance;
static const _clipSimilarImageThreshold =
PhotoSelector.clipSimilarImageThreshold;
@@ -94,9 +94,7 @@ class SmartMemoriesService {
required TimeLogger t,
}) async {
if (!shouldLoadUnnamedClusterData) {
- _logger.info(
- 'Skipping unnamed cluster data load (fallback disabled) $t',
- );
+ _logger.info('Skipping unnamed cluster data load (fallback disabled) $t');
return (
assignedClusterIDs: <String>{},
clusterIdToFaceCount: <String, int>{},
@@ -140,8 +138,8 @@ class SmartMemoriesService {
);
final allFileIdsToFile = await _getFilesAndMapForMemories(
- useLocalIntIds: isOfflineMode,
- requireLocalId: isOfflineMode,
+ useLocalIntIds: isLocalGalleryMode,
+ requireLocalId: isLocalGalleryMode,
);
_logger.info("All files length: ${allFileIdsToFile.length} $t");
@@ -154,21 +152,19 @@ class SmartMemoriesService {
_logger.info('seenTimes has ${seenTimes.length} entries $t');
final mlDataDB =
- isOfflineMode ? MLDataDB.offlineInstance : MLDataDB.instance;
- final allPersons = (!mlEnabled || isOfflineMode)
+ isLocalGalleryMode ? MLDataDB.offlineInstance : MLDataDB.instance;
+ final allPersons = (!mlEnabled || isLocalGalleryMode)
? const <PersonEntity>[]
: await PersonService.instance.getPersons();
final persons =
allPersons.where((person) => !person.data.hideFromMemories).toList();
- _logger.info(
- 'gotten all ${persons.length} persons after filtering $t',
- );
+ _logger.info('gotten all ${persons.length} persons after filtering $t');
final bool unnamedPeopleFallbackEnabled =
- mlEnabled && localSettings.showOfflineModeOption;
+ mlEnabled && localSettings.showLocalGalleryModeOption;
final amountOfNonIgnoredPersons =
persons.where((person) => !person.data.isIgnored).length;
final canUseUnnamedFallback = unnamedPeopleFallbackEnabled &&
- (isOfflineMode ||
+ (isLocalGalleryMode ||
amountOfNonIgnoredPersons <
_minimumNamedPeopleBeforeDisablingUnnamedFallback);
final shouldLoadUnnamedClusterData = unnamedPeopleFallbackEnabled &&
@@ -186,7 +182,7 @@ class SmartMemoriesService {
final clusterIdToFaceIDs = unnamedClusterData.clusterIdToFaceIDs;
final currentUserEmail =
- isOfflineMode ? null : Configuration.instance.getEmail();
+ isLocalGalleryMode ? null : Configuration.instance.getEmail();
_logger.info('currentUserEmail: $currentUserEmail $t');
final cities = await locationService.getCities();
@@ -248,7 +244,7 @@ class SmartMemoriesService {
final computationContext = MemoriesComputationContext(
allFileIdsToFile: allFileIdsToFile,
collectionIDsToExclude: collectionIDsToExclude,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
mlEnabled: mlEnabled,
now: now,
oldCache: oldCache,
@@ -275,7 +271,7 @@ class SmartMemoriesService {
'${memoriesResult.memories.length} memories computed in computer $t',
);
- if (isOfflineMode && memoriesResult.isEmpty) {
+ if (isLocalGalleryMode && memoriesResult.isEmpty) {
_logger.severe(
"Smart memories returned empty in offline mode, falling back to simple memories",
);
@@ -290,7 +286,7 @@ class SmartMemoriesService {
return memoriesResult;
} catch (e, s) {
_logger.severe("Error calculating smart memories", e, s);
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
try {
_logger.warning(
"Falling back to simple memories after smart memories failure in offline mode",
@@ -330,17 +326,17 @@ class SmartMemoriesService {
static int? _memoryFileId(
EnteFile file, {
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
}) =>
- PhotoSelector.memoryFileId(file, isOfflineMode: isOfflineMode);
+ PhotoSelector.memoryFileId(file, isLocalGalleryMode: isLocalGalleryMode);
static int? _memoryFileIdFromMemory(
Memory memory, {
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
}) =>
PhotoSelector.memoryFileIdFromMemory(
memory,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
);
static bool _isTooCloseInTime(
@@ -358,14 +354,14 @@ class SmartMemoriesService {
List<Memory> memories,
Map<int, EmbeddingVector> fileIDToImageEmbedding, {
int? minKeep,
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
double similarityThreshold = _clipSimilarImageThreshold,
}) =>
PhotoSelector.filterNearDuplicates(
memories,
fileIDToImageEmbedding,
minKeep: minKeep,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
similarityThreshold: similarityThreshold,
);
@@ -386,7 +382,7 @@ class SmartMemoriesService {
required Map<int, int> seenTimes,
required int nowInMicroseconds,
required int windowEnd,
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
required PeopleSelectionBuilder selectionBuilder,
}) {
if (clusterIdToFaceCount.isEmpty || clusterIdToFaceIDs.isEmpty) {
@@ -407,14 +403,14 @@ class SmartMemoriesService {
int bestIdx = 0;
int bestFaceCount = fileIdToFaces[_memoryFileIdFromMemory(
selected[0],
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
)]
?.length ??
999;
for (int i = 1; i < selected.length; i++) {
final faceCount = fileIdToFaces[_memoryFileIdFromMemory(
selected[i],
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
)]
?.length ??
999;
@@ -468,8 +464,9 @@ class SmartMemoriesService {
if (nonGroupFiles.length < _minimumUnnamedPeopleNonGroupPhotos) {
continue;
}
- final nonConsecutiveDays =
- _countNonConsecutiveDays(nonGroupCreationTimes);
+ final nonConsecutiveDays = _countNonConsecutiveDays(
+ nonGroupCreationTimes,
+ );
if (nonConsecutiveDays < _minimumUnnamedPeopleNonConsecutiveDays) {
continue;
}
@@ -570,8 +567,9 @@ class SmartMemoriesService {
}) {
for (final shownLog in shownPeople) {
if (shownLog.personID != personID) continue;
- final shownDate =
- DateTime.fromMicrosecondsSinceEpoch(shownLog.lastTimeShown);
+ final shownDate = DateTime.fromMicrosecondsSinceEpoch(
+ shownLog.lastTimeShown,
+ );
if (currentTime.difference(shownDate) < shownPersonTimeout) {
return true;
}
@@ -590,10 +588,8 @@ class SmartMemoriesService {
CollectionsService.instance.archivedOrHiddenCollectionIds();
final excludedUploadFileIDs = <int>{};
if (archivedOrHiddenCollectionIDs.isNotEmpty) {
- final filesInArchivedCollections =
- await FilesDB.instance.getAllFilesFromCollections(
- archivedOrHiddenCollectionIDs,
- );
+ final filesInArchivedCollections = await FilesDB.instance
+ .getAllFilesFromCollections(archivedOrHiddenCollectionIDs);
for (final archivedFile in filesInArchivedCollections) {
final archivedUploadID = archivedFile.uploadedFileID;
if (archivedUploadID != null && archivedUploadID != -1) {
@@ -641,11 +637,8 @@ class SmartMemoriesService {
final allFileIdsToFile = <int, EnteFile>{};
for (final file in candidateFiles) {
final localIntId = useLocalIntIds ? localIdToIntId[file.localID] : null;
- final mappedFile = localIntId != null
- ? file.copyWith(
- generatedID: localIntId,
- )
- : file;
+ final mappedFile =
+ localIntId != null ? file.copyWith(generatedID: localIntId) : file;
final key = useLocalIntIds
? localIntId
: useGeneratedIds
@@ -670,7 +663,7 @@ class SmartMemoriesService {
computationContext.allFileIdsToFile;
final Set<int> collectionIDsToExclude =
computationContext.collectionIDsToExclude;
- final bool isOfflineMode = computationContext.isOfflineMode;
+ final bool isLocalGalleryMode = computationContext.isLocalGalleryMode;
final bool mlEnabled = computationContext.mlEnabled;
final DateTime now = computationContext.now;
final MemoriesCache oldCache = computationContext.oldCache;
@@ -737,7 +730,7 @@ class SmartMemoriesService {
_markUsedMemories(
usedMemoryFileIds,
onThisDayMemories,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
);
memories.addAll(onThisDayMemories);
dev.log(
@@ -754,7 +747,7 @@ class SmartMemoriesService {
surfaceAll: debugSurfaceAll,
seenTimes: seenTimes,
persons: persons,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
canUseUnnamedFallback: canUseUnnamedFallback,
currentUserEmail: currentUserEmail,
fileIdToFaces: fileIdToFaces,
@@ -768,7 +761,7 @@ class SmartMemoriesService {
_markUsedMemories(
usedMemoryFileIds,
peopleMemories,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
);
memories.addAll(peopleMemories);
dev.log(
@@ -787,7 +780,7 @@ class SmartMemoriesService {
shownTrips: oldCache.tripsShownLogs,
surfaceAll: debugSurfaceAll,
cachedTripMemories: oldCache.toShowMemories,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
mlEnabled: mlEnabled,
seenTimes: seenTimes,
fileIdToFaces: fileIdToFaces,
@@ -799,7 +792,7 @@ class SmartMemoriesService {
_markUsedMemories(
usedMemoryFileIds,
tripMemories,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
);
memories.addAll(tripMemories);
dev.log(
@@ -814,7 +807,7 @@ class SmartMemoriesService {
now,
oldCache.clipShownLogs,
surfaceAll: debugSurfaceAll,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
seenTimes: seenTimes,
fileIDToImageEmbedding: fileIDToImageEmbedding,
clipMemoryTypeVectors: clipMemoryTypeVectors,
@@ -822,7 +815,7 @@ class SmartMemoriesService {
_markUsedMemories(
usedMemoryFileIds,
clipMemories,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
);
memories.addAll(clipMemories);
dev.log(
@@ -842,7 +835,7 @@ class SmartMemoriesService {
timeFiles,
now,
recentSourceFiles: fullSourceFiles,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
mlEnabled: mlEnabled,
seenTimes: seenTimes,
fileIdToFaces: fileIdToFaces,
@@ -853,7 +846,7 @@ class SmartMemoriesService {
_markUsedMemories(
usedMemoryFileIds,
timeMemories,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
);
memories.addAll(timeMemories);
dev.log(
@@ -866,12 +859,15 @@ class SmartMemoriesService {
allFileIdsToFile,
usedMemoryFileIds,
);
- final fillerMemories =
- await _getFillerResults(fillerFiles, now, seenTimes: seenTimes);
+ final fillerMemories = await _getFillerResults(
+ fillerFiles,
+ now,
+ seenTimes: seenTimes,
+ );
_markUsedMemories(
usedMemoryFileIds,
fillerMemories,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
);
memories.addAll(fillerMemories);
dev.log(
@@ -889,13 +885,13 @@ class SmartMemoriesService {
Future<List<SmartMemory>> calcSimpleMemories() async {
final now = DateTime.now();
final allFileIdsToFile = await _getFilesAndMapForMemories(
- useLocalIntIds: isOfflineMode,
- requireLocalId: isOfflineMode,
+ useLocalIntIds: isLocalGalleryMode,
+ requireLocalId: isLocalGalleryMode,
);
final usedMemoryFileIds = <int>{};
final seenTimes = await _memoriesDB.getSeenTimes();
final collectionIDsToExclude = await getCollectionIDsToExclude();
- final localIdToIntId = isOfflineMode
+ final localIdToIntId = isLocalGalleryMode
? await OfflineFilesDB.instance.ensureLocalIntIds(
allFileIdsToFile.values
.map((file) => file.localID)
@@ -923,8 +919,10 @@ class SmartMemoriesService {
memories.add(onThisDayMemories.first);
_markUsedMemories(
usedMemoryFileIds,
- [onThisDayMemories.first],
- isOfflineMode: isOfflineMode,
+ [
+ onThisDayMemories.first,
+ ],
+ isLocalGalleryMode: isLocalGalleryMode,
);
}
@@ -976,13 +974,13 @@ class SmartMemoriesService {
static void _markUsedMemories(
Set<int> usedMemoryFileIds,
Iterable<SmartMemory> memories, {
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
}) {
for (final memory in memories) {
for (final fileMemory in memory.memories) {
final fileId = _memoryFileIdFromMemory(
fileMemory,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
);
if (fileId != null) {
usedMemoryFileIds.add(fileId);
@@ -998,7 +996,7 @@ class SmartMemoriesService {
bool surfaceAll = false,
required Map<int, int> seenTimes,
required List<PersonEntity> persons,
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
required bool canUseUnnamedFallback,
String? currentUserEmail,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
@@ -1016,7 +1014,7 @@ class SmartMemoriesService {
surfaceAll: surfaceAll,
seenTimes: seenTimes,
persons: persons,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
canUseUnnamedFallback: canUseUnnamedFallback,
currentUserEmail: currentUserEmail,
fileIdToFaces: fileIdToFaces,
@@ -1034,7 +1032,7 @@ class SmartMemoriesService {
DateTime currentTime,
List<ClipShownLog> shownClip, {
bool surfaceAll = false,
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
required Map<int, int> seenTimes,
required Map<int, EmbeddingVector> fileIDToImageEmbedding,
required Map<ClipMemoryType, Vector> clipMemoryTypeVectors,
@@ -1044,7 +1042,7 @@ class SmartMemoriesService {
currentTime,
shownClip,
surfaceAll: surfaceAll,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
seenTimes: seenTimes,
fileIDToImageEmbedding: fileIDToImageEmbedding,
clipMemoryTypeVectors: clipMemoryTypeVectors,
@@ -1058,7 +1056,7 @@ class SmartMemoriesService {
required List<TripsShownLog> shownTrips,
bool surfaceAll = false,
required Iterable<ToShowMemory> cachedTripMemories,
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
required bool mlEnabled,
required Map<int, int> seenTimes,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
@@ -1074,7 +1072,7 @@ class SmartMemoriesService {
shownTrips,
surfaceAll: surfaceAll,
cachedTripMemories: cachedTripMemories,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
mlEnabled: mlEnabled,
seenTimes: seenTimes,
fileIdToFaces: fileIdToFaces,
@@ -1089,7 +1087,7 @@ class SmartMemoriesService {
Iterable<EnteFile> allFiles,
DateTime currentTime, {
required Iterable<EnteFile> recentSourceFiles,
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
required bool mlEnabled,
required Map<int, int> seenTimes,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
@@ -1101,7 +1099,7 @@ class SmartMemoriesService {
allFiles,
currentTime,
recentSourceFiles: recentSourceFiles,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
mlEnabled: mlEnabled,
seenTimes: seenTimes,
fileIdToFaces: fileIdToFaces,
@@ -1126,7 +1124,7 @@ class SmartMemoriesService {
}
Future<Set<int>> getCollectionIDsToExclude() async {
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
return <int>{};
}
final collections = CollectionsService.instance.getCollectionsForUI();
@@ -1206,9 +1204,7 @@ class SmartMemoriesService {
context != null
? Localizations.localeOf(context).languageCode
: languageCode ?? "en",
- ).format(
- DateTime.fromMicrosecondsSinceEpoch(creationTime),
- );
+ ).format(DateTime.fromMicrosecondsSinceEpoch(creationTime));
}
static int? _seenTimeKeyForFile(
@@ -1240,19 +1236,13 @@ class SmartMemoriesService {
if (results.length > 2 &&
results.keys.map((city) => city.country).toSet().length == 1 &&
!base &&
- !_isExcludedCountryName(
- biggestPlace.country,
- excludedCountryNames,
- )) {
+ !_isExcludedCountryName(biggestPlace.country, excludedCountryNames)) {
return biggestPlace.country;
}
return null;
}
- static String? _tryFindCountryName(
- List<Memory> memories,
- List<City> cities,
- ) {
+ static String? _tryFindCountryName(List<Memory> memories, List<City> cities) {
final locationContext = _getLocationNameContext(memories, cities);
return locationContext?.biggestPlace.country;
}
@@ -1261,10 +1251,7 @@ class SmartMemoriesService {
List<EnteFile> files,
Map<City, List<EnteFile>> results,
City biggestPlace,
- })? _getLocationNameContext(
- List<Memory> memories,
- List<City> cities,
- ) {
+ })? _getLocationNameContext(List<Memory> memories, List<City> cities) {
final files = Memory.filesFromMemories(memories);
final results = getCityResults({
"query": '',
@@ -1298,14 +1285,14 @@ class SmartMemoriesService {
static Future<List<Memory>> _bestSelectionPeople(
List<Memory> memories, {
int? prefferedSize,
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
required Map<int, EmbeddingVector> fileIDToImageEmbedding,
required Vector clipPositiveTextVector,
}) =>
PhotoSelector.bestSelectionPeople(
memories,
prefferedSize: prefferedSize,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
fileIDToImageEmbedding: fileIDToImageEmbedding,
clipPositiveTextVector: clipPositiveTextVector,
);
@@ -1314,7 +1301,7 @@ class SmartMemoriesService {
List<Memory> memories, {
int? prefferedSize,
SelectionDistribution? distributionOverride,
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
required bool mlEnabled,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
required Map<String, String> faceIDsToPersonID,
@@ -1325,7 +1312,7 @@ class SmartMemoriesService {
memories,
prefferedSize: prefferedSize,
distributionOverride: distributionOverride,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
diff --git a/mobile/apps/photos/lib/services/smart_memories_time_calculator.dart b/mobile/apps/photos/lib/services/smart_memories_time_calculator.dart
index 63bc188fbf..01166c8917 100644
--- a/mobile/apps/photos/lib/services/smart_memories_time_calculator.dart
+++ b/mobile/apps/photos/lib/services/smart_memories_time_calculator.dart
@@ -7,7 +7,7 @@ class TimeMemoriesCalculator {
Iterable<EnteFile> allFiles,
DateTime currentTime, {
Iterable<EnteFile>? recentSourceFiles,
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
required bool mlEnabled,
required Map<int, int> seenTimes,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
@@ -23,8 +23,9 @@ class TimeMemoriesCalculator {
final recentCandidates = recentSourceFiles ?? availableFiles;
final startOfCurrentWeek = _startOfWeek(currentTime);
- final startOfPreviousWeek =
- startOfCurrentWeek.subtract(const Duration(days: 7));
+ final startOfPreviousWeek = startOfCurrentWeek.subtract(
+ const Duration(days: 7),
+ );
await _maybeAddRecentTimeMemory(
recentMemoryResult,
recentCandidates,
@@ -33,7 +34,7 @@ class TimeMemoriesCalculator {
showStart: startOfCurrentWeek,
showEnd: startOfCurrentWeek.add(const Duration(days: 7)),
kind: TimeMemoryKind.lastWeek,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
mlEnabled: mlEnabled,
seenTimes: seenTimes,
fileIdToFaces: fileIdToFaces,
@@ -58,7 +59,7 @@ class TimeMemoriesCalculator {
startOfCurrentMonth.month + 1,
),
kind: TimeMemoryKind.lastMonth,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
mlEnabled: mlEnabled,
seenTimes: seenTimes,
fileIdToFaces: fileIdToFaces,
@@ -81,8 +82,9 @@ class TimeMemoriesCalculator {
for (final file in availableFiles) {
if (file.creationTime! > cutOffTime.microsecondsSinceEpoch) continue;
- final creationTime =
- DateTime.fromMicrosecondsSinceEpoch(file.creationTime!);
+ final creationTime = DateTime.fromMicrosecondsSinceEpoch(
+ file.creationTime!,
+ );
final dayMonth = creationTime.month * 100 + creationTime.day;
final year = creationTime.year;
@@ -103,12 +105,15 @@ class TimeMemoriesCalculator {
.toList();
if (significantDays.length >= 3) {
- final date =
- DateTime(currentTime.year, dayMonth ~/ 100, dayMonth % 100);
+ final date = DateTime(
+ currentTime.year,
+ dayMonth ~/ 100,
+ dayMonth % 100,
+ );
final allPhotos = yearGroups.values.expand((x) => x).toList();
final photoSelection = await SmartMemoriesService._bestSelection(
allPhotos,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
@@ -127,12 +132,15 @@ class TimeMemoriesCalculator {
} else {
for (final year in significantDays) {
final date = DateTime(year, dayMonth ~/ 100, dayMonth % 100);
- final showDate =
- DateTime(currentYear, dayMonth ~/ 100, dayMonth % 100);
+ final showDate = DateTime(
+ currentYear,
+ dayMonth ~/ 100,
+ dayMonth % 100,
+ );
final files = yearGroups[year]!;
final photoSelection = await SmartMemoriesService._bestSelection(
files,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
@@ -157,8 +165,9 @@ class TimeMemoriesCalculator {
for (final file in availableFiles) {
if (file.creationTime! > cutOffTime.microsecondsSinceEpoch) continue;
- final creationTime =
- DateTime.fromMicrosecondsSinceEpoch(file.creationTime!);
+ final creationTime = DateTime.fromMicrosecondsSinceEpoch(
+ file.creationTime!,
+ );
final week = getWeekNumber(creationTime);
if (week != currentWeek) continue;
final year = creationTime.year;
@@ -178,7 +187,7 @@ class TimeMemoriesCalculator {
currentWeekYearGroups.values.expand((x) => x).toList();
final photoSelection = await SmartMemoriesService._bestSelection(
allPhotos,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
@@ -194,13 +203,15 @@ class TimeMemoriesCalculator {
);
} else {
for (final year in significantWeeks) {
- final date = DateTime(year, 1, 1).add(
- Duration(days: (currentWeek - 1) * 7),
- );
+ final date = DateTime(
+ year,
+ 1,
+ 1,
+ ).add(Duration(days: (currentWeek - 1) * 7));
final files = currentWeekYearGroups[year]!;
final photoSelection = await SmartMemoriesService._bestSelection(
files,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
@@ -228,20 +239,21 @@ class TimeMemoriesCalculator {
SmartMemoriesService._markUsedMemories(
historicalMemoryFileIds,
historicalMemoryResult,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
);
for (final file in availableFiles) {
final fileId = SmartMemoriesService._memoryFileId(
file,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
);
if (fileId != null && historicalMemoryFileIds.contains(fileId)) {
continue;
}
if (file.creationTime! > cutOffTime.microsecondsSinceEpoch) continue;
- final creationTime =
- DateTime.fromMicrosecondsSinceEpoch(file.creationTime!);
+ final creationTime = DateTime.fromMicrosecondsSinceEpoch(
+ file.creationTime!,
+ );
final month = creationTime.month;
if (month != currentMonth) continue;
final year = creationTime.year;
@@ -264,7 +276,7 @@ class TimeMemoriesCalculator {
final photoSelection = await SmartMemoriesService._bestSelection(
monthYearFiles,
prefferedSize: monthSelectionSize,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
@@ -294,7 +306,7 @@ class TimeMemoriesCalculator {
final photoSelection = await SmartMemoriesService._bestSelection(
allPhotos,
prefferedSize: monthSelectionSize,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
@@ -323,7 +335,7 @@ class TimeMemoriesCalculator {
required DateTime showStart,
required DateTime showEnd,
required TimeMemoryKind kind,
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
required bool mlEnabled,
required Map<int, int> seenTimes,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
@@ -352,7 +364,7 @@ class TimeMemoriesCalculator {
candidates,
prefferedSize: _recentTimeMemorySelectionSize,
distributionOverride: SelectionDistribution.timeBuckets,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
@@ -381,8 +393,9 @@ class TimeMemoriesCalculator {
final windowEnd =
currentTime.add(kMemoriesUpdateFrequency).microsecondsSinceEpoch;
final currentYear = currentTime.year;
- final cutOffTime = currentTime
- .subtract(const Duration(days: 364) - kMemoriesUpdateFrequency);
+ final cutOffTime = currentTime.subtract(
+ const Duration(days: 364) - kMemoriesUpdateFrequency,
+ );
final timeTillYearEnd = DateTime(currentYear + 1).difference(currentTime);
final bool almostYearEnd = timeTillYearEnd < kMemoriesUpdateFrequency;
@@ -407,9 +420,8 @@ class TimeMemoriesCalculator {
),
);
} else if (almostYearEnd) {
- final altDiff = fileDate.copyWith(year: currentYear + 1).difference(
- currentTime,
- );
+ final altDiff =
+ fileDate.copyWith(year: currentYear + 1).difference(currentTime);
if (!altDiff.isNegative && altDiff < kMemoriesUpdateFrequency) {
final yearsAgo = currentYear - fileDate.year + 1;
yearsAgoToMemories.putIfAbsent(yearsAgo, () => []).add(
@@ -459,8 +471,9 @@ class TimeMemoriesCalculator {
final currentMonth = currentTime.month;
final currentDay = currentTime.day;
final startPoint = DateTime(currentYear, currentMonth, currentDay);
- final cutOffTime = startPoint
- .subtract(const Duration(days: 363) - kMemoriesUpdateFrequency);
+ final cutOffTime = startPoint.subtract(
+ const Duration(days: 363) - kMemoriesUpdateFrequency,
+ );
final diffThreshold = Duration(days: daysToCompute);
final Map<int, List<Memory>> daysToMemories = {};
@@ -490,9 +503,8 @@ class TimeMemoriesCalculator {
);
daysToYears.putIfAbsent(diff.inDays, () => []).add(fileDate.year);
} else if (almostYearEnd) {
- final altDiff = fileDate.copyWith(year: currentYear + 1).difference(
- currentTime,
- );
+ final altDiff =
+ fileDate.copyWith(year: currentYear + 1).difference(currentTime);
if (!altDiff.isNegative && altDiff < diffThreshold) {
daysToMemories.putIfAbsent(altDiff.inDays, () => []).add(
Memory.fromFile(
@@ -520,8 +532,9 @@ class TimeMemoriesCalculator {
if (memories.length > 20) {
final Map<int, List<Memory>> memoriesByYear = {};
for (final memory in memories) {
- final creationTime =
- DateTime.fromMicrosecondsSinceEpoch(memory.file.creationTime!);
+ final creationTime = DateTime.fromMicrosecondsSinceEpoch(
+ memory.file.creationTime!,
+ );
final year = creationTime.year;
memoriesByYear.putIfAbsent(year, () => []).add(memory);
}
diff --git a/mobile/apps/photos/lib/services/smart_memories_trip_calculator_v2.dart b/mobile/apps/photos/lib/services/smart_memories_trip_calculator_v2.dart
index b0053a7480..a86d6420c3 100644
--- a/mobile/apps/photos/lib/services/smart_memories_trip_calculator_v2.dart
+++ b/mobile/apps/photos/lib/services/smart_memories_trip_calculator_v2.dart
@@ -138,7 +138,7 @@ class TripMemoriesCalculatorV2 {
List<TripsShownLog> shownTrips, {
bool surfaceAll = false,
required Iterable<ToShowMemory> cachedTripMemories,
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
required bool mlEnabled,
required Map<int, int> seenTimes,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
@@ -158,7 +158,7 @@ class TripMemoriesCalculatorV2 {
final baseLocations = _detectBaseLocations(
allFiles,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
);
final baseCountriesToExclude = _baseCountriesToExcludeFromTripTitles(
baseLocations,
@@ -245,7 +245,7 @@ class TripMemoriesCalculatorV2 {
nowInMicroseconds,
windowEnd,
seenTimes: seenTimes,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
@@ -264,7 +264,7 @@ class TripMemoriesCalculatorV2 {
shownTrips,
baseCountriesToExclude: baseCountriesToExclude,
cachedTripMemories: cachedTripMemories,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
mlEnabled: mlEnabled,
seenTimes: seenTimes,
fileIdToFaces: fileIdToFaces,
@@ -279,17 +279,14 @@ class TripMemoriesCalculatorV2 {
static List<BaseLocation> _detectBaseLocations(
Iterable<EnteFile> allFiles, {
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
}) {
final filesWithLocation = allFiles
.where((file) => file.hasLocation)
.toList()
..sort((a, b) => a.creationTime!.compareTo(b.creationTime!));
final smallRadiusClusters = _mergeNearbyLocationClusters(
- _clusterByLocation(
- filesWithLocation,
- radius: baseRadius,
- ),
+ _clusterByLocation(filesWithLocation, radius: baseRadius),
radius: _baseMergeRadius,
);
@@ -313,7 +310,7 @@ class TripMemoriesCalculatorV2 {
.map(
(file) => SmartMemoriesService._memoryFileId(
file,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
),
)
.whereType<int>()
@@ -556,9 +553,7 @@ class TripMemoriesCalculatorV2 {
static List<TripMemory> _mergeNearbyTrips(List<TripMemory> trips) {
final sortedTrips = List<TripMemory>.from(trips)
- ..sort(
- (a, b) => a.firstCreationTime!.compareTo(b.firstCreationTime!),
- );
+ ..sort((a, b) => a.firstCreationTime!.compareTo(b.firstCreationTime!));
final merged = <TripMemory>[];
for (final trip in sortedTrips) {
final tripFirst = DateTime.fromMicrosecondsSinceEpoch(
@@ -590,12 +585,17 @@ class TripMemoriesCalculatorV2 {
final mergedSpanDays = mergedLast.difference(mergedFirst).inDays;
if (timeClose && spaceClose && mergedSpanDays <= _maxTripDays) {
final combinedMemories = other.memories + trip.memories;
- final mergedLocation =
- _representativeLocationFromMemories(combinedMemories);
- final mergedFirstCreationTime =
- min(other.firstCreationTime!, trip.firstCreationTime!);
- final mergedLastCreationTime =
- max(other.lastCreationTime!, trip.lastCreationTime!);
+ final mergedLocation = _representativeLocationFromMemories(
+ combinedMemories,
+ );
+ final mergedFirstCreationTime = min(
+ other.firstCreationTime!,
+ trip.firstCreationTime!,
+ );
+ final mergedLastCreationTime = max(
+ other.lastCreationTime!,
+ trip.lastCreationTime!,
+ );
merged[i] = TripMemory(
combinedMemories,
0,
@@ -735,8 +735,9 @@ class TripMemoriesCalculatorV2 {
TripMemory trip,
DateTime currentTime,
) {
- final tripStart =
- DateTime.fromMicrosecondsSinceEpoch(trip.firstCreationTime!);
+ final tripStart = DateTime.fromMicrosecondsSinceEpoch(
+ trip.firstCreationTime!,
+ );
final tripEnd = DateTime.fromMicrosecondsSinceEpoch(trip.lastCreationTime!);
final yearOffset = tripEnd.year - tripStart.year;
_TripAnniversaryWindow? bestWindow;
@@ -871,7 +872,7 @@ class TripMemoriesCalculatorV2 {
int nowInMicroseconds,
int windowEnd, {
required Map<int, int> seenTimes,
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
required bool mlEnabled,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
required Map<String, String> faceIDsToPersonID,
@@ -914,7 +915,7 @@ class TripMemoriesCalculatorV2 {
);
final photoSelection = await SmartMemoriesService._bestSelection(
trip.memories,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
@@ -945,7 +946,7 @@ class TripMemoriesCalculatorV2 {
List<TripsShownLog> shownTrips, {
required Set<String> baseCountriesToExclude,
required Iterable<ToShowMemory> cachedTripMemories,
- required bool isOfflineMode,
+ required bool isLocalGalleryMode,
required bool mlEnabled,
required Map<int, int> seenTimes,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
@@ -958,8 +959,10 @@ class TripMemoriesCalculatorV2 {
cachedTripMemories,
currentTime,
);
- final remainingSlots =
- max(0, kTripSurfaceSlots - activeTripIdentityKeys.length);
+ final remainingSlots = max(
+ 0,
+ kTripSurfaceSlots - activeTripIdentityKeys.length,
+ );
if (remainingSlots == 0 || validTrips.isEmpty) {
return (memoryResults, baseLocations);
}
@@ -1021,7 +1024,7 @@ class TripMemoriesCalculatorV2 {
final currentShownCount =
activeTripIdentityKeys.length + selectedCandidates.length;
- if (isOfflineMode && currentShownCount == 0 && candidates.isNotEmpty) {
+ if (isLocalGalleryMode && currentShownCount == 0 && candidates.isNotEmpty) {
final fallbackSeasonalCandidates = candidates
.where(
(candidate) =>
@@ -1047,8 +1050,9 @@ class TripMemoriesCalculatorV2 {
currentTime.add(_tripDisplayDuration).microsecondsSinceEpoch;
for (final candidate in selectedCandidates) {
final trip = candidate.trip;
- final year =
- DateTime.fromMicrosecondsSinceEpoch(trip.averageCreationTime()).year;
+ final year = DateTime.fromMicrosecondsSinceEpoch(
+ trip.averageCreationTime(),
+ ).year;
final String? locationName = SmartMemoriesService._tryFindLocationName(
trip.memories,
cities,
@@ -1056,7 +1060,7 @@ class TripMemoriesCalculatorV2 {
);
final photoSelection = await SmartMemoriesService._bestSelection(
trip.memories,
- isOfflineMode: isOfflineMode,
+ isLocalGalleryMode: isLocalGalleryMode,
mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
@@ -1100,8 +1104,9 @@ class TripMemoriesCalculatorV2 {
continue;
}
- final normalizedCountry =
- SmartMemoriesService._normalizePlaceName(countryName);
+ final normalizedCountry = SmartMemoriesService._normalizePlaceName(
+ countryName,
+ );
if (normalizedCountry.isNotEmpty) {
excludedCountries.add(normalizedCountry);
}
diff --git a/mobile/apps/photos/lib/services/sync/local_sync_service.dart b/mobile/apps/photos/lib/services/sync/local_sync_service.dart
index 4d7c3d2eba..fb5b19cb30 100644
--- a/mobile/apps/photos/lib/services/sync/local_sync_service.dart
+++ b/mobile/apps/photos/lib/services/sync/local_sync_service.dart
@@ -67,7 +67,7 @@ class LocalSyncService {
_permissionGrantedSubscription =
Bus.instance.on<PermissionGrantedEvent>().listen((event) async {
_registerChangeCallback();
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
// Offline onboarding grants permission without explicitly invoking
// SyncService, so trigger local import right away.
unawaited(checkAndSync());
@@ -117,8 +117,9 @@ class LocalSyncService {
);
} else {
// Load from 0 - 01.01.2010
- Bus.instance
- .fire(SyncStatusUpdate(SyncStatus.startedFirstGalleryImport));
+ Bus.instance.fire(
+ SyncStatusUpdate(SyncStatus.startedFirstGalleryImport),
+ );
var startTime = 0;
var toYear = 2010;
var toTime = DateTime(toYear).microsecondsSinceEpoch;
@@ -145,8 +146,9 @@ class LocalSyncService {
}
await _refreshDeviceFolderCountAndCover(isFirstSync: true);
_logger.info("first gallery import finished");
- Bus.instance
- .fire(SyncStatusUpdate(SyncStatus.completedFirstGalleryImport));
+ Bus.instance.fire(
+ SyncStatusUpdate(SyncStatus.completedFirstGalleryImport),
+ );
}
final endTime = DateTime.now().microsecondsSinceEpoch;
final duration = Duration(microseconds: endTime - startTime);
@@ -176,15 +178,16 @@ class LocalSyncService {
Future<bool> syncAll() async {
if (!Configuration.instance.isLoggedIn()) {
- if (!isOfflineMode) {
+ if (!isLocalGalleryMode) {
_logger.warning("syncAll called when user is not logged in");
return false;
}
}
final stopwatch = EnteWatch("localSyncAll")..start();
- final localAssets =
- await getAllLocalAssets(needsTitle: isOfflineMode ? true : null);
+ final localAssets = await getAllLocalAssets(
+ needsTitle: isLocalGalleryMode ? true : null,
+ );
_logger.info(
"Loading allLocalAssets ${localAssets.length} took ${stopwatch.elapsedMilliseconds}ms ",
);
@@ -204,13 +207,15 @@ class LocalSyncService {
);
bool hasAnyMappingChanged = false;
if (localDiffResult.newPathToLocalIDs?.isNotEmpty ?? false) {
- await _db
- .insertPathIDToLocalIDMapping(localDiffResult.newPathToLocalIDs!);
+ await _db.insertPathIDToLocalIDMapping(
+ localDiffResult.newPathToLocalIDs!,
+ );
hasAnyMappingChanged = true;
}
if (localDiffResult.deletePathToLocalIDs?.isNotEmpty ?? false) {
- await _db
- .deletePathIDToLocalIDMapping(localDiffResult.deletePathToLocalIDs!);
+ await _db.deletePathIDToLocalIDMapping(
+ localDiffResult.deletePathToLocalIDs!,
+ );
hasAnyMappingChanged = true;
}
final bool hasUnsyncedFiles =
@@ -429,8 +434,9 @@ class LocalSyncService {
if (updatedLocalIDs.isNotEmpty) {
final int updateCount = updatedLocalIDs.length;
- updatedLocalIDs
- .removeWhere((x) => trackOriginFetchForUploadOrML.get(x) ?? false);
+ updatedLocalIDs.removeWhere(
+ (x) => trackOriginFetchForUploadOrML.get(x) ?? false,
+ );
_logger.info(
"track ${updatedLocalIDs.length}/ $updateCount files due to modification change",
);
diff --git a/mobile/apps/photos/lib/services/sync/offline_import_metadata_service.dart b/mobile/apps/photos/lib/services/sync/offline_import_metadata_service.dart
index d8f9a2ea46..a38125b1f7 100644
--- a/mobile/apps/photos/lib/services/sync/offline_import_metadata_service.dart
+++ b/mobile/apps/photos/lib/services/sync/offline_import_metadata_service.dart
@@ -32,7 +32,7 @@ class OfflineImportMetadataService {
int batchSize = kDefaultBatchSize,
int maxBatches = 4,
}) async {
- if (!Platform.isAndroid || !isOfflineMode) {
+ if (!Platform.isAndroid || !isLocalGalleryMode) {
return;
}
if (_running != null) {
@@ -43,10 +43,8 @@ class OfflineImportMetadataService {
_running = Completer<void>();
try {
for (var batch = 0; batch < maxBatches; batch++) {
- if (!isOfflineMode) {
- _logger.info(
- "Offline mode disabled, stopping metadata processing",
- );
+ if (!isLocalGalleryMode) {
+ _logger.info("Offline mode disabled, stopping metadata processing");
return;
}
@@ -60,7 +58,7 @@ class OfflineImportMetadataService {
final updatedFiles = <EnteFile>[];
for (final file in files) {
- if (!isOfflineMode) {
+ if (!isLocalGalleryMode) {
_logger.info(
"Offline mode disabled during per-file processing, stopping",
);
@@ -107,11 +105,7 @@ class OfflineImportMetadataService {
final exifData = await tryExifFromFile(originFile);
final exifTime = await tryParseExifDateTime(null, exifData);
- await _updateLocationForOfflineFile(
- file,
- originFile,
- exifData,
- );
+ await _updateLocationForOfflineFile(file, originFile, exifData);
final mediaUploadData = MediaUploadData(
originFile,
@@ -159,8 +153,10 @@ class OfflineImportMetadataService {
final asset = await file.getAsset;
if (asset != null) {
final latLong = await asset.latlngAsync();
- file.location =
- Location(latitude: latLong.latitude, longitude: latLong.longitude);
+ file.location = Location(
+ latitude: latLong.latitude,
+ longitude: latLong.longitude,
+ );
}
}
diff --git a/mobile/apps/photos/lib/services/sync/sync_service.dart b/mobile/apps/photos/lib/services/sync/sync_service.dart
index 470517afda..044c02cc63 100644
--- a/mobile/apps/photos/lib/services/sync/sync_service.dart
+++ b/mobile/apps/photos/lib/services/sync/sync_service.dart
@@ -42,9 +42,9 @@ class SyncService {
sync();
});
- Connectivity()
- .onConnectivityChanged
- .listen((List<ConnectivityResult> result) {
+ Connectivity().onConnectivityChanged.listen((
+ List<ConnectivityResult> result,
+ ) {
_logger.info("Connectivity change detected " + result.toString());
if (Configuration.instance.hasConfiguredAccount()) {
sync();
@@ -103,18 +103,12 @@ class SyncService {
);
} on NoActiveSubscriptionError {
Bus.instance.fire(
- SyncStatusUpdate(
- SyncStatus.error,
- error: NoActiveSubscriptionError(),
- ),
+ SyncStatusUpdate(SyncStatus.error, error: NoActiveSubscriptionError()),
);
} on StorageLimitExceededError {
_showStorageLimitExceededNotification();
Bus.instance.fire(
- SyncStatusUpdate(
- SyncStatus.error,
- error: StorageLimitExceededError(),
- ),
+ SyncStatusUpdate(SyncStatus.error, error: StorageLimitExceededError()),
);
} on UnauthorizedError {
_logger.info("Logging user out");
@@ -122,10 +116,7 @@ class SyncService {
} on NoMediaLocationAccessError {
_logger.severe("Not uploading due to no media location access");
Bus.instance.fire(
- SyncStatusUpdate(
- SyncStatus.error,
- error: NoMediaLocationAccessError(),
- ),
+ SyncStatusUpdate(SyncStatus.error, error: NoMediaLocationAccessError()),
);
} catch (e) {
if (e is DioException) {
@@ -198,7 +189,7 @@ class SyncService {
Future<void> _doSync() async {
_logger.info("[SYNC] Starting local sync");
await _localSyncService.sync();
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
await _localSyncService.syncAll();
if (Platform.isAndroid) {
unawaited(
@@ -217,7 +208,8 @@ class SyncService {
}
final bool allowRemoteSync =
- _localSyncService.hasCompletedFirstImportOrBypassed() && !isOfflineMode;
+ _localSyncService.hasCompletedFirstImportOrBypassed() &&
+ !isLocalGalleryMode;
if (allowRemoteSync) {
_logger.info("[SYNC] Starting remote sync");
diff --git a/mobile/apps/photos/lib/services/text_embeddings_cache_service.dart b/mobile/apps/photos/lib/services/text_embeddings_cache_service.dart
index 52a1380fb1..15b20c0d76 100644
--- a/mobile/apps/photos/lib/services/text_embeddings_cache_service.dart
+++ b/mobile/apps/photos/lib/services/text_embeddings_cache_service.dart
@@ -1,6 +1,6 @@
import 'package:logging/logging.dart';
import 'package:photos/db/ml/db.dart';
-import "package:photos/service_locator.dart" show isOfflineMode;
+import "package:photos/service_locator.dart" show isLocalGalleryMode;
import 'package:photos/services/machine_learning/ml_computer.dart';
class TextEmbeddingsCacheService {
@@ -11,7 +11,7 @@ class TextEmbeddingsCacheService {
Future<List<double>> getEmbedding(String query) async {
final mlDataDB =
- isOfflineMode ? MLDataDB.offlineInstance : MLDataDB.instance;
+ isLocalGalleryMode ? MLDataDB.offlineInstance : MLDataDB.instance;
// 1. Check database cache
final dbResult = await mlDataDB.getRepeatedTextEmbeddingCache(query);
if (dbResult != null) {
diff --git a/mobile/apps/photos/lib/services/video_preview_service.dart b/mobile/apps/photos/lib/services/video_preview_service.dart
index dc22e0045e..8e614f9fad 100644
--- a/mobile/apps/photos/lib/services/video_preview_service.dart
+++ b/mobile/apps/photos/lib/services/video_preview_service.dart
@@ -116,7 +116,7 @@ class VideoPreviewService {
static const String _videoStreamingEnabled = "videoStreamingEnabled";
bool get isVideoStreamingEnabled {
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
return false;
}
return serviceLocator.prefs.getBool(_videoStreamingEnabled) ??
@@ -426,10 +426,13 @@ class VideoPreviewService {
"Starting video preview generation for ${enteFile.displayName}",
);
// elimination case for <=10 MB with H.264
- final isManual =
- await uploadLocksDB.isInStreamQueue(enteFile.uploadedFileID!);
- var (props, result, file) =
- await _checkFileForPreviewCreation(enteFile, isManual);
+ final isManual = await uploadLocksDB.isInStreamQueue(
+ enteFile.uploadedFileID!,
+ );
+ var (props, result, file) = await _checkFileForPreviewCreation(
+ enteFile,
+ isManual,
+ );
if (result) {
removeFile = true;
return;
@@ -705,17 +708,11 @@ class VideoPreviewService {
}
// process next file
- _logger.info(
- "[chunk] Processing ${_items.length} items for streaming",
- );
+ _logger.info("[chunk] Processing ${_items.length} items for streaming");
final entry = fileQueue.entries.first;
final file = entry.value;
fileQueue.remove(entry.key);
- await chunkAndUploadVideo(
- ctx,
- file,
- continuation: true,
- );
+ await chunkAndUploadVideo(ctx, file, continuation: true);
} else {
// Release compute when queue is empty or network is unavailable
stop(shouldStopProcessing ? "network error" : "nothing to process");
diff --git a/mobile/apps/photos/lib/states/user_details_state.dart b/mobile/apps/photos/lib/states/user_details_state.dart
index f09d2b7be0..ec6b2d813a 100644
--- a/mobile/apps/photos/lib/states/user_details_state.dart
+++ b/mobile/apps/photos/lib/states/user_details_state.dart
@@ -11,10 +11,7 @@ import 'package:photos/services/account/user_service.dart';
class UserDetailsStateWidget extends StatefulWidget {
final Widget child;
- const UserDetailsStateWidget({
- required this.child,
- super.key,
- });
+ const UserDetailsStateWidget({required this.child, super.key});
@override
State<UserDetailsStateWidget> createState() => UserDetailsStateWidgetState();
@@ -57,7 +54,7 @@ class UserDetailsStateWidgetState extends State<UserDetailsStateWidget> {
);
void _fetchUserDetails() async {
- if (isOfflineMode) return;
+ if (isLocalGalleryMode) return;
_userDetails = await UserService.instance.getUserDetailsV2(
memoryCount: true,
shouldCache: true,
diff --git a/mobile/apps/photos/lib/ui/actions/file/file_actions.dart b/mobile/apps/photos/lib/ui/actions/file/file_actions.dart
index ae4790b976..262884e8d4 100644
--- a/mobile/apps/photos/lib/ui/actions/file/file_actions.dart
+++ b/mobile/apps/photos/lib/ui/actions/file/file_actions.dart
@@ -32,7 +32,7 @@ Future<void> showSingleFileDeleteSheet(
file.uploadedFileID != null && file.localID != null;
final bool isLocalOnly = file.uploadedFileID == null && file.localID != null;
final bool isRemoteOnly = file.uploadedFileID != null && file.localID == null;
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
if (file.localID == null) {
showShortToast(
context,
@@ -46,18 +46,22 @@ Future<void> showSingleFileDeleteSheet(
}
return;
}
- final String bodyHighlight =
- AppLocalizations.of(context).singleFileDeleteHighlight;
+ final String bodyHighlight = AppLocalizations.of(
+ context,
+ ).singleFileDeleteHighlight;
String body = "";
if (isBothLocalAndRemote) {
- body = AppLocalizations.of(context)
- .singleFileInBothLocalAndRemote(fileType: fileType);
+ body = AppLocalizations.of(
+ context,
+ ).singleFileInBothLocalAndRemote(fileType: fileType);
} else if (isRemoteOnly) {
- body =
- AppLocalizations.of(context).singleFileInRemoteOnly(fileType: fileType);
+ body = AppLocalizations.of(
+ context,
+ ).singleFileInRemoteOnly(fileType: fileType);
} else if (isLocalOnly) {
- body = AppLocalizations.of(context)
- .singleFileDeleteFromDevice(fileType: fileType);
+ body = AppLocalizations.of(
+ context,
+ ).singleFileDeleteFromDevice(fileType: fileType);
} else {
throw AssertionError("Unexpected state");
}
diff --git a/mobile/apps/photos/lib/ui/collections/device/device_folder_item.dart b/mobile/apps/photos/lib/ui/collections/device/device_folder_item.dart
index 1a53793c87..56927f3410 100644
--- a/mobile/apps/photos/lib/ui/collections/device/device_folder_item.dart
+++ b/mobile/apps/photos/lib/ui/collections/device/device_folder_item.dart
@@ -73,7 +73,7 @@ class DeviceFolderItem extends StatelessWidget {
deviceCollection.thumbnail!.tag,
),
),
- if (!isBackedUp && !isOfflineMode)
+ if (!isBackedUp && !isLocalGalleryMode)
const UnSyncedIcon(),
],
),
@@ -99,8 +99,9 @@ class DeviceFolderItem extends StatelessWidget {
child: Text(
deviceCollection.count.toString(),
textAlign: TextAlign.left,
- style:
- Theme.of(context).colorScheme.enteTheme.textTheme.miniMuted,
+ style: Theme.of(
+ context,
+ ).colorScheme.enteTheme.textTheme.miniMuted,
overflow: TextOverflow.ellipsis,
),
),
diff --git a/mobile/apps/photos/lib/ui/components/banners/get_started_banner.dart b/mobile/apps/photos/lib/ui/components/banners/get_started_banner.dart
index 749a219350..001126f708 100644
--- a/mobile/apps/photos/lib/ui/components/banners/get_started_banner.dart
+++ b/mobile/apps/photos/lib/ui/components/banners/get_started_banner.dart
@@ -36,7 +36,7 @@ class _GetStartedBannerState extends State<GetStartedBanner> {
@override
Widget build(BuildContext context) {
if (_dismissed) return const SizedBox.shrink();
- if (localSettings.isOfflineGetStartedBannerDismissed) {
+ if (localSettings.isLocalGalleryGetStartedBannerDismissed) {
return const SizedBox.shrink();
}
@@ -117,10 +117,7 @@ class _GetStartedBannerState extends State<GetStartedBanner> {
TextStyle descriptionStyleForWidth(double maxWidth) {
if (maxWidth < 180) {
- return descriptionStyle.copyWith(
- fontSize: 11,
- height: 18 / 11,
- );
+ return descriptionStyle.copyWith(fontSize: 11, height: 18 / 11);
}
return descriptionStyle;
}
@@ -128,8 +125,9 @@ class _GetStartedBannerState extends State<GetStartedBanner> {
var resolvedDuckWidth = sculptedDuckWidth;
var resolvedFirstLineMaxWidth = firstLineMaxWidth;
var resolvedSecondLineMaxWidth = secondLineMaxWidth;
- var sculptedDescriptionStyle =
- descriptionStyleForWidth(secondLineMaxWidth);
+ var sculptedDescriptionStyle = descriptionStyleForWidth(
+ secondLineMaxWidth,
+ );
var useAccessibilityDescriptionLayout =
_descriptionNeedsAccessibilityFallback(
context: context,
@@ -160,8 +158,9 @@ class _GetStartedBannerState extends State<GetStartedBanner> {
duckOpaqueStartFraction: _duckSecondLineOpaqueStartFraction,
),
);
- final candidateDescriptionStyle =
- descriptionStyleForWidth(candidateSecondLineMaxWidth);
+ final candidateDescriptionStyle = descriptionStyleForWidth(
+ candidateSecondLineMaxWidth,
+ );
final fitsWithCandidateDuck =
!_descriptionNeedsAccessibilityFallback(
context: context,
@@ -198,10 +197,13 @@ class _GetStartedBannerState extends State<GetStartedBanner> {
final descriptionMaxWidth = useAccessibilityDescriptionLayout
? fallbackDescriptionMaxWidth
: resolvedSecondLineMaxWidth;
- final effectiveDescriptionStyle =
- descriptionStyleForWidth(descriptionMaxWidth);
- final descriptionLineHeight =
- _scaledLineHeight(effectiveDescriptionStyle, textScaler);
+ final effectiveDescriptionStyle = descriptionStyleForWidth(
+ descriptionMaxWidth,
+ );
+ final descriptionLineHeight = _scaledLineHeight(
+ effectiveDescriptionStyle,
+ textScaler,
+ );
final descriptionLines = useAccessibilityDescriptionLayout
? _measureTextLineCount(
context: context,
@@ -338,11 +340,7 @@ class _GetStartedBannerState extends State<GetStartedBanner> {
behavior: HitTestBehavior.opaque,
child: const Padding(
padding: EdgeInsets.all(4),
- child: Icon(
- Icons.close,
- color: Colors.white,
- size: 16,
- ),
+ child: Icon(Icons.close, color: Colors.white, size: 16),
),
),
),
@@ -359,7 +357,7 @@ class _GetStartedBannerState extends State<GetStartedBanner> {
setState(() {
_dismissed = true;
});
- await localSettings.setOfflineGetStartedBannerDismissed(true);
+ await localSettings.setLocalGalleryGetStartedBannerDismissed(true);
}
Future<void> _onGetStarted() async {
@@ -406,8 +404,9 @@ class _GetStartedBannerState extends State<GetStartedBanner> {
textDirection: Directionality.of(context),
textScaler: textScaler,
)..layout(maxWidth: firstLineMaxWidth);
- final firstLineRange =
- firstLinePainter.getLineBoundary(const TextPosition(offset: 0));
+ final firstLineRange = firstLinePainter.getLineBoundary(
+ const TextPosition(offset: 0),
+ );
final splitIndex = firstLineRange.end.clamp(0, text.length);
final secondLine = text.substring(splitIndex).trimLeft();
firstLinePainter.dispose();
@@ -554,8 +553,9 @@ class _BannerDescriptionTextState extends State<_BannerDescriptionText> {
textDirection: Directionality.of(context),
textScaler: textScaler,
)..layout(maxWidth: widget.firstLineMaxWidth);
- final firstLineRange =
- painter.getLineBoundary(const TextPosition(offset: 0));
+ final firstLineRange = painter.getLineBoundary(
+ const TextPosition(offset: 0),
+ );
final splitIndex = firstLineRange.end.clamp(0, widget.text.length);
final firstLine = widget.text.substring(0, splitIndex).trimRight();
final secondLine = widget.text.substring(splitIndex).trimLeft();
diff --git a/mobile/apps/photos/lib/ui/components/banners/ml_progress_banner.dart b/mobile/apps/photos/lib/ui/components/banners/ml_progress_banner.dart
index 23cac06e32..5ed497471e 100644
--- a/mobile/apps/photos/lib/ui/components/banners/ml_progress_banner.dart
+++ b/mobile/apps/photos/lib/ui/components/banners/ml_progress_banner.dart
@@ -38,8 +38,9 @@ class _MLProgressBannerState extends State<MLProgressBanner> {
@override
void initState() {
super.initState();
- _tabChangedSubscription =
- Bus.instance.on<TabChangedEvent>().listen((event) {
+ _tabChangedSubscription = Bus.instance.on<TabChangedEvent>().listen((
+ event,
+ ) {
final wasOnSearchTab = _isOnSearchTab;
_isOnSearchTab = event.selectedIndex == _searchTabIndex;
if (_isOnSearchTab && !wasOnSearchTab) {
@@ -54,8 +55,9 @@ class _MLProgressBannerState extends State<MLProgressBanner> {
_indexingComplete = false;
_ensurePolling();
});
- _notificationSubscription =
- Bus.instance.on<NotificationEvent>().listen((_) {
+ _notificationSubscription = Bus.instance.on<NotificationEvent>().listen((
+ _,
+ ) {
_indexingComplete = false;
_ensurePolling();
});
@@ -90,7 +92,7 @@ class _MLProgressBannerState extends State<MLProgressBanner> {
!_dismissed &&
hasGrantedMLConsent &&
!localSettings.isMLProgressBannerDismissed &&
- !(isOfflineMode && !localSettings.isMLLocalIndexingEnabled) &&
+ !(isLocalGalleryMode && !localSettings.isMLLocalIndexingEnabled) &&
!_indexingComplete;
Future<void> _fetchStatus() async {
@@ -124,7 +126,7 @@ class _MLProgressBannerState extends State<MLProgressBanner> {
if (localSettings.isMLProgressBannerDismissed) {
return const SizedBox.shrink();
}
- if (isOfflineMode && !localSettings.isMLLocalIndexingEnabled) {
+ if (isLocalGalleryMode && !localSettings.isMLLocalIndexingEnabled) {
return const SizedBox.shrink();
}
@@ -170,10 +172,7 @@ class _MLProgressBannerState extends State<MLProgressBanner> {
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
- Text(
- l10n.mlProgressBannerTitle,
- style: titleStyle,
- ),
+ Text(l10n.mlProgressBannerTitle, style: titleStyle),
GestureDetector(
onTap: _onDismiss,
behavior: HitTestBehavior.opaque,
diff --git a/mobile/apps/photos/lib/ui/components/banners/name_face_banner.dart b/mobile/apps/photos/lib/ui/components/banners/name_face_banner.dart
index 1f83f93982..739ebd4008 100644
--- a/mobile/apps/photos/lib/ui/components/banners/name_face_banner.dart
+++ b/mobile/apps/photos/lib/ui/components/banners/name_face_banner.dart
@@ -41,10 +41,11 @@ class _NameFaceBannerState extends State<NameFaceBanner> {
@override
Widget build(BuildContext context) {
if (_dismissed) return const SizedBox.shrink();
- if (!(isOfflineMode && !Configuration.instance.hasConfiguredAccount())) {
+ if (!(isLocalGalleryMode &&
+ !Configuration.instance.hasConfiguredAccount())) {
return const SizedBox.shrink();
}
- if (localSettings.isOfflineNameFaceBannerDismissed) {
+ if (localSettings.isLocalGalleryNameFaceBannerDismissed) {
return const SizedBox.shrink();
}
@@ -138,6 +139,6 @@ class _NameFaceBannerState extends State<NameFaceBanner> {
setState(() {
_dismissed = true;
});
- localSettings.setOfflineNameFaceBannerDismissed(true);
+ localSettings.setLocalGalleryNameFaceBannerDismissed(true);
}
}
diff --git a/mobile/apps/photos/lib/ui/components/banners/offline_settings_banner.dart b/mobile/apps/photos/lib/ui/components/banners/offline_settings_banner.dart
index 2a1a1ccff7..6a618e44b6 100644
--- a/mobile/apps/photos/lib/ui/components/banners/offline_settings_banner.dart
+++ b/mobile/apps/photos/lib/ui/components/banners/offline_settings_banner.dart
@@ -11,10 +11,7 @@ import "package:photos/ui/components/banners/banner_action_button.dart";
class OfflineSettingsBanner extends StatefulWidget {
final VoidCallback onGetStarted;
- const OfflineSettingsBanner({
- super.key,
- required this.onGetStarted,
- });
+ const OfflineSettingsBanner({super.key, required this.onGetStarted});
@override
State<OfflineSettingsBanner> createState() => _OfflineSettingsBannerState();
@@ -26,7 +23,7 @@ class _OfflineSettingsBannerState extends State<OfflineSettingsBanner> {
@override
Widget build(BuildContext context) {
if (_dismissed) return const SizedBox.shrink();
- if (localSettings.isOfflineSettingsBannerDismissed) {
+ if (localSettings.isLocalGallerySettingsBannerDismissed) {
return const SizedBox.shrink();
}
@@ -59,11 +56,7 @@ class _OfflineSettingsBannerState extends State<OfflineSettingsBanner> {
),
child: Stack(
children: [
- Positioned.fill(
- child: CustomPaint(
- painter: _DotsPainter(),
- ),
- ),
+ Positioned.fill(child: CustomPaint(painter: _DotsPainter())),
Padding(
padding: const EdgeInsets.all(16),
child: Column(
@@ -141,7 +134,7 @@ class _OfflineSettingsBannerState extends State<OfflineSettingsBanner> {
setState(() {
_dismissed = true;
});
- unawaited(localSettings.setOfflineSettingsBannerDismissed(true));
+ unawaited(localSettings.setLocalGallerySettingsBannerDismissed(true));
}
}
diff --git a/mobile/apps/photos/lib/ui/components/banners/save_faces_banner.dart b/mobile/apps/photos/lib/ui/components/banners/save_faces_banner.dart
index b3db5a84f5..843696cbe4 100644
--- a/mobile/apps/photos/lib/ui/components/banners/save_faces_banner.dart
+++ b/mobile/apps/photos/lib/ui/components/banners/save_faces_banner.dart
@@ -41,10 +41,11 @@ class _SaveFacesBannerState extends State<SaveFacesBanner> {
@override
Widget build(BuildContext context) {
if (_dismissed) return const SizedBox.shrink();
- if (!(isOfflineMode && !Configuration.instance.hasConfiguredAccount())) {
+ if (!(isLocalGalleryMode &&
+ !Configuration.instance.hasConfiguredAccount())) {
return const SizedBox.shrink();
}
- if (localSettings.isOfflineFacesBannerDismissed) {
+ if (localSettings.isLocalGalleryFacesBannerDismissed) {
return const SizedBox.shrink();
}
@@ -138,6 +139,6 @@ class _SaveFacesBannerState extends State<SaveFacesBanner> {
setState(() {
_dismissed = true;
});
- localSettings.setOfflineFacesBannerDismissed(true);
+ localSettings.setLocalGalleryFacesBannerDismissed(true);
}
}
diff --git a/mobile/apps/photos/lib/ui/components/home_header_widget.dart b/mobile/apps/photos/lib/ui/components/home_header_widget.dart
index c75c10769a..a478f1cc28 100644
--- a/mobile/apps/photos/lib/ui/components/home_header_widget.dart
+++ b/mobile/apps/photos/lib/ui/components/home_header_widget.dart
@@ -15,7 +15,7 @@ class _HomeHeaderWidgetState extends State<HomeHeaderWidget> {
@override
Widget build(BuildContext context) {
final showAddAlbumAction =
- !isOfflineMode || permissionService.hasGrantedLimitedPermissions();
+ !isLocalGalleryMode || permissionService.hasGrantedLimitedPermissions();
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
diff --git a/mobile/apps/photos/lib/ui/home/grant_permissions_widget.dart b/mobile/apps/photos/lib/ui/home/grant_permissions_widget.dart
index bfc411702f..2fef7928c2 100644
--- a/mobile/apps/photos/lib/ui/home/grant_permissions_widget.dart
+++ b/mobile/apps/photos/lib/ui/home/grant_permissions_widget.dart
@@ -25,10 +25,7 @@ import "package:photos/utils/dialog_util.dart";
import "package:styled_text/styled_text.dart";
class GrantPermissionsWidget extends StatefulWidget {
- const GrantPermissionsWidget({
- super.key,
- this.startWithoutAccount = false,
- });
+ const GrantPermissionsWidget({super.key, this.startWithoutAccount = false});
final bool startWithoutAccount;
@@ -73,10 +70,7 @@ class _GrantPermissionsWidgetState extends State<GrantPermissionsWidget> {
title: SvgPicture.asset(
"assets/ente-branding.svg",
height: 15,
- colorFilter: ColorFilter.mode(
- colorScheme.content,
- BlendMode.srcIn,
- ),
+ colorFilter: ColorFilter.mode(colorScheme.content, BlendMode.srcIn),
),
),
body: SafeArea(
@@ -84,9 +78,7 @@ class _GrantPermissionsWidgetState extends State<GrantPermissionsWidget> {
child: CustomScrollView(
slivers: [
const SliverPadding(padding: EdgeInsets.only(top: 24)),
- SliverToBoxAdapter(
- child: _buildHeaderContent(context),
- ),
+ SliverToBoxAdapter(child: _buildHeaderContent(context)),
SliverFillRemaining(
hasScrollBody: false,
child: Padding(
@@ -115,10 +107,7 @@ class _GrantPermissionsWidgetState extends State<GrantPermissionsWidget> {
Center(
child: Padding(
padding: const EdgeInsets.only(top: 28),
- child: Image.asset(
- "assets/photo_backup.png",
- height: 252,
- ),
+ child: Image.asset("assets/photo_backup.png", height: 252),
),
),
const SizedBox(height: 22),
@@ -158,10 +147,7 @@ class _GrantPermissionsWidgetState extends State<GrantPermissionsWidget> {
if (state == PermissionState.authorized ||
state == PermissionState.limited) {
await backupPreferenceService.setOnlyNewSinceSevenDaysAgo();
- await onPermissionGranted(
- state,
- shouldMarkLimitedFolders: false,
- );
+ await onPermissionGranted(state, shouldMarkLimitedFolders: false);
if (mounted) {
showToast(context, context.l10n.backingUpLastSevenDaysPhotos);
}
@@ -169,10 +155,7 @@ class _GrantPermissionsWidgetState extends State<GrantPermissionsWidget> {
await _showPermissionDeniedDialog();
}
} catch (e) {
- _logger.severe(
- "Failed to request permission: ${e.toString()}",
- e,
- );
+ _logger.severe("Failed to request permission: ${e.toString()}", e);
showGenericErrorDialog(context: context, error: e).ignore();
}
}
@@ -188,10 +171,7 @@ class _GrantPermissionsWidgetState extends State<GrantPermissionsWidget> {
await _showPermissionDeniedDialog();
}
} catch (e) {
- _logger.severe(
- "Failed to request permission: ${e.toString()}",
- e,
- );
+ _logger.severe("Failed to request permission: ${e.toString()}", e);
showGenericErrorDialog(context: context, error: e).ignore();
}
}
@@ -202,7 +182,7 @@ class _GrantPermissionsWidgetState extends State<GrantPermissionsWidget> {
_logger.info("Offline permission state: $state");
if (state == PermissionState.authorized ||
state == PermissionState.limited) {
- await localSettings.setAppMode(AppMode.offline);
+ await localSettings.setAppMode(AppMode.localGallery);
Bus.instance.fire(AppModeChangedEvent());
await permissionService.onUpdatePermission(state);
SyncService.instance.onPermissionGranted().ignore();
@@ -219,10 +199,7 @@ class _GrantPermissionsWidgetState extends State<GrantPermissionsWidget> {
await _showPermissionDeniedDialog();
}
} catch (e) {
- _logger.severe(
- "Failed to request permission: ${e.toString()}",
- e,
- );
+ _logger.severe("Failed to request permission: ${e.toString()}", e);
}
}
@@ -384,8 +361,9 @@ class _GrantPermissionsWidgetState extends State<GrantPermissionsWidget> {
),
const SizedBox(height: 24),
Text(
- AppLocalizations.of(context)
- .grantGalleryPermissionDesc,
+ AppLocalizations.of(
+ context,
+ ).grantGalleryPermissionDesc,
textAlign: TextAlign.center,
style: textTheme.body.copyWith(
color: colorScheme.textMuted,
@@ -394,8 +372,9 @@ class _GrantPermissionsWidgetState extends State<GrantPermissionsWidget> {
const SizedBox(height: 20),
ButtonWidgetV2(
buttonType: ButtonTypeV2.neutral,
- labelText:
- AppLocalizations.of(context).grantPermission,
+ labelText: AppLocalizations.of(
+ context,
+ ).grantPermission,
onTap: _onTapOfflineGrantPermission,
),
const SizedBox(height: 20),
diff --git a/mobile/apps/photos/lib/ui/home/header_widget.dart b/mobile/apps/photos/lib/ui/home/header_widget.dart
index d420bc7779..01973d6cf3 100644
--- a/mobile/apps/photos/lib/ui/home/header_widget.dart
+++ b/mobile/apps/photos/lib/ui/home/header_widget.dart
@@ -13,9 +13,7 @@ import 'package:photos/ui/home/status_bar_widget.dart';
import "package:photos/ui/wrapped/rewind_banner.dart";
class HeaderWidget extends StatefulWidget {
- const HeaderWidget({
- super.key,
- });
+ const HeaderWidget({super.key});
@override
State<HeaderWidget> createState() => _HeaderWidgetState();
@@ -63,7 +61,7 @@ class _HeaderWidgetState extends State<HeaderWidget> {
_logger.info("Building header widget");
final bool showWrappedBanner = wrappedService.shouldShowHomeBanner;
final bool showGetStartedBanner =
- isOfflineMode && !Configuration.instance.hasConfiguredAccount();
+ isLocalGalleryMode && !Configuration.instance.hasConfiguredAccount();
final List<Widget> children = <Widget>[
const StatusBarWidget(),
if (showGetStartedBanner) const GetStartedBanner(),
diff --git a/mobile/apps/photos/lib/ui/home/home_gallery_widget.dart b/mobile/apps/photos/lib/ui/home/home_gallery_widget.dart
index 5b1cbf673b..07c833e4fd 100644
--- a/mobile/apps/photos/lib/ui/home/home_gallery_widget.dart
+++ b/mobile/apps/photos/lib/ui/home/home_gallery_widget.dart
@@ -84,7 +84,7 @@ class _HomeGalleryWidgetState extends State<HomeGalleryWidget> {
final ownerID = Configuration.instance.getUserIDV2();
final hasSelectedAllForBackup =
backupPreferenceService.hasSelectedAllFoldersForBackup ||
- isOfflineMode;
+ isLocalGalleryMode;
final collectionsToHide =
CollectionsService.instance.archivedOrHiddenCollectionIds();
FileLoadResult result;
diff --git a/mobile/apps/photos/lib/ui/home/landing_page_widget.dart b/mobile/apps/photos/lib/ui/home/landing_page_widget.dart
index a51479719e..f3737dedb4 100644
--- a/mobile/apps/photos/lib/ui/home/landing_page_widget.dart
+++ b/mobile/apps/photos/lib/ui/home/landing_page_widget.dart
@@ -119,10 +119,7 @@ class _LandingPageWidgetState extends State<LandingPageWidget> {
title: SvgPicture.asset(
"assets/ente-branding.svg",
height: 18,
- colorFilter: const ColorFilter.mode(
- Colors.white,
- BlendMode.srcIn,
- ),
+ colorFilter: const ColorFilter.mode(Colors.white, BlendMode.srcIn),
),
centerTitle: true,
),
@@ -152,18 +149,20 @@ class _LandingPageWidgetState extends State<LandingPageWidget> {
children: [
ButtonWidgetV2(
buttonType: ButtonTypeV2.neutral,
- labelText:
- AppLocalizations.of(context).createAnEnteAccount,
+ labelText: AppLocalizations.of(
+ context,
+ ).createAnEnteAccount,
onTap: _navigateToSignUpPage,
shouldSurfaceExecutionStates: false,
shouldStickToLightTheme: true,
),
- if (localSettings.showOfflineModeOption) ...[
+ if (localSettings.showLocalGalleryModeOption) ...[
const SizedBox(height: 12),
ButtonWidgetV2(
buttonType: ButtonTypeV2.secondary,
- labelText:
- AppLocalizations.of(context).continueWithoutAccount,
+ labelText: AppLocalizations.of(
+ context,
+ ).continueWithoutAccount,
onTap: _navigateWithoutAccount,
shouldSurfaceExecutionStates: false,
shouldStickToLightTheme: true,
@@ -202,10 +201,7 @@ class _LandingPageWidgetState extends State<LandingPageWidget> {
alignment: Alignment.topRight,
child: Padding(
padding: EdgeInsets.only(right: 16),
- child: Text(
- "Lang",
- style: TextStyle(color: Colors.black54),
- ),
+ child: Text("Lang", style: TextStyle(color: Colors.black54)),
),
),
onTap: () async {
@@ -290,9 +286,7 @@ class _LandingPageWidgetState extends State<LandingPageWidget> {
activeShape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
),
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(14),
- ),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
size: const Size(10, 10),
activeSize: const Size(20, 10),
spacing: const EdgeInsets.all(6),
@@ -318,9 +312,7 @@ class _LandingPageWidgetState extends State<LandingPageWidget> {
// No key
if (Configuration.instance.getKeyAttributes() == null) {
// Never had a key
- page = const PasswordEntryPage(
- mode: PasswordEntryMode.set,
- );
+ page = const PasswordEntryPage(mode: PasswordEntryMode.set);
} else if (Configuration.instance.getKey() == null) {
// Yet to decrypt the key
page = const PasswordReentryPage();
@@ -348,9 +340,7 @@ class _LandingPageWidgetState extends State<LandingPageWidget> {
// No key
if (Configuration.instance.getKeyAttributes() == null) {
// Never had a key
- page = const PasswordEntryPage(
- mode: PasswordEntryMode.set,
- );
+ page = const PasswordEntryPage(mode: PasswordEntryMode.set);
} else if (Configuration.instance.getKey() == null) {
// Yet to decrypt the key
page = const PasswordReentryPage();
@@ -428,10 +418,7 @@ class FeatureItemWidget extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.end,
children: [
- Image.asset(
- assetPath,
- height: 200,
- ),
+ Image.asset(assetPath, height: 200),
const Padding(padding: EdgeInsets.all(16)),
Column(
crossAxisAlignment: CrossAxisAlignment.center,
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.dart
index b3efde148d..9fac07444e 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
@@ -97,17 +97,20 @@ class _FullScreenMemoryDataUpdaterState
Future<void> _setupConnectivityListener() async {
try {
final initialResults = await Connectivity().checkConnectivity();
- _wasConnected =
- initialResults.any((result) => result != ConnectivityResult.none);
+ _wasConnected = initialResults.any(
+ (result) => result != ConnectivityResult.none,
+ );
} catch (_) {
// Prefer a spurious retry over a missed one if the check fails.
_wasConnected = false;
}
if (!mounted) return;
- _connectivitySubscription =
- Connectivity().onConnectivityChanged.listen((results) {
- final hasConnection =
- results.any((result) => result != ConnectivityResult.none);
+ _connectivitySubscription = Connectivity().onConnectivityChanged.listen((
+ results,
+ ) {
+ final hasConnection = results.any(
+ (result) => result != ConnectivityResult.none,
+ );
if (!hasConnection) {
_wasConnected = false;
return;
@@ -683,7 +686,7 @@ class BottomIcons extends StatelessWidget {
},
),
]);
- if (!isOfflineMode) {
+ if (!isLocalGalleryMode) {
rowChildren.add(
SizedBox(height: 32, child: FavoriteWidget(currentFile)),
);
@@ -697,11 +700,7 @@ class BottomIcons extends StatelessWidget {
),
onPressed: () async {
fullScreenState?._toggleAnimation(pause: true);
- await _shareMemory(
- context,
- inheritedData,
- memoryTitle,
- );
+ await _shareMemory(context, inheritedData, memoryTitle);
fullScreenState?._toggleAnimation(pause: false);
},
),
@@ -908,7 +907,7 @@ Future<void> _shareMemory(
? _titleCase(l10n.videoSmallCase)
: _titleCase(l10n.photoSmallCase);
final canShowMemoryShareLinkOption = flagService.enableMemoryShareLink &&
- !(isOfflineMode && !Configuration.instance.hasConfiguredAccount());
+ !(isLocalGalleryMode && !Configuration.instance.hasConfiguredAccount());
final shouldShareLink = await showBaseBottomSheet<bool>(
context,
title: l10n.shareMemories,
@@ -1043,11 +1042,7 @@ class _MemoryShareOption extends StatelessWidget {
),
)
else
- HugeIcon(
- icon: icon,
- color: colorScheme.textBase,
- size: 24,
- ),
+ HugeIcon(icon: icon, color: colorScheme.textBase, size: 24),
const SizedBox(height: 8),
Text(
label,
diff --git a/mobile/apps/photos/lib/ui/home/status_bar_widget.dart b/mobile/apps/photos/lib/ui/home/status_bar_widget.dart
index c0f0bd701f..a419890cdf 100644
--- a/mobile/apps/photos/lib/ui/home/status_bar_widget.dart
+++ b/mobile/apps/photos/lib/ui/home/status_bar_widget.dart
@@ -44,7 +44,7 @@ class _StatusBarWidgetState extends State<StatusBarWidget> {
bool _showStatus = false;
bool _showErrorBanner = false;
bool _showMlBanner = !hasGrantedMLConsent &&
- (isOfflineMode || flagService.hasSyncedAccountFlags()) &&
+ (isLocalGalleryMode || flagService.hasSyncedAccountFlags()) &&
!localSettings.hasSeenMLEnablingBanner;
Error? _syncError;
@@ -79,8 +79,9 @@ class _StatusBarWidgetState extends State<StatusBarWidget> {
});
}
});
- _notificationSubscription =
- Bus.instance.on<NotificationEvent>().listen((event) {
+ _notificationSubscription = Bus.instance.on<NotificationEvent>().listen((
+ event,
+ ) {
if (mounted) {
_showMlBanner =
!hasGrantedMLConsent && !localSettings.hasSeenMLEnablingBanner;
@@ -136,23 +137,23 @@ class _StatusBarWidgetState extends State<StatusBarWidget> {
),
),
_showErrorBanner
- ? Divider(
- height: 8,
- color: getEnteColorScheme(context).strokeFaint,
- )
+ ? Divider(height: 8, color: getEnteColorScheme(context).strokeFaint)
: const SizedBox.shrink(),
_showErrorBanner
? HeaderErrorWidget(error: _syncError)
: const SizedBox.shrink(),
_showMlBanner && !_showErrorBanner
? Padding(
- padding:
- const EdgeInsets.symmetric(horizontal: 2.0, vertical: 12),
+ padding: const EdgeInsets.symmetric(
+ horizontal: 2.0,
+ vertical: 12,
+ ),
child: NotificationWidget(
startIcon: Icons.offline_bolt,
actionIcon: Icons.arrow_forward,
- text:
- AppLocalizations.of(context).enableMachineLearningBanner,
+ text: AppLocalizations.of(
+ context,
+ ).enableMachineLearningBanner,
type: NotificationType.greenBanner,
mainTextStyle: darkTextTheme.smallMuted,
onTap: () async => {
@@ -167,8 +168,10 @@ class _StatusBarWidgetState extends State<StatusBarWidget> {
: const SizedBox.shrink(),
_showVerificationBanner()
? Padding(
- padding:
- const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12),
+ padding: const EdgeInsets.symmetric(
+ horizontal: 16.0,
+ vertical: 12,
+ ),
child: NotificationWidget(
startIcon: Icons.error_outline,
actionIcon: Icons.arrow_forward,
@@ -362,8 +365,9 @@ class SyncStatusCompletedWidget extends StatelessWidget {
),
Padding(
padding: const EdgeInsets.only(left: 12),
- child:
- Text(AppLocalizations.of(context).allMemoriesPreserved),
+ child: Text(
+ AppLocalizations.of(context).allMemoriesPreserved,
+ ),
),
],
),
diff --git a/mobile/apps/photos/lib/ui/notification/update/change_log_page.dart b/mobile/apps/photos/lib/ui/notification/update/change_log_page.dart
index 85c04a39b6..6318206c1f 100644
--- a/mobile/apps/photos/lib/ui/notification/update/change_log_page.dart
+++ b/mobile/apps/photos/lib/ui/notification/update/change_log_page.dart
@@ -10,9 +10,7 @@ import 'package:photos/ui/notification/update/change_log_entry.dart';
import 'package:photos/ui/notification/update/change_log_strings.dart';
class ChangeLogPage extends StatefulWidget {
- const ChangeLogPage({
- super.key,
- });
+ const ChangeLogPage({super.key});
@override
State<ChangeLogPage> createState() => _ChangeLogPageState();
@@ -46,13 +44,9 @@ class _ChangeLogPageState extends State<ChangeLogPage> {
),
),
),
- const SizedBox(
- height: 24,
- ),
+ const SizedBox(height: 24),
Flexible(child: _getChangeLog()),
- const DividerWidget(
- dividerType: DividerType.solid,
- ),
+ const DividerWidget(dividerType: DividerType.solid),
SafeArea(
child: Padding(
padding: const EdgeInsets.only(
@@ -99,7 +93,7 @@ class _ChangeLogPageState extends State<ChangeLogPage> {
Widget _getChangeLog() {
final strings = ChangeLogStrings.maybeForLocale(
Localizations.localeOf(context),
- isOffline: isOfflineMode,
+ isOffline: isLocalGalleryMode,
);
if (strings == null) {
return const SizedBox.shrink();
@@ -108,10 +102,9 @@ class _ChangeLogPageState extends State<ChangeLogPage> {
ChangeLogEntry(
strings.title1,
description: strings.desc1,
- items: [
- strings.desc1Item1,
- strings.desc1Item2,
- ].where((item) => item.trim().isNotEmpty).toList(growable: false),
+ items: [strings.desc1Item1, strings.desc1Item2]
+ .where((item) => item.trim().isNotEmpty)
+ .toList(growable: false),
isFeature: true,
),
ChangeLogEntry(
diff --git a/mobile/apps/photos/lib/ui/settings/debug/ml_debug_settings_page.dart b/mobile/apps/photos/lib/ui/settings/debug/ml_debug_settings_page.dart
index a5fa6ea1d4..dd1ff59d7d 100644
--- a/mobile/apps/photos/lib/ui/settings/debug/ml_debug_settings_page.dart
+++ b/mobile/apps/photos/lib/ui/settings/debug/ml_debug_settings_page.dart
@@ -106,10 +106,7 @@ class _MLDebugSettingsPageState extends State<MLDebugSettingsPage> {
),
),
const SizedBox(height: 24),
- Text(
- "ML Debug",
- style: textTheme.h3Bold,
- ),
+ Text("ML Debug", style: textTheme.h3Bold),
const SizedBox(height: 24),
Expanded(
child: SingleChildScrollView(
@@ -374,17 +371,15 @@ class _MLDebugSettingsPageState extends State<MLDebugSettingsPage> {
color = colorScheme.warning500;
}
- return Text(
- label,
- style: textTheme.miniBold.copyWith(color: color),
- );
+ return Text(label, style: textTheme.miniBold.copyWith(color: color));
}
Future<({bool clipDone, bool clusterCentroidDone})>
_getVectorDbMigrationStatus() async {
- final clipVectorDB =
- isOfflineMode ? ClipVectorDB.offlineInstance : ClipVectorDB.instance;
- final clusterCentroidVectorDB = isOfflineMode
+ final clipVectorDB = isLocalGalleryMode
+ ? ClipVectorDB.offlineInstance
+ : ClipVectorDB.instance;
+ final clusterCentroidVectorDB = isLocalGalleryMode
? ClusterCentroidVectorDB.offlineInstance
: ClusterCentroidVectorDB.instance;
final migrationStatus = await Future.wait<bool>([
@@ -449,22 +444,13 @@ class _MLDebugSettingsPageState extends State<MLDebugSettingsPage> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- Text(
- title,
- style: textTheme.smallBold,
- ),
+ Text(title, style: textTheme.smallBold),
const SizedBox(height: 4),
- Text(
- description,
- style: textTheme.miniMuted,
- ),
+ Text(description, style: textTheme.miniMuted),
const SizedBox(height: 12),
Row(
children: [
- Text(
- min.toStringAsFixed(2),
- style: textTheme.mini,
- ),
+ Text(min.toStringAsFixed(2), style: textTheme.mini),
Expanded(
child: Slider(
value: clampedValue,
@@ -476,10 +462,7 @@ class _MLDebugSettingsPageState extends State<MLDebugSettingsPage> {
},
),
),
- Text(
- max.toStringAsFixed(2),
- style: textTheme.mini,
- ),
+ Text(max.toStringAsFixed(2), style: textTheme.mini),
],
),
Text(
@@ -495,10 +478,7 @@ class _MLDebugSettingsPageState extends State<MLDebugSettingsPage> {
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
- Text(
- "Save on device",
- style: textTheme.mini,
- ),
+ Text("Save on device", style: textTheme.mini),
ToggleSwitchWidget(
value: () => persistValue,
onChanged: () async {
@@ -528,9 +508,7 @@ class _MLDebugSettingsPageState extends State<MLDebugSettingsPage> {
final rounded = _roundToStep(value);
PersonService.autoMergeThreshold = rounded;
if (_persistAutoMergeThreshold) {
- unawaited(
- localSettings.setAutoMergeThresholdOverride(rounded),
- );
+ unawaited(localSettings.setAutoMergeThresholdOverride(rounded));
}
setState(() {
_autoMergeThreshold = rounded;
@@ -550,9 +528,7 @@ class _MLDebugSettingsPageState extends State<MLDebugSettingsPage> {
final rounded = _roundToStep(value);
FaceClusteringService.defaultDistanceThreshold = rounded;
if (_persistDefaultClusteringDistance) {
- unawaited(
- localSettings.setDefaultClusteringDistanceOverride(rounded),
- );
+ unawaited(localSettings.setDefaultClusteringDistanceOverride(rounded));
}
setState(() {
_defaultClusteringDistance = rounded;
@@ -806,7 +782,7 @@ class _MLDebugSettingsPageState extends State<MLDebugSettingsPage> {
MLService.instance.debugIndexingDisabled = false;
unawaited(
MLService.instance.fetchAndIndexAllImages(
- mode: isOfflineMode ? MLMode.offline : MLMode.online,
+ mode: isLocalGalleryMode ? MLMode.localGallery : MLMode.enteGallery,
),
);
showShortToast(context, "Indexing started");
@@ -852,10 +828,7 @@ class _MLDebugSettingsPageState extends State<MLDebugSettingsPage> {
}
Future<void> _onShowAllMemoriesDebug(BuildContext context) async {
- await routeToPage(
- context,
- const MemoriesDebugPage(),
- );
+ await routeToPage(context, const MemoriesDebugPage());
}
Future<void> _onSyncPersonMappings(BuildContext context) async {
@@ -984,7 +957,7 @@ class _MLDebugSettingsPageState extends State<MLDebugSettingsPage> {
firstButtonLabel: "Yes, confirm",
firstButtonOnTap: () async {
try {
- final vectorDB = isOfflineMode
+ final vectorDB = isLocalGalleryMode
? ClipVectorDB.offlineInstance
: ClipVectorDB.instance;
await vectorDB.deleteIndexFile();
diff --git a/mobile/apps/photos/lib/ui/settings/developer_settings_page.dart b/mobile/apps/photos/lib/ui/settings/developer_settings_page.dart
index b2695b3089..68c620aec8 100644
--- a/mobile/apps/photos/lib/ui/settings/developer_settings_page.dart
+++ b/mobile/apps/photos/lib/ui/settings/developer_settings_page.dart
@@ -79,7 +79,9 @@ class _DeveloperSettingsPageState extends State<DeveloperSettingsPage> {
final url = _urlController.text.trim();
_logger.info("Entered endpoint: $url");
final modeToggleMessage =
- await _maybeToggleOfflineModeOption(url);
+ await _maybeToggleLocalGalleryModeOption(
+ url,
+ );
if (modeToggleMessage != null) {
Bus.instance.fire(AppModeChangedEvent());
showToast(context, modeToggleMessage);
@@ -122,8 +124,9 @@ class _DeveloperSettingsPageState extends State<DeveloperSettingsPage> {
Future<void> _ping(String endpoint) async {
try {
- final response =
- await NetworkClient.instance.getDio().get('$endpoint/ping');
+ final response = await NetworkClient.instance.getDio().get(
+ '$endpoint/ping',
+ );
if (response.data['message'] != 'pong') {
throw Exception('Invalid response');
}
@@ -132,14 +135,14 @@ class _DeveloperSettingsPageState extends State<DeveloperSettingsPage> {
}
}
- Future<String?> _maybeToggleOfflineModeOption(String input) async {
+ Future<String?> _maybeToggleLocalGalleryModeOption(String input) async {
switch (input) {
case "offline":
- await localSettings.setShowOfflineModeOption(true);
- return "Offline mode option enabled";
+ await localSettings.setShowLocalGalleryModeOption(true);
+ return "Local gallery mode option enabled";
case "online":
- await localSettings.setShowOfflineModeOption(false);
- return "Offline mode option disabled";
+ await localSettings.setShowLocalGalleryModeOption(false);
+ return "Local gallery mode option disabled";
default:
return null;
}
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 4561a5bf19..8fdbb89556 100644
--- a/mobile/apps/photos/lib/ui/settings/gallery_settings_screen.dart
+++ b/mobile/apps/photos/lib/ui/settings/gallery_settings_screen.dart
@@ -107,11 +107,12 @@ class _GallerySettingsScreenState extends State<GallerySettingsScreen> {
},
),
if (!widget.fromGalleryLayoutSettingsCTA &&
- !isOfflineMode) ...[
+ !isLocalGalleryMode) ...[
const SizedBox(height: 8),
MenuItemWidgetNew(
- title: AppLocalizations.of(context)
- .hideSharedItemsFromHomeGallery,
+ title: AppLocalizations.of(
+ context,
+ ).hideSharedItemsFromHomeGallery,
trailingWidget: ToggleSwitchWidget(
value: () =>
localSettings.hideSharedItemsFromHomeGallery,
diff --git a/mobile/apps/photos/lib/ui/settings/ml/machine_learning_settings_page.dart b/mobile/apps/photos/lib/ui/settings/ml/machine_learning_settings_page.dart
index 6f51c1d31e..c82b475874 100644
--- a/mobile/apps/photos/lib/ui/settings/ml/machine_learning_settings_page.dart
+++ b/mobile/apps/photos/lib/ui/settings/ml/machine_learning_settings_page.dart
@@ -136,9 +136,7 @@ class _MachineLearningSettingsPageState
Text(
AppLocalizations.of(context).mlIndexingDescription,
textAlign: TextAlign.left,
- style: textTheme.small.copyWith(
- color: colorScheme.textMuted,
- ),
+ style: textTheme.small.copyWith(color: colorScheme.textMuted),
),
const SizedBox(height: 20),
_getMlSettings(context),
@@ -240,9 +238,7 @@ class _MachineLearningSettingsPageState
Bus.instance.fire(NotificationEvent());
if (!mlConsent) {
MLService.instance.pauseIndexingAndClustering();
- unawaited(
- MLIndexingIsolate.instance.cleanupLocalIndexingModels(),
- );
+ unawaited(MLIndexingIsolate.instance.cleanupLocalIndexingModels());
if (oldMlEnabled && !newMlEnabled) {
await memoriesCacheService.purgeMlOnlyMemoriesFromCache();
}
@@ -311,20 +307,16 @@ class _MachineLearningSettingsPageState
),
alignment: Alignment.center,
child: _hasAcknowledgedMLConsent
- ? Icon(
- Icons.check,
- size: 14,
- color: colorScheme.contentReverse,
- )
+ ? Icon(Icons.check, size: 14, color: colorScheme.contentReverse)
: null,
),
const SizedBox(width: 10),
Expanded(
child: Text(
AppLocalizations.of(context).mlConsentConfirmation,
- style: getEnteTextTheme(context).small.copyWith(
- color: colorScheme.textMuted,
- ),
+ style: getEnteTextTheme(
+ context,
+ ).small.copyWith(color: colorScheme.textMuted),
),
),
],
@@ -391,9 +383,7 @@ class _MachineLearningSettingsPageState
},
),
),
- const SizedBox(
- height: 12,
- ),
+ const SizedBox(height: 12),
MLIndexingIsolate.instance.areModelsDownloaded ||
!localSettings.isMLLocalIndexingEnabled
? const MLStatusWidget()
@@ -404,9 +394,7 @@ class _MachineLearningSettingsPageState
}
class ModelLoadingState extends StatefulWidget {
- const ModelLoadingState({
- super.key,
- });
+ const ModelLoadingState({super.key});
@override
State<ModelLoadingState> createState() => _ModelLoadingStateState();
@@ -419,8 +407,9 @@ class _ModelLoadingStateState extends State<ModelLoadingState> {
@override
void initState() {
- _progressStream =
- RemoteAssetsService.instance.progressStream.listen((event) {
+ _progressStream = RemoteAssetsService.instance.progressStream.listen((
+ event,
+ ) {
final String url = event.$1;
String title = "";
if (url.contains(ClipImageEncoder.kRemoteBucketModelPath)) {
@@ -459,7 +448,7 @@ class _ModelLoadingStateState extends State<ModelLoadingState> {
MenuSectionTitle(title: AppLocalizations.of(context).status),
const SizedBox(height: 8),
FutureBuilder(
- future: canUseHighBandwidth().then((v) => isOfflineMode || v),
+ future: canUseHighBandwidth().then((v) => isLocalGalleryMode || v),
builder: (context, snapshot) {
String title = "";
if (snapshot.hasData) {
@@ -501,9 +490,7 @@ class _ModelLoadingStateState extends State<ModelLoadingState> {
}
class MLStatusWidget extends StatefulWidget {
- const MLStatusWidget({
- super.key,
- });
+ const MLStatusWidget({super.key});
@override
State<MLStatusWidget> createState() => MLStatusWidgetState();
@@ -552,8 +539,9 @@ class MLStatusWidgetState extends State<MLStatusWidget> {
if (!_isDeviceHealthy && pendingFiles > 0) {
return MenuSectionDescriptionWidget(
- content: AppLocalizations.of(context)
- .indexingPausedStatusDescription,
+ content: AppLocalizations.of(
+ context,
+ ).indexingPausedStatusDescription,
);
}
diff --git a/mobile/apps/photos/lib/ui/settings/notification_settings_screen.dart b/mobile/apps/photos/lib/ui/settings/notification_settings_screen.dart
index 643585313d..b79289b32f 100644
--- a/mobile/apps/photos/lib/ui/settings/notification_settings_screen.dart
+++ b/mobile/apps/photos/lib/ui/settings/notification_settings_screen.dart
@@ -14,7 +14,7 @@ class NotificationSettingsScreen extends StatelessWidget {
final colorScheme = getEnteColorScheme(context);
final textTheme = getEnteTextTheme(context);
final isDarkMode = Theme.of(context).brightness == Brightness.dark;
- final showOnlyOnThisDay = isOfflineMode;
+ final showOnlyOnThisDay = isLocalGalleryMode;
final pageBackgroundColor =
isDarkMode ? const Color(0xFF161616) : const Color(0xFFFAFAFA);
@@ -49,8 +49,9 @@ class NotificationSettingsScreen extends StatelessWidget {
children: [
if (!showOnlyOnThisDay) ...[
MenuItemWidgetNew(
- title: AppLocalizations.of(context)
- .sharedPhotoNotifications,
+ title: AppLocalizations.of(
+ context,
+ ).sharedPhotoNotifications,
trailingWidget: ToggleSwitchWidget(
value: () =>
NotificationService.instance
@@ -76,15 +77,18 @@ class NotificationSettingsScreen extends StatelessWidget {
bottom: 16,
),
child: Text(
- AppLocalizations.of(context)
- .sharedPhotoNotificationsExplanation,
- style: textTheme.mini
- .copyWith(color: colorScheme.textMuted),
+ AppLocalizations.of(
+ context,
+ ).sharedPhotoNotificationsExplanation,
+ style: textTheme.mini.copyWith(
+ color: colorScheme.textMuted,
+ ),
),
),
MenuItemWidgetNew(
- title:
- AppLocalizations.of(context).socialNotifications,
+ title: AppLocalizations.of(
+ context,
+ ).socialNotifications,
trailingWidget: ToggleSwitchWidget(
value: () =>
NotificationService.instance
@@ -110,10 +114,12 @@ class NotificationSettingsScreen extends StatelessWidget {
bottom: 16,
),
child: Text(
- AppLocalizations.of(context)
- .socialNotificationsExplanation,
- style: textTheme.mini
- .copyWith(color: colorScheme.textMuted),
+ AppLocalizations.of(
+ context,
+ ).socialNotificationsExplanation,
+ style: textTheme.mini.copyWith(
+ color: colorScheme.textMuted,
+ ),
),
),
],
@@ -140,10 +146,12 @@ class NotificationSettingsScreen extends StatelessWidget {
bottom: 16,
),
child: Text(
- AppLocalizations.of(context)
- .onThisDayNotificationExplanation,
- style: textTheme.mini
- .copyWith(color: colorScheme.textMuted),
+ AppLocalizations.of(
+ context,
+ ).onThisDayNotificationExplanation,
+ style: textTheme.mini.copyWith(
+ color: colorScheme.textMuted,
+ ),
),
),
if (!showOnlyOnThisDay) ...[
@@ -170,10 +178,12 @@ class NotificationSettingsScreen extends StatelessWidget {
bottom: 16,
),
child: Text(
- AppLocalizations.of(context)
- .receiveRemindersOnBirthdays,
- style: textTheme.mini
- .copyWith(color: colorScheme.textMuted),
+ AppLocalizations.of(
+ context,
+ ).receiveRemindersOnBirthdays,
+ style: textTheme.mini.copyWith(
+ color: colorScheme.textMuted,
+ ),
),
),
],
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 564c46e4b2..a4c8990c80 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
@@ -27,7 +27,7 @@ class SettingsSearchRegistry {
static List<SettingsSearchItem> getSearchableItems(BuildContext context) {
final l10n = AppLocalizations.of(context);
final hasLoggedIn = Configuration.instance.isLoggedIn();
- final isOffline = isOfflineMode;
+ final isOffline = isLocalGalleryMode;
final items = <SettingsSearchItem>[];
// Account settings
@@ -327,9 +327,8 @@ class SettingsSearchRegistry {
subtitle: l10n.appearance,
sectionPath: "${l10n.appearance} > ${l10n.gallery}",
icon: HugeIcons.strokeRoundedDashboardSquare02,
- routeBuilder: (_) => const GallerySettingsScreen(
- fromGalleryLayoutSettingsCTA: false,
- ),
+ routeBuilder: (_) =>
+ const GallerySettingsScreen(fromGalleryLayoutSettingsCTA: false),
isSubPage: true,
keywords: ["grid size", "group by", "layout"],
),
@@ -342,9 +341,8 @@ class SettingsSearchRegistry {
subtitle: l10n.gallery,
sectionPath: "${l10n.appearance} > ${l10n.gallery}",
icon: HugeIcons.strokeRoundedDashboardSquare02,
- routeBuilder: (_) => const GallerySettingsScreen(
- fromGalleryLayoutSettingsCTA: false,
- ),
+ routeBuilder: (_) =>
+ const GallerySettingsScreen(fromGalleryLayoutSettingsCTA: false),
isSubPage: true,
keywords: ["grid", "size", "columns", "thumbnail"],
),
@@ -357,9 +355,8 @@ class SettingsSearchRegistry {
subtitle: l10n.gallery,
sectionPath: "${l10n.appearance} > ${l10n.gallery}",
icon: HugeIcons.strokeRoundedDashboardSquare02,
- routeBuilder: (_) => const GallerySettingsScreen(
- fromGalleryLayoutSettingsCTA: false,
- ),
+ routeBuilder: (_) =>
+ const GallerySettingsScreen(fromGalleryLayoutSettingsCTA: false),
isSubPage: true,
keywords: ["group", "day", "month", "year"],
),
@@ -372,9 +369,8 @@ class SettingsSearchRegistry {
subtitle: l10n.gallery,
sectionPath: "${l10n.appearance} > ${l10n.gallery}",
icon: HugeIcons.strokeRoundedImage01,
- routeBuilder: (_) => const GallerySettingsScreen(
- fromGalleryLayoutSettingsCTA: false,
- ),
+ routeBuilder: (_) =>
+ const GallerySettingsScreen(fromGalleryLayoutSettingsCTA: false),
isSubPage: true,
keywords: ["shared", "hide", "home gallery"],
),
@@ -566,14 +562,7 @@ class SettingsSearchRegistry {
sectionPath: l10n.freeUpSpace,
icon: HugeIcons.strokeRoundedRocket01,
routeBuilder: (_) => const FreeUpSpaceOptionsScreen(),
- keywords: [
- "storage",
- "space",
- "clean",
- "delete",
- "local",
- "device",
- ],
+ keywords: ["storage", "space", "clean", "delete", "local", "device"],
),
);
@@ -611,12 +600,7 @@ class SettingsSearchRegistry {
icon: HugeIcons.strokeRoundedRocket01,
routeBuilder: (_) => const FreeUpSpaceOptionsScreen(),
isSubPage: true,
- keywords: [
- "similar",
- "alike",
- "resembling",
- "cleanup",
- ],
+ keywords: ["similar", "alike", "resembling", "cleanup"],
),
SettingsSearchItem(
title: l10n.viewLargeFiles,
@@ -777,16 +761,15 @@ class SettingsSearchRegistry {
) {
final l10n = AppLocalizations.of(context);
final hasLoggedIn = Configuration.instance.isLoggedIn();
- final isOffline = isOfflineMode;
+ final isOffline = isLocalGalleryMode;
return [
// Gallery suggestion
SettingsSearchSuggestion(
title: l10n.gallery,
onTap: () => onNavigate(
- (_) => const GallerySettingsScreen(
- fromGalleryLayoutSettingsCTA: false,
- ),
+ (_) =>
+ const GallerySettingsScreen(fromGalleryLayoutSettingsCTA: false),
),
),
// App lock suggestion
diff --git a/mobile/apps/photos/lib/ui/settings/security/security_settings_page.dart b/mobile/apps/photos/lib/ui/settings/security/security_settings_page.dart
index f3b8acf44b..80614bcfe7 100644
--- a/mobile/apps/photos/lib/ui/settings/security/security_settings_page.dart
+++ b/mobile/apps/photos/lib/ui/settings/security/security_settings_page.dart
@@ -64,7 +64,7 @@ class _SecuritySettingsPageState extends State<SecuritySettingsPage> {
final textTheme = getEnteTextTheme(context);
final isDarkMode = Theme.of(context).brightness == Brightness.dark;
final showAccountSecurity =
- _config.hasConfiguredAccount() && !isOfflineMode;
+ _config.hasConfiguredAccount() && !isLocalGalleryMode;
final pageBackgroundColor =
isDarkMode ? const Color(0xFF161616) : const Color(0xFFFAFAFA);
@@ -111,8 +111,9 @@ class _SecuritySettingsPageState extends State<SecuritySettingsPage> {
),
const SizedBox(height: 8),
MenuItemWidgetNew(
- title: AppLocalizations.of(context)
- .emailVerificationToggle,
+ title: AppLocalizations.of(
+ context,
+ ).emailVerificationToggle,
leadingIconWidget: _buildIconWidget(
context,
HugeIcons.strokeRoundedMailSecure01,
@@ -199,7 +200,7 @@ class _SecuritySettingsPageState extends State<SecuritySettingsPage> {
}
Future<void> _refreshSecurityDetails() async {
- if (!_config.hasConfiguredAccount() || isOfflineMode) {
+ if (!_config.hasConfiguredAccount() || isLocalGalleryMode) {
return;
}
try {
@@ -234,16 +235,12 @@ class _SecuritySettingsPageState extends State<SecuritySettingsPage> {
Future<void> _disableTwoFactor() async {
final alert = AlertDialog(
title: Text(AppLocalizations.of(context).disableTwofactor),
- content: Text(
- AppLocalizations.of(context).confirm2FADisable,
- ),
+ content: Text(AppLocalizations.of(context).confirm2FADisable),
actions: [
TextButton(
child: Text(
AppLocalizations.of(context).no,
- style: TextStyle(
- color: getEnteColorScheme(context).primary500,
- ),
+ style: TextStyle(color: getEnteColorScheme(context).primary500),
),
onPressed: () {
Navigator.of(context).pop("dialog");
@@ -252,9 +249,7 @@ class _SecuritySettingsPageState extends State<SecuritySettingsPage> {
TextButton(
child: Text(
AppLocalizations.of(context).yes,
- style: const TextStyle(
- color: Colors.red,
- ),
+ style: const TextStyle(color: Colors.red),
),
onPressed: () async {
await UserService.instance.disableTwoFactor(context);
@@ -287,15 +282,17 @@ class _SecuritySettingsPageState extends State<SecuritySettingsPage> {
Future<void> _updateEmailMFA(bool isEnabled) async {
try {
- final UserDetails details =
- await UserService.instance.getUserDetailsV2(memoryCount: false);
+ final UserDetails details = await UserService.instance.getUserDetailsV2(
+ memoryCount: false,
+ );
if ((details.profileData?.canDisableEmailMFA ?? false) == false) {
await routeToPage(
context,
RequestPasswordVerificationPage(
onPasswordVerified: (Uint8List keyEncryptionKey) async {
- final Uint8List loginKey =
- await CryptoUtil.deriveLoginKey(keyEncryptionKey);
+ final Uint8List loginKey = await CryptoUtil.deriveLoginKey(
+ keyEncryptionKey,
+ );
await UserService.instance.registerOrUpdateSrp(loginKey);
},
),
@@ -327,10 +324,7 @@ class _SecuritySettingsPageState extends State<SecuritySettingsPage> {
await UserService.instance.getOrCreateRecoveryKey(context);
final resetKey = CryptoUtil.generateKey();
final resetKeyBase64 = CryptoUtil.bin2base64(resetKey);
- final encryptionResult = CryptoUtil.encryptSync(
- resetKey,
- recoveryKey,
- );
+ final encryptionResult = CryptoUtil.encryptSync(resetKey, recoveryKey);
await PasskeyService.instance.configurePasskeyRecovery(
resetKeyBase64,
CryptoUtil.bin2base64(encryptionResult.encryptedData!),
@@ -363,8 +357,9 @@ class _SecuritySettingsPageState extends State<SecuritySettingsPage> {
await showErrorDialog(
context,
AppLocalizations.of(context).noSystemLockFound,
- AppLocalizations.of(context)
- .toEnableAppLockPleaseSetupDevicePasscodeOrScreen,
+ AppLocalizations.of(
+ context,
+ ).toEnableAppLockPleaseSetupDevicePasscodeOrScreen,
);
}
}
diff --git a/mobile/apps/photos/lib/ui/settings/security_section_widget.dart b/mobile/apps/photos/lib/ui/settings/security_section_widget.dart
index 1a54c801e2..654e1272d1 100644
--- a/mobile/apps/photos/lib/ui/settings/security_section_widget.dart
+++ b/mobile/apps/photos/lib/ui/settings/security_section_widget.dart
@@ -72,83 +72,78 @@ class _SecuritySectionWidgetState extends State<SecuritySectionWidget> {
final Completer completer = Completer();
final List<Widget> children = [];
if (_config.hasConfiguredAccount()) {
- children.addAll(
- [
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(
- title: AppLocalizations.of(context).twofactor,
- ),
- trailingWidget: ToggleSwitchWidget(
- value: () => UserService.instance.hasEnabledTwoFactor(),
- onChanged: () async {
- final hasAuthenticated = await LocalAuthenticationService
- .instance
- .requestLocalAuthentication(
- context,
- AppLocalizations.of(context)
- .authToConfigureTwofactorAuthentication,
- );
- final isTwoFactorEnabled =
- UserService.instance.hasEnabledTwoFactor();
- if (hasAuthenticated) {
- if (isTwoFactorEnabled) {
- await _disableTwoFactor();
- completer.isCompleted ? null : completer.complete();
- } else {
- await UserService.instance
- .setupTwoFactor(context, completer);
- }
- return completer.future;
- }
- },
- ),
+ children.addAll([
+ sectionOptionSpacing,
+ MenuItemWidget(
+ captionedTextWidget: CaptionedTextWidget(
+ title: AppLocalizations.of(context).twofactor,
),
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(
- title: AppLocalizations.of(context).emailVerificationToggle,
- ),
- trailingWidget: ToggleSwitchWidget(
- value: () => UserService.instance.hasEmailMFAEnabled(),
- onChanged: () async {
- final hasAuthenticated = await LocalAuthenticationService
- .instance
- .requestLocalAuthentication(
+ trailingWidget: ToggleSwitchWidget(
+ value: () => UserService.instance.hasEnabledTwoFactor(),
+ onChanged: () async {
+ final hasAuthenticated = await LocalAuthenticationService.instance
+ .requestLocalAuthentication(
+ context,
+ AppLocalizations.of(
context,
- AppLocalizations.of(context)
- .authToChangeEmailVerificationSetting,
- );
- final isEmailMFAEnabled =
- UserService.instance.hasEmailMFAEnabled();
- if (hasAuthenticated) {
- await updateEmailMFA(!isEmailMFAEnabled);
+ ).authToConfigureTwofactorAuthentication,
+ );
+ final isTwoFactorEnabled =
+ UserService.instance.hasEnabledTwoFactor();
+ if (hasAuthenticated) {
+ if (isTwoFactorEnabled) {
+ await _disableTwoFactor();
+ completer.isCompleted ? null : completer.complete();
+ } else {
+ await UserService.instance.setupTwoFactor(context, completer);
}
- },
- ),
+ return completer.future;
+ }
+ },
),
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(
- title: context.l10n.passkey,
- ),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
+ ),
+ sectionOptionSpacing,
+ MenuItemWidget(
+ captionedTextWidget: CaptionedTextWidget(
+ title: AppLocalizations.of(context).emailVerificationToggle,
+ ),
+ trailingWidget: ToggleSwitchWidget(
+ value: () => UserService.instance.hasEmailMFAEnabled(),
+ onChanged: () async {
final hasAuthenticated = await LocalAuthenticationService.instance
.requestLocalAuthentication(
context,
- AppLocalizations.of(context).authToViewPasskey,
+ AppLocalizations.of(
+ context,
+ ).authToChangeEmailVerificationSetting,
);
+ final isEmailMFAEnabled =
+ UserService.instance.hasEmailMFAEnabled();
if (hasAuthenticated) {
- await onPasskeyClick(context);
+ await updateEmailMFA(!isEmailMFAEnabled);
}
},
),
- sectionOptionSpacing,
- ],
- );
+ ),
+ sectionOptionSpacing,
+ MenuItemWidget(
+ captionedTextWidget: CaptionedTextWidget(title: context.l10n.passkey),
+ pressedColor: getEnteColorScheme(context).fillFaint,
+ trailingIcon: Icons.chevron_right_outlined,
+ trailingIconIsMuted: true,
+ onTap: () async {
+ final hasAuthenticated = await LocalAuthenticationService.instance
+ .requestLocalAuthentication(
+ context,
+ AppLocalizations.of(context).authToViewPasskey,
+ );
+ if (hasAuthenticated) {
+ await onPasskeyClick(context);
+ }
+ },
+ ),
+ sectionOptionSpacing,
+ ]);
}
children.addAll([
MenuItemWidget(
@@ -176,8 +171,9 @@ class _SecuritySectionWidgetState extends State<SecuritySectionWidget> {
await showErrorDialog(
context,
AppLocalizations.of(context).noSystemLockFound,
- AppLocalizations.of(context)
- .toEnableAppLockPleaseSetupDevicePasscodeOrScreen,
+ AppLocalizations.of(
+ context,
+ ).toEnableAppLockPleaseSetupDevicePasscodeOrScreen,
);
}
},
@@ -212,13 +208,11 @@ class _SecuritySectionWidgetState extends State<SecuritySectionWidget> {
),
sectionOptionSpacing,
]);
- return Column(
- children: children,
- );
+ return Column(children: children);
}
Future<void> _refreshSecurityDetails() async {
- if (!_config.hasConfiguredAccount() || isOfflineMode) {
+ if (!_config.hasConfiguredAccount() || isLocalGalleryMode) {
return;
}
try {
@@ -234,9 +228,7 @@ class _SecuritySectionWidgetState extends State<SecuritySectionWidget> {
Future<void> _disableTwoFactor() async {
final AlertDialog alert = AlertDialog(
title: Text(AppLocalizations.of(context).disableTwofactor),
- content: Text(
- AppLocalizations.of(context).confirm2FADisable,
- ),
+ content: Text(AppLocalizations.of(context).confirm2FADisable),
actions: [
TextButton(
child: Text(
@@ -252,9 +244,7 @@ class _SecuritySectionWidgetState extends State<SecuritySectionWidget> {
TextButton(
child: Text(
AppLocalizations.of(context).yes,
- style: const TextStyle(
- color: Colors.red,
- ),
+ style: const TextStyle(color: Colors.red),
),
onPressed: () async {
await UserService.instance.disableTwoFactor(context);
@@ -282,10 +272,7 @@ class _SecuritySectionWidgetState extends State<SecuritySectionWidget> {
await UserService.instance.getOrCreateRecoveryKey(context);
final resetKey = CryptoUtil.generateKey();
final resetKeyBase64 = CryptoUtil.bin2base64(resetKey);
- final encryptionResult = CryptoUtil.encryptSync(
- resetKey,
- recoveryKey,
- );
+ final encryptionResult = CryptoUtil.encryptSync(resetKey, recoveryKey);
await PasskeyService.instance.configurePasskeyRecovery(
resetKeyBase64,
CryptoUtil.bin2base64(encryptionResult.encryptedData!),
@@ -301,15 +288,17 @@ class _SecuritySectionWidgetState extends State<SecuritySectionWidget> {
Future<void> updateEmailMFA(bool isEnabled) async {
try {
- final UserDetails details =
- await UserService.instance.getUserDetailsV2(memoryCount: false);
+ final UserDetails details = await UserService.instance.getUserDetailsV2(
+ memoryCount: false,
+ );
if ((details.profileData?.canDisableEmailMFA ?? false) == false) {
await routeToPage(
context,
RequestPasswordVerificationPage(
onPasswordVerified: (Uint8List keyEncryptionKey) async {
- final Uint8List loginKey =
- await CryptoUtil.deriveLoginKey(keyEncryptionKey);
+ final Uint8List loginKey = await CryptoUtil.deriveLoginKey(
+ keyEncryptionKey,
+ );
await UserService.instance.registerOrUpdateSrp(loginKey);
},
),
diff --git a/mobile/apps/photos/lib/ui/settings_page.dart b/mobile/apps/photos/lib/ui/settings_page.dart
index aef62e5b86..03eaa09253 100644
--- a/mobile/apps/photos/lib/ui/settings_page.dart
+++ b/mobile/apps/photos/lib/ui/settings_page.dart
@@ -71,7 +71,7 @@ class _SettingsBody extends StatelessWidget {
final isDarkMode = Theme.of(context).brightness == Brightness.dark;
final hasLoggedIn = Configuration.instance.isLoggedIn();
final hasConfiguredAccount = Configuration.instance.hasConfiguredAccount();
- final showLoginEntry = isOfflineMode && !hasConfiguredAccount;
+ final showLoginEntry = isLocalGalleryMode && !hasConfiguredAccount;
final pageBackgroundColor =
isDarkMode ? const Color(0xFF161616) : const Color(0xFFFAFAFA);
@@ -109,7 +109,7 @@ class _SettingsBody extends StatelessWidget {
_buildOfflineLoginCard(context, colorScheme),
const SizedBox(height: 8),
],
- if (hasLoggedIn && !isOfflineMode) ...[
+ if (hasLoggedIn && !isLocalGalleryMode) ...[
const StorageCardWidget(),
const SizedBox(height: 16),
_buildAccountCard(context, colorScheme),
@@ -121,11 +121,11 @@ class _SettingsBody extends StatelessWidget {
const SizedBox(height: 8),
_buildAppearanceCard(context, colorScheme),
const SizedBox(height: 8),
- if (isOfflineMode) ...[
+ if (isLocalGalleryMode) ...[
_buildOfflineFeaturesCard(context, colorScheme),
const SizedBox(height: 8),
],
- if (hasLoggedIn && !isOfflineMode) ...[
+ if (hasLoggedIn && !isLocalGalleryMode) ...[
_buildPersonalFeaturesCard(context, colorScheme),
const SizedBox(height: 8),
_buildFeaturesAndPlansCard(context, colorScheme),
@@ -137,7 +137,7 @@ class _SettingsBody extends StatelessWidget {
const SizedBox(height: 8),
_buildAboutUsCard(context, colorScheme),
const SizedBox(height: 8),
- if (hasLoggedIn && !isOfflineMode) ...[
+ if (hasLoggedIn && !isLocalGalleryMode) ...[
_buildLogoutCard(context, colorScheme),
],
const Padding(
@@ -146,7 +146,7 @@ class _SettingsBody extends StatelessWidget {
),
const AppVersionWidget(),
if (hasLoggedIn &&
- !isOfflineMode &&
+ !isLocalGalleryMode &&
(flagService.flags.internalUser || kDebugMode)) ...[
_buildDebugCard(context, colorScheme),
const SizedBox(height: 8),
@@ -191,10 +191,7 @@ class _SettingsBody extends StatelessWidget {
),
);
},
- icon: Icon(
- Icons.search_rounded,
- color: colorScheme.textMuted,
- ),
+ icon: Icon(Icons.search_rounded, color: colorScheme.textMuted),
),
if (localSettings.enableDatabaseLogging)
IconButton(
@@ -208,10 +205,7 @@ class _SettingsBody extends StatelessWidget {
),
);
},
- icon: Icon(
- Icons.bug_report,
- color: colorScheme.textMuted,
- ),
+ icon: Icon(Icons.bug_report, color: colorScheme.textMuted),
),
],
),
@@ -487,8 +481,9 @@ class _SettingsBody extends StatelessWidget {
onTap: () async {
late final UserDetails userDetails;
try {
- userDetails = await UserService.instance
- .getUserDetailsV2(memoryCount: false);
+ userDetails = await UserService.instance.getUserDetailsV2(
+ memoryCount: false,
+ );
} catch (error) {
if (!context.mounted) {
return;
diff --git a/mobile/apps/photos/lib/ui/tabs/home_widget.dart b/mobile/apps/photos/lib/ui/tabs/home_widget.dart
index aa05dedbc3..0f4e50e439 100644
--- a/mobile/apps/photos/lib/ui/tabs/home_widget.dart
+++ b/mobile/apps/photos/lib/ui/tabs/home_widget.dart
@@ -93,10 +93,7 @@ import "package:photos/utils/dialog_util.dart";
import "package:receive_sharing_intent/receive_sharing_intent.dart";
class HomeWidget extends StatefulWidget {
- const HomeWidget({
- super.key,
- this.startWithoutAccount = false,
- });
+ const HomeWidget({super.key, this.startWithoutAccount = false});
final bool startWithoutAccount;
@@ -164,8 +161,9 @@ class _HomeWidgetState extends State<HomeWidget> {
if (LocalSyncService.instance.hasCompletedFirstImportOrBypassed()) {
syncWidget();
}
- _tabChangedEventSubscription =
- Bus.instance.on<TabChangedEvent>().listen((event) {
+ _tabChangedEventSubscription = Bus.instance.on<TabChangedEvent>().listen((
+ event,
+ ) {
final previousTabIndex = _selectedTabIndex;
_selectedTabIndex = event.selectedIndex;
@@ -197,16 +195,18 @@ class _HomeWidgetState extends State<HomeWidget> {
Bus.instance.on<SubscriptionPurchasedEvent>().listen((event) {
setState(() {});
});
- _accountConfiguredEvent =
- Bus.instance.on<AccountConfiguredEvent>().listen((event) {
+ _accountConfiguredEvent = Bus.instance.on<AccountConfiguredEvent>().listen((
+ event,
+ ) {
setState(() {});
// fetch user flags on login
- if (!isOfflineMode) {
+ if (!isLocalGalleryMode) {
flagService.flags;
}
});
- _triggerLogoutEvent =
- Bus.instance.on<TriggerLogoutEvent>().listen((event) async {
+ _triggerLogoutEvent = Bus.instance.on<TriggerLogoutEvent>().listen((
+ event,
+ ) async {
await _autoLogoutAlert();
});
_loggedOutEvent = Bus.instance.on<UserLoggedOutEvent>().listen((event) {
@@ -216,8 +216,9 @@ class _HomeWidgetState extends State<HomeWidget> {
setState(() {});
}
});
- _permissionGrantedEvent =
- Bus.instance.on<PermissionGrantedEvent>().listen((event) async {
+ _permissionGrantedEvent = Bus.instance.on<PermissionGrantedEvent>().listen((
+ event,
+ ) async {
if (mounted) {
setState(() {});
}
@@ -226,13 +227,12 @@ class _HomeWidgetState extends State<HomeWidget> {
Bus.instance.on<AppModeChangedEvent>().listen((event) async {
if (mounted) {
setState(() {});
- _scheduleChangeLogCheck(
- delay: const Duration(milliseconds: 250),
- );
+ _scheduleChangeLogCheck(delay: const Duration(milliseconds: 250));
}
});
- _firstImportEvent =
- Bus.instance.on<SyncStatusUpdate>().listen((event) async {
+ _firstImportEvent = Bus.instance.on<SyncStatusUpdate>().listen((
+ event,
+ ) async {
if (mounted && event.status == SyncStatus.completedFirstGalleryImport) {
Duration delayInRefresh = const Duration(milliseconds: 0);
// Loading page will redirect to BackupFolderSelectionPage.
@@ -241,22 +241,19 @@ class _HomeWidgetState extends State<HomeWidget> {
if (!permissionService.hasGrantedLimitedPermissions()) {
delayInRefresh = const Duration(milliseconds: 250);
}
- Future.delayed(
- delayInRefresh,
- () {
- if (mounted) {
- setState(() {});
- syncWidget();
- if (!NotificationService.instance.hasGrantedPermissions() &&
- isOfflineMode &&
- !Configuration.instance.hasConfiguredAccount()) {
- Future.delayed(const Duration(seconds: 2), () {
- NotificationService.instance.requestPermissions().ignore();
- });
- }
+ Future.delayed(delayInRefresh, () {
+ if (mounted) {
+ setState(() {});
+ syncWidget();
+ if (!NotificationService.instance.hasGrantedPermissions() &&
+ isLocalGalleryMode &&
+ !Configuration.instance.hasConfiguredAccount()) {
+ Future.delayed(const Duration(seconds: 2), () {
+ NotificationService.instance.requestPermissions().ignore();
+ });
}
- },
- );
+ }
+ });
}
});
_backupFoldersUpdatedEvent =
@@ -265,18 +262,18 @@ class _HomeWidgetState extends State<HomeWidget> {
setState(() {});
}
});
- _collectionUpdatedEvent = Bus.instance.on<CollectionUpdatedEvent>().listen(
- (event) async {
- // only reset state if backup hook is shown. This is to ensure that
- // during first sync, we don't keep showing backup hook if user has
- // files
- if (mounted &&
- _showShowBackupHook &&
- event.type == EventType.addedOrUpdated) {
- setState(() {});
- }
- },
- );
+ _collectionUpdatedEvent = Bus.instance.on<CollectionUpdatedEvent>().listen((
+ event,
+ ) async {
+ // only reset state if backup hook is shown. This is to ensure that
+ // during first sync, we don't keep showing backup hook if user has
+ // files
+ if (mounted &&
+ _showShowBackupHook &&
+ event.type == EventType.addedOrUpdated) {
+ setState(() {});
+ }
+ });
_initDeepLinks();
updateService.shouldShowUpdateNotification().then((value) {
Future.delayed(Duration.zero, () {
@@ -285,9 +282,7 @@ class _HomeWidgetState extends State<HomeWidget> {
useRootNavigator: false,
context: context,
builder: (BuildContext context) {
- return AppUpdateDialog(
- updateService.getLatestVersionInfo(),
- );
+ return AppUpdateDialog(updateService.getLatestVersionInfo());
},
barrierColor: Colors.black.withValues(alpha: 0.85),
);
@@ -301,9 +296,7 @@ class _HomeWidgetState extends State<HomeWidget> {
// For sharing images coming from outside the app
_initMediaShareSubscription();
- _scheduleChangeLogCheck(
- delay: const Duration(seconds: 1),
- );
+ _scheduleChangeLogCheck(delay: const Duration(seconds: 1));
if (Platform.isAndroid &&
!localSettings.hasConfiguredInAppLinkPermissions() &&
@@ -334,7 +327,7 @@ class _HomeWidgetState extends State<HomeWidget> {
setState(() {});
}
});
- if (!isOfflineMode && Configuration.instance.hasConfiguredAccount()) {
+ if (!isLocalGalleryMode && Configuration.instance.hasConfiguredAccount()) {
MemoryShareService.instance.listMemoryShares().ignore();
}
}
@@ -348,9 +341,7 @@ class _HomeWidgetState extends State<HomeWidget> {
await MemoryHomeWidgetService.instance.checkPendingMemorySync();
}
- void _scheduleChangeLogCheck({
- required Duration delay,
- }) {
+ void _scheduleChangeLogCheck({required Duration delay}) {
WidgetsBinding.instance.addPostFrameCallback((_) {
Future.delayed(delay, () {
if (mounted) {
@@ -388,16 +379,15 @@ class _HomeWidgetState extends State<HomeWidget> {
return;
}
- final existingCollection =
- CollectionsService.instance.getCollectionByID(collection.id);
+ final existingCollection = CollectionsService.instance.getCollectionByID(
+ collection.id,
+ );
if (collection.isOwner(Configuration.instance.getUserID() ?? -1) ||
(existingCollection != null && !existingCollection.isDeleted)) {
await routeToPage(
context,
- CollectionPage(
- CollectionWithThumbnail(collection, null),
- ),
+ CollectionPage(CollectionWithThumbnail(collection, null)),
);
return;
}
@@ -458,10 +448,7 @@ class _HomeWidgetState extends State<HomeWidget> {
await routeToPage(
context,
SharedPublicCollectionPage(
- CollectionWithThumbnail(
- collection,
- null,
- ),
+ CollectionWithThumbnail(collection, null),
files: sharedFiles,
shouldShowJoinDialog: shouldShowJoinDialog,
),
@@ -489,10 +476,7 @@ class _HomeWidgetState extends State<HomeWidget> {
await routeToPage(
context,
SharedPublicCollectionPage(
- CollectionWithThumbnail(
- collection,
- null,
- ),
+ CollectionWithThumbnail(collection, null),
files: sharedFiles,
shouldShowJoinDialog: shouldShowJoinDialog,
),
@@ -609,9 +593,7 @@ class _HomeWidgetState extends State<HomeWidget> {
Navigator.of(context).pop(true);
},
),
- const SizedBox(
- height: 12,
- ),
+ const SizedBox(height: 12),
ButtonWidget(
buttonType: ButtonType.secondary,
labelText: AppLocalizations.of(context).backupFile,
@@ -628,9 +610,7 @@ class _HomeWidgetState extends State<HomeWidget> {
context,
MaterialPageRoute(
builder: (_) {
- return FileViewer(
- sharedMediaFile: value[0],
- );
+ return FileViewer(sharedMediaFile: value[0]);
},
),
);
@@ -650,9 +630,9 @@ class _HomeWidgetState extends State<HomeWidget> {
},
);
// For sharing images/public links coming from outside the app while the app is closed
- ReceiveSharingIntent.instance
- .getInitialMedia()
- .then((List<SharedMediaFile> value) {
+ ReceiveSharingIntent.instance.getInitialMedia().then((
+ List<SharedMediaFile> value,
+ ) {
if (mounted) {
// Check if this is a public album link
if (value.isNotEmpty && _isPublicAlbumUrl(value[0].path)) {
@@ -698,9 +678,7 @@ class _HomeWidgetState extends State<HomeWidget> {
(Platform.isAndroid && initialUri.scheme == "ente"))) {
await _handlePublicAlbumLink(initialUri, "appLinks.getInitialLink");
} else {
- _logger.info(
- "Ignoring deep link: $initialUri",
- );
+ _logger.info("Ignoring deep link: $initialUri");
}
} else {
_logger.info(
@@ -719,9 +697,7 @@ class _HomeWidgetState extends State<HomeWidget> {
(Platform.isAndroid && uri.scheme == "ente"))) {
_handlePublicAlbumLink(uri, "appLinks.uriLinkStream");
} else {
- _logger.info(
- "Ignoring deep link: $uri",
- );
+ _logger.info("Ignoring deep link: $uri");
}
} else {
_logger.info("No link received in public album link subscription.");
@@ -745,7 +721,7 @@ class _HomeWidgetState extends State<HomeWidget> {
final action = AppLifecycleService.instance.mediaExtensionAction.action;
final isOnOnlineGrantPermissionScreen =
Configuration.instance.hasConfiguredAccount() &&
- !isOfflineMode &&
+ !isLocalGalleryMode &&
_shouldShowPermissionWidget();
return UserDetailsStateWidget(
child: PopScope(
@@ -779,8 +755,9 @@ class _HomeWidgetState extends State<HomeWidget> {
return;
}
}
- Bus.instance
- .fire(TabChangedEvent(0, TabChangedEventSource.backButton));
+ Bus.instance.fire(
+ TabChangedEvent(0, TabChangedEventSource.backButton),
+ );
},
child: Scaffold(
drawerScrimColor: getEnteColorScheme(context).strokeFainter,
@@ -863,11 +840,11 @@ class _HomeWidgetState extends State<HomeWidget> {
IndexOfStackNotifier().index == 1;
final isOnLandingPage =
!Configuration.instance.hasConfiguredAccount() &&
- !isOfflineMode &&
+ !isLocalGalleryMode &&
!widget.startWithoutAccount;
final isOnOnlineGrantPermissionScreen =
Configuration.instance.hasConfiguredAccount() &&
- !isOfflineMode &&
+ !isLocalGalleryMode &&
_shouldShowPermissionWidget();
return AppBar(
backgroundColor: isOnLandingPage
@@ -890,24 +867,25 @@ class _HomeWidgetState extends State<HomeWidget> {
}
Widget _getBody(BuildContext context) {
- final bool offlineMode = isOfflineMode;
+ final bool localGalleryMode = isLocalGalleryMode;
if (!Configuration.instance.hasConfiguredAccount()) {
_closeDrawerIfOpen(context);
- final shouldBootstrapOfflineEntryFlow =
- widget.startWithoutAccount && !offlineMode;
- final hasPersistedOfflineMode = localSettings.isAppModeSet && offlineMode;
- final canResumePersistedOfflineMode =
- hasPersistedOfflineMode && permissionService.hasGrantedPermissions();
- final shouldUseOfflineEntryFlow =
- widget.startWithoutAccount || canResumePersistedOfflineMode;
-
- if (shouldBootstrapOfflineEntryFlow) {
+ final shouldBootstrapLocalGalleryEntryFlow =
+ widget.startWithoutAccount && !localGalleryMode;
+ final hasPersistedLocalGalleryMode =
+ localSettings.isAppModeSet && localGalleryMode;
+ final canResumePersistedLocalGalleryMode = hasPersistedLocalGalleryMode &&
+ permissionService.hasGrantedPermissions();
+ final shouldUseLocalGalleryEntryFlow =
+ widget.startWithoutAccount || canResumePersistedLocalGalleryMode;
+
+ if (shouldBootstrapLocalGalleryEntryFlow) {
return const GrantPermissionsWidget(startWithoutAccount: true);
}
- if (shouldUseOfflineEntryFlow && _shouldShowPermissionWidget()) {
+ if (shouldUseLocalGalleryEntryFlow && _shouldShowPermissionWidget()) {
return const GrantPermissionsWidget(startWithoutAccount: true);
}
- if (!shouldUseOfflineEntryFlow) {
+ if (!shouldUseLocalGalleryEntryFlow) {
return const LandingPageWidget();
}
}
@@ -951,10 +929,7 @@ class _HomeWidgetState extends State<HomeWidget> {
return ExtentsPageView(
onPageChanged: (page) {
Bus.instance.fire(
- TabChangedEvent(
- page,
- TabChangedEventSource.pageView,
- ),
+ TabChangedEvent(page, TabChangedEventSource.pageView),
);
},
controller: _pageController,
@@ -986,13 +961,16 @@ class _HomeWidgetState extends State<HomeWidget> {
final double pixels = notification.metrics.pixels;
if (pixels < 0) {
if (pixels < -maxPullOffset) {
- final scrollPosition =
- Scrollable.of(notification.context!).position;
+ final scrollPosition = Scrollable.of(
+ notification.context!,
+ ).position;
scrollPosition.correctBy(-maxPullOffset - pixels);
}
- final double clampedOffset =
- (-pixels).clamp(0.0, maxPullOffset);
+ final double clampedOffset = (-pixels).clamp(
+ 0.0,
+ maxPullOffset,
+ );
_christmasPullOffsetNotifier.value = clampedOffset;
if (_christmasPullReleasedNotifier.value) {
_christmasPullReleasedNotifier.value = false;
@@ -1009,9 +987,7 @@ class _HomeWidgetState extends State<HomeWidget> {
},
child: HomeGalleryWidget(
header: const HeaderWidget(),
- footer: const SizedBox(
- height: 160,
- ),
+ footer: const SizedBox(height: 160),
selectedFiles: _selectedFiles,
),
),
@@ -1098,7 +1074,7 @@ class _HomeWidgetState extends State<HomeWidget> {
try {
final action = await updateService.getChangeLogAction(
locale: Localizations.localeOf(context),
- isOffline: isOfflineMode,
+ isOffline: isLocalGalleryMode,
isSignedIn: Configuration.instance.isLoggedIn(),
);
if (!mounted || action == ChangeLogAction.skip) {
@@ -1172,10 +1148,7 @@ class _HomeWidgetState extends State<HomeWidget> {
if (!canOpenRitual) return;
// ignore: unawaited_futures
AppNavigationService.instance.pushPage(
- RitualCameraPage(
- ritualId: ritualId,
- albumId: albumId,
- ),
+ RitualCameraPage(ritualId: ritualId, albumId: albumId),
);
return;
}
@@ -1186,9 +1159,7 @@ class _HomeWidgetState extends State<HomeWidget> {
final target = FeedNavigationTarget.fromUri(uri);
// ignore: unawaited_futures
AppNavigationService.instance.pushPage(
- FeedScreen(
- initialTarget: target,
- ),
+ FeedScreen(initialTarget: target),
);
return;
}
@@ -1202,18 +1173,15 @@ class _HomeWidgetState extends State<HomeWidget> {
} else {
final collectionID = Uri.parse(payload).queryParameters["collectionID"];
if (collectionID != null) {
- final collection = CollectionsService.instance
- .getCollectionByID(int.parse(collectionID))!;
- final thumbnail =
- await CollectionsService.instance.getCover(collection);
+ final collection = CollectionsService.instance.getCollectionByID(
+ int.parse(collectionID),
+ )!;
+ final thumbnail = await CollectionsService.instance.getCover(
+ collection,
+ );
// ignore: unawaited_futures
AppNavigationService.instance.pushPage(
- CollectionPage(
- CollectionWithThumbnail(
- collection,
- thumbnail,
- ),
- ),
+ CollectionPage(CollectionWithThumbnail(collection, thumbnail)),
);
}
}
@@ -1236,7 +1204,7 @@ class _HomeWidgetState extends State<HomeWidget> {
}
bool _shouldShowLoadingWidget() {
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
return false;
}
if (flagService.enableOnlyBackupFuturePhotos) {
@@ -1250,7 +1218,7 @@ class _HomeWidgetState extends State<HomeWidget> {
}
bool _shouldShowBackupHook() {
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
return false;
}
final bool noFoldersSelected =
@@ -1267,7 +1235,7 @@ class _HomeWidgetState extends State<HomeWidget> {
if (_personSyncTriggered) {
return;
}
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
return;
}
_personSyncTriggered = true;
@@ -1280,7 +1248,7 @@ class _HomeWidgetState extends State<HomeWidget> {
if (_collectionsSyncTriggered) {
return;
}
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
return;
}
if (!(backupPreferenceService.hasSkippedOnboardingPermission ||
diff --git a/mobile/apps/photos/lib/ui/tabs/shared_collections_tab.dart b/mobile/apps/photos/lib/ui/tabs/shared_collections_tab.dart
index a49243783f..4e4356995f 100644
--- a/mobile/apps/photos/lib/ui/tabs/shared_collections_tab.dart
+++ b/mobile/apps/photos/lib/ui/tabs/shared_collections_tab.dart
@@ -88,15 +88,16 @@ class _SharedCollectionsTabState extends State<SharedCollectionsTab>
@override
void initState() {
super.initState();
- _localFilesSubscription =
- Bus.instance.on<LocalPhotosUpdatedEvent>().listen((event) {
- _debouncer.run(() async {
- if (mounted) {
- debugPrint("SetState Shared Collections on ${event.reason}");
- setState(() {});
- }
- });
- });
+ _localFilesSubscription = Bus.instance.on<LocalPhotosUpdatedEvent>().listen(
+ (event) {
+ _debouncer.run(() async {
+ if (mounted) {
+ debugPrint("SetState Shared Collections on ${event.reason}");
+ setState(() {});
+ }
+ });
+ },
+ );
_collectionUpdatesSubscription =
Bus.instance.on<CollectionUpdatedEvent>().listen((event) {
_debouncer.run(() async {
@@ -121,8 +122,9 @@ class _SharedCollectionsTabState extends State<SharedCollectionsTab>
_loggedOutEvent = Bus.instance.on<UserLoggedOutEvent>().listen((event) {
setState(() {});
});
- _appModeChangedEvent =
- Bus.instance.on<AppModeChangedEvent>().listen((event) {
+ _appModeChangedEvent = Bus.instance.on<AppModeChangedEvent>().listen((
+ event,
+ ) {
if (mounted) {
setState(() {});
}
@@ -222,7 +224,7 @@ class _SharedCollectionsTabState extends State<SharedCollectionsTab>
Widget build(BuildContext context) {
super.build(context);
final bool offlineUiMode =
- isOfflineMode && !Configuration.instance.hasConfiguredAccount();
+ isLocalGalleryMode && !Configuration.instance.hasConfiguredAccount();
return FutureBuilder<SharedCollectionsAndMemoryLinks>(
future: offlineUiMode
? Future.value(SharedCollectionsAndMemoryLinks.empty())
@@ -231,9 +233,7 @@ class _SharedCollectionsTabState extends State<SharedCollectionsTab>
if (snapshot.hasData) {
final data = snapshot.data!;
if (offlineUiMode) {
- return const SafeArea(
- child: SharedEmptyOfflineStateWidget(),
- );
+ return const SafeArea(child: SharedEmptyOfflineStateWidget());
}
if (data.collections.incoming.isEmpty &&
data.collections.quickLinks.isEmpty &&
@@ -278,10 +278,12 @@ class _SharedCollectionsTabState extends State<SharedCollectionsTab>
albumsCountInRow;
const quickLinkTitleHeroTag = "quick_link_title";
const memoryLinkTitleHeroTag = "memory_link_title";
- final SectionTitle sharedWithYou =
- SectionTitle(title: AppLocalizations.of(context).sharedWithYou);
- final SectionTitle sharedByYou =
- SectionTitle(title: AppLocalizations.of(context).sharedByYou);
+ final SectionTitle sharedWithYou = SectionTitle(
+ title: AppLocalizations.of(context).sharedWithYou,
+ );
+ final SectionTitle sharedByYou = SectionTitle(
+ title: AppLocalizations.of(context).sharedByYou,
+ );
final colorTheme = getEnteColorScheme(context);
return SingleChildScrollView(
physics: const BouncingScrollPhysics(),
@@ -439,9 +441,7 @@ class _SharedCollectionsTabState extends State<SharedCollectionsTab>
? SizedBox(
height: sideOfThumbnail + 46,
child: ListView.builder(
- padding: const EdgeInsets.symmetric(
- horizontal: 8,
- ),
+ padding: const EdgeInsets.symmetric(horizontal: 8),
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
return Padding(
@@ -577,9 +577,11 @@ class _SharedCollectionsTabState extends State<SharedCollectionsTab>
physics: const NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
final share = memoryLinks[index];
- final title = MemoryShareService.instance
- .getMemoryShareTitle(share) ??
- "Memory link";
+ final title =
+ MemoryShareService.instance.getMemoryShareTitle(
+ share,
+ ) ??
+ "Memory link";
return GestureDetector(
onTap: () async {
final deleted = await showMemoryLinkDetailsSheet(
diff --git a/mobile/apps/photos/lib/ui/tabs/user_collections_tab.dart b/mobile/apps/photos/lib/ui/tabs/user_collections_tab.dart
index 4bf68a03a5..96d65c25c5 100644
--- a/mobile/apps/photos/lib/ui/tabs/user_collections_tab.dart
+++ b/mobile/apps/photos/lib/ui/tabs/user_collections_tab.dart
@@ -68,15 +68,16 @@ class _UserCollectionsTabState extends State<UserCollectionsTab>
@override
void initState() {
super.initState();
- _localFilesSubscription =
- Bus.instance.on<LocalPhotosUpdatedEvent>().listen((event) {
- _debouncer.run(() async {
- if (mounted) {
- _loadReason = event.reason;
- setState(() {});
- }
- });
- });
+ _localFilesSubscription = Bus.instance.on<LocalPhotosUpdatedEvent>().listen(
+ (event) {
+ _debouncer.run(() async {
+ if (mounted) {
+ _loadReason = event.reason;
+ setState(() {});
+ }
+ });
+ },
+ );
_collectionUpdatesSubscription =
Bus.instance.on<CollectionUpdatedEvent>().listen((event) {
_debouncer.run(() async {
@@ -120,7 +121,7 @@ class _UserCollectionsTabState extends State<UserCollectionsTab>
super.build(context);
_logger.info("Building, trigger: $_loadReason");
final bool offlineUiMode =
- isOfflineMode && !Configuration.instance.hasConfiguredAccount();
+ isLocalGalleryMode && !Configuration.instance.hasConfiguredAccount();
return FutureBuilder<List<Collection>>(
future: offlineUiMode
? Future.value(<Collection>[])
@@ -146,11 +147,9 @@ class _UserCollectionsTabState extends State<UserCollectionsTab>
}) {
final TextStyle trashAndHiddenTextStyle =
Theme.of(context).textTheme.titleMedium!.copyWith(
- color: Theme.of(context)
- .textTheme
- .titleMedium!
- .color!
- .withValues(alpha: 0.5),
+ color: Theme.of(
+ context,
+ ).textTheme.titleMedium!.color!.withValues(alpha: 0.5),
);
final colorScheme = getEnteColorScheme(context);
@@ -184,39 +183,40 @@ class _UserCollectionsTabState extends State<UserCollectionsTab>
title: AppLocalizations.of(context).onDevice,
),
),
- trailingWidget: backupPreferenceService
- .hasSkippedOnboardingPermission
- ? null
- : Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- IconButtonWidget(
- icon: Icons.search,
- iconButtonType: IconButtonType.secondary,
- iconColor: colorScheme.blurStrokePressed,
- onTap: () {
- unawaited(
- routeToPage(
- context,
- DeviceFolderVerticalGridView(
- appTitle: SectionTitle(
- title:
- AppLocalizations.of(context).onDevice,
+ trailingWidget:
+ backupPreferenceService.hasSkippedOnboardingPermission
+ ? null
+ : Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ IconButtonWidget(
+ icon: Icons.search,
+ iconButtonType: IconButtonType.secondary,
+ iconColor: colorScheme.blurStrokePressed,
+ onTap: () {
+ unawaited(
+ routeToPage(
+ context,
+ DeviceFolderVerticalGridView(
+ appTitle: SectionTitle(
+ title: AppLocalizations.of(
+ context,
+ ).onDevice,
+ ),
+ tag: "OnDeviceAppTitle",
+ startInSearchMode: true,
+ ),
),
- tag: "OnDeviceAppTitle",
- startInSearchMode: true,
- ),
- ),
- );
- },
- ),
- IconButtonWidget(
- icon: Icons.chevron_right,
- iconButtonType: IconButtonType.secondary,
- iconColor: colorScheme.blurStrokePressed,
+ );
+ },
+ ),
+ IconButtonWidget(
+ icon: Icons.chevron_right,
+ iconButtonType: IconButtonType.secondary,
+ iconColor: colorScheme.blurStrokePressed,
+ ),
+ ],
),
- ],
- ),
),
),
const SliverToBoxAdapter(child: DeviceFoldersGridView()),
@@ -275,9 +275,7 @@ class _UserCollectionsTabState extends State<UserCollectionsTab>
),
SliverToBoxAdapter(child: DeleteEmptyAlbums(collections)),
offlineUiMode
- ? const SliverToBoxAdapter(
- child: EmptyOnEnteSection(),
- )
+ ? const SliverToBoxAdapter(child: EmptyOnEnteSection())
: Configuration.instance.hasConfiguredAccount()
? CollectionsFlexiGridViewWidget(
collections,
@@ -290,9 +288,7 @@ class _UserCollectionsTabState extends State<UserCollectionsTab>
: const SliverToBoxAdapter(child: EmptyState()),
if (!offlineUiMode) ...[
SliverToBoxAdapter(
- child: Divider(
- color: colorScheme.strokeFaint,
- ),
+ child: Divider(color: colorScheme.strokeFaint),
),
const SliverToBoxAdapter(child: SizedBox(height: 12)),
SliverToBoxAdapter(
@@ -313,8 +309,9 @@ class _UserCollectionsTabState extends State<UserCollectionsTab>
),
],
SliverToBoxAdapter(
- child:
- SizedBox(height: 64 + MediaQuery.paddingOf(context).bottom),
+ child: SizedBox(
+ height: 64 + MediaQuery.paddingOf(context).bottom,
+ ),
),
],
),
diff --git a/mobile/apps/photos/lib/ui/viewer/actions/file_selection_actions_widget.dart b/mobile/apps/photos/lib/ui/viewer/actions/file_selection_actions_widget.dart
index a175ed1e5e..390492210c 100644
--- a/mobile/apps/photos/lib/ui/viewer/actions/file_selection_actions_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/actions/file_selection_actions_widget.dart
@@ -90,8 +90,9 @@ class _FileSelectionActionsWidgetState
bool get _canRemoveOthersFiles =>
widget.collection != null &&
- CollectionsService.instance
- .canRemoveFilesFromAllParticipants(widget.collection!);
+ CollectionsService.instance.canRemoveFilesFromAllParticipants(
+ widget.collection!,
+ );
@override
void initState() {
@@ -142,14 +143,14 @@ class _FileSelectionActionsWidgetState
ownedAndPendingUploadFilesCount > 0 && split.ownedByOtherUsers.isEmpty;
final bool anyUploadedFiles = split.ownedByCurrentUser.isNotEmpty;
- final bool hasUploadedFileIDs =
- widget.selectedFiles.files.any((file) => file.uploadedFileID != null);
- final showCollageOption = CollageCreatorPage.isValidCount(
- widget.selectedFiles.files.length,
- ) &&
- !widget.selectedFiles.files.any(
- (element) => element.fileType == FileType.video,
- );
+ final bool hasUploadedFileIDs = widget.selectedFiles.files.any(
+ (file) => file.uploadedFileID != null,
+ );
+ final showCollageOption =
+ CollageCreatorPage.isValidCount(widget.selectedFiles.files.length) &&
+ !widget.selectedFiles.files.any(
+ (element) => element.fileType == FileType.video,
+ );
final showDownloadOption = hasUploadedFileIDs;
final bool isCollectionOwnerOrAdmin = widget.collection != null &&
(widget.collection!.isOwner(currentUserID) ||
@@ -230,8 +231,9 @@ class _FileSelectionActionsWidgetState
items.add(
SelectionActionButton(
icon: Icons.remove_circle_outline,
- labelText: AppLocalizations.of(context)
- .notPersonLabel(name: widget.person!.data.name),
+ labelText: AppLocalizations.of(
+ context,
+ ).notPersonLabel(name: widget.person!.data.name),
onTap: _onNotpersonClicked,
),
);
@@ -258,7 +260,7 @@ class _FileSelectionActionsWidgetState
final showUploadIcon = widget.type == GalleryType.localFolder &&
split.ownedByCurrentUser.isEmpty;
- if (widget.type.showAddToAlbum() && !isOfflineMode) {
+ if (widget.type.showAddToAlbum() && !isLocalGalleryMode) {
if (showUploadIcon) {
items.add(
SelectionActionButton(
@@ -552,9 +554,7 @@ class _FileSelectionActionsWidgetState
Future<void> _editLocation() async {
await showBarModalBottomSheet(
shape: const RoundedRectangleBorder(
- borderRadius: BorderRadius.vertical(
- top: Radius.circular(5),
- ),
+ borderRadius: BorderRadius.vertical(top: Radius.circular(5)),
),
backgroundColor: getEnteColorScheme(context).backgroundElevated,
barrierColor: backdropFaintDark,
@@ -572,37 +572,33 @@ class _FileSelectionActionsWidgetState
width: 40,
decoration: const BoxDecoration(
color: backgroundElevated2Light,
- borderRadius: BorderRadius.all(
- Radius.circular(5),
- ),
+ borderRadius: BorderRadius.all(Radius.circular(5)),
),
),
],
),
context: context,
builder: (context) {
- return UpdateLocationDataWidget(
- widget.selectedFiles.files.toList(),
- );
+ return UpdateLocationDataWidget(widget.selectedFiles.files.toList());
},
);
}
Future<void> _shareSelectedFiles() async {
- shareSelected(
- context,
- shareButtonKey,
- widget.selectedFiles.files.toList(),
- );
+ shareSelected(context, shareButtonKey, widget.selectedFiles.files.toList());
widget.selectedFiles.clearAll();
}
Future<void> _moveFiles() async {
if (split.pendingUploads.isNotEmpty || split.ownedByOtherUsers.isNotEmpty) {
- widget.selectedFiles
- .unSelectAll(split.pendingUploads.toSet(), skipNotify: true);
- widget.selectedFiles
- .unSelectAll(split.ownedByOtherUsers.toSet(), skipNotify: true);
+ widget.selectedFiles.unSelectAll(
+ split.pendingUploads.toSet(),
+ skipNotify: true,
+ );
+ widget.selectedFiles.unSelectAll(
+ split.ownedByOtherUsers.toSet(),
+ skipNotify: true,
+ );
}
showCollectionActionSheet(
context,
@@ -648,17 +644,11 @@ class _FileSelectionActionsWidgetState
await CollectionsService.instance.rejectDeleteSuggestions(fileIDs);
widget.selectedFiles.clearAll();
Bus.instance.fire(
- FilesUpdatedEvent(
- const [],
- source: "reject-delete-suggestions",
- ),
+ FilesUpdatedEvent(const [], source: "reject-delete-suggestions"),
);
} catch (e, s) {
_logger.warning("Failed to reject delete suggestions", e, s);
- await showGenericErrorDialog(
- context: context,
- error: e,
- );
+ await showGenericErrorDialog(context: context, error: e);
}
}
@@ -691,12 +681,16 @@ class _FileSelectionActionsWidgetState
Future<void> _removeFilesFromAlbum() async {
if (split.pendingUploads.isNotEmpty) {
- widget.selectedFiles
- .unSelectAll(split.pendingUploads.toSet(), skipNotify: true);
+ widget.selectedFiles.unSelectAll(
+ split.pendingUploads.toSet(),
+ skipNotify: true,
+ );
}
if (!_canRemoveOthersFiles && split.ownedByOtherUsers.isNotEmpty) {
- widget.selectedFiles
- .unSelectAll(split.ownedByOtherUsers.toSet(), skipNotify: true);
+ widget.selectedFiles.unSelectAll(
+ split.ownedByOtherUsers.toSet(),
+ skipNotify: true,
+ );
}
final bool removingOthersFile =
_canRemoveOthersFiles && split.ownedByOtherUsers.isNotEmpty;
@@ -751,8 +745,9 @@ class _FileSelectionActionsWidgetState
);
return;
}
- final namedPersons =
- await AddFilesToPersonPage.prefetchNamedPersons(context);
+ final namedPersons = await AddFilesToPersonPage.prefetchNamedPersons(
+ context,
+ );
if (!mounted) {
return;
}
@@ -761,10 +756,7 @@ class _FileSelectionActionsWidgetState
}
final result = await routeToPage(
context,
- AddFilesToPersonPage(
- files: filesWithIds,
- initialPersons: namedPersons,
- ),
+ AddFilesToPersonPage(files: filesWithIds, initialPersons: namedPersons),
forceCustomPageRoute: true,
);
if (result is! ManualPersonAssignmentResult) {
@@ -866,10 +858,14 @@ class _FileSelectionActionsWidgetState
Future<void> _onUnhideClick() async {
if (split.pendingUploads.isNotEmpty || split.ownedByOtherUsers.isNotEmpty) {
- widget.selectedFiles
- .unSelectAll(split.pendingUploads.toSet(), skipNotify: true);
- widget.selectedFiles
- .unSelectAll(split.ownedByOtherUsers.toSet(), skipNotify: true);
+ widget.selectedFiles.unSelectAll(
+ split.pendingUploads.toSet(),
+ skipNotify: true,
+ );
+ widget.selectedFiles.unSelectAll(
+ split.ownedByOtherUsers.toSet(),
+ skipNotify: true,
+ );
}
showCollectionActionSheet(
context,
@@ -919,8 +915,10 @@ class _FileSelectionActionsWidgetState
Future<void> _setPersonCover() async {
final EnteFile file = widget.selectedFiles.files.first;
- final updatedPerson =
- await PersonService.instance.updateAvatar(widget.person!, file);
+ final updatedPerson = await PersonService.instance.updateAvatar(
+ widget.person!,
+ file,
+ );
widget.selectedFiles.clearAll();
if (mounted) {
setState(() => {});
@@ -956,8 +954,9 @@ class _FileSelectionActionsWidgetState
isInAlert: true,
),
],
- body: AppLocalizations.of(context)
- .selectedItemsWillBeRemovedFromThisPerson,
+ body: AppLocalizations.of(
+ context,
+ ).selectedItemsWillBeRemovedFromThisPerson,
actionSheetType: ActionSheetType.defaultActionSheet,
);
if (actionResult?.action != null) {
@@ -1002,8 +1001,9 @@ class _FileSelectionActionsWidgetState
isInAlert: true,
),
],
- body:
- AppLocalizations.of(context).selectedItemsWillBeRemovedFromThisPerson,
+ body: AppLocalizations.of(
+ context,
+ ).selectedItemsWillBeRemovedFromThisPerson,
actionSheetType: ActionSheetType.defaultActionSheet,
);
if (actionResult?.action != null) {
@@ -1043,10 +1043,7 @@ class _FileSelectionActionsWidgetState
}
Future<void> _permanentlyDelete() async {
- if (await deleteFromTrash(
- context,
- widget.selectedFiles.files.toList(),
- )) {
+ if (await deleteFromTrash(context, widget.selectedFiles.files.toList())) {
widget.selectedFiles.clearAll();
}
}
@@ -1102,9 +1099,7 @@ class _FileSelectionActionsWidgetState
final l10n = AppLocalizations.of(context);
final existingLocalFolderNames = await Future.wait(
- files.map(
- (file) => getExistingLocalFolderNameForDownloadSkipToast(file),
- ),
+ files.map((file) => getExistingLocalFolderNameForDownloadSkipToast(file)),
);
final filesToDownload = <EnteFile>[];
@@ -1193,11 +1188,7 @@ class _FileSelectionActionsWidgetState
fileCount: skippedFilesCount,
);
}
- showToast(
- context,
- finalMessage,
- iosLongToastLengthInSec: 4,
- );
+ showToast(context, finalMessage, iosLongToastLengthInSec: 4);
}
if (!flagService.internalUser &&
diff --git a/mobile/apps/photos/lib/ui/viewer/file/file_app_bar.dart b/mobile/apps/photos/lib/ui/viewer/file/file_app_bar.dart
index 8b1db9362b..cdfb5998cc 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/file_app_bar.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/file_app_bar.dart
@@ -89,8 +89,9 @@ class FileAppBarState extends State<FileAppBar> {
@override
void initState() {
super.initState();
- _guestViewEventSubscription =
- Bus.instance.on<GuestViewEvent>().listen((event) {
+ _guestViewEventSubscription = Bus.instance.on<GuestViewEvent>().listen((
+ event,
+ ) {
setState(() {
isGuestView = event.isGuestView;
});
@@ -98,12 +99,14 @@ class FileAppBarState extends State<FileAppBar> {
// Listen to shared collection and thumbnail fallback changes to rebuild actions
WidgetsBinding.instance.addPostFrameCallback((_) {
- final sharedNotifier = InheritedDetailPageState.maybeOf(context)
- ?.isInSharedCollectionNotifier;
+ final sharedNotifier = InheritedDetailPageState.maybeOf(
+ context,
+ )?.isInSharedCollectionNotifier;
sharedNotifier?.addListener(_onSharedCollectionChanged);
- final fallbackNotifier = InheritedDetailPageState.maybeOf(context)
- ?.showingThumbnailFallbackNotifier;
+ final fallbackNotifier = InheritedDetailPageState.maybeOf(
+ context,
+ )?.showingThumbnailFallbackNotifier;
fallbackNotifier?.addListener(_onThumbnailFallbackChanged);
});
}
@@ -118,9 +121,9 @@ class FileAppBarState extends State<FileAppBar> {
@override
void dispose() {
- InheritedDetailPageState.maybeOf(context)
- ?.isInSharedCollectionNotifier
- .removeListener(_onSharedCollectionChanged);
+ InheritedDetailPageState.maybeOf(
+ context,
+ )?.isInSharedCollectionNotifier.removeListener(_onSharedCollectionChanged);
InheritedDetailPageState.maybeOf(context)
?.showingThumbnailFallbackNotifier
.removeListener(_onThumbnailFallbackChanged);
@@ -227,9 +230,9 @@ class FileAppBarState extends State<FileAppBar> {
_actions.clear();
// Show info icon when thumbnail fallback is active for THIS file
- final fallbackFileId = InheritedDetailPageState.maybeOf(context)
- ?.showingThumbnailFallbackNotifier
- .value;
+ final fallbackFileId = InheritedDetailPageState.maybeOf(
+ context,
+ )?.showingThumbnailFallbackNotifier.value;
final currentFileId = detailPageFileIdentifier(widget.file);
final showingFallback =
fallbackFileId != null && fallbackFileId == currentFileId;
@@ -246,10 +249,7 @@ class FileAppBarState extends State<FileAppBar> {
color: backgroundElevated2Dark,
borderRadius: BorderRadius.circular(8),
),
- textStyle: const TextStyle(
- color: Colors.white,
- fontSize: 14,
- ),
+ textStyle: const TextStyle(color: Colors.white, fontSize: 14),
preferBelow: true,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
@@ -268,9 +268,9 @@ class FileAppBarState extends State<FileAppBar> {
final Collection? collection = collectionID != null
? CollectionsService.instance.getCollectionByID(collectionID)
: null;
- final isInSharedCollection = InheritedDetailPageState.maybeOf(context)
- ?.isInSharedCollectionNotifier
- .value ??
+ final isInSharedCollection = InheritedDetailPageState.maybeOf(
+ context,
+ )?.isInSharedCollectionNotifier.value ??
false;
bool isFileHidden = false;
if (isOwnedByUser && isFileUploaded) {
@@ -294,16 +294,11 @@ class FileAppBarState extends State<FileAppBar> {
);
}
if (!isFileHidden && isFileUploaded && widget.file is! TrashFile) {
- _actions.add(
- Center(child: FavoriteWidget(widget.file)),
- );
+ _actions.add(Center(child: FavoriteWidget(widget.file)));
}
- if (!isFileUploaded && !isOfflineMode) {
+ if (!isFileUploaded && !isLocalGalleryMode) {
_actions.add(
- UploadIconWidget(
- file: widget.file,
- key: ValueKey(widget.file.tag),
- ),
+ UploadIconWidget(file: widget.file, key: ValueKey(widget.file.tag)),
);
}
@@ -607,8 +602,9 @@ class FileAppBarState extends State<FileAppBar> {
Future<void> _handleHideRequest(BuildContext context) async {
try {
- final hideResult =
- await CollectionsService.instance.hideFiles(context, [widget.file]);
+ final hideResult = await CollectionsService.instance.hideFiles(context, [
+ widget.file,
+ ]);
if (hideResult) {
widget.onFileRemoved(widget.file);
}
@@ -633,7 +629,9 @@ class FileAppBarState extends State<FileAppBar> {
widget.file.magicMetadata.visibility == archiveVisibility;
await changeVisibility(
context,
- [widget.file],
+ [
+ widget.file,
+ ],
isArchived ? visibleVisibility : archiveVisibility,
);
if (mounted) {
@@ -668,7 +666,9 @@ class FileAppBarState extends State<FileAppBar> {
if (flagService.internalUser) {
try {
await galleryDownloadQueueService.enqueueFiles(
- [fileToDownload],
+ [
+ fileToDownload,
+ ],
persistToFilesDB: persistToFilesDB,
);
} catch (e) {
@@ -719,19 +719,19 @@ class FileAppBarState extends State<FileAppBar> {
await dialog.hide();
return;
}
- final String url =
- CollectionsService.instance.getPublicUrl(sharedLinkCollection);
+ final String url = CollectionsService.instance.getPublicUrl(
+ sharedLinkCollection,
+ );
await dialog.hide();
unawaited(Clipboard.setData(ClipboardData(text: url)));
- await shareLinkWithDescription(
- url,
- context: context,
- );
+ await shareLinkWithDescription(url, context: context);
}
Future<void> _setAs(EnteFile file) async {
- final dialog =
- createProgressDialog(context, AppLocalizations.of(context).pleaseWait);
+ final dialog = createProgressDialog(
+ context,
+ AppLocalizations.of(context).pleaseWait,
+ );
await dialog.show();
try {
final File? fileToSave = await (getFile(file));
@@ -804,15 +804,14 @@ class FileAppBarState extends State<FileAppBar> {
Future<void> _handleVideoStream(String streamType) async {
try {
- final bool wasAdded = await VideoPreviewService.instance
- .addToManualQueue(widget.file, streamType);
+ final bool wasAdded = await VideoPreviewService.instance.addToManualQueue(
+ widget.file,
+ streamType,
+ );
if (!wasAdded) {
// File was already in queue
- showToast(
- context,
- AppLocalizations.of(context).videoAlreadyInQueue,
- );
+ showToast(context, AppLocalizations.of(context).videoAlreadyInQueue);
return;
}
diff --git a/mobile/apps/photos/lib/ui/viewer/file/thumbnail_widget.dart b/mobile/apps/photos/lib/ui/viewer/file/thumbnail_widget.dart
index 6f6ea6ab46..446f1f70ce 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/thumbnail_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/thumbnail_widget.dart
@@ -188,10 +188,7 @@ class _ThumbnailWidgetState extends State<ThumbnailWidget> {
final galleryContext = GalleryContextState.of(context);
Widget? image;
if (_imageProvider != null) {
- image = Image(
- image: _imageProvider!,
- fit: widget.fit,
- );
+ image = Image(image: _imageProvider!, fit: widget.fit);
}
// todo: [2ndJuly22] pref-review if the content Widget which depends on
// thumbnail fetch logic should be part of separate stateFull widget.
@@ -220,11 +217,11 @@ class _ThumbnailWidgetState extends State<ThumbnailWidget> {
}
if (shouldShowOwnerAvatar) {
if (!widget.file.isOwner) {
- final owner = CollectionsService.instance
- .getFileOwner(widget.file.ownerID!, widget.file.collectionID);
- contentChildren.add(
- OwnerAvatarOverlayIcon(owner),
+ final owner = CollectionsService.instance.getFileOwner(
+ widget.file.ownerID!,
+ widget.file.collectionID,
);
+ contentChildren.add(OwnerAvatarOverlayIcon(owner));
} else if (widget.file.isCollect) {
contentChildren.add(
// Use -1 as userID for enforcing black avatar color
@@ -236,10 +233,7 @@ class _ThumbnailWidgetState extends State<ThumbnailWidget> {
}
content = contentChildren.length == 1
? contentChildren.first
- : Stack(
- fit: StackFit.expand,
- children: contentChildren,
- );
+ : Stack(fit: StackFit.expand, children: contentChildren);
}
final List<Widget> viewChildren = [
const ThumbnailPlaceHolder(),
@@ -247,16 +241,14 @@ class _ThumbnailWidgetState extends State<ThumbnailWidget> {
];
if (!widget.rawThumbnail && widget.file.fileType == FileType.video) {
if (widget.shouldShowVideoDuration) {
- viewChildren.add(
- VideoOverlayDuration(duration: widget.file.duration),
- );
+ viewChildren.add(VideoOverlayDuration(duration: widget.file.duration));
} else if (widget.shouldShowVideoOverlayIcon) {
viewChildren.add(const VideoOverlayIcon());
}
}
if (widget.shouldShowSyncStatus &&
!widget.file.isUploaded &&
- !isOfflineMode) {
+ !isLocalGalleryMode) {
viewChildren.add(const UnSyncedIcon());
}
@@ -313,8 +305,10 @@ class _ThumbnailWidgetState extends State<ThumbnailWidget> {
!_errorLoadingLocalThumbnail &&
!_isLoadingLocalThumbnail) {
_isLoadingLocalThumbnail = true;
- final cachedSmallThumbnail =
- ThumbnailInMemoryLruCache.get(widget.file, _localCacheThumbnailSize);
+ final cachedSmallThumbnail = ThumbnailInMemoryLruCache.get(
+ widget.file,
+ _localCacheThumbnailSize,
+ );
if (cachedSmallThumbnail != null) {
final imageProvider = Image.memory(
cachedSmallThumbnail,
diff --git a/mobile/apps/photos/lib/ui/viewer/file_details/file_info_face_widget.dart b/mobile/apps/photos/lib/ui/viewer/file_details/file_info_face_widget.dart
index 6c94084013..05d1ee79a1 100644
--- a/mobile/apps/photos/lib/ui/viewer/file_details/file_info_face_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file_details/file_info_face_widget.dart
@@ -11,7 +11,7 @@ import "package:photos/models/base/id.dart";
import "package:photos/models/file/file.dart";
import "package:photos/models/ml/face/face.dart";
import "package:photos/models/ml/face/person.dart";
-import "package:photos/service_locator.dart" show isOfflineMode;
+import "package:photos/service_locator.dart" show isLocalGalleryMode;
import "package:photos/services/machine_learning/face_ml/face_detection/detection.dart";
import "package:photos/services/machine_learning/face_ml/face_filtering/face_filtering_constants.dart";
import "package:photos/services/machine_learning/face_ml/feedback/cluster_feedback.dart";
@@ -74,7 +74,7 @@ class _FileInfoFaceWidgetState extends State<FileInfoFaceWidget> {
onTap: isEditMode
? hasPerson
? _onMinusIconTap
- : (isOfflineMode ? null : _onPlusIconTap)
+ : (isLocalGalleryMode ? null : _onPlusIconTap)
: _routeToPersonOrClusterPage,
child: Container(
height: thumbnailWidth,
@@ -162,30 +162,27 @@ class _FileInfoFaceWidgetState extends State<FileInfoFaceWidget> {
Future<void> _routeToPersonOrClusterPage() async {
final mlDataDB =
- isOfflineMode ? MLDataDB.offlineInstance : MLDataDB.instance;
- if (!isOfflineMode && widget.person != null) {
+ isLocalGalleryMode ? MLDataDB.offlineInstance : MLDataDB.instance;
+ if (!isLocalGalleryMode && widget.person != null) {
await Navigator.of(context).push(
MaterialPageRoute(
- builder: (context) => PeoplePage(
- person: widget.person!,
- searchResult: null,
- ),
+ builder: (context) =>
+ PeoplePage(person: widget.person!, searchResult: null),
),
);
return;
}
final String? clusterID = widget.clusterID ??
- await mlDataDB.getClusterIDForFaceID(
- widget.face.faceID,
- );
+ await mlDataDB.getClusterIDForFaceID(widget.face.faceID);
if (clusterID != null) {
final fileIdsToClusterIds = await mlDataDB.getFileIdToClusterIds();
final files = await SearchService.instance.getAllFilesForSearch();
List<EnteFile> clusterFiles;
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
final localIntIds = fileIdsToClusterIds.keys.toSet();
- final localIdMap =
- await OfflineFilesDB.instance.getLocalIdsForIntIds(localIntIds);
+ final localIdMap = await OfflineFilesDB.instance.getLocalIdsForIntIds(
+ localIntIds,
+ );
final localIdToFile = <String, EnteFile>{};
for (final file in files) {
final localId = file.localID;
@@ -219,37 +216,30 @@ class _FileInfoFaceWidgetState extends State<FileInfoFaceWidget> {
builder: (context) => ClusterPage(
clusterFiles,
clusterID: clusterID,
- showNamingBanner: !isOfflineMode,
+ showNamingBanner: !isLocalGalleryMode,
),
),
);
return;
}
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
return;
}
if (widget.face.score <= kMinimumQualityFaceScore) {
// The face score is too low for automatic clustering,
// assigning a manual new clusterID so that the user can cluster it manually
final String clusterID = newClusterID();
- await mlDataDB.updateFaceIdToClusterId(
- {widget.face.faceID: clusterID},
- );
+ await mlDataDB.updateFaceIdToClusterId({widget.face.faceID: clusterID});
await Navigator.of(context).push(
MaterialPageRoute(
- builder: (context) => ClusterPage(
- [widget.file],
- clusterID: clusterID,
- ),
+ builder: (context) =>
+ ClusterPage([widget.file], clusterID: clusterID),
),
);
return;
}
- showShortToast(
- context,
- AppLocalizations.of(context).faceNotClusteredYet,
- );
+ showShortToast(context, AppLocalizations.of(context).faceNotClusteredYet);
unawaited(MLService.instance.clusterAllImages(force: true));
return;
}
diff --git a/mobile/apps/photos/lib/ui/viewer/file_details/file_info_faces_item_widget.dart b/mobile/apps/photos/lib/ui/viewer/file_details/file_info_faces_item_widget.dart
index 69a6bc1f2f..abd018a54f 100644
--- a/mobile/apps/photos/lib/ui/viewer/file_details/file_info_faces_item_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file_details/file_info_faces_item_widget.dart
@@ -12,7 +12,8 @@ import "package:photos/generated/l10n.dart";
import "package:photos/models/file/file.dart";
import "package:photos/models/ml/face/face.dart";
import "package:photos/models/ml/face/person.dart";
-import "package:photos/service_locator.dart" show flagService, isOfflineMode;
+import "package:photos/service_locator.dart"
+ show flagService, isLocalGalleryMode;
import "package:photos/services/machine_learning/face_ml/face_filtering/face_filtering_constants.dart";
import "package:photos/services/machine_learning/face_ml/feedback/cluster_feedback.dart";
import "package:photos/services/machine_learning/face_ml/person/person_service.dart"
@@ -199,7 +200,7 @@ class _FacesItemWidgetState extends State<FacesItemWidget> {
}
// Add "Add person" button at the end
- if (!isOfflineMode &&
+ if (!isLocalGalleryMode &&
flagService.manualTagFileToPerson &&
widget.file.uploadedFileID != null) {
children.add(_buildAddPersonButton(thumbnailWidth));
@@ -207,11 +208,7 @@ class _FacesItemWidgetState extends State<FacesItemWidget> {
return Padding(
padding: const EdgeInsets.only(right: 12.0),
- child: Wrap(
- runSpacing: 8,
- spacing: 12,
- children: children,
- ),
+ child: Wrap(runSpacing: 8, spacing: 12, children: children),
);
}
@@ -333,7 +330,7 @@ class _FacesItemWidgetState extends State<FacesItemWidget> {
Widget _buildNoFacesWidget() {
final reason = _errorReason ?? NoFacesReason.noFacesFound;
- final showManualTagOption = !isOfflineMode &&
+ final showManualTagOption = !isLocalGalleryMode &&
flagService.manualTagFileToPerson &&
reason == NoFacesReason.noFacesFound;
final label = showManualTagOption
@@ -414,7 +411,7 @@ class _FacesItemWidgetState extends State<FacesItemWidget> {
}
Widget _editStateButton() {
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
return const SizedBox.shrink();
}
if (_isEditMode) {
@@ -455,7 +452,7 @@ class _FacesItemWidgetState extends State<FacesItemWidget> {
}
Future<_FaceDataResult> _fetchFaceData() async {
- final bool isOffline = isOfflineMode;
+ final bool isOffline = isLocalGalleryMode;
int? fileKey;
if (isOffline) {
final localId = widget.file.localID;
@@ -509,8 +506,11 @@ class _FacesItemWidgetState extends State<FacesItemWidget> {
final clusterIDToPerson = isOffline
? <String, String>{}
: await mlDataDB.getClusterIDToPersonID();
- final faceCrops =
- await getCachedFaceCrops(widget.file, faces, useTempCache: true);
+ final faceCrops = await getCachedFaceCrops(
+ widget.file,
+ faces,
+ useTempCache: true,
+ );
final defaultFaces = <Face>[];
final remainingFaces = <Face>[];
@@ -601,8 +601,9 @@ class _FacesItemWidgetState extends State<FacesItemWidget> {
setState(() => _showRemainingFaces = !_showRemainingFaces);
Future<void> _openAddFilesToPersonPage() async {
- final namedPersons =
- await AddFilesToPersonPage.prefetchNamedPersons(context);
+ final namedPersons = await AddFilesToPersonPage.prefetchNamedPersons(
+ context,
+ );
if (!mounted) {
return;
}
@@ -636,7 +637,9 @@ class _FacesItemWidgetState extends State<FacesItemWidget> {
if (result?.action == ButtonAction.first) {
try {
await ClusterFeedbackService.instance.removeFilesFromPerson(
- [widget.file],
+ [
+ widget.file,
+ ],
person,
);
await loadFaces(isRefresh: true);
@@ -649,10 +652,7 @@ class _FacesItemWidgetState extends State<FacesItemWidget> {
Future<void> _openPersonPage(PersonEntity person) async {
await Navigator.of(context).push(
MaterialPageRoute(
- builder: (context) => PeoplePage(
- person: person,
- searchResult: null,
- ),
+ builder: (context) => PeoplePage(person: person, searchResult: null),
),
);
}
diff --git a/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart b/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart
index 8d037bc4b9..a2497e2061 100644
--- a/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart
@@ -10,7 +10,7 @@ import "package:photos/models/file/file.dart";
import "package:photos/models/ml/face/box.dart";
import "package:photos/models/ml/face/detection.dart";
import "package:photos/models/ml/face/face.dart";
-import "package:photos/service_locator.dart" show isOfflineMode;
+import "package:photos/service_locator.dart" show isLocalGalleryMode;
import "package:photos/theme/ente_theme.dart";
import "package:photos/theme/text_style.dart";
import "package:photos/ui/common/loading_widget.dart";
@@ -41,7 +41,7 @@ class _PetsItemWidgetState extends State<PetsItemWidget> {
Future<void> _loadPetFaces() async {
try {
- final bool isOffline = isOfflineMode;
+ final bool isOffline = isLocalGalleryMode;
int? fileKey;
if (isOffline) {
final localId = widget.file.localID;
@@ -214,10 +214,7 @@ class _PetsItemWidgetState extends State<PetsItemWidget> {
height: thumbnailWidth,
width: thumbnailWidth,
child: FaceThumbnailSquircleClip(
- child: FileFaceWidget(
- widget.file,
- faceCrop: info.faceCrop,
- ),
+ child: FileFaceWidget(widget.file, faceCrop: info.faceCrop),
),
),
const SizedBox(height: 4),
diff --git a/mobile/apps/photos/lib/ui/viewer/gallery/jump_to_date_gallery.dart b/mobile/apps/photos/lib/ui/viewer/gallery/jump_to_date_gallery.dart
index cd4c02e2f0..78179f8de5 100644
--- a/mobile/apps/photos/lib/ui/viewer/gallery/jump_to_date_gallery.dart
+++ b/mobile/apps/photos/lib/ui/viewer/gallery/jump_to_date_gallery.dart
@@ -9,7 +9,7 @@ import 'package:photos/models/file/file.dart';
import 'package:photos/models/file_load_result.dart';
import 'package:photos/models/gallery_type.dart';
import 'package:photos/models/selected_files.dart';
-import "package:photos/service_locator.dart" show isOfflineMode;
+import "package:photos/service_locator.dart" show isLocalGalleryMode;
import 'package:photos/services/search_service.dart';
import "package:photos/theme/ente_theme.dart";
import 'package:photos/ui/common/loading_widget.dart';
@@ -54,8 +54,9 @@ class _JumpToDateGalleryState extends State<JumpToDateGallery> {
void initState() {
super.initState();
files = [];
- _filesUpdatedEvent =
- Bus.instance.on<LocalPhotosUpdatedEvent>().listen((event) {
+ _filesUpdatedEvent = Bus.instance.on<LocalPhotosUpdatedEvent>().listen((
+ event,
+ ) {
if (event.type == EventType.deletedFromDevice ||
event.type == EventType.deletedFromEverywhere ||
event.type == EventType.deletedFromRemote ||
@@ -74,7 +75,7 @@ class _JumpToDateGalleryState extends State<JumpToDateGallery> {
Future<void> _loadFiles() async {
final startTime = DateTime.now();
final onlyUploadedFiles =
- !(isOfflineMode && !Configuration.instance.hasConfiguredAccount());
+ !(isLocalGalleryMode && !Configuration.instance.hasConfiguredAccount());
final allFiles = await SearchService.instance.getAllFilesForGenericGallery(
onlyUploadedFiles: onlyUploadedFiles,
);
diff --git a/mobile/apps/photos/lib/ui/viewer/people/cluster_app_bar.dart b/mobile/apps/photos/lib/ui/viewer/people/cluster_app_bar.dart
index 8ed6e8dd2b..4c7546e714 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/cluster_app_bar.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/cluster_app_bar.dart
@@ -15,7 +15,7 @@ import "package:photos/models/file/file.dart";
import 'package:photos/models/gallery_type.dart';
import "package:photos/models/ml/face/person.dart";
import 'package:photos/models/selected_files.dart';
-import "package:photos/service_locator.dart" show isOfflineMode;
+import "package:photos/service_locator.dart" show isLocalGalleryMode;
import 'package:photos/services/collections_service.dart';
import "package:photos/services/machine_learning/face_ml/feedback/cluster_feedback.dart";
import "package:photos/services/machine_learning/ml_result.dart";
@@ -94,8 +94,9 @@ class _AppBarWidgetState extends State<ClusterAppBar> {
centerTitle: false,
title: Text(
_appBarTitle!,
- style:
- Theme.of(context).textTheme.headlineSmall!.copyWith(fontSize: 16),
+ style: Theme.of(
+ context,
+ ).textTheme.headlineSmall!.copyWith(fontSize: 16),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
@@ -109,27 +110,25 @@ class _AppBarWidgetState extends State<ClusterAppBar> {
final List<Widget> actions = <Widget>[];
// If the user has selected files, don't show any actions
if (widget.selectedFiles.files.isNotEmpty ||
- isOfflineMode ||
+ isLocalGalleryMode ||
!Configuration.instance.hasConfiguredAccount()) {
return actions;
}
final List<EntePopupMenuItem<ClusterPopupAction>> items = [];
- items.addAll(
- [
- EntePopupMenuItem(
- AppLocalizations.of(context).ignorePerson,
- value: ClusterPopupAction.ignore,
- icon: Icons.hide_image_outlined,
- ),
- EntePopupMenuItem(
- AppLocalizations.of(context).mixedGrouping,
- value: ClusterPopupAction.breakupCluster,
- icon: Icons.analytics_outlined,
- ),
- ],
- );
+ items.addAll([
+ EntePopupMenuItem(
+ AppLocalizations.of(context).ignorePerson,
+ value: ClusterPopupAction.ignore,
+ icon: Icons.hide_image_outlined,
+ ),
+ EntePopupMenuItem(
+ AppLocalizations.of(context).mixedGrouping,
+ value: ClusterPopupAction.breakupCluster,
+ icon: Icons.analytics_outlined,
+ ),
+ ]);
if (kDebugMode) {
items.add(
EntePopupMenuItem(
@@ -208,8 +207,9 @@ class _AppBarWidgetState extends State<ClusterAppBar> {
// Update to delete the old clusters and save the new clusters
await mlDataDB.deleteClusterSummary(widget.clusterID);
- await MLDataDB.instance
- .clusterSummaryUpdate(breakupResult.newClusterSummaries);
+ await MLDataDB.instance.clusterSummaryUpdate(
+ breakupResult.newClusterSummaries,
+ );
await mlDataDB.updateFaceIdToClusterId(newFaceIdToClusterID);
// Find the biggest cluster
@@ -227,13 +227,12 @@ class _AppBarWidgetState extends State<ClusterAppBar> {
.map((e) => getFileIdFromFaceId<int>(e))
.toList();
biggestClusterFiles = await FilesDB.instance
- .getFileIDToFileFromIDs(
- biggestClusterFileIDs,
- )
+ .getFileIDToFileFromIDs(biggestClusterFileIDs)
.then((mapping) => mapping.values.toList());
// Sort the files to prevent issues with the order of the files in gallery
- biggestClusterFiles
- .sort((a, b) => b.creationTime!.compareTo(a.creationTime!));
+ biggestClusterFiles.sort(
+ (a, b) => b.creationTime!.compareTo(a.creationTime!),
+ );
userConfirmed = true;
} catch (e, s) {
@@ -249,10 +248,8 @@ class _AppBarWidgetState extends State<ClusterAppBar> {
// Push the new cluster page
await Navigator.of(context).push(
MaterialPageRoute(
- builder: (context) => ClusterPage(
- biggestClusterFiles,
- clusterID: biggestClusterID,
- ),
+ builder: (context) =>
+ ClusterPage(biggestClusterFiles, clusterID: biggestClusterID),
),
);
Bus.instance.fire(PeopleChangedEvent());
@@ -260,8 +257,9 @@ class _AppBarWidgetState extends State<ClusterAppBar> {
}
Future<void> _breakUpClusterDebug(BuildContext context) async {
- final breakupResult =
- await ClusterFeedbackService.instance.breakUpCluster(widget.clusterID);
+ final breakupResult = await ClusterFeedbackService.instance.breakUpCluster(
+ widget.clusterID,
+ );
final Map<String, List<String>> newClusterIDToFaceIDs =
breakupResult.newClusterIdToFaceIds;
diff --git a/mobile/apps/photos/lib/ui/viewer/people/cluster_page.dart b/mobile/apps/photos/lib/ui/viewer/people/cluster_page.dart
index 6c3a525c3b..dbd2f80ce3 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/cluster_page.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/cluster_page.dart
@@ -15,7 +15,7 @@ import "package:photos/models/file_load_result.dart";
import "package:photos/models/gallery_type.dart";
import "package:photos/models/ml/face/person.dart";
import "package:photos/models/selected_files.dart";
-import "package:photos/service_locator.dart" show isOfflineMode;
+import "package:photos/service_locator.dart" show isLocalGalleryMode;
import "package:photos/services/machine_learning/face_ml/feedback/cluster_feedback.dart";
import "package:photos/services/machine_learning/face_ml/person/person_service.dart";
import "package:photos/services/machine_learning/ml_result.dart";
@@ -62,9 +62,7 @@ class ClusterPage extends StatefulWidget {
State<ClusterPage> createState() => _ClusterPageState();
}
-enum ClusterPageResult {
- ignoredPerson,
-}
+enum ClusterPageResult { ignoredPerson }
class _ClusterPageState extends State<ClusterPage> {
final _selectedFiles = SelectedFiles();
@@ -74,18 +72,17 @@ class _ClusterPageState extends State<ClusterPage> {
late final StreamSubscription<AppModeChangedEvent> _appModeChangedEvent;
bool _isNamingBannerDismissed = false;
bool get _offlineUiMode =>
- isOfflineMode && !Configuration.instance.hasConfiguredAccount();
+ isLocalGalleryMode && !Configuration.instance.hasConfiguredAccount();
@override
void initState() {
super.initState();
ClusterFeedbackService.setLastViewedClusterID(widget.clusterID);
files = List<EnteFile>.from(widget.searchResult)
- ..sort(
- (a, b) => (b.creationTime ?? 0).compareTo(a.creationTime ?? 0),
- );
- _filesUpdatedEvent =
- Bus.instance.on<LocalPhotosUpdatedEvent>().listen((event) {
+ ..sort((a, b) => (b.creationTime ?? 0).compareTo(a.creationTime ?? 0));
+ _filesUpdatedEvent = Bus.instance.on<LocalPhotosUpdatedEvent>().listen((
+ event,
+ ) {
if (event.type == EventType.deletedFromEverywhere ||
event.type == EventType.deletedFromRemote ||
event.type == EventType.hide) {
@@ -154,10 +151,7 @@ class _ClusterPageState extends State<ClusterPage> {
final person = result is (PersonEntity, EnteFile) ? result.$1 : result;
routeToPage(
context,
- PeoplePage(
- person: person,
- searchResult: null,
- ),
+ PeoplePage(person: person, searchResult: null),
).ignore();
}
} else {
@@ -197,10 +191,7 @@ class _ClusterPageState extends State<ClusterPage> {
Navigator.pop(context);
routeToPage(
context,
- PeoplePage(
- person: person,
- searchResult: null,
- ),
+ PeoplePage(person: person, searchResult: null),
).ignore();
}
@@ -216,10 +207,7 @@ class _ClusterPageState extends State<ClusterPage> {
)
.toList();
return Future.value(
- FileLoadResult(
- result,
- result.length < files.length,
- ),
+ FileLoadResult(result, result.length < files.length),
);
},
reloadEvent: Bus.instance.on<LocalPhotosUpdatedEvent>(),
@@ -240,9 +228,7 @@ class _ClusterPageState extends State<ClusterPage> {
? _offlineUiMode
? const NameFaceBanner()
: SavePersonBanner(
- faceWidget: PersonFaceWidget(
- clusterID: widget.clusterID,
- ),
+ faceWidget: PersonFaceWidget(clusterID: widget.clusterID),
text: AppLocalizations.of(context).savePerson,
subText: AppLocalizations.of(context).findThemQuickly,
primaryActionLabel: AppLocalizations.of(context).save,
@@ -321,9 +307,6 @@ class _AppBarWithBoundaryState extends State<_AppBarWithBoundary>
with BoundaryReporter {
@override
Widget build(BuildContext context) {
- return boundaryWidget(
- position: BoundaryPosition.top,
- child: widget.child,
- );
+ return boundaryWidget(position: BoundaryPosition.top, child: widget.child);
}
}
diff --git a/mobile/apps/photos/lib/ui/viewer/people/file_face_widget.dart b/mobile/apps/photos/lib/ui/viewer/people/file_face_widget.dart
index 86b18c75c0..4bead2dff9 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/file_face_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/file_face_widget.dart
@@ -6,7 +6,7 @@ import "package:photos/db/ml/db.dart";
import "package:photos/db/offline_files_db.dart";
import 'package:photos/models/file/file.dart';
import "package:photos/models/ml/face/face.dart";
-import "package:photos/service_locator.dart" show isOfflineMode;
+import "package:photos/service_locator.dart" show isLocalGalleryMode;
import "package:photos/theme/ente_theme.dart";
import "package:photos/ui/common/loading_widget.dart";
import "package:photos/ui/viewer/file/thumbnail_widget.dart";
@@ -92,12 +92,7 @@ class _FileFaceWidgetState extends State<FileFaceWidget> {
: MemoryImage(snapshot.data!);
return Stack(
fit: StackFit.expand,
- children: [
- Image(
- image: imageProvider,
- fit: BoxFit.cover,
- ),
- ],
+ children: [Image(image: imageProvider, fit: BoxFit.cover)],
);
} else {
if (snapshot.hasError) {
@@ -109,9 +104,7 @@ class _FileFaceWidgetState extends State<FileFaceWidget> {
}
return widget.thumbnailFallback
? ThumbnailWidget(widget.file)
- : EnteLoadingWidget(
- color: getEnteColorScheme(context).fillMuted,
- );
+ : EnteLoadingWidget(color: getEnteColorScheme(context).fillMuted);
}
},
);
@@ -123,16 +116,17 @@ class _FileFaceWidgetState extends State<FileFaceWidget> {
}
try {
final mlDataDB =
- isOfflineMode ? MLDataDB.offlineInstance : MLDataDB.instance;
+ isLocalGalleryMode ? MLDataDB.offlineInstance : MLDataDB.instance;
int? recentFileID;
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
final localId = widget.file.localID;
if (localId == null || localId.isEmpty) {
_logger.severe("Missing local ID for face crop generation");
return null;
}
- recentFileID =
- await OfflineFilesDB.instance.getOrCreateLocalIntId(localId);
+ recentFileID = await OfflineFilesDB.instance.getOrCreateLocalIntId(
+ localId,
+ );
} else {
recentFileID = widget.file.uploadedFileID;
}
diff --git a/mobile/apps/photos/lib/ui/viewer/people/memory_lane_page.dart b/mobile/apps/photos/lib/ui/viewer/people/memory_lane_page.dart
index 2de9971ed3..5be568959c 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/memory_lane_page.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/memory_lane_page.dart
@@ -94,17 +94,17 @@ class _MemoryLanePageState extends State<MemoryLanePage>
int _maxCaptionDigits = 1;
bool get _featureEnabled => flagService.facesTimeline;
bool get _showShareAction =>
- _featureEnabled && flagService.enableMemoryShareLink && !isOfflineMode;
+ _featureEnabled &&
+ flagService.enableMemoryShareLink &&
+ !isLocalGalleryMode;
@override
void initState() {
super.initState();
- _cardTransitionController = AnimationController(
- vsync: this,
- duration: _cardTransitionDuration,
- )
- ..addListener(_onCardAnimationTick)
- ..addStatusListener(_onCardAnimationStatusChanged);
+ _cardTransitionController =
+ AnimationController(vsync: this, duration: _cardTransitionDuration)
+ ..addListener(_onCardAnimationTick)
+ ..addStatusListener(_onCardAnimationStatusChanged);
_stackProgressNotifier = ValueNotifier<double>(_stackProgress);
if (_featureEnabled) {
unawaited(_loadFrames());
@@ -134,8 +134,9 @@ class _MemoryLanePageState extends State<MemoryLanePage>
}
Future<void> _loadFrames() async {
- _hasMarkedTimelineSeen =
- localSettings.hasSeenMemoryLane(widget.person.remoteID);
+ _hasMarkedTimelineSeen = localSettings.hasSeenMemoryLane(
+ widget.person.remoteID,
+ );
_playTimer?.cancel();
if (mounted) {
setState(() {
@@ -197,8 +198,9 @@ class _MemoryLanePageState extends State<MemoryLanePage>
int loadedCount = 0;
final uniqueFileIds =
entries.map((entry) => entry.fileId).toSet().toList();
- final filesById =
- await FilesDB.instance.getFileIDToFileFromIDs(uniqueFileIds);
+ final filesById = await FilesDB.instance.getFileIDToFileFromIDs(
+ uniqueFileIds,
+ );
final Map<int, Future<List<Face>?>> facesFutures = {};
await _buildFramesInParallel(
@@ -222,11 +224,7 @@ class _MemoryLanePageState extends State<MemoryLanePage>
});
_maybeMarkTimelineSeen();
} catch (error, stackTrace) {
- _logger.severe(
- "Faces timeline failed to load",
- error,
- stackTrace,
- );
+ _logger.severe("Faces timeline failed to load", error, stackTrace);
if (!mounted) {
return;
}
@@ -255,9 +253,7 @@ class _MemoryLanePageState extends State<MemoryLanePage>
return;
}
_hasMarkedTimelineSeen = true;
- unawaited(
- localSettings.markMemoryLaneSeen(widget.person.remoteID),
- );
+ unawaited(localSettings.markMemoryLaneSeen(widget.person.remoteID));
}
void _handleFrameLoaded(_TimelineFrame frame, int loadedCount) {
@@ -612,9 +608,7 @@ class _MemoryLanePageState extends State<MemoryLanePage>
final title = l10n.facesTimelineAppBarTitle;
final colorScheme = getEnteColorScheme(context);
final textTheme = getEnteTextTheme(context);
- final titleStyle = textTheme.h3Bold.copyWith(
- letterSpacing: -2,
- );
+ final titleStyle = textTheme.h3Bold.copyWith(letterSpacing: -2);
return DecoratedBox(
decoration: const BoxDecoration(
gradient: _memoryLaneBackgroundGradient,
@@ -695,8 +689,10 @@ class _MemoryLanePageState extends State<MemoryLanePage>
const double topPadding = 12;
final double gapToTop = _cardGap + topPadding;
const double desiredGap = _controlsDesiredGapToCard;
- final double overlap =
- math.max(0, gapToTop - desiredGap);
+ final double overlap = math.max(
+ 0,
+ gapToTop - desiredGap,
+ );
final double controlsHeight = _controlsHeight > 0
? _controlsHeight
: _controlsHeightFallback;
@@ -813,14 +809,11 @@ class _MemoryLanePageState extends State<MemoryLanePage>
}
final futureSlices = slices.where((slice) => slice.distance >= 0).toList()
- ..sort(
- (a, b) => b.distance.compareTo(a.distance),
- );
- final presentAndPastSlices =
- slices.where((slice) => slice.distance < 0).toList()
- ..sort(
- (a, b) => a.distance.compareTo(b.distance),
- );
+ ..sort((a, b) => b.distance.compareTo(a.distance));
+ final presentAndPastSlices = slices
+ .where((slice) => slice.distance < 0)
+ .toList()
+ ..sort((a, b) => a.distance.compareTo(b.distance));
return Center(
child: FractionallySizedBox(
@@ -933,10 +926,7 @@ class _MemoryLanePageState extends State<MemoryLanePage>
final int insertionIndex = fullText.indexOf(formattedCurrent);
final InlineSpan captionSpan;
if (insertionIndex == -1) {
- captionSpan = TextSpan(
- text: fullText,
- style: baseStyle,
- );
+ captionSpan = TextSpan(text: fullText, style: baseStyle);
} else {
final String prefix = fullText.substring(0, insertionIndex);
final String suffix = fullText.substring(
@@ -991,10 +981,7 @@ class _MemoryLanePageState extends State<MemoryLanePage>
),
const SizedBox(width: 12),
Flexible(
- child: RichText(
- textAlign: TextAlign.center,
- text: captionSpan,
- ),
+ child: RichText(textAlign: TextAlign.center, text: captionSpan),
),
],
),
@@ -1101,11 +1088,7 @@ class _MemoryLanePageState extends State<MemoryLanePage>
color: colorScheme.fillFaint,
),
padding: const EdgeInsets.all(8),
- child: Icon(
- icon,
- size: 20,
- color: colorScheme.textBase,
- ),
+ child: Icon(icon, size: 20, color: colorScheme.textBase),
),
),
);
@@ -1173,8 +1156,9 @@ class _MemoryLanePageState extends State<MemoryLanePage>
if (!_cardTransitionController.isAnimating && !_isAnimatingCard) {
return;
}
- final eased =
- Curves.easeInOutCubic.transform(_cardTransitionController.value);
+ final eased = Curves.easeInOutCubic.transform(
+ _cardTransitionController.value,
+ );
final progress = ui.lerpDouble(
_animationStartProgress,
_targetIndex.toDouble(),
@@ -1231,21 +1215,16 @@ class _TimelineFrame {
required this.cropAspectRatio,
});
- ImageProvider<Object>? resizedImage({
- int? cacheWidth,
- }) {
+ ImageProvider<Object>? resizedImage({int? cacheWidth}) {
final baseImage = image;
if (baseImage == null) {
return null;
}
- return _resizedImageCache.putIfAbsent(
- cacheWidth,
- () {
- // Decode face crops with width only so BoxFit.cover can crop them
- // naturally without forcing the crop to the card's aspect ratio.
- return ResizeImage.resizeIfNeeded(cacheWidth, null, baseImage);
- },
- );
+ return _resizedImageCache.putIfAbsent(cacheWidth, () {
+ // Decode face crops with width only so BoxFit.cover can crop them
+ // naturally without forcing the crop to the card's aspect ratio.
+ return ResizeImage.resizeIfNeeded(cacheWidth, null, baseImage);
+ });
}
}
@@ -1253,10 +1232,7 @@ class _CardSlice {
final int index;
final double distance;
- const _CardSlice({
- required this.index,
- required this.distance,
- });
+ const _CardSlice({required this.index, required this.distance});
}
class _MemoryLaneCard extends StatelessWidget {
@@ -1296,15 +1272,19 @@ class _MemoryLaneCard extends StatelessWidget {
final rotation = _calculateRotation(distance);
final overlayOpacity = _calculateOverlayOpacity(distance);
final double dpr = MediaQuery.devicePixelRatioOf(context);
- final int? imageCacheWidth =
- _cacheDimensionFor(_coveringDecodeWidth(frame.cropAspectRatio), dpr);
+ final int? imageCacheWidth = _cacheDimensionFor(
+ _coveringDecodeWidth(frame.cropAspectRatio),
+ dpr,
+ );
final cardShadow = _shadowForCard(distance);
// Emphasize the active card by delaying the date reveal until the card is
// nearly centered; keeps background cards calm while the primary one lifts.
final double emphasisDistance = distance.abs();
- final double activation =
- (1 - (emphasisDistance * 1.8)).clamp(0.0, 1.0); // hide until near front
+ final double activation = (1 - (emphasisDistance * 1.8)).clamp(
+ 0.0,
+ 1.0,
+ ); // hide until near front
final double emphasis = Curves.easeOutQuad.transform(activation);
final double dateOpacity = emphasis;
final double gradientAlpha = 0.6 * emphasis;
@@ -1326,8 +1306,9 @@ class _MemoryLaneCard extends StatelessWidget {
_buildImage(blurSigma, imageCacheWidth),
if (overlayOpacity > 0)
Container(
- color:
- colorScheme.backgroundBase.withValues(alpha: overlayOpacity),
+ color: colorScheme.backgroundBase.withValues(
+ alpha: overlayOpacity,
+ ),
),
if (frame.image == null)
Center(
@@ -1366,8 +1347,9 @@ class _MemoryLaneCard extends StatelessWidget {
style: textTheme.smallMuted.copyWith(
shadows: [
Shadow(
- color:
- Colors.black.withValues(alpha: textShadowAlpha),
+ color: Colors.black.withValues(
+ alpha: textShadowAlpha,
+ ),
blurRadius: 12,
),
],
@@ -1408,9 +1390,7 @@ class _MemoryLaneCard extends StatelessWidget {
}
Widget _buildImage(double blurSigma, int? cacheWidth) {
- final resizedImage = frame.resizedImage(
- cacheWidth: cacheWidth,
- );
+ final resizedImage = frame.resizedImage(cacheWidth: cacheWidth);
final Widget base = resizedImage != null
? Image(
image: resizedImage,
@@ -1419,17 +1399,12 @@ class _MemoryLaneCard extends StatelessWidget {
height: double.infinity,
gaplessPlayback: true,
)
- : ColoredBox(
- color: colorScheme.backgroundElevated2,
- );
+ : ColoredBox(color: colorScheme.backgroundElevated2);
if (blurSigma <= 0) {
return base;
}
return ImageFiltered(
- imageFilter: ui.ImageFilter.blur(
- sigmaX: blurSigma,
- sigmaY: blurSigma,
- ),
+ imageFilter: ui.ImageFilter.blur(sigmaX: blurSigma, sigmaY: blurSigma),
child: base,
);
}
@@ -1462,8 +1437,9 @@ class _MemoryLaneCard extends StatelessWidget {
if (distance > 0) {
return [
BoxShadow(
- color: Colors.black
- .withValues(alpha: math.max(0.0, baseOpacity - distance * 0.12)),
+ color: Colors.black.withValues(
+ alpha: math.max(0.0, baseOpacity - distance * 0.12),
+ ),
blurRadius: 38,
offset: const Offset(0, 26),
spreadRadius: -6,
@@ -1509,10 +1485,7 @@ class _MemoryLaneCard extends StatelessWidget {
const double clearDistance = 0.15;
const double blurMultiplier = 10;
final double effective = math.max(0, distance - clearDistance);
- return math.min(
- 20,
- (effective + 0.05) * blurMultiplier,
- );
+ return math.min(20, (effective + 0.05) * blurMultiplier);
}
double _calculateRotation(double distance) {
@@ -1613,10 +1586,7 @@ class _RollingCounter extends StatelessWidget {
switchOutCurve: Curves.easeInCubic,
layoutBuilder: (currentChild, previousChildren) => Stack(
alignment: Alignment.center,
- children: [
- ...previousChildren,
- if (currentChild != null) currentChild,
- ],
+ children: [...previousChildren, if (currentChild != null) currentChild],
),
transitionBuilder: (child, animation) {
final bool isCurrent = child.key == currentKey;
@@ -1646,10 +1616,7 @@ class _RollingCounter extends StatelessWidget {
child: Align(
key: currentKey,
alignment: Alignment.center,
- child: Text(
- numberFormat.format(value),
- style: textStyle,
- ),
+ child: Text(numberFormat.format(value), style: textStyle),
),
);
}
diff --git a/mobile/apps/photos/lib/ui/viewer/people/person_face_widget.dart b/mobile/apps/photos/lib/ui/viewer/people/person_face_widget.dart
index 70fa06b062..36e4b717cc 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/person_face_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/person_face_widget.dart
@@ -9,7 +9,7 @@ import "package:photos/db/offline_files_db.dart";
import 'package:photos/models/file/file.dart';
import "package:photos/models/ml/face/face.dart";
import "package:photos/models/ml/face/person.dart";
-import "package:photos/service_locator.dart" show isOfflineMode;
+import "package:photos/service_locator.dart" show isLocalGalleryMode;
import "package:photos/services/machine_learning/face_ml/person/person_service.dart";
import "package:photos/services/machine_learning/ml_result.dart";
import "package:photos/services/search_service.dart";
@@ -116,10 +116,7 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>
return Stack(
fit: StackFit.expand,
children: [
- Image(
- image: imageProvider,
- fit: BoxFit.cover,
- ),
+ Image(image: imageProvider, fit: BoxFit.cover),
if (kDebugMode && _showingFallback)
Positioned(
top: 4,
@@ -163,17 +160,16 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>
"faceCropFuture is null, no cover face found for person or cluster.",
);
}
- return _EmptyPersonThumbnail(
- initial: isPerson ? _personName : null,
- );
+ return _EmptyPersonThumbnail(initial: isPerson ? _personName : null);
},
);
}
Future<Uint8List?> _loadFaceCrop() async {
if (!widget.useFullFile) {
- final Uint8List? thumbnailCrop =
- await _getFaceCrop(useFullFile: widget.useFullFile);
+ final Uint8List? thumbnailCrop = await _getFaceCrop(
+ useFullFile: widget.useFullFile,
+ );
if (thumbnailCrop != null) {
_fallbackEverUsed = true;
}
@@ -181,8 +177,9 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>
return thumbnailCrop;
}
- final Uint8List? fullCrop =
- await _getFaceCrop(useFullFile: widget.useFullFile);
+ final Uint8List? fullCrop = await _getFaceCrop(
+ useFullFile: widget.useFullFile,
+ );
if (fullCrop != null) {
_showingFallback = false;
return fullCrop;
@@ -209,14 +206,15 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>
Future<Uint8List?> _getFaceCrop({required bool useFullFile}) async {
try {
final String personOrClusterId = widget.personId ?? widget.clusterID!;
- final tryInMemoryCachedCrop =
- checkInMemoryCachedCropForPersonOrClusterID(personOrClusterId);
+ final tryInMemoryCachedCrop = checkInMemoryCachedCropForPersonOrClusterID(
+ personOrClusterId,
+ );
if (tryInMemoryCachedCrop != null) return tryInMemoryCachedCrop;
String? fixedFaceID;
PersonEntity? personEntity;
final mlDataDB =
- isOfflineMode ? MLDataDB.offlineInstance : MLDataDB.instance;
- if (isPerson && !isOfflineMode) {
+ isLocalGalleryMode ? MLDataDB.offlineInstance : MLDataDB.instance;
+ if (isPerson && !isLocalGalleryMode) {
personEntity = await PersonService.instance.getPerson(widget.personId!);
if (personEntity == null) {
_logger.severe(
@@ -227,11 +225,12 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>
_personName = personEntity.data.name;
fixedFaceID = personEntity.data.avatarFaceID;
}
- fixedFaceID ??=
- await checkUsedFaceIDForPersonOrClusterId(personOrClusterId);
+ fixedFaceID ??= await checkUsedFaceIDForPersonOrClusterId(
+ personOrClusterId,
+ );
EnteFile? fileForFaceCrop;
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
final allFiles = await SearchService.instance.getAllFilesForSearch();
final localIdToFile = <String, EnteFile>{};
for (final file in allFiles) {
@@ -242,8 +241,9 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>
}
if (fixedFaceID != null) {
final localIntId = getFileIdFromFaceId<int>(fixedFaceID);
- final localId =
- await OfflineFilesDB.instance.getLocalIdForIntId(localIntId);
+ final localId = await OfflineFilesDB.instance.getLocalIdForIntId(
+ localIntId,
+ );
if (localId == null) {
await checkRemoveCachedFaceIDForPersonOrClusterId(
personOrClusterId,
@@ -259,15 +259,18 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>
}
if (fileForFaceCrop == null) {
final List<String> allFaces = isPerson
- ? await mlDataDB
- .getFaceIDsForPersonOrderedByScore(widget.personId!)
- : await mlDataDB
- .getFaceIDsForClusterOrderedByScore(widget.clusterID!);
+ ? await mlDataDB.getFaceIDsForPersonOrderedByScore(
+ widget.personId!,
+ )
+ : await mlDataDB.getFaceIDsForClusterOrderedByScore(
+ widget.clusterID!,
+ );
final localIntIds = allFaces
.map((faceID) => getFileIdFromFaceId<int>(faceID))
.toSet();
- final localIdMap =
- await OfflineFilesDB.instance.getLocalIdsForIntIds(localIntIds);
+ final localIdMap = await OfflineFilesDB.instance.getLocalIdsForIntIds(
+ localIntIds,
+ );
for (final faceID in allFaces) {
final localIntId = getFileIdFromFaceId<int>(faceID);
final localId = localIdMap[localIntId];
@@ -312,10 +315,12 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>
}
if (fileForFaceCrop == null) {
final List<String> allFaces = isPerson
- ? await mlDataDB
- .getFaceIDsForPersonOrderedByScore(widget.personId!)
- : await mlDataDB
- .getFaceIDsForClusterOrderedByScore(widget.clusterID!);
+ ? await mlDataDB.getFaceIDsForPersonOrderedByScore(
+ widget.personId!,
+ )
+ : await mlDataDB.getFaceIDsForClusterOrderedByScore(
+ widget.clusterID!,
+ );
for (final faceID in allFaces) {
final fileID = getFileIdFromFaceId<int>(faceID);
if (hiddenFileIDs.contains(fileID)) {
@@ -342,7 +347,7 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>
}
}
int? recentFileID;
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
final localId = fileForFaceCrop.localID;
if (localId == null || localId.isEmpty) {
_logger.severe(
@@ -350,8 +355,9 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>
);
return null;
}
- recentFileID =
- await OfflineFilesDB.instance.getOrCreateLocalIntId(localId);
+ recentFileID = await OfflineFilesDB.instance.getOrCreateLocalIntId(
+ localId,
+ );
} else {
recentFileID = fileForFaceCrop.uploadedFileID;
}
@@ -371,9 +377,7 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>
_logger.severe(
"No cover face for person: ${widget.personId} or cluster ${widget.clusterID} and fileID $recentFileID",
);
- await checkRemoveCachedFaceIDForPersonOrClusterId(
- personOrClusterId,
- );
+ await checkRemoveCachedFaceIDForPersonOrClusterId(personOrClusterId);
return null;
}
final cropMap = await getCachedFaceCrops(
@@ -407,9 +411,7 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>
class _EmptyPersonThumbnail extends StatelessWidget {
final String? initial;
- const _EmptyPersonThumbnail({
- this.initial,
- });
+ const _EmptyPersonThumbnail({this.initial});
@override
Widget build(BuildContext context) {
@@ -420,10 +422,7 @@ class _EmptyPersonThumbnail extends StatelessWidget {
return Container(
decoration: BoxDecoration(
color: colorScheme.fillFaint,
- border: Border.all(
- color: colorScheme.strokeFaint,
- width: 1,
- ),
+ border: Border.all(color: colorScheme.strokeFaint, width: 1),
),
child: Center(
child: hasInitial
@@ -445,10 +444,7 @@ class _EmptyPersonThumbnail extends StatelessWidget {
);
},
)
- : Icon(
- Icons.person_outline,
- color: colorScheme.strokeMuted,
- ),
+ : Icon(Icons.person_outline, color: colorScheme.strokeMuted),
),
);
}
diff --git a/mobile/apps/photos/lib/ui/viewer/search/result/magic_result_screen.dart b/mobile/apps/photos/lib/ui/viewer/search/result/magic_result_screen.dart
index 41770707c2..7715164840 100644
--- a/mobile/apps/photos/lib/ui/viewer/search/result/magic_result_screen.dart
+++ b/mobile/apps/photos/lib/ui/viewer/search/result/magic_result_screen.dart
@@ -12,7 +12,7 @@ import 'package:photos/models/file_load_result.dart';
import 'package:photos/models/gallery_type.dart';
import "package:photos/models/search/hierarchical/magic_filter.dart";
import 'package:photos/models/selected_files.dart';
-import "package:photos/service_locator.dart" show isOfflineMode;
+import "package:photos/service_locator.dart" show isLocalGalleryMode;
import 'package:photos/ui/viewer/actions/file_selection_overlay_bar.dart';
import 'package:photos/ui/viewer/gallery/gallery.dart';
import 'package:photos/ui/viewer/gallery/gallery_app_bar_widget.dart';
@@ -68,11 +68,12 @@ class _MagicResultScreenState extends State<MagicResultScreen> {
files = widget.files;
_enableGrouping = widget.enableGrouping;
fileIDToRelevantPos = getFileIDToRelevantPos();
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
_loadLocalIntIds();
}
- _filesUpdatedEvent =
- Bus.instance.on<LocalPhotosUpdatedEvent>().listen((event) {
+ _filesUpdatedEvent = Bus.instance.on<LocalPhotosUpdatedEvent>().listen((
+ event,
+ ) {
if (event.type == EventType.deletedFromDevice ||
event.type == EventType.deletedFromEverywhere ||
event.type == EventType.deletedFromRemote ||
@@ -84,14 +85,13 @@ class _MagicResultScreenState extends State<MagicResultScreen> {
}
});
- _magicSortChangeEvent =
- Bus.instance.on<MagicSortChangeEvent>().listen((event) {
+ _magicSortChangeEvent = Bus.instance.on<MagicSortChangeEvent>().listen((
+ event,
+ ) {
if (event.sortType == MagicSortType.mostRelevant) {
if (_enableGrouping) {
if (fileIDToRelevantPos.isNotEmpty) {
- files.sort(
- (a, b) => _posForFile(a) - _posForFile(b),
- );
+ files.sort((a, b) => _posForFile(a) - _posForFile(b));
} else {
_logger.warning(
"fileIdToPosMap is empty, cannot sort by most relevant.",
@@ -149,9 +149,7 @@ class _MagicResultScreenState extends State<MagicResultScreen> {
}
return map;
} else {
- _logger.warning(
- "fileIdToPosMap is empty, cannot sort by most relevant.",
- );
+ _logger.warning("fileIdToPosMap is empty, cannot sort by most relevant.");
return <int, int>{};
}
}
@@ -163,7 +161,7 @@ class _MagicResultScreenState extends State<MagicResultScreen> {
}
int? _fileIdForSort(EnteFile file) {
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
final localId = file.localID;
if (localId == null || localId.isEmpty) return null;
return _localIdToIntId[localId];
@@ -191,10 +189,7 @@ class _MagicResultScreenState extends State<MagicResultScreen> {
)
.toList();
return Future.value(
- FileLoadResult(
- result,
- result.length < files.length,
- ),
+ FileLoadResult(result, result.length < files.length),
);
},
reloadEvent: Bus.instance.on<LocalPhotosUpdatedEvent>(),
@@ -237,9 +232,9 @@ class _MagicResultScreenState extends State<MagicResultScreen> {
Builder(
builder: (context) {
return ValueListenableBuilder(
- valueListenable: InheritedSearchFilterData.of(context)
- .searchFilterDataProvider!
- .isSearchingNotifier,
+ valueListenable: InheritedSearchFilterData.of(
+ context,
+ ).searchFilterDataProvider!.isSearchingNotifier,
builder: (context, value, _) {
return value
? HierarchicalSearchGallery(
@@ -285,9 +280,6 @@ class _AppBarWithBoundaryState extends State<_AppBarWithBoundary>
with BoundaryReporter {
@override
Widget build(BuildContext context) {
- return boundaryWidget(
- position: BoundaryPosition.top,
- child: widget.child,
- );
+ return boundaryWidget(position: BoundaryPosition.top, child: widget.child);
}
}
diff --git a/mobile/apps/photos/lib/ui/viewer/search/result/people_section_all_page.dart b/mobile/apps/photos/lib/ui/viewer/search/result/people_section_all_page.dart
index 14e9513a0e..8a7e40829c 100644
--- a/mobile/apps/photos/lib/ui/viewer/search/result/people_section_all_page.dart
+++ b/mobile/apps/photos/lib/ui/viewer/search/result/people_section_all_page.dart
@@ -38,10 +38,7 @@ import "package:photos/utils/local_settings.dart";
import "package:photos/utils/people_sort_util.dart";
class PeopleSectionAllPage extends StatefulWidget {
- const PeopleSectionAllPage({
- super.key,
- this.startInSearchMode = false,
- });
+ const PeopleSectionAllPage({super.key, this.startInSearchMode = false});
final bool startInSearchMode;
@@ -123,7 +120,7 @@ class SelectablePersonSearchExample extends StatelessWidget {
});
void _handleTap(BuildContext context) {
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
_handleNavigation(context);
return;
}
@@ -135,7 +132,7 @@ class SelectablePersonSearchExample extends StatelessWidget {
}
void _handleLongPress() {
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
return;
}
_toggleSelection();
@@ -158,10 +155,7 @@ class SelectablePersonSearchExample extends StatelessWidget {
if (searchResult.onResultTap != null) {
searchResult.onResultTap!(context);
} else {
- routeToPage(
- context,
- SearchResultPage(searchResult),
- );
+ routeToPage(context, SearchResultPage(searchResult));
}
}
@@ -220,9 +214,7 @@ class SelectablePersonSearchExample extends StatelessWidget {
isDefaultFace: isDefaultFace,
);
} else {
- child = const NoThumbnailWidget(
- addBorder: false,
- );
+ child = const NoThumbnailWidget(addBorder: false);
}
return SizedBox(
width: size - 2,
@@ -345,8 +337,9 @@ class _PeopleSectionAllWidgetState extends State<PeopleSectionAllWidget> {
bool userDismissedPersonGallerySuggestion = false;
String _searchQuery = "";
int _suggestionReloadToken = 0;
- final Debouncer _peopleReloadDebouncer =
- Debouncer(const Duration(milliseconds: 400));
+ final Debouncer _peopleReloadDebouncer = Debouncer(
+ const Duration(milliseconds: 400),
+ );
late PeopleSortKey _sortKey;
bool _nameSortAscending = true;
bool _updatedSortAscending = false;
@@ -363,9 +356,7 @@ class _PeopleSectionAllWidgetState extends State<PeopleSectionAllWidget> {
!_showingIgnoredPeople &&
extraFaces.isNotEmpty;
- List<GenericSearchResult> _filterFaces(
- List<GenericSearchResult> faces,
- ) {
+ List<GenericSearchResult> _filterFaces(List<GenericSearchResult> faces) {
if (!_isSearching) {
return faces;
}
@@ -497,18 +488,18 @@ class _PeopleSectionAllWidgetState extends State<PeopleSectionAllWidget> {
showAllFaces ? [...normalFaces, ...extraFaces] : normalFaces;
if (widget.namedOnly) {
- results.removeWhere(
- (element) => element.params[kPersonParamID] == null,
- );
+ results.removeWhere((element) => element.params[kPersonParamID] == null);
if (init) {
// sort widget.selectedPeople first
results.sort((a, b) {
- final aIndex = widget.selectedPeople?.personIds
- .contains(a.params[kPersonParamID]) ??
+ final aIndex = widget.selectedPeople?.personIds.contains(
+ a.params[kPersonParamID],
+ ) ??
false;
- final bIndex = widget.selectedPeople?.personIds
- .contains(b.params[kPersonParamID]) ??
+ final bIndex = widget.selectedPeople?.personIds.contains(
+ b.params[kPersonParamID],
+ ) ??
false;
if (aIndex && !bIndex) return -1;
if (!aIndex && bIndex) return 1;
@@ -634,8 +625,12 @@ class _PeopleSectionAllWidgetState extends State<PeopleSectionAllWidget> {
onSearch: _updateSearchQuery,
onSearchClosed: _clearSearchQuery,
centerTitle: false,
- searchIconPadding:
- const EdgeInsets.fromLTRB(12, 12, horizontalEdgePadding, 12),
+ searchIconPadding: const EdgeInsets.fromLTRB(
+ 12,
+ 12,
+ horizontalEdgePadding,
+ 12,
+ ),
actions: [
Padding(
padding: const EdgeInsets.only(right: horizontalEdgePadding),
@@ -730,48 +725,79 @@ class _PeopleSectionAllWidgetState extends State<PeopleSectionAllWidget> {
),
),
);
- slivers.add(
- const SliverToBoxAdapter(
- child: SizedBox(height: 16),
- ),
- );
+ slivers.add(const SliverToBoxAdapter(child: SizedBox(height: 16)));
} else {
final showAllFaces = _showingAllFaces || _showingIgnoredPeople;
final showExtraFaces =
showAllFaces && filteredExtraFaces.isNotEmpty;
- slivers.addAll(
- [
- if (isOfflineMode &&
- !Configuration.instance.hasConfiguredAccount())
- const SliverToBoxAdapter(
- child: SaveFacesBanner(),
- ),
- (!userDismissedPersonGallerySuggestion &&
- !widget.namedOnly &&
- !_showingIgnoredPeople)
- ? SliverToBoxAdapter(
- child: Dismissible(
- key: const Key("personGallerySuggestionAll"),
- direction: DismissDirection.horizontal,
- onDismissed: (direction) {
+ slivers.addAll([
+ if (isLocalGalleryMode &&
+ !Configuration.instance.hasConfiguredAccount())
+ const SliverToBoxAdapter(child: SaveFacesBanner()),
+ (!userDismissedPersonGallerySuggestion &&
+ !widget.namedOnly &&
+ !_showingIgnoredPeople)
+ ? SliverToBoxAdapter(
+ child: Dismissible(
+ key: const Key("personGallerySuggestionAll"),
+ direction: DismissDirection.horizontal,
+ onDismissed: (direction) {
+ setState(() {
+ userDismissedPersonGallerySuggestion = true;
+ });
+ },
+ child: PersonGallerySuggestion(
+ key: ValueKey(
+ 'personGallerySuggestionAll_$_suggestionReloadToken',
+ ),
+ person: null,
+ onClose: () {
setState(() {
userDismissedPersonGallerySuggestion = true;
});
},
- child: PersonGallerySuggestion(
- key: ValueKey(
- 'personGallerySuggestionAll_$_suggestionReloadToken',
- ),
- person: null,
- onClose: () {
- setState(() {
- userDismissedPersonGallerySuggestion = true;
- });
- },
- ),
),
- )
- : const SliverToBoxAdapter(child: SizedBox.shrink()),
+ ),
+ )
+ : const SliverToBoxAdapter(child: SizedBox.shrink()),
+ SliverPadding(
+ padding: const EdgeInsets.fromLTRB(
+ horizontalEdgePadding,
+ 16,
+ horizontalEdgePadding,
+ 16,
+ ),
+ sliver: SliverGrid(
+ gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
+ mainAxisSpacing: gridPadding,
+ crossAxisSpacing: gridPadding,
+ crossAxisCount: crossAxisCount,
+ childAspectRatio:
+ itemSize / (itemSize + (24 * textScaleFactor)),
+ ),
+ delegate: SliverChildBuilderDelegate(
+ childCount: filteredNormalFaces.length,
+ (context, index) {
+ return !widget.namedOnly
+ ? SelectablePersonSearchExample(
+ searchResult: filteredNormalFaces[index],
+ size: itemSize,
+ selectedPeople: widget.selectedPeople!,
+ isDefaultFace: true,
+ )
+ : PersonSearchExample(
+ searchResult: filteredNormalFaces[index],
+ size: itemSize,
+ selectedPeople: widget.selectedPeople!,
+ );
+ },
+ ),
+ ),
+ ),
+ if (_showMoreLessOption)
+ SliverToBoxAdapter(child: _buildShowMoreOrLessButton(context)),
+ const SliverToBoxAdapter(child: SizedBox(height: 16)),
+ if (showExtraFaces)
SliverPadding(
padding: const EdgeInsets.fromLTRB(
horizontalEdgePadding,
@@ -788,17 +814,17 @@ class _PeopleSectionAllWidgetState extends State<PeopleSectionAllWidget> {
itemSize / (itemSize + (24 * textScaleFactor)),
),
delegate: SliverChildBuilderDelegate(
- childCount: filteredNormalFaces.length,
+ childCount: filteredExtraFaces.length,
(context, index) {
return !widget.namedOnly
? SelectablePersonSearchExample(
- searchResult: filteredNormalFaces[index],
+ searchResult: filteredExtraFaces[index],
size: itemSize,
selectedPeople: widget.selectedPeople!,
- isDefaultFace: true,
+ isDefaultFace: false,
)
: PersonSearchExample(
- searchResult: filteredNormalFaces[index],
+ searchResult: filteredExtraFaces[index],
size: itemSize,
selectedPeople: widget.selectedPeople!,
);
@@ -806,54 +832,9 @@ class _PeopleSectionAllWidgetState extends State<PeopleSectionAllWidget> {
),
),
),
- if (_showMoreLessOption)
- SliverToBoxAdapter(
- child: _buildShowMoreOrLessButton(context),
- ),
- const SliverToBoxAdapter(
- child: SizedBox(height: 16),
- ),
- if (showExtraFaces)
- SliverPadding(
- padding: const EdgeInsets.fromLTRB(
- horizontalEdgePadding,
- 16,
- horizontalEdgePadding,
- 16,
- ),
- sliver: SliverGrid(
- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
- mainAxisSpacing: gridPadding,
- crossAxisSpacing: gridPadding,
- crossAxisCount: crossAxisCount,
- childAspectRatio:
- itemSize / (itemSize + (24 * textScaleFactor)),
- ),
- delegate: SliverChildBuilderDelegate(
- childCount: filteredExtraFaces.length,
- (context, index) {
- return !widget.namedOnly
- ? SelectablePersonSearchExample(
- searchResult: filteredExtraFaces[index],
- size: itemSize,
- selectedPeople: widget.selectedPeople!,
- isDefaultFace: false,
- )
- : PersonSearchExample(
- searchResult: filteredExtraFaces[index],
- size: itemSize,
- selectedPeople: widget.selectedPeople!,
- );
- },
- ),
- ),
- ),
- if (showExtraFaces)
- const SliverToBoxAdapter(
- child: SizedBox(height: 16),
- ),
- ],
- );
+ if (showExtraFaces)
+ const SliverToBoxAdapter(child: SizedBox(height: 16)),
+ ]);
}
return CustomScrollView(slivers: slivers);
}
@@ -880,10 +861,7 @@ class _PeopleSectionAllWidgetState extends State<PeopleSectionAllWidget> {
context: context,
elevation: 0,
shape: RoundedRectangleBorder(
- side: BorderSide(
- width: 0.5,
- color: colorScheme.strokeFaint,
- ),
+ side: BorderSide(width: 0.5, color: colorScheme.strokeFaint),
borderRadius: BorderRadius.circular(_sortMenuCornerRadius),
),
position: RelativeRect.fromLTRB(
@@ -1002,10 +980,7 @@ class _PeopleSectionAllWidgetState extends State<PeopleSectionAllWidget> {
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
- Text(
- label,
- style: textTheme.mini,
- ),
+ Text(label, style: textTheme.mini),
if (isSelected) ...[
const SizedBox(width: 8),
Container(
@@ -1017,16 +992,9 @@ class _PeopleSectionAllWidgetState extends State<PeopleSectionAllWidget> {
),
),
const SizedBox(width: 6),
- Text(
- detail,
- style: textTheme.miniMuted,
- ),
+ Text(detail, style: textTheme.miniMuted),
const SizedBox(width: 4),
- Icon(
- directionIcon,
- size: 16,
- color: colorScheme.textMuted,
- ),
+ Icon(directionIcon, size: 16, color: colorScheme.textMuted),
],
],
),
@@ -1051,19 +1019,13 @@ class _PeopleSectionAllWidgetState extends State<PeopleSectionAllWidget> {
padding: const EdgeInsets.symmetric(horizontal: 16),
decoration: BoxDecoration(
border: Border(
- top: BorderSide(
- width: 0.5,
- color: colorScheme.strokeFaint,
- ),
+ top: BorderSide(width: 0.5, color: colorScheme.strokeFaint),
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
- Text(
- l10n.showIgnored,
- style: textTheme.miniMuted,
- ),
+ Text(l10n.showIgnored, style: textTheme.miniMuted),
IgnorePointer(
child: CupertinoSwitch(
value: _showingIgnoredPeople,
@@ -1099,10 +1061,9 @@ class _PeopleSectionAllWidgetState extends State<PeopleSectionAllWidget> {
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side: BorderSide(
- color: Theme.of(context)
- .colorScheme
- .outline
- .withValues(alpha: 0.3),
+ color: Theme.of(
+ context,
+ ).colorScheme.outline.withValues(alpha: 0.3),
width: 1,
),
),
@@ -1114,9 +1075,9 @@ class _PeopleSectionAllWidgetState extends State<PeopleSectionAllWidget> {
_showingAllFaces
? AppLocalizations.of(context).showLessFaces
: AppLocalizations.of(context).showMoreFaces,
- style: getEnteTextTheme(context).small.copyWith(
- color: Theme.of(context).colorScheme.primary,
- ),
+ style: getEnteTextTheme(
+ context,
+ ).small.copyWith(color: Theme.of(context).colorScheme.primary),
),
const SizedBox(width: 8),
Icon(
diff --git a/mobile/apps/photos/lib/ui/viewer/search_tab/people_section.dart b/mobile/apps/photos/lib/ui/viewer/search_tab/people_section.dart
index 48c8e95d05..62ecf79bb9 100644
--- a/mobile/apps/photos/lib/ui/viewer/search_tab/people_section.dart
+++ b/mobile/apps/photos/lib/ui/viewer/search_tab/people_section.dart
@@ -13,7 +13,7 @@ import "package:photos/models/search/search_constants.dart";
import "package:photos/models/search/search_result.dart";
import "package:photos/models/search/search_types.dart";
import "package:photos/models/selected_people.dart";
-import "package:photos/service_locator.dart" show isOfflineMode;
+import "package:photos/service_locator.dart" show isLocalGalleryMode;
import "package:photos/theme/ente_theme.dart";
import "package:photos/ui/settings/ml/machine_learning_settings_page.dart";
import "package:photos/ui/viewer/file/no_thumbnail_widget.dart";
@@ -31,11 +31,7 @@ class PeopleSection extends StatefulWidget {
final List<GenericSearchResult> examples;
final int limit;
- const PeopleSection({
- super.key,
- required this.examples,
- this.limit = 7,
- });
+ const PeopleSection({super.key, required this.examples, this.limit = 7});
@override
State<PeopleSection> createState() => _PeopleSectionState();
@@ -89,10 +85,7 @@ class _PeopleSectionState extends State<PeopleSection> {
behavior: HitTestBehavior.opaque,
onTap: () {
if (shouldShowMore) {
- routeToPage(
- context,
- const PeopleSectionAllPage(),
- );
+ routeToPage(context, const PeopleSectionAllPage());
}
},
child: Column(
@@ -126,10 +119,7 @@ class _PeopleSectionState extends State<PeopleSection> {
: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
- routeToPage(
- context,
- const MachineLearningSettingsPage(),
- );
+ routeToPage(context, const MachineLearningSettingsPage());
},
child: Padding(
padding: const EdgeInsets.only(left: 16, right: 8),
@@ -203,8 +193,9 @@ class PersonSearchExample extends StatelessWidget {
});
void toggleSelection() {
- selectedPeople
- ?.toggleSelection(searchResult.params[kPersonParamID]! as String);
+ selectedPeople?.toggleSelection(
+ searchResult.params[kPersonParamID]! as String,
+ );
}
@override
@@ -227,10 +218,7 @@ class PersonSearchExample extends StatelessWidget {
if (searchResult.onResultTap != null) {
searchResult.onResultTap!(context);
} else {
- routeToPage(
- context,
- SearchResultPage(searchResult),
- );
+ routeToPage(context, SearchResultPage(searchResult));
}
},
child: Column(
@@ -266,9 +254,7 @@ class PersonSearchExample extends StatelessWidget {
displaySize: size - 2,
);
} else {
- child = const NoThumbnailWidget(
- addBorder: false,
- );
+ child = const NoThumbnailWidget(addBorder: false);
}
return SizedBox(
width: size - 2,
@@ -309,7 +295,7 @@ class PersonSearchExample extends StatelessWidget {
],
),
isCluster
- ? isOfflineMode
+ ? isLocalGalleryMode
? const SizedBox.shrink()
: GestureDetector(
behavior: HitTestBehavior.translucent,
diff --git a/mobile/apps/photos/lib/ui/viewer/search_tab/search_tab.dart b/mobile/apps/photos/lib/ui/viewer/search_tab/search_tab.dart
index 804814270e..d4492738fc 100644
--- a/mobile/apps/photos/lib/ui/viewer/search_tab/search_tab.dart
+++ b/mobile/apps/photos/lib/ui/viewer/search_tab/search_tab.dart
@@ -70,10 +70,7 @@ class _SearchTabState extends State<SearchTab> {
children: [
ColoredBox(
color: headerColor,
- child: const SafeArea(
- bottom: false,
- child: SearchWidget(),
- ),
+ child: const SafeArea(bottom: false, child: SearchWidget()),
),
Expanded(
child: AllSectionsExamplesProvider(
@@ -113,13 +110,14 @@ class _AllSearchSectionsState extends State<AllSearchSections> {
child: Stack(
children: [
FutureBuilder<List<List<SearchResult>>>(
- future: InheritedAllSectionsExamples.of(context)
- .allSectionsExamplesFuture,
+ future: InheritedAllSectionsExamples.of(
+ context,
+ ).allSectionsExamplesFuture,
builder: (context, snapshot) {
if (snapshot.hasData && snapshot.data!.isNotEmpty) {
// In offline mode, skip the empty state check since DeviceAlbumsSection
// fetches its own data and may have albums to show
- if (!isOfflineMode &&
+ if (!isLocalGalleryMode &&
snapshot.data!.every((element) => element.isEmpty)) {
return const Padding(
padding: EdgeInsets.only(bottom: 72),
@@ -138,7 +136,7 @@ class _AllSearchSectionsState extends State<AllSearchSections> {
);
}
final faceSectionIndex = searchTypes.indexOf(SectionType.face);
- final hasSurfacedOfflineFaces = isOfflineMode &&
+ final hasSurfacedOfflineFaces = isLocalGalleryMode &&
faceSectionIndex >= 0 &&
faceSectionIndex < snapshot.data!.length &&
snapshot.data!.elementAt(faceSectionIndex).isNotEmpty;
@@ -148,7 +146,9 @@ class _AllSearchSectionsState extends State<AllSearchSections> {
itemCount: searchTypes.length + 1,
itemBuilder: (context, index) {
if (index == 0) {
- if (!isOfflineMode) return const SizedBox.shrink();
+ if (!isLocalGalleryMode) {
+ return const SizedBox.shrink();
+ }
if (hasSurfacedOfflineFaces) {
return const SizedBox.shrink();
}
@@ -166,7 +166,7 @@ class _AllSearchSectionsState extends State<AllSearchSections> {
as List<GenericSearchResult>,
);
case SectionType.album:
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
return const DeviceAlbumsSection();
}
return AlbumsSection(
@@ -174,7 +174,7 @@ class _AllSearchSectionsState extends State<AllSearchSections> {
as List<AlbumSearchResult>,
);
case SectionType.ritual:
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
return const SizedBox.shrink();
}
return const _RitualsDiscoverySection();
@@ -189,7 +189,9 @@ class _AllSearchSectionsState extends State<AllSearchSections> {
if (!wrappedService.shouldShowDiscoveryEntry) {
return const SizedBox.shrink();
}
- return WrappedDiscoverySection(state: state);
+ return WrappedDiscoverySection(
+ state: state,
+ );
},
);
case SectionType.location:
@@ -212,9 +214,7 @@ class _AllSearchSectionsState extends State<AllSearchSections> {
}
},
)
- .animate(
- delay: const Duration(milliseconds: 150),
- )
+ .animate(delay: const Duration(milliseconds: 150))
.slide(
begin: const Offset(0, -0.015),
end: const Offset(0, 0),
diff --git a/mobile/apps/photos/lib/utils/delete_file_util.dart b/mobile/apps/photos/lib/utils/delete_file_util.dart
index 4da8e4a7ae..08a2a4f470 100644
--- a/mobile/apps/photos/lib/utils/delete_file_util.dart
+++ b/mobile/apps/photos/lib/utils/delete_file_util.dart
@@ -59,7 +59,7 @@ Future<void> deleteFilesFromEverywhere(
hasLocalOnlyFiles = true;
}
}
- if (hasLocalOnlyFiles && Platform.isAndroid && !isOfflineMode) {
+ if (hasLocalOnlyFiles && Platform.isAndroid && !isLocalGalleryMode) {
final shouldProceed = await shouldProceedWithDeletion(context);
if (!shouldProceed) {
return;
@@ -67,8 +67,10 @@ Future<void> deleteFilesFromEverywhere(
}
Set<String> deletedIDs = <String>{};
try {
- deletedIDs =
- (await PhotoManager.editor.deleteWithIds(localAssetIDs)).toSet();
+ deletedIDs = (await PhotoManager.editor.deleteWithIds(
+ localAssetIDs,
+ ))
+ .toSet();
} catch (e, s) {
_logger.severe("Could not delete file", e, s);
}
@@ -83,8 +85,9 @@ Future<void> deleteFilesFromEverywhere(
alreadyDeletedIDs.contains(file.localID)) {
deletedFiles.add(file);
if (file.uploadedFileID != null) {
- uploadedFilesToBeTrashed
- .add(TrashRequest(file.uploadedFileID!, file.collectionID!));
+ uploadedFilesToBeTrashed.add(
+ TrashRequest(file.uploadedFileID!, file.collectionID!),
+ );
updatedCollectionIDs.add(file.collectionID!);
} else {
await FilesDB.instance.deleteLocalFile(file);
@@ -93,8 +96,9 @@ Future<void> deleteFilesFromEverywhere(
} else {
updatedCollectionIDs.add(file.collectionID!);
deletedFiles.add(file);
- uploadedFilesToBeTrashed
- .add(TrashRequest(file.uploadedFileID!, file.collectionID!));
+ uploadedFilesToBeTrashed.add(
+ TrashRequest(file.uploadedFileID!, file.collectionID!),
+ );
}
}
if (uploadedFilesToBeTrashed.isNotEmpty) {
@@ -219,7 +223,7 @@ Future<void> deleteFilesOnDeviceOnly(
localOnlyIDs.add(file.localID);
}
}
- if (hasLocalOnlyFiles && Platform.isAndroid && !isOfflineMode) {
+ if (hasLocalOnlyFiles && Platform.isAndroid && !isLocalGalleryMode) {
final shouldProceed = await shouldProceedWithDeletion(context);
if (!shouldProceed) {
return;
@@ -227,8 +231,10 @@ Future<void> deleteFilesOnDeviceOnly(
}
Set<String> deletedIDs = <String>{};
try {
- deletedIDs =
- (await PhotoManager.editor.deleteWithIds(localAssetIDs)).toSet();
+ deletedIDs = (await PhotoManager.editor.deleteWithIds(
+ localAssetIDs,
+ ))
+ .toSet();
} catch (e, s) {
_logger.severe("Could not delete file", e, s);
}
@@ -367,13 +373,15 @@ Future<bool> deleteLocalFiles(
);
} else {
_logger.info("Deleting in batches");
- deletedIDs
- .addAll(await deleteLocalFilesInBatches(context, localAssetIDs));
+ deletedIDs.addAll(
+ await deleteLocalFilesInBatches(context, localAssetIDs),
+ );
}
} else {
_logger.info("Deleting in one shot");
- deletedIDs
- .addAll(await _deleteLocalFilesInOneShot(context, localAssetIDs));
+ deletedIDs.addAll(
+ await _deleteLocalFilesInOneShot(context, localAssetIDs),
+ );
}
if (deletedIDs.isEmpty && Platform.isIOS) {
_logger.warning(
@@ -420,8 +428,10 @@ Future<bool> deleteLocalFilesAfterRemovingAlreadyDeletedIDs(
final dialog = createProgressDialog(context, "Loading...");
await dialog.show();
try {
- final files =
- await FilesDB.instance.getLocalFiles(localIDs, dedupeByLocalID: true);
+ final files = await FilesDB.instance.getLocalFiles(
+ localIDs,
+ dedupeByLocalID: true,
+ );
for (final file in files) {
if (!(await _localFileExist(file))) {
_logger.warning("Already deleted ${file.tag}");
@@ -437,16 +447,19 @@ Future<bool> deleteLocalFilesAfterRemovingAlreadyDeletedIDs(
await dialog.hide();
- final bool shouldDeleteInBatches =
- await isAndroidSDKVersionLowerThan(android11SDKINT);
+ final bool shouldDeleteInBatches = await isAndroidSDKVersionLowerThan(
+ android11SDKINT,
+ );
if (shouldDeleteInBatches) {
_logger.info("Deleting in batches");
- deletedIDs
- .addAll(await deleteLocalFilesInBatches(context, localAssetIDs));
+ deletedIDs.addAll(
+ await deleteLocalFilesInBatches(context, localAssetIDs),
+ );
} else {
_logger.info("Deleting in one shot");
- deletedIDs
- .addAll(await _deleteLocalFilesInOneShot(context, localAssetIDs));
+ deletedIDs.addAll(
+ await _deleteLocalFilesInOneShot(context, localAssetIDs),
+ );
}
if (deletedIDs.isEmpty && Platform.isIOS) {
@@ -487,8 +500,10 @@ Future<bool> retryFreeUpSpaceAfterRemovingAssetsNonExistingInDisk(
"Retrying free up space after removing assets non-existing in disk",
);
- final dialog =
- createProgressDialog(context, context.l10n.pleaseWaitThisWillTakeAWhile);
+ final dialog = createProgressDialog(
+ context,
+ context.l10n.pleaseWaitThisWillTakeAWhile,
+ );
await dialog.show();
try {
final stopwatch = Stopwatch()..start();
@@ -518,16 +533,19 @@ Future<bool> retryFreeUpSpaceAfterRemovingAssetsNonExistingInDisk(
await dialog.hide();
- final bool shouldDeleteInBatches =
- await isAndroidSDKVersionLowerThan(android11SDKINT);
+ final bool shouldDeleteInBatches = await isAndroidSDKVersionLowerThan(
+ android11SDKINT,
+ );
if (shouldDeleteInBatches) {
_logger.info("Deleting in batches");
- deletedIDs
- .addAll(await deleteLocalFilesInBatches(context, localAssetIDs));
+ deletedIDs.addAll(
+ await deleteLocalFilesInBatches(context, localAssetIDs),
+ );
} else {
_logger.info("Deleting in one shot");
- deletedIDs
- .addAll(await _deleteLocalFilesInOneShot(context, localAssetIDs));
+ deletedIDs.addAll(
+ await _deleteLocalFilesInOneShot(context, localAssetIDs),
+ );
}
if (deletedIDs.isNotEmpty) {
@@ -733,8 +751,10 @@ Future<void> showDeleteSheet(
FilesSplit filesSplit,
) async {
if (selectedFiles.files.length != filesSplit.count) {
- throw AssertionError("Unexpected state, #{selectedFiles.files.length} != "
- "${filesSplit.count}");
+ throw AssertionError(
+ "Unexpected state, #{selectedFiles.files.length} != "
+ "${filesSplit.count}",
+ );
}
final List<EnteFile> deletableFiles =
filesSplit.ownedByCurrentUser + filesSplit.pendingUploads;
@@ -745,7 +765,7 @@ Future<void> showDeleteSheet(
);
return;
}
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
final offlineDeletableFiles =
deletableFiles.where((file) => file.localID != null).toList();
if (offlineDeletableFiles.isEmpty) {
@@ -773,8 +793,9 @@ Future<void> showDeleteSheet(
if (isBothLocalAndRemote) {
body = AppLocalizations.of(context).someItemsAreInBothEnteAndYourDevice;
} else if (isRemoteOnly) {
- body = AppLocalizations.of(context)
- .selectedItemsWillBeDeletedFromAllAlbumsAndMoved;
+ body = AppLocalizations.of(
+ context,
+ ).selectedItemsWillBeDeletedFromAllAlbumsAndMoved;
} else if (isLocalOnly) {
body = AppLocalizations.of(context).theseItemsWillBeDeletedFromYourDevice;
} else {
@@ -794,10 +815,7 @@ Future<void> showDeleteSheet(
shouldSurfaceExecutionStates: true,
isInAlert: true,
onTap: () async {
- await deleteFilesFromRemoteOnly(
- context,
- deletableFiles,
- ).then(
+ await deleteFilesFromRemoteOnly(context, deletableFiles).then(
(value) {
showShortToast(
context,
@@ -843,10 +861,7 @@ Future<void> showDeleteSheet(
shouldSurfaceExecutionStates: true,
isInAlert: true,
onTap: () async {
- await deleteFilesFromEverywhere(
- context,
- deletableFiles,
- );
+ await deleteFilesFromEverywhere(context, deletableFiles);
},
),
);
diff --git a/mobile/apps/photos/lib/utils/face/face_thumbnail_cache.dart b/mobile/apps/photos/lib/utils/face/face_thumbnail_cache.dart
index aafe96a151..bbf6881a62 100644
--- a/mobile/apps/photos/lib/utils/face/face_thumbnail_cache.dart
+++ b/mobile/apps/photos/lib/utils/face/face_thumbnail_cache.dart
@@ -13,7 +13,7 @@ import "package:photos/models/file/file.dart";
import "package:photos/models/file/file_type.dart";
import "package:photos/models/ml/face/box.dart";
import "package:photos/models/ml/face/face.dart";
-import "package:photos/service_locator.dart" show isOfflineMode;
+import "package:photos/service_locator.dart" show isLocalGalleryMode;
import "package:photos/services/machine_learning/face_thumbnail_generator.dart";
import "package:photos/utils/file_util.dart";
import "package:photos/utils/thumbnail_util.dart";
@@ -40,8 +40,9 @@ TaskQueue _queueThumbnailFaceGenerations = TaskQueue<String>(
Uint8List? checkInMemoryCachedCropForPersonOrClusterID(
String personOrClusterID,
) {
- final String? faceID =
- _personOrClusterIdToCachedFaceID.get(personOrClusterID);
+ final String? faceID = _personOrClusterIdToCachedFaceID.get(
+ personOrClusterID,
+ );
if (faceID == null) return null;
final Uint8List? cachedCover = _faceCropCache.get(faceID);
return cachedCover;
@@ -55,12 +56,15 @@ Uint8List? _checkInMemoryCachedCropForFaceID(String faceID) {
Future<String?> checkUsedFaceIDForPersonOrClusterId(
String personOrClusterID,
) async {
- final String? cachedFaceID =
- _personOrClusterIdToCachedFaceID.get(personOrClusterID);
+ final String? cachedFaceID = _personOrClusterIdToCachedFaceID.get(
+ personOrClusterID,
+ );
if (cachedFaceID != null) return cachedFaceID;
- final mlDataDB = isOfflineMode ? MLDataDB.offlineInstance : MLDataDB.instance;
- final String? faceIDFromDB =
- await mlDataDB.getFaceIdUsedForPersonOrCluster(personOrClusterID);
+ final mlDataDB =
+ isLocalGalleryMode ? MLDataDB.offlineInstance : MLDataDB.instance;
+ final String? faceIDFromDB = await mlDataDB.getFaceIdUsedForPersonOrCluster(
+ personOrClusterID,
+ );
if (faceIDFromDB != null) {
_personOrClusterIdToCachedFaceID.put(personOrClusterID, faceIDFromDB);
}
@@ -71,11 +75,9 @@ Future<void> putFaceIdCachedForPersonOrCluster(
String personOrClusterID,
String faceID,
) async {
- final mlDataDB = isOfflineMode ? MLDataDB.offlineInstance : MLDataDB.instance;
- await mlDataDB.putFaceIdCachedForPersonOrCluster(
- personOrClusterID,
- faceID,
- );
+ final mlDataDB =
+ isLocalGalleryMode ? MLDataDB.offlineInstance : MLDataDB.instance;
+ await mlDataDB.putFaceIdCachedForPersonOrCluster(personOrClusterID, faceID);
_personOrClusterIdToCachedFaceID.put(personOrClusterID, faceID);
}
@@ -93,9 +95,11 @@ Future<void> _putCachedCropForFaceID(
Future<void> checkRemoveCachedFaceIDForPersonOrClusterId(
String personOrClusterID,
) async {
- final mlDataDB = isOfflineMode ? MLDataDB.offlineInstance : MLDataDB.instance;
- final String? cachedFaceID =
- await mlDataDB.getFaceIdUsedForPersonOrCluster(personOrClusterID);
+ final mlDataDB =
+ isLocalGalleryMode ? MLDataDB.offlineInstance : MLDataDB.instance;
+ final String? cachedFaceID = await mlDataDB.getFaceIdUsedForPersonOrCluster(
+ personOrClusterID,
+ );
if (cachedFaceID != null) {
_personOrClusterIdToCachedFaceID.remove(personOrClusterID);
await mlDataDB.removeFaceIdCachedForPersonOrCluster(personOrClusterID);
@@ -115,8 +119,9 @@ Future<Map<String, Uint8List>?> getCachedFaceCrops(
final faceIdToCrop = <String, Uint8List>{};
final facesWithoutCrops = <String, FaceBox>{};
for (final face in faces) {
- final Uint8List? cachedFace =
- _checkInMemoryCachedCropForFaceID(face.faceID);
+ final Uint8List? cachedFace = _checkInMemoryCachedCropForFaceID(
+ face.faceID,
+ );
if (cachedFace != null) {
faceIdToCrop[face.faceID] = cachedFace;
} else {
@@ -158,8 +163,9 @@ Future<Map<String, Uint8List>?> getCachedFaceCrops(
if (!useFullFile) {
for (final face in faces) {
if (facesWithoutCrops.containsKey(face.faceID)) {
- final Uint8List? cachedFaceThumbnail =
- _faceCropThumbnailCache.get(face.faceID);
+ final Uint8List? cachedFaceThumbnail = _faceCropThumbnailCache.get(
+ face.faceID,
+ );
if (cachedFaceThumbnail != null) {
faceIdToCrop[face.faceID] = cachedFaceThumbnail;
facesWithoutCrops.remove(face.faceID);
@@ -278,11 +284,7 @@ Future<Uint8List?> precomputeClusterFaceCrop(
w?.logAndReset('getCachedFaceCrops');
return cropMap?[face.faceID];
} catch (e, s) {
- _logger.severe(
- "Error getting cover face for cluster $clusterID",
- e,
- s,
- );
+ _logger.severe("Error getting cover face for cluster $clusterID", e, s);
return null;
}
}
@@ -333,11 +335,12 @@ Future<String> _faceCropTaskId(
required bool useFullFile,
}) async {
final suffix = useFullFile ? "-full" : "-thumbnail";
- if (isOfflineMode) {
+ if (isLocalGalleryMode) {
final localId = file.localID;
if (localId != null && localId.isNotEmpty) {
- final localIntId =
- await OfflineFilesDB.instance.getOrCreateLocalIntId(localId);
+ final localIntId = await OfflineFilesDB.instance.getOrCreateLocalIntId(
+ localId,
+ );
return "$localIntId$suffix";
}
return "${file.hashCode}$suffix";
diff --git a/mobile/apps/photos/lib/utils/local_settings.dart b/mobile/apps/photos/lib/utils/local_settings.dart
index 7c6978d6d9..7590492849 100644
--- a/mobile/apps/photos/lib/utils/local_settings.dart
+++ b/mobile/apps/photos/lib/utils/local_settings.dart
@@ -8,27 +8,13 @@ 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';
-enum AlbumSortKey {
- albumName,
- newestPhoto,
- lastUpdated,
-}
+enum AlbumSortKey { albumName, newestPhoto, lastUpdated }
-enum AlbumSortDirection {
- ascending,
- descending,
-}
+enum AlbumSortDirection { ascending, descending }
-enum AlbumViewType {
- grid,
- list,
-}
+enum AlbumViewType { grid, list }
-enum PeopleSortKey {
- mostPhotos,
- name,
- lastUpdated,
-}
+enum PeopleSortKey { mostPhotos, name, lastUpdated }
/// Bit positions for per-widget-type "hide text" flags stored as a single
/// integer. The same integer is mirrored to the home_widget plugin's data
@@ -36,9 +22,9 @@ enum PeopleSortKey {
/// IMPORTANT: Never reorder or remove values. Only append new values at the end.
enum WidgetHideTextFlag { memory, album, people }
-/// Bit positions for offline-related boolean flags stored as a single integer.
+/// Bit positions for local-gallery boolean flags stored as a single integer.
/// IMPORTANT: Never reorder or remove values. Only append new values at the end.
-enum OfflineFlag {
+enum LocalGalleryFlag {
mlConsent,
mapEnabled,
// Reserved: previously getStartedBannerDismissed. Kept to preserve bit
@@ -48,7 +34,7 @@ enum OfflineFlag {
nameFaceBannerDismissed,
seenMLEnablingBanner,
mlProgressBannerDismissed,
- offlineSettingsBannerDismissed,
+ localGallerySettingsBannerDismissed,
}
class LocalSettings {
@@ -56,7 +42,8 @@ class LocalSettings {
static const kGalleryGroupType = "gallery_group_type";
static const kPhotoGridSize = "photo_grid_size";
static const _kisMLLocalIndexingEnabled = "ls.ml_local_indexing";
- static const _kOfflineMLLocalIndexingEnabled = "ls.offline_ml_local_indexing";
+ static const _kLocalGalleryMLLocalIndexingEnabled =
+ "ls.offline_ml_local_indexing";
static const kRateUsShownCount = "rate_us_shown_count";
static const kEnableMultiplePart = "ls.enable_multiple_part";
static const kCuratedMemoriesEnabled = "ls.curated_memories_enabled";
@@ -100,7 +87,7 @@ class LocalSettings {
static const _kSemanticSearchExactInRustEnabled =
"ml_debug.semantic_search_exact_in_rust";
static const _kAppMode = "ls.app_mode";
- static const _kShowOfflineModeOption = "ls.show_offline_mode_option";
+ static const _kShowLocalGalleryModeOption = "ls.show_offline_mode_option";
static const _kWidgetHideTextFlags = "ls.widget_hide_text_flags";
@@ -109,11 +96,13 @@ class LocalSettings {
/// data store. Must stay in sync with the native code.
static const _kWidgetHideTextFlagsNativeKey = "widgetHideTitleFlags";
- static const _kOfflineFlags = "ls.offline_flags";
- static const _kOfflineMapEnabled = "ls.offline_map_enabled";
- static const _kOfflineGetStartedBannerDismissedAt =
+ static const _kLocalGalleryFlags = "ls.offline_flags";
+ static const _kLocalGalleryMapEnabled = "ls.offline_map_enabled";
+ static const _kLocalGalleryGetStartedBannerDismissedAt =
"ls.offline_get_started_banner_dismissed_at";
- static const _kOfflineGetStartedBannerDismissDuration = Duration(days: 7);
+ static const _kLocalGalleryGetStartedBannerDismissDuration = Duration(
+ days: 7,
+ );
final SharedPreferences _prefs;
@@ -121,19 +110,19 @@ class LocalSettings {
LocalSettings(this._prefs);
- bool _getFlag(OfflineFlag flag) {
- final bitmap = _prefs.getInt(_kOfflineFlags) ?? 0;
+ bool _getFlag(LocalGalleryFlag flag) {
+ final bitmap = _prefs.getInt(_kLocalGalleryFlags) ?? 0;
return (bitmap & (1 << flag.index)) != 0;
}
- Future<void> _setFlag(OfflineFlag flag, bool value) {
- var bitmap = _prefs.getInt(_kOfflineFlags) ?? 0;
+ Future<void> _setFlag(LocalGalleryFlag flag, bool value) {
+ var bitmap = _prefs.getInt(_kLocalGalleryFlags) ?? 0;
if (value) {
bitmap |= (1 << flag.index);
} else {
bitmap &= ~(1 << flag.index);
}
- return _prefs.setInt(_kOfflineFlags, bitmap);
+ return _prefs.setInt(_kLocalGalleryFlags, bitmap);
}
bool isWidgetTextHidden(WidgetHideTextFlag flag) {
@@ -287,24 +276,25 @@ class LocalSettings {
return getRateUsShownCount() < kRateUsPromptThreshold;
}
- bool get offlineMLConsent => _getFlag(OfflineFlag.mlConsent);
+ bool get localGalleryMLConsent => _getFlag(LocalGalleryFlag.mlConsent);
- Future<void> setOfflineMLConsent(bool value) =>
- _setFlag(OfflineFlag.mlConsent, value);
+ Future<void> setLocalGalleryMLConsent(bool value) =>
+ _setFlag(LocalGalleryFlag.mlConsent, value);
- bool get offlineMapEnabled => _prefs.getBool(_kOfflineMapEnabled) ?? true;
+ bool get localGalleryMapEnabled =>
+ _prefs.getBool(_kLocalGalleryMapEnabled) ?? true;
- Future<void> setOfflineMapEnabled(bool value) async {
- await _prefs.setBool(_kOfflineMapEnabled, value);
- await _setFlag(OfflineFlag.mapEnabled, value);
+ Future<void> setLocalGalleryMapEnabled(bool value) async {
+ await _prefs.setBool(_kLocalGalleryMapEnabled, value);
+ await _setFlag(LocalGalleryFlag.mapEnabled, value);
}
- String get _mlLocalIndexingKey => appMode == AppMode.offline
- ? _kOfflineMLLocalIndexingEnabled
+ String get _mlLocalIndexingKey => appMode == AppMode.localGallery
+ ? _kLocalGalleryMLLocalIndexingEnabled
: _kisMLLocalIndexingEnabled;
- bool get _defaultMLLocalIndexingEnabled => appMode == AppMode.offline
- ? enoughRamForOfflineLocalIndexing
+ bool get _defaultMLLocalIndexingEnabled => appMode == AppMode.localGallery
+ ? enoughRamForLocalGalleryLocalIndexing
: enoughRamForLocalIndexing;
bool get isMLLocalIndexingEnabled {
@@ -396,9 +386,9 @@ class LocalSettings {
}
bool get hasSeenMLEnablingBanner =>
- _getFlag(OfflineFlag.seenMLEnablingBanner);
+ _getFlag(LocalGalleryFlag.seenMLEnablingBanner);
Future<void> setHasSeenMLEnablingBanner() =>
- _setFlag(OfflineFlag.seenMLEnablingBanner, true);
+ _setFlag(LocalGalleryFlag.seenMLEnablingBanner, true);
bool hasSeenMemoryLane(String personId) {
final seenIds = _prefs.getStringList(_memoryLaneSeenKey);
@@ -547,7 +537,7 @@ class LocalSettings {
return _cachedAppMode!;
}
- _cachedAppMode = AppMode.online;
+ _cachedAppMode = AppMode.enteGallery;
return _cachedAppMode!;
}
@@ -558,53 +548,53 @@ class LocalSettings {
_cachedAppMode = mode;
}
- bool get showOfflineModeOption =>
- _prefs.getBool(_kShowOfflineModeOption) ?? true;
+ bool get showLocalGalleryModeOption =>
+ _prefs.getBool(_kShowLocalGalleryModeOption) ?? true;
- Future<void> setShowOfflineModeOption(bool value) async {
- await _prefs.setBool(_kShowOfflineModeOption, value);
+ Future<void> setShowLocalGalleryModeOption(bool value) async {
+ await _prefs.setBool(_kShowLocalGalleryModeOption, value);
}
- bool get isOfflineGetStartedBannerDismissed {
+ bool get isLocalGalleryGetStartedBannerDismissed {
final dismissedAtMs =
- _prefs.getInt(_kOfflineGetStartedBannerDismissedAt) ?? 0;
+ _prefs.getInt(_kLocalGalleryGetStartedBannerDismissedAt) ?? 0;
if (dismissedAtMs == 0) return false;
final elapsed = DateTime.now().millisecondsSinceEpoch - dismissedAtMs;
return elapsed >= 0 &&
- elapsed < _kOfflineGetStartedBannerDismissDuration.inMilliseconds;
+ elapsed < _kLocalGalleryGetStartedBannerDismissDuration.inMilliseconds;
}
- Future<void> setOfflineGetStartedBannerDismissed(bool value) {
+ Future<void> setLocalGalleryGetStartedBannerDismissed(bool value) {
if (value) {
return _prefs.setInt(
- _kOfflineGetStartedBannerDismissedAt,
+ _kLocalGalleryGetStartedBannerDismissedAt,
DateTime.now().millisecondsSinceEpoch,
);
}
- return _prefs.remove(_kOfflineGetStartedBannerDismissedAt);
+ return _prefs.remove(_kLocalGalleryGetStartedBannerDismissedAt);
}
bool get isMLProgressBannerDismissed =>
- _getFlag(OfflineFlag.mlProgressBannerDismissed);
+ _getFlag(LocalGalleryFlag.mlProgressBannerDismissed);
Future<void> setMLProgressBannerDismissed(bool value) =>
- _setFlag(OfflineFlag.mlProgressBannerDismissed, value);
+ _setFlag(LocalGalleryFlag.mlProgressBannerDismissed, value);
- bool get isOfflineFacesBannerDismissed =>
- _getFlag(OfflineFlag.facesBannerDismissed);
+ bool get isLocalGalleryFacesBannerDismissed =>
+ _getFlag(LocalGalleryFlag.facesBannerDismissed);
- Future<void> setOfflineFacesBannerDismissed(bool value) =>
- _setFlag(OfflineFlag.facesBannerDismissed, value);
+ Future<void> setLocalGalleryFacesBannerDismissed(bool value) =>
+ _setFlag(LocalGalleryFlag.facesBannerDismissed, value);
- bool get isOfflineNameFaceBannerDismissed =>
- _getFlag(OfflineFlag.nameFaceBannerDismissed);
+ bool get isLocalGalleryNameFaceBannerDismissed =>
+ _getFlag(LocalGalleryFlag.nameFaceBannerDismissed);
- Future<void> setOfflineNameFaceBannerDismissed(bool value) =>
- _setFlag(OfflineFlag.nameFaceBannerDismissed, value);
+ Future<void> setLocalGalleryNameFaceBannerDismissed(bool value) =>
+ _setFlag(LocalGalleryFlag.nameFaceBannerDismissed, value);
- bool get isOfflineSettingsBannerDismissed =>
- _getFlag(OfflineFlag.offlineSettingsBannerDismissed);
+ bool get isLocalGallerySettingsBannerDismissed =>
+ _getFlag(LocalGalleryFlag.localGallerySettingsBannerDismissed);
- Future<void> setOfflineSettingsBannerDismissed(bool value) =>
- _setFlag(OfflineFlag.offlineSettingsBannerDismissed, value);
+ Future<void> setLocalGallerySettingsBannerDismissed(bool value) =>
+ _setFlag(LocalGalleryFlag.localGallerySettingsBannerDismissed, value);
}
diff --git a/mobile/apps/photos/lib/utils/ml_util.dart b/mobile/apps/photos/lib/utils/ml_util.dart
index 4f21dedcfb..2ec3b2ac63 100644
--- a/mobile/apps/photos/lib/utils/ml_util.dart
+++ b/mobile/apps/photos/lib/utils/ml_util.dart
@@ -43,7 +43,7 @@ const _kMlStaleCleanupMaxIds = 5;
enum FileDataForML { thumbnailData, fileData }
-enum MLMode { online, offline }
+enum MLMode { enteGallery, localGallery }
class IndexStatus {
final int indexedItems, pendingItems;
@@ -70,8 +70,8 @@ class FileMLInstruction {
this.shouldRunPets = false,
});
bool get pendingML => shouldRunFaces || shouldRunClip || shouldRunPets;
- bool get isOffline => mode == MLMode.offline;
- int get fileKey => isOffline ? offlineFileKey! : file.uploadedFileID!;
+ bool get isLocalGallery => mode == MLMode.localGallery;
+ int get fileKey => isLocalGallery ? offlineFileKey! : file.uploadedFileID!;
}
class RemoteMLHydrationSummary {
@@ -102,9 +102,11 @@ class _OnlineMLIndexingCandidates {
Future<IndexStatus> getIndexStatus() async {
try {
- final MLMode mode = isOfflineMode ? MLMode.offline : MLMode.online;
- final mlDataDB =
- mode == MLMode.offline ? MLDataDB.offlineInstance : MLDataDB.instance;
+ final MLMode mode =
+ isLocalGalleryMode ? MLMode.localGallery : MLMode.enteGallery;
+ final mlDataDB = mode == MLMode.localGallery
+ ? MLDataDB.offlineInstance
+ : MLDataDB.instance;
final int indexableFiles = await _getIndexableFileCount(mode: mode);
final int facesIndexedFiles = await mlDataDB.getFaceIndexedFileCount();
final int clipIndexedFiles = await mlDataDB.getClipIndexedFileCount();
@@ -112,7 +114,7 @@ Future<IndexStatus> getIndexStatus() async {
if (flagService.petEnabled &&
localSettings.petRecognitionEnabled &&
localSettings.isMLLocalIndexingEnabled &&
- (flagService.useRustForML || isOfflineMode)) {
+ (flagService.useRustForML || isLocalGalleryMode)) {
final int petIndexedFiles = await mlDataDB.getPetIndexedFileCount();
indexedFiles = math.min(indexedFiles, petIndexedFiles);
}
@@ -121,7 +123,7 @@ Future<IndexStatus> getIndexStatus() async {
final showPendingFiles = math.max(indexableFiles - indexedFiles, 0);
final hasWifiEnabled = await canUseHighBandwidth();
_logger.info(
- "Shown IndexStatus: indexedFiles: $showIndexedFiles, pendingFiles: $showPendingFiles, hasWifiEnabled: $hasWifiEnabled, ifOffline: $isOfflineMode. Real values: indexedFiles: $indexedFiles (faces: $facesIndexedFiles, clip: $clipIndexedFiles), indexableFiles: $indexableFiles",
+ "Shown IndexStatus: indexedFiles: $showIndexedFiles, pendingFiles: $showPendingFiles, hasWifiEnabled: $hasWifiEnabled, ifOffline: $isLocalGalleryMode. Real values: indexedFiles: $indexedFiles (faces: $facesIndexedFiles, clip: $clipIndexedFiles), indexableFiles: $indexableFiles",
);
return IndexStatus(showIndexedFiles, showPendingFiles, hasWifiEnabled);
} catch (e, s) {
@@ -146,7 +148,7 @@ Future<_OnlineMLIndexingCandidates>
final bool petEnabled = flagService.petEnabled &&
localSettings.petRecognitionEnabled &&
localSettings.isMLLocalIndexingEnabled &&
- (flagService.useRustForML || isOfflineMode);
+ (flagService.useRustForML || isLocalGalleryMode);
final Map<int, int> petIndexedFileIDs =
petEnabled ? await mlDataDB.petIndexedFileIds() : const {};
final Set<int> queuedFiledIDs = {};
@@ -175,10 +177,16 @@ Future<_OnlineMLIndexingCandidates>
}
queuedFiledIDs.add(enteFile.uploadedFileID!);
- final shouldRunFaces =
- _shouldRunIndexing(enteFile, faceIndexedFileIDs, faceMlVersion);
- final shouldRunClip =
- _shouldRunIndexing(enteFile, clipIndexedFileIDs, clipMlVersion);
+ final shouldRunFaces = _shouldRunIndexing(
+ enteFile,
+ faceIndexedFileIDs,
+ faceMlVersion,
+ );
+ final shouldRunClip = _shouldRunIndexing(
+ enteFile,
+ clipIndexedFileIDs,
+ clipMlVersion,
+ );
final shouldRunPets = petEnabled &&
_shouldRunIndexing(enteFile, petIndexedFileIDs, petMlVersion);
if (!shouldRunFaces && !shouldRunClip && !shouldRunPets) {
@@ -186,7 +194,7 @@ Future<_OnlineMLIndexingCandidates>
}
final instruction = FileMLInstruction(
file: enteFile,
- mode: MLMode.online,
+ mode: MLMode.enteGallery,
shouldRunFaces: shouldRunFaces,
shouldRunClip: shouldRunClip,
shouldRunPets: shouldRunPets,
@@ -208,10 +216,16 @@ Future<_OnlineMLIndexingCandidates>
continue;
}
queuedFiledIDs.add(enteFile.uploadedFileID!);
- final shouldRunFaces =
- _shouldRunIndexing(enteFile, faceIndexedFileIDs, faceMlVersion);
- final shouldRunClip =
- _shouldRunIndexing(enteFile, clipIndexedFileIDs, clipMlVersion);
+ final shouldRunFaces = _shouldRunIndexing(
+ enteFile,
+ faceIndexedFileIDs,
+ faceMlVersion,
+ );
+ final shouldRunClip = _shouldRunIndexing(
+ enteFile,
+ clipIndexedFileIDs,
+ clipMlVersion,
+ );
final shouldRunPets = petEnabled &&
_shouldRunIndexing(enteFile, petIndexedFileIDs, petMlVersion);
if (!shouldRunFaces && !shouldRunClip && !shouldRunPets) {
@@ -220,7 +234,7 @@ Future<_OnlineMLIndexingCandidates>
hiddenFilesToIndex.add(
FileMLInstruction(
file: enteFile,
- mode: MLMode.online,
+ mode: MLMode.enteGallery,
shouldRunFaces: shouldRunFaces,
shouldRunClip: shouldRunClip,
shouldRunPets: shouldRunPets,
@@ -279,7 +293,7 @@ Future<List<FileMLInstruction>> getOfflineFilesForMlIndexing() async {
await mlDataDB.clipIndexedFileWithVersion();
final bool petEnabled = flagService.petEnabled &&
localSettings.petRecognitionEnabled &&
- (flagService.useRustForML || isOfflineMode);
+ (flagService.useRustForML || isLocalGalleryMode);
final Map<int, int> petIndexedFileIDs =
petEnabled ? await mlDataDB.petIndexedFileIds() : const {};
final Set<int> queuedFileIDs = {};
@@ -302,8 +316,9 @@ Future<List<FileMLInstruction>> getOfflineFilesForMlIndexing() async {
localIds.add(localID);
}
- final localIdToIntId =
- await OfflineFilesDB.instance.ensureLocalIntIds(localIds);
+ final localIdToIntId = await OfflineFilesDB.instance.ensureLocalIntIds(
+ localIds,
+ );
for (final enteFile in candidateFiles) {
final localID = enteFile.localID!;
@@ -337,7 +352,7 @@ Future<List<FileMLInstruction>> getOfflineFilesForMlIndexing() async {
instructions.add(
FileMLInstruction(
file: enteFile,
- mode: MLMode.offline,
+ mode: MLMode.localGallery,
offlineFileKey: localIntId,
shouldRunFaces: shouldRunFaces,
shouldRunClip: shouldRunClip,
@@ -355,7 +370,7 @@ Stream<List<FileMLInstruction>> fetchEmbeddingsAndInstructions(
int yieldSize, {
required MLMode mode,
}) async* {
- if (mode == MLMode.offline) {
+ if (mode == MLMode.localGallery) {
final List<FileMLInstruction> filesToIndex =
await getOfflineFilesForMlIndexing();
final List<List<FileMLInstruction>> chunks = filesToIndex.chunks(yieldSize);
@@ -366,8 +381,9 @@ Stream<List<FileMLInstruction>> fetchEmbeddingsAndInstructions(
}
final mlDataDB = MLDataDB.instance;
final List<FileMLInstruction> filesToIndex = await getFilesForMlIndexing();
- final List<List<FileMLInstruction>> chunks =
- filesToIndex.chunks(embeddingFetchLimit);
+ final List<List<FileMLInstruction>> chunks = filesToIndex.chunks(
+ embeddingFetchLimit,
+ );
List<FileMLInstruction> batchToYield = [];
for (final chunk in chunks) {
@@ -468,8 +484,9 @@ Future<FileDataResponse> _fetchFilesDataForMlHydrationWithRecovery(
await CollectionsService.instance.sync();
final suspects = <int>{};
for (final id in batchIds) {
- final collectionIds =
- await FilesDB.instance.getAllCollectionIDsOfFile(id);
+ final collectionIds = await FilesDB.instance.getAllCollectionIDsOfFile(
+ id,
+ );
final hasAccess = collectionIds.any((cid) {
final c = CollectionsService.instance.getCollectionByID(cid);
return c != null && !c.isDeleted;
@@ -528,7 +545,7 @@ Future<List<FileMLInstruction>> hydrateRemoteMLDataForInstructions(
final Set<int> ids = {};
final Map<int, FileMLInstruction> pendingIndex = {};
for (final instruction in instructions) {
- if (instruction.isOffline) {
+ if (instruction.isLocalGallery) {
continue;
}
ids.add(instruction.file.uploadedFileID!);
@@ -592,9 +609,7 @@ List<Face>? _getFacesFromRemoteEmbedding(FileDataEntity fileMl) {
}
final List<Face> faces = [];
if (remoteFaceEmbedding!.faces.isEmpty) {
- faces.add(
- Face.empty(fileMl.fileID),
- );
+ faces.add(Face.empty(fileMl.fileID));
} else {
for (final f in remoteFaceEmbedding.faces) {
f.fileInfo = FileInfo(
@@ -611,8 +626,10 @@ bool _shouldDiscardRemoteEmbedding(FileDataEntity fileML) {
final fileID = fileML.fileID;
final RemoteFaceEmbedding? faceEmbedding = fileML.faceEmbedding;
if (faceEmbedding == null || faceEmbedding.version < faceMlVersion) {
- _logger.info("Discarding remote embedding for fileID $fileID "
- "because version is ${faceEmbedding?.version} and we need $faceMlVersion");
+ _logger.info(
+ "Discarding remote embedding for fileID $fileID "
+ "because version is ${faceEmbedding?.version} and we need $faceMlVersion",
+ );
return true;
}
// are all landmarks equal?
@@ -631,8 +648,10 @@ bool _shouldDiscardRemoteEmbedding(FileDataEntity fileML) {
}
}
if (allLandmarksEqual) {
- _logger.info("Discarding remote embedding for fileID $fileID "
- "because landmarks are equal");
+ _logger.info(
+ "Discarding remote embedding for fileID $fileID "
+ "because landmarks are equal",
+ );
_logger.info(
faceEmbedding.faces
.map((e) => e.detection.landmarks.toString())
@@ -650,7 +669,7 @@ Future<int> getIndexableFileCount() async {
}
Future<int> _getIndexableFileCount({required MLMode mode}) async {
- if (mode == MLMode.offline) {
+ if (mode == MLMode.localGallery) {
final files = await SearchService.instance.getAllFilesForSearch();
return files
.where(
@@ -694,11 +713,7 @@ Future<String> getImagePathForML(EnteFile enteFile) async {
}
file = await getFile(enteFile, isOrigin: true);
} catch (e, s) {
- _logger.severe(
- "Could not get file for $enteFile",
- e,
- s,
- );
+ _logger.severe("Could not get file for $enteFile", e, s);
}
}
imagePath = file?.path;
@@ -1259,10 +1274,7 @@ class _DecodeFallbackFile {
final File file;
final Directory directory;
- const _DecodeFallbackFile({
- required this.file,
- required this.directory,
- });
+ const _DecodeFallbackFile({required this.file, required this.directory});
}
Future<_DecodeFallbackFile?> _createJpegDecodeFallbackFile({
diff --git a/mobile/apps/photos/lib/utils/ram_check_util.dart b/mobile/apps/photos/lib/utils/ram_check_util.dart
index 45bccc049e..1593c3164b 100644
--- a/mobile/apps/photos/lib/utils/ram_check_util.dart
+++ b/mobile/apps/photos/lib/utils/ram_check_util.dart
@@ -9,7 +9,7 @@ bool get enoughRamForLocalIndexing =>
bool get hasLessThan5GBRAM =>
deviceTotalRAM != null && deviceTotalRAM! < 5 * 1024;
-bool get enoughRamForOfflineLocalIndexing =>
+bool get enoughRamForLocalGalleryLocalIndexing =>
deviceTotalRAM == null || deviceTotalRAM! > 3 * 1024;
/// Return the total amount of RAM in the device in MB
diff --git a/mobile/apps/photos/test/services/memories/photo_selector_test.dart b/mobile/apps/photos/test/services/memories/photo_selector_test.dart
index 39a34406ca..e086a933cc 100644
--- a/mobile/apps/photos/test/services/memories/photo_selector_test.dart
+++ b/mobile/apps/photos/test/services/memories/photo_selector_test.dart
@@ -91,13 +91,7 @@ Map<int, EmbeddingVector> _embMap(List<EmbeddingVector> embeddings) {
/// Creates a simple [FaceWithoutEmbedding] for testing.
FaceWithoutEmbedding _face(String faceID, int fileID) {
- return FaceWithoutEmbedding(
- faceID,
- fileID,
- 0.9,
- Detection.empty(),
- 50.0,
- );
+ return FaceWithoutEmbedding(faceID, fileID, 0.9, Detection.empty(), 50.0);
}
// ---------------------------------------------------------------------------
@@ -109,7 +103,7 @@ void main() {
test('memoryFileId returns uploadedFileID when not offline', () {
final f = _file(uploadedFileID: 42, creationTime: _baseTime);
expect(
- PhotoSelector.memoryFileId(f, isOfflineMode: false),
+ PhotoSelector.memoryFileId(f, isLocalGalleryMode: false),
equals(42),
);
});
@@ -121,7 +115,7 @@ void main() {
generatedID: 99,
);
expect(
- PhotoSelector.memoryFileId(f, isOfflineMode: true),
+ PhotoSelector.memoryFileId(f, isLocalGalleryMode: true),
equals(99),
);
});
@@ -147,30 +141,21 @@ void main() {
});
test('isTooCloseInTime returns false for null creationTime', () {
- expect(
- PhotoSelector.isTooCloseInTime(null, [_baseTime]),
- isFalse,
- );
+ expect(PhotoSelector.isTooCloseInTime(null, [_baseTime]), isFalse);
});
test('isNearDuplicate detects similar embeddings', () {
final e1 = _emb(1, seed: 100);
final e2 = _nearDuplicateEmb(2, e1);
final map = _embMap([e1, e2]);
- expect(
- PhotoSelector.isNearDuplicate(2, [1], map),
- isTrue,
- );
+ expect(PhotoSelector.isNearDuplicate(2, [1], map), isTrue);
});
test('isNearDuplicate allows distinct embeddings', () {
final e1 = _emb(1, seed: 100);
final e2 = _emb(2, seed: 200);
final map = _embMap([e1, e2]);
- expect(
- PhotoSelector.isNearDuplicate(2, [1], map),
- isFalse,
- );
+ expect(PhotoSelector.isNearDuplicate(2, [1], map), isFalse);
});
test('filterNearDuplicates removes visually similar memories', () {
@@ -186,7 +171,7 @@ void main() {
final result = PhotoSelector.filterNearDuplicates(
memories,
map,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
);
final ids = result.map((m) => m.file.uploadedFileID).toList();
expect(ids, contains(1));
@@ -198,10 +183,7 @@ void main() {
final memories = [
_mem(_file(uploadedFileID: 1, creationTime: _baseTime)),
_mem(
- _file(
- uploadedFileID: 2,
- creationTime: _baseTime + 5 * 60 * 1000000,
- ),
+ _file(uploadedFileID: 2, creationTime: _baseTime + 5 * 60 * 1000000),
), // 5 min later
_mem(_file(uploadedFileID: 3, creationTime: _baseTime + _hour)),
];
@@ -226,7 +208,7 @@ void main() {
memories.map((m) => _emb(m.file.uploadedFileID!)).toList();
final result = await PhotoSelector.bestSelection(
memories,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
@@ -248,7 +230,7 @@ void main() {
memories.map((m) => _emb(m.file.uploadedFileID!)).toList();
final result = await PhotoSelector.bestSelection(
memories,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
@@ -268,7 +250,7 @@ void main() {
memories.map((m) => _emb(m.file.uploadedFileID!)).toList();
final result = await PhotoSelector.bestSelection(
memories,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
@@ -288,15 +270,13 @@ void main() {
final memories = List.generate(30, (i) {
// Alternate: some 1 minute apart, some 1 hour apart
final offset = (i.isEven ? i * _hour : (i - 1) * _hour + 60000000);
- return _mem(
- _file(uploadedFileID: i, creationTime: _baseTime + offset),
- );
+ return _mem(_file(uploadedFileID: i, creationTime: _baseTime + offset));
});
final embeddings =
memories.map((m) => _emb(m.file.uploadedFileID!)).toList();
final result = await PhotoSelector.bestSelection(
memories,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
@@ -319,30 +299,32 @@ void main() {
}
});
- test('skips no-ML time buckets that cannot satisfy the min-gap filter',
- () async {
- const minute = 60 * 1000000;
- final memories = [
- _mem(_file(uploadedFileID: 0, creationTime: _baseTime)),
- _mem(_file(uploadedFileID: 1, creationTime: _baseTime + 7 * minute)),
- _mem(_file(uploadedFileID: 2, creationTime: _baseTime + 8 * minute)),
- _mem(_file(uploadedFileID: 3, creationTime: _baseTime + 9 * minute)),
- _mem(_file(uploadedFileID: 4, creationTime: _baseTime + 20 * minute)),
- ];
+ test(
+ 'skips no-ML time buckets that cannot satisfy the min-gap filter',
+ () async {
+ const minute = 60 * 1000000;
+ final memories = [
+ _mem(_file(uploadedFileID: 0, creationTime: _baseTime)),
+ _mem(_file(uploadedFileID: 1, creationTime: _baseTime + 7 * minute)),
+ _mem(_file(uploadedFileID: 2, creationTime: _baseTime + 8 * minute)),
+ _mem(_file(uploadedFileID: 3, creationTime: _baseTime + 9 * minute)),
+ _mem(_file(uploadedFileID: 4, creationTime: _baseTime + 20 * minute)),
+ ];
- final result = await PhotoSelector.bestSelection(
- memories,
- prefferedSize: 3,
- isOfflineMode: false,
- mlEnabled: false,
- fileIdToFaces: const {},
- faceIDsToPersonID: const {},
- fileIDToImageEmbedding: const {},
- clipPositiveTextVector: _positiveTextVector,
- );
+ final result = await PhotoSelector.bestSelection(
+ memories,
+ prefferedSize: 3,
+ isLocalGalleryMode: false,
+ mlEnabled: false,
+ fileIdToFaces: const {},
+ faceIDsToPersonID: const {},
+ fileIDToImageEmbedding: const {},
+ clipPositiveTextVector: _positiveTextVector,
+ );
- expect(result.map((m) => m.file.uploadedFileID), equals([0, 4]));
- });
+ expect(result.map((m) => m.file.uploadedFileID), equals([0, 4]));
+ },
+ );
test('prioritizes files with named faces', () async {
// 20 photos, file 0 has a named face, others don't
@@ -366,7 +348,7 @@ void main() {
final faceIDsToPersonID = {'face_0': 'person_1'};
final result = await PhotoSelector.bestSelection(
memories,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
mlEnabled: true,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
@@ -396,7 +378,7 @@ void main() {
});
final result = await PhotoSelector.bestSelection(
memories,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
@@ -440,7 +422,7 @@ void main() {
}
final result = await PhotoSelector.bestSelection(
memories,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
@@ -477,7 +459,7 @@ void main() {
// 35 photos, 7 years. targetSize should be 21 when prefferedSize is null.
final result = await PhotoSelector.bestSelection(
memories,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
@@ -489,65 +471,61 @@ void main() {
});
test(
- 'still filters close-in-time photos when expanded target matches count',
- () async {
- // 7 years x 3 photos triggers the expanded targetSize of 21 exactly.
- final memories = <Memory>[];
- final embeddings = <EmbeddingVector>[];
- final fileIdToFaces = <int, List<FaceWithoutEmbedding>>{};
- final faceIDsToPersonID = <String, String>{};
- int id = 0;
-
- for (int year = 2016; year <= 2022; year++) {
- for (int i = 0; i < 3; i++) {
- final fileID = id++;
- final creationTime = switch (i) {
- 0 => _timeInYear(year),
- 1 => _timeInYear(year) + 5 * 60 * 1000000,
- _ => _timeInYear(year, hours: 1),
- };
-
- memories.add(
- _mem(
- _file(
- uploadedFileID: fileID,
- creationTime: creationTime,
- ),
- ),
- );
- embeddings.add(_emb(fileID));
-
- final faceID = 'face_$fileID';
- fileIdToFaces[fileID] = List.generate(3 - i, (_) {
- return _face(faceID, fileID);
- });
- faceIDsToPersonID[faceID] = 'person_$fileID';
+ 'still filters close-in-time photos when expanded target matches count',
+ () async {
+ // 7 years x 3 photos triggers the expanded targetSize of 21 exactly.
+ final memories = <Memory>[];
+ final embeddings = <EmbeddingVector>[];
+ final fileIdToFaces = <int, List<FaceWithoutEmbedding>>{};
+ final faceIDsToPersonID = <String, String>{};
+ int id = 0;
+
+ for (int year = 2016; year <= 2022; year++) {
+ for (int i = 0; i < 3; i++) {
+ final fileID = id++;
+ final creationTime = switch (i) {
+ 0 => _timeInYear(year),
+ 1 => _timeInYear(year) + 5 * 60 * 1000000,
+ _ => _timeInYear(year, hours: 1),
+ };
+
+ memories.add(
+ _mem(_file(uploadedFileID: fileID, creationTime: creationTime)),
+ );
+ embeddings.add(_emb(fileID));
+
+ final faceID = 'face_$fileID';
+ fileIdToFaces[fileID] = List.generate(3 - i, (_) {
+ return _face(faceID, fileID);
+ });
+ faceIDsToPersonID[faceID] = 'person_$fileID';
+ }
}
- }
- final result = await PhotoSelector.bestSelection(
- memories,
- isOfflineMode: false,
- mlEnabled: true,
- fileIdToFaces: fileIdToFaces,
- faceIDsToPersonID: faceIDsToPersonID,
- fileIDToImageEmbedding: _embMap(embeddings),
- clipPositiveTextVector: _positiveTextVector,
- );
+ final result = await PhotoSelector.bestSelection(
+ memories,
+ isLocalGalleryMode: false,
+ mlEnabled: true,
+ fileIdToFaces: fileIdToFaces,
+ faceIDsToPersonID: faceIDsToPersonID,
+ fileIDToImageEmbedding: _embMap(embeddings),
+ clipPositiveTextVector: _positiveTextVector,
+ );
- expect(
- result.length,
- equals(14),
- reason:
- 'Round-robin filtering should still run when fileCount == expanded targetSize',
- );
- for (int i = 1; i < result.length; i++) {
expect(
- result[i].file.creationTime!,
- greaterThanOrEqualTo(result[i - 1].file.creationTime!),
+ result.length,
+ equals(14),
+ reason:
+ 'Round-robin filtering should still run when fileCount == expanded targetSize',
);
- }
- });
+ for (int i = 1; i < result.length; i++) {
+ expect(
+ result[i].file.creationTime!,
+ greaterThanOrEqualTo(result[i - 1].file.creationTime!),
+ );
+ }
+ },
+ );
test('output is sorted chronologically (oldest first)', () async {
final memories = <Memory>[];
@@ -569,7 +547,7 @@ void main() {
}
final result = await PhotoSelector.bestSelection(
memories,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
@@ -584,44 +562,46 @@ void main() {
}
});
- test('round 0 does not filter duplicates (ensures year coverage)',
- () async {
- // 2 years, 6 photos each. All photos are near-duplicates of each other.
- final base = _emb(0, seed: 42);
- final memories = <Memory>[];
- final embeddings = <EmbeddingVector>[];
- int id = 0;
- for (final year in [2021, 2022]) {
- for (int i = 0; i < 6; i++) {
- final fileID = id++;
- memories.add(
- _mem(
- _file(
- uploadedFileID: fileID,
- creationTime: _timeInYear(year, hours: i),
+ test(
+ 'round 0 does not filter duplicates (ensures year coverage)',
+ () async {
+ // 2 years, 6 photos each. All photos are near-duplicates of each other.
+ final base = _emb(0, seed: 42);
+ final memories = <Memory>[];
+ final embeddings = <EmbeddingVector>[];
+ int id = 0;
+ for (final year in [2021, 2022]) {
+ for (int i = 0; i < 6; i++) {
+ final fileID = id++;
+ memories.add(
+ _mem(
+ _file(
+ uploadedFileID: fileID,
+ creationTime: _timeInYear(year, hours: i),
+ ),
),
- ),
- );
- embeddings.add(_nearDuplicateEmb(fileID, base));
+ );
+ embeddings.add(_nearDuplicateEmb(fileID, base));
+ }
}
- }
- final result = await PhotoSelector.bestSelection(
- memories,
- isOfflineMode: false,
- mlEnabled: true,
- fileIdToFaces: {},
- faceIDsToPersonID: {},
- fileIDToImageEmbedding: _embMap(embeddings),
- clipPositiveTextVector: _positiveTextVector,
- );
- // Despite all being near-duplicates, both years should be represented
- // because round 0 skips the duplicate check.
- final yearsRepresented = result.map((m) {
- return DateTime.fromMicrosecondsSinceEpoch(m.file.creationTime!).year;
- }).toSet();
- expect(yearsRepresented, contains(2021));
- expect(yearsRepresented, contains(2022));
- });
+ final result = await PhotoSelector.bestSelection(
+ memories,
+ isLocalGalleryMode: false,
+ mlEnabled: true,
+ fileIdToFaces: {},
+ faceIDsToPersonID: {},
+ fileIDToImageEmbedding: _embMap(embeddings),
+ clipPositiveTextVector: _positiveTextVector,
+ );
+ // Despite all being near-duplicates, both years should be represented
+ // because round 0 skips the duplicate check.
+ final yearsRepresented = result.map((m) {
+ return DateTime.fromMicrosecondsSinceEpoch(m.file.creationTime!).year;
+ }).toSet();
+ expect(yearsRepresented, contains(2021));
+ expect(yearsRepresented, contains(2022));
+ },
+ );
test('no two selected photos are within minimumMemoryTimeGap', () async {
final memories = <Memory>[];
@@ -645,7 +625,7 @@ void main() {
}
final result = await PhotoSelector.bestSelection(
memories,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
@@ -684,39 +664,37 @@ void main() {
memories.map((m) => _emb(m.file.uploadedFileID!)).toList();
final result = await PhotoSelector.bestSelectionPeople(
memories,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
fileIDToImageEmbedding: _embMap(embeddings),
clipPositiveTextVector: _positiveTextVector,
);
expect(result.length, equals(5));
});
- test('ignores unrelated embeddings when precomputing people scores',
- () async {
- final memories = List.generate(20, (i) {
- return _mem(
- _file(uploadedFileID: i, creationTime: _baseTime + i * _hour),
- );
- });
- final embeddings =
- memories.map((m) => _emb(m.file.uploadedFileID!)).toList()
- ..add(
- EmbeddingVector(
- fileID: 9999,
- embedding: const [1.0, 0.0],
- ),
- );
+ test(
+ 'ignores unrelated embeddings when precomputing people scores',
+ () async {
+ final memories = List.generate(20, (i) {
+ return _mem(
+ _file(uploadedFileID: i, creationTime: _baseTime + i * _hour),
+ );
+ });
+ final embeddings = memories
+ .map((m) => _emb(m.file.uploadedFileID!))
+ .toList()
+ ..add(EmbeddingVector(fileID: 9999, embedding: const [1.0, 0.0]));
- final result = await PhotoSelector.bestSelectionPeople(
- memories,
- isOfflineMode: false,
- fileIDToImageEmbedding: _embMap(embeddings),
- clipPositiveTextVector: _positiveTextVector,
- );
+ final result = await PhotoSelector.bestSelectionPeople(
+ memories,
+ isLocalGalleryMode: false,
+ fileIDToImageEmbedding: _embMap(embeddings),
+ clipPositiveTextVector: _positiveTextVector,
+ );
- expect(result, isNotEmpty);
- expect(result.length, lessThanOrEqualTo(10));
- });
+ expect(result, isNotEmpty);
+ expect(result.length, lessThanOrEqualTo(10));
+ },
+ );
test('limits output to targetSize', () async {
final memories = List.generate(30, (i) {
@@ -728,7 +706,7 @@ void main() {
memories.map((m) => _emb(m.file.uploadedFileID!)).toList();
final result = await PhotoSelector.bestSelectionPeople(
memories,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
fileIDToImageEmbedding: _embMap(embeddings),
clipPositiveTextVector: _positiveTextVector,
);
@@ -746,7 +724,7 @@ void main() {
final result = await PhotoSelector.bestSelectionPeople(
memories,
prefferedSize: 5,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
fileIDToImageEmbedding: _embMap(embeddings),
clipPositiveTextVector: _positiveTextVector,
);
@@ -763,7 +741,7 @@ void main() {
memories.map((m) => _emb(m.file.uploadedFileID!)).toList();
final result = await PhotoSelector.bestSelectionPeople(
memories,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
fileIDToImageEmbedding: _embMap(embeddings),
clipPositiveTextVector: _positiveTextVector,
);
@@ -786,7 +764,7 @@ void main() {
memories.map((m) => _emb(m.file.uploadedFileID!)).toList();
final result = await PhotoSelector.bestSelectionPeople(
memories,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
fileIDToImageEmbedding: _embMap(embeddings),
clipPositiveTextVector: _positiveTextVector,
);
@@ -836,7 +814,7 @@ void main() {
}
final result = await PhotoSelector.bestSelectionPeople(
memories,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
fileIDToImageEmbedding: _embMap(embeddings),
clipPositiveTextVector: _positiveTextVector,
);
@@ -861,7 +839,7 @@ void main() {
final embeddings = [_emb(0), _emb(5), _emb(15)];
final result = await PhotoSelector.bestSelectionPeople(
memories,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
fileIDToImageEmbedding: _embMap(embeddings),
clipPositiveTextVector: _positiveTextVector,
);
@@ -893,15 +871,12 @@ void main() {
memories.map((m) => _emb(m.file.uploadedFileID!)).toList();
final result = await PhotoSelector.bestSelectionPeople(
memories,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
fileIDToImageEmbedding: _embMap(embeddings),
clipPositiveTextVector: _positiveTextVector,
);
// File 1 (no creationTime) should not be in result
- expect(
- result.any((m) => m.file.uploadedFileID == 1),
- isFalse,
- );
+ expect(result.any((m) => m.file.uploadedFileID == 1), isFalse);
});
});
@@ -934,7 +909,7 @@ void main() {
.toList();
final result = await PhotoSelector.bestSelection(
copy,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
@@ -982,7 +957,7 @@ void main() {
.toList();
final result = await PhotoSelector.bestSelection(
copy,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
@@ -997,41 +972,43 @@ void main() {
expect(run1, equals(run2));
});
- test('bestSelectionPeople: produces same output on repeated calls',
- () async {
- final memories = List.generate(30, (i) {
- return _mem(
- _file(uploadedFileID: i, creationTime: _baseTime + i * _hour),
- );
- });
- final embeddings =
- memories.map((m) => _emb(m.file.uploadedFileID!)).toList();
- final embMap = _embMap(embeddings);
-
- Future<List<int>> run() async {
- final copy = memories
- .map(
- (m) => _mem(
- _file(
- uploadedFileID: m.file.uploadedFileID!,
- creationTime: m.file.creationTime!,
+ test(
+ 'bestSelectionPeople: produces same output on repeated calls',
+ () async {
+ final memories = List.generate(30, (i) {
+ return _mem(
+ _file(uploadedFileID: i, creationTime: _baseTime + i * _hour),
+ );
+ });
+ final embeddings =
+ memories.map((m) => _emb(m.file.uploadedFileID!)).toList();
+ final embMap = _embMap(embeddings);
+
+ Future<List<int>> run() async {
+ final copy = memories
+ .map(
+ (m) => _mem(
+ _file(
+ uploadedFileID: m.file.uploadedFileID!,
+ creationTime: m.file.creationTime!,
+ ),
),
- ),
- )
- .toList();
- final result = await PhotoSelector.bestSelectionPeople(
- copy,
- isOfflineMode: false,
- fileIDToImageEmbedding: embMap,
- clipPositiveTextVector: _positiveTextVector,
- );
- return result.map((m) => m.file.uploadedFileID!).toList();
- }
+ )
+ .toList();
+ final result = await PhotoSelector.bestSelectionPeople(
+ copy,
+ isLocalGalleryMode: false,
+ fileIDToImageEmbedding: embMap,
+ clipPositiveTextVector: _positiveTextVector,
+ );
+ return result.map((m) => m.file.uploadedFileID!).toList();
+ }
- final run1 = await run();
- final run2 = await run();
- expect(run1, equals(run2));
- });
+ final run1 = await run();
+ final run2 = await run();
+ expect(run1, equals(run2));
+ },
+ );
});
// -------------------------------------------------------------------------
@@ -1049,7 +1026,7 @@ void main() {
memories,
const SelectionConfig(
targetSize: 10,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
fileIDToImageEmbedding: {},
scores: {},
distribution: SelectionDistribution.none,
@@ -1060,41 +1037,43 @@ void main() {
expect(result.length, equals(5));
});
- test('flat distribution selects by score and respects targetSize',
- () async {
- final memories = List.generate(20, (i) {
- return _mem(
- _file(uploadedFileID: i, creationTime: _baseTime + i * _hour),
+ test(
+ 'flat distribution selects by score and respects targetSize',
+ () async {
+ final memories = List.generate(20, (i) {
+ return _mem(
+ _file(uploadedFileID: i, creationTime: _baseTime + i * _hour),
+ );
+ });
+ final embeddings =
+ memories.map((m) => _emb(m.file.uploadedFileID!)).toList();
+ final embMap = _embMap(embeddings);
+ // Score = fileID (so higher IDs are preferred)
+ final scores = {
+ for (final m in memories)
+ m.file.uploadedFileID!: m.file.uploadedFileID!.toDouble(),
+ };
+ final result = await PhotoSelector.select(
+ memories,
+ SelectionConfig(
+ targetSize: 10,
+ isLocalGalleryMode: false,
+ fileIDToImageEmbedding: embMap,
+ scores: scores,
+ distribution: SelectionDistribution.none,
+ pick: SelectionPick.ranked,
+ sort: SelectionSort.chronological,
+ ),
);
- });
- final embeddings =
- memories.map((m) => _emb(m.file.uploadedFileID!)).toList();
- final embMap = _embMap(embeddings);
- // Score = fileID (so higher IDs are preferred)
- final scores = {
- for (final m in memories)
- m.file.uploadedFileID!: m.file.uploadedFileID!.toDouble(),
- };
- final result = await PhotoSelector.select(
- memories,
- SelectionConfig(
- targetSize: 10,
- isOfflineMode: false,
- fileIDToImageEmbedding: embMap,
- scores: scores,
- distribution: SelectionDistribution.none,
- pick: SelectionPick.ranked,
- sort: SelectionSort.chronological,
- ),
- );
- expect(result.length, lessThanOrEqualTo(10));
- // Should prefer higher-scored files
- expect(
- result.any((m) => m.file.uploadedFileID == 19),
- isTrue,
- reason: 'Highest-scored file should be selected',
- );
- });
+ expect(result.length, lessThanOrEqualTo(10));
+ // Should prefer higher-scored files
+ expect(
+ result.any((m) => m.file.uploadedFileID == 19),
+ isTrue,
+ reason: 'Highest-scored file should be selected',
+ );
+ },
+ );
test('timeBuckets distribution spreads across time range', () async {
final memories = List.generate(30, (i) {
@@ -1112,7 +1091,7 @@ void main() {
memories,
SelectionConfig(
targetSize: 10,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
fileIDToImageEmbedding: embMap,
scores: scores,
distribution: SelectionDistribution.timeBuckets,
@@ -1164,7 +1143,7 @@ void main() {
memories,
SelectionConfig(
targetSize: 10,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
fileIDToImageEmbedding: embMap,
scores: scores,
distribution: SelectionDistribution.yearRoundRobin,
@@ -1207,7 +1186,7 @@ void main() {
),
SelectionConfig(
targetSize: 10,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
fileIDToImageEmbedding: embMap,
scores: scores,
distribution: SelectionDistribution.none,
@@ -1235,7 +1214,7 @@ void main() {
),
SelectionConfig(
targetSize: 10,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
fileIDToImageEmbedding: embMap,
scores: scores,
distribution: SelectionDistribution.none,
diff --git a/mobile/apps/photos/test/services/memories/smart_memories_source_selection_test.dart b/mobile/apps/photos/test/services/memories/smart_memories_source_selection_test.dart
index 03a41dce74..26f55a45bf 100644
--- a/mobile/apps/photos/test/services/memories/smart_memories_source_selection_test.dart
+++ b/mobile/apps/photos/test/services/memories/smart_memories_source_selection_test.dart
@@ -46,12 +46,7 @@ void main() {
for (int i = 0; i < 20; i++)
_file(
id: i + 1,
- createdAt: DateTime.utc(
- 2024,
- 1,
- 10 + (i ~/ 7),
- 8 + (i % 7) * 2,
- ),
+ createdAt: DateTime.utc(2024, 1, 10 + (i ~/ 7), 8 + (i % 7) * 2),
location: tripLocation,
),
];
@@ -67,7 +62,7 @@ void main() {
<TripsShownLog>[],
surfaceAll: true,
cachedTripMemories: const <ToShowMemory>[],
- isOfflineMode: false,
+ isLocalGalleryMode: false,
mlEnabled: true,
seenTimes: const <int, int>{},
fileIdToFaces: const <int, List<FaceWithoutEmbedding>>{},
@@ -84,7 +79,7 @@ void main() {
<TripsShownLog>[],
surfaceAll: true,
cachedTripMemories: const <ToShowMemory>[],
- isOfflineMode: false,
+ isLocalGalleryMode: false,
mlEnabled: true,
seenTimes: const <int, int>{},
fileIdToFaces: const <int, List<FaceWithoutEmbedding>>{},
@@ -109,12 +104,7 @@ void main() {
for (int photoIndex = 0; photoIndex < 4; photoIndex++)
_file(
id: dayOffset * 10 + photoIndex + 1,
- createdAt: DateTime.utc(
- 2026,
- 4,
- 1 + dayOffset,
- 9 + photoIndex,
- ),
+ createdAt: DateTime.utc(2026, 4, 1 + dayOffset, 9 + photoIndex),
),
];
final depletedRemainingFiles = fullRecentSource.take(6).toList();
@@ -123,7 +113,7 @@ void main() {
depletedRemainingFiles,
currentTime,
recentSourceFiles: fullRecentSource,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
mlEnabled: true,
seenTimes: const <int, int>{},
fileIdToFaces: const <int, List<FaceWithoutEmbedding>>{},
@@ -180,7 +170,7 @@ void main() {
currentTime,
<ClipShownLog>[],
surfaceAll: true,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
seenTimes: const <int, int>{},
fileIDToImageEmbedding: fileIDToImageEmbedding,
clipMemoryTypeVectors: <ClipMemoryType, Vector>{
@@ -193,7 +183,7 @@ void main() {
currentTime,
<ClipShownLog>[],
surfaceAll: true,
- isOfflineMode: false,
+ isLocalGalleryMode: false,
seenTimes: const <int, int>{},
fileIDToImageEmbedding: fileIDToImageEmbedding,
clipMemoryTypeVectors: <ClipMemoryType, Vector>{