Skip to content

armgit / ente

Public Imported from GitHub
0

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

Prune Locker and Auth comments

Manav Rathi5bba22f662f9
diff --git a/mobile/apps/auth/lib/core/configuration.dart b/mobile/apps/auth/lib/core/configuration.dart
index f56acbad2f..50b7375b5e 100644
--- a/mobile/apps/auth/lib/core/configuration.dart
+++ b/mobile/apps/auth/lib/core/configuration.dart
@@ -106,7 +106,6 @@ class Configuration extends BaseConfiguration
await _preferences.setBool(hasOptedForOfflineModeKey, true);
}
- // Backup password methods
Future<String?> getBackupPassword() async {
return _secureStorage.read(key: autoBackupPasswordKey);
}
diff --git a/mobile/apps/auth/lib/core/constants.dart b/mobile/apps/auth/lib/core/constants.dart
index 94b707bcb0..7f459a8abe 100644
--- a/mobile/apps/auth/lib/core/constants.dart
+++ b/mobile/apps/auth/lib/core/constants.dart
@@ -31,10 +31,8 @@ const thumbnailServerLoadDeferDuration = Duration(milliseconds: 80);
// https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki#Generating_the_mnemonic
const mnemonicKeyWordCount = 24;
-// https://stackoverflow.com/a/61162219
const dragSensitivity = 8;
-// Default values for various feature flags
class FFDefault {
static const bool enableStripe = true;
static const bool disableCFWorker = false;
diff --git a/mobile/apps/auth/lib/ente_theme_data.dart b/mobile/apps/auth/lib/ente_theme_data.dart
index e0875f4bc9..fcad92286a 100644
--- a/mobile/apps/auth/lib/ente_theme_data.dart
+++ b/mobile/apps/auth/lib/ente_theme_data.dart
@@ -33,7 +33,6 @@ final lightThemeData = ThemeData(
iconTheme: const IconThemeData(color: Colors.black),
elevation: 0,
),
- //https://api.flutter.dev/flutter/material/TextTheme-class.html
textTheme: _buildTextTheme(const Color.fromRGBO(0, 0, 0, 1)),
primaryTextTheme: const TextTheme().copyWith(
bodyMedium: const TextStyle(color: Colors.yellow),
diff --git a/mobile/apps/auth/lib/locale.dart b/mobile/apps/auth/lib/locale.dart
index ff3cb4c357..cb17ae759b 100644
--- a/mobile/apps/auth/lib/locale.dart
+++ b/mobile/apps/auth/lib/locale.dart
@@ -38,9 +38,6 @@ const List<Locale> appSupportedLocales = <Locale>[
];
Locale? autoDetectedLocale;
-// This function takes device locales and supported locales as input
-// and returns the best matching locale.
-// The device locales are sorted by priority, so the first one is the most preferred.
Locale localResolutionCallBack(
List<Locale>? onDeviceLocales,
Iterable<Locale> supportedLocales,
@@ -51,18 +48,15 @@ Locale localResolutionCallBack(
}
for (final deviceLocale in onDeviceLocales ?? const []) {
final locale = _normalizedLocale(deviceLocale);
- // check if exact local is supported, if yes, return it
if (appSupportedLocales.contains(locale)) {
autoDetectedLocale = locale;
return locale;
}
- // check if language code is supported, if yes, return it
if (languageSupport.contains(locale.languageCode)) {
autoDetectedLocale = locale;
return locale;
}
}
- // Return the first language code match or default to 'en'
return autoDetectedLocale ?? const Locale('en');
}
@@ -70,7 +64,6 @@ Future<Locale?> getLocale({bool noFallback = false}) async {
final String? savedValue = (await SharedPreferences.getInstance()).getString(
'locale',
);
- // if savedLocale is not null and is supported by the app, return it
if (savedValue != null) {
late Locale savedLocale;
if (savedValue.contains('_')) {
diff --git a/mobile/apps/auth/lib/main.dart b/mobile/apps/auth/lib/main.dart
index cf066449a3..17d823df91 100644
--- a/mobile/apps/auth/lib/main.dart
+++ b/mobile/apps/auth/lib/main.dart
@@ -186,7 +186,6 @@ Future _runWithLogs(Function() function, {String prefix = ""}) async {
void _registerWindowsProtocol() {
const kWindowsScheme = 'enteauth';
- // Register our protocol only on Windows platform
if (!kIsWeb && Platform.isWindows) {
WindowsProtocolHandler().register(
kWindowsScheme,
diff --git a/mobile/apps/auth/lib/models/code_display.dart b/mobile/apps/auth/lib/models/code_display.dart
index 2cb8688208..0fbc6e00af 100644
--- a/mobile/apps/auth/lib/models/code_display.dart
+++ b/mobile/apps/auth/lib/models/code_display.dart
@@ -28,7 +28,6 @@ class CodeDisplay {
bool get isCustomIcon => (iconSrc != '' && iconID != '');
- // copyWith
CodeDisplay copyWith({
bool? pinned,
bool? trashed,
diff --git a/mobile/apps/auth/lib/models/export/ente.dart b/mobile/apps/auth/lib/models/export/ente.dart
index a9a5e57bd3..2336d27805 100644
--- a/mobile/apps/auth/lib/models/export/ente.dart
+++ b/mobile/apps/auth/lib/models/export/ente.dart
@@ -11,7 +11,6 @@ class EnteAuthExport {
final String encryptedData;
final String encryptionNonce;
- // Named constructor which can be used to specify each field individually
EnteAuthExport({
required this.version,
required this.kdfParams,
@@ -19,7 +18,6 @@ class EnteAuthExport {
required this.encryptionNonce,
});
- // Convert EnteExport object to JSON
Map<String, dynamic> toJson() => {
'version': version,
'kdfParams': kdfParams.toJson(),
@@ -27,7 +25,6 @@ class EnteAuthExport {
'encryptionNonce': encryptionNonce,
};
- // Convert JSON to EnteExport object
static EnteAuthExport fromJson(Map<String, dynamic> json) => EnteAuthExport(
version: json['version'],
kdfParams: KDFParams.fromJson(json['kdfParams']),
@@ -36,28 +33,23 @@ class EnteAuthExport {
);
}
-// KDFParams is a class that holds the parameters for the KDF function.
-// It is used to derive a key from a password.
class KDFParams {
final int memLimit;
final int opsLimit;
final String salt;
- // Named constructor which can be used to specify each field individually
KDFParams({
required this.memLimit,
required this.opsLimit,
required this.salt,
});
- // Convert KDFParams object to JSON
Map<String, dynamic> toJson() => {
'memLimit': memLimit,
'opsLimit': opsLimit,
'salt': salt,
};
- // Convert JSON to KDFParams object
static KDFParams fromJson(Map<String, dynamic> json) => KDFParams(
memLimit: json['memLimit'],
opsLimit: json['opsLimit'],
diff --git a/mobile/apps/auth/lib/onboarding/view/onboarding_page.dart b/mobile/apps/auth/lib/onboarding/view/onboarding_page.dart
index 447fa620fd..8d66cf9743 100644
--- a/mobile/apps/auth/lib/onboarding/view/onboarding_page.dart
+++ b/mobile/apps/auth/lib/onboarding/view/onboarding_page.dart
@@ -423,19 +423,15 @@ class _OnboardingPageState extends State<OnboardingPage> {
if (Configuration.instance.getEncryptedToken() == null) {
page = EmailEntryPage(Configuration.instance);
} else {
- // No key
if (Configuration.instance.getKeyAttributes() == null) {
- // Never had a key
page = PasswordEntryPage(
Configuration.instance,
PasswordEntryMode.set,
const HomePage(),
);
} else if (Configuration.instance.getKey() == null) {
- // Yet to decrypt the key
page = PasswordReentryPage(Configuration.instance, const HomePage());
} else {
- // All is well, user just has not subscribed
page = const HomePage();
}
}
@@ -453,20 +449,15 @@ class _OnboardingPageState extends State<OnboardingPage> {
if (Configuration.instance.getEncryptedToken() == null) {
page = LoginPage(Configuration.instance);
} else {
- // No key
if (Configuration.instance.getKeyAttributes() == null) {
- // Never had a key
page = PasswordEntryPage(
Configuration.instance,
PasswordEntryMode.set,
const HomePage(),
);
} else if (Configuration.instance.getKey() == null) {
- // Yet to decrypt the key
page = PasswordReentryPage(Configuration.instance, const HomePage());
} else {
- // All is well, user just has not subscribed
- // page = getSubscriptionPage(isOnBoarding: true);
page = const HomePage();
}
}
diff --git a/mobile/apps/auth/lib/onboarding/view/setup_enter_secret_key_page.dart b/mobile/apps/auth/lib/onboarding/view/setup_enter_secret_key_page.dart
index 13f814d29f..05164fef3c 100644
--- a/mobile/apps/auth/lib/onboarding/view/setup_enter_secret_key_page.dart
+++ b/mobile/apps/auth/lib/onboarding/view/setup_enter_secret_key_page.dart
@@ -589,7 +589,6 @@ class _SetupEnterSecretKeyPageState extends State<SetupEnterSecretKeyPage> {
period: period,
);
- // Verify the validity of the code
getOTP(newCode);
if (!mounted) return;
Navigator.of(context).pop(newCode);
diff --git a/mobile/apps/auth/lib/services/local_backup_service.dart b/mobile/apps/auth/lib/services/local_backup_service.dart
index fedb04c22c..3df0f7ddef 100644
--- a/mobile/apps/auth/lib/services/local_backup_service.dart
+++ b/mobile/apps/auth/lib/services/local_backup_service.dart
@@ -134,7 +134,6 @@ class LocalBackupService {
final dirUtils = DirUtils.instance;
final contentBytes = Uint8List.fromList(utf8.encode(content));
- // Android SAF
if (target.treeUri != null) {
final dir = PickedDirectory(path: '', treeUri: target.treeUri);
final success = await dirUtils.writeFile(dir, fileName, contentBytes);
@@ -144,7 +143,6 @@ class LocalBackupService {
return success;
}
- // iOS/macOS with bookmark - write directly to the selected directory
if ((Platform.isIOS || Platform.isMacOS) && target.iosBookmark != null) {
final dir = PickedDirectory(
path: target.path!,
@@ -164,7 +162,6 @@ class LocalBackupService {
return result ?? false;
}
- // Other platforms (Windows, Linux): direct file write
final basePath = target.path!;
await Directory(basePath).create(recursive: true);
final filePath = '$basePath/$fileName';
@@ -209,7 +206,6 @@ class LocalBackupService {
.where((f) => _isBackupFile(p.basename(f.path)))
.toList();
- // Sort by mtime async
final filesWithMtime = await Future.wait(
files.map((f) async => (f, await f.lastModified())),
);
@@ -255,7 +251,6 @@ class LocalBackupService {
}
}
- // On iOS/macOS, use scoped access via bookmark
if ((Platform.isIOS || Platform.isMacOS) &&
iosBookmark != null &&
iosBookmark.isNotEmpty) {
diff --git a/mobile/apps/auth/lib/store/authenticator_db.dart b/mobile/apps/auth/lib/store/authenticator_db.dart
index dcc59ae02f..da23e84cdb 100644
--- a/mobile/apps/auth/lib/store/authenticator_db.dart
+++ b/mobile/apps/auth/lib/store/authenticator_db.dart
@@ -147,7 +147,6 @@ class AuthenticatorDB extends EnteBaseDatabase {
return _convertRows(rows);
}
- // removeSyncedData will remove all the data which is synced with the server
Future<int> removeSyncedData() async {
final db = await instance.database;
return await db.delete(
@@ -157,7 +156,6 @@ class AuthenticatorDB extends EnteBaseDatabase {
);
}
- // getCount of entries which are not synced with the server
Future<int> getNeedSyncCount() async {
final db = await instance.database;
final rows = await db.rawQuery(
@@ -166,7 +164,6 @@ class AuthenticatorDB extends EnteBaseDatabase {
return Sqflite.firstIntValue(rows)!;
}
- // deleteByID will prefer generated id if both ids are passed during deletion
Future<void> deleteByIDs({List<int>? generatedIDs, List<String>? ids}) async {
final db = await instance.database;
final batch = db.batch();
diff --git a/mobile/apps/auth/lib/store/code_display_store.dart b/mobile/apps/auth/lib/store/code_display_store.dart
index 4d2dd5bdc9..efa97e53f9 100644
--- a/mobile/apps/auth/lib/store/code_display_store.dart
+++ b/mobile/apps/auth/lib/store/code_display_store.dart
@@ -16,7 +16,6 @@ class CodeDisplayStore {
final ValueNotifier<bool> isSelectionModeActive = ValueNotifier(false);
final ValueNotifier<Set<String>> selectedCodeIds = ValueNotifier(<String>{});
- // toggles the selection status of a code
void toggleSelection(String codeId) {
final newSelection = Set<String>.from(selectedCodeIds.value);
@@ -26,12 +25,10 @@ class CodeDisplayStore {
newSelection.add(codeId);
}
- selectedCodeIds.value =
- newSelection; //if we selected atleast one code, then we're in selection mode.. else: exit selection mode
+ selectedCodeIds.value = newSelection;
isSelectionModeActive.value = newSelection.isNotEmpty;
}
- //method to clear the entire selection
void clearSelection() {
selectedCodeIds.value = <String>{};
isSelectionModeActive.value = false;
@@ -44,7 +41,6 @@ class CodeDisplayStore {
return;
}
- // Build lookup structures in a single pass - O(n)
final validKeys = <String>{};
final keyRemapping = <String, String>{};
@@ -56,7 +52,6 @@ class CodeDisplayStore {
final key = code.selectionKey;
validKeys.add(key);
- // Map old keys to current key to handle transitions
keyRemapping[code.rawData] = key;
final generatedID = code.generatedID;
if (generatedID != null) {
@@ -64,7 +59,6 @@ class CodeDisplayStore {
}
}
- // Update selection in one pass - O(m)
final updatedSelection = currentSelection
.map(
(oldKey) =>
@@ -73,7 +67,6 @@ class CodeDisplayStore {
.whereType<String>()
.toSet();
- // Only update if selection changed
if (updatedSelection != currentSelection) {
selectedCodeIds.value = updatedSelection;
isSelectionModeActive.value = updatedSelection.isNotEmpty;
@@ -114,7 +107,6 @@ class CodeDisplayStore {
firstButtonLabel: l10n.delete,
isCritical: true,
firstButtonOnTap: () async {
- // traverse through all the codes and edit this tag's value
final relevantCodes = await _getCodesByTag(tag);
final tasks = <Future<AddResult>>[];
@@ -166,7 +158,6 @@ class CodeDisplayStore {
}
Future<void> editTag(String previousTag, String updatedTag) async {
- // traverse through all the codes and edit this tag's value
final relevantCodes = await _getCodesByTag(previousTag);
final tasks = <Future<AddResult>>[];
diff --git a/mobile/apps/auth/lib/store/offline_authenticator_db.dart b/mobile/apps/auth/lib/store/offline_authenticator_db.dart
index 58160a947a..9fe86f2660 100644
--- a/mobile/apps/auth/lib/store/offline_authenticator_db.dart
+++ b/mobile/apps/auth/lib/store/offline_authenticator_db.dart
@@ -146,7 +146,6 @@ class OfflineAuthenticatorDB {
return _convertRows(rows);
}
- // deleteByID will prefer generated id if both ids are passed during deletion
Future<void> deleteByIDs({List<int>? generatedIDs, List<String>? ids}) async {
final db = await instance.database;
final batch = db.batch();
diff --git a/mobile/apps/auth/lib/theme/colors.dart b/mobile/apps/auth/lib/theme/colors.dart
index 91b7b4bbd2..d5ae1c02c0 100644
--- a/mobile/apps/auth/lib/theme/colors.dart
+++ b/mobile/apps/auth/lib/theme/colors.dart
@@ -1,29 +1,24 @@
import 'package:flutter/material.dart';
class EnteColorScheme {
- // Background Colors
final Color backgroundBase;
final Color backgroundElevated;
final Color backgroundElevated2;
- // Backdrop Colors
final Color backdropBase;
final Color backdropBaseMute;
final Color backdropFaint;
- // Text Colors
final Color textBase;
final Color textMuted;
final Color textFaint;
- // Fill Colors
final Color fillBase;
final Color fillBasePressed;
final Color fillMuted;
final Color fillFaint;
final Color fillFaintPressed;
- // Stroke Colors
final Color strokeBase;
final Color strokeMuted;
final Color strokeFaint;
@@ -32,7 +27,6 @@ class EnteColorScheme {
final Color blurStrokeFaint;
final Color blurStrokePressed;
- // Fixed Colors
final Color primaryGreen;
final Color primary700;
final Color primary500;
@@ -49,7 +43,6 @@ class EnteColorScheme {
final Color caution500;
final List<Color> avatarColors;
- // Tags
final Color tagChipSelectedColor;
final Color tagChipUnselectedColor;
final List<Color> tagChipSelectedGradient;
@@ -58,7 +51,6 @@ class EnteColorScheme {
final Color deleteTagIconColor;
final Color deleteTagTextColor;
- // Code Widget
final Color errorCodeProgressColor;
final Color infoIconColor;
final Color errorCardTextColor;
@@ -66,7 +58,6 @@ class EnteColorScheme {
final List<BoxShadow> pinnedCardBoxShadow;
final Color pinnedBgColor;
- // Gradient Button
final Color gradientButtonBgColor;
final List<Color> gradientButtonBgColors;
@@ -186,10 +177,8 @@ const EnteColorScheme darkScheme = EnteColorScheme(
const accentColor = Color(0xFF8F33D6);
-// QR code container background
const Color qrBoxColor = Color.fromRGBO(245, 245, 247, 1);
-// Background Colors
const Color backgroundBaseLight = Color.fromRGBO(255, 255, 255, 1);
const Color backgroundElevatedLight = Color.fromRGBO(255, 255, 255, 1);
const Color backgroundElevated2Light = Color.fromRGBO(251, 251, 251, 1);
@@ -198,7 +187,6 @@ const Color backgroundBaseDark = Color.fromRGBO(0, 0, 0, 1);
const Color backgroundElevatedDark = Color.fromRGBO(27, 27, 27, 1);
const Color backgroundElevated2Dark = Color.fromRGBO(37, 37, 37, 1);
-// Backdrop Colors
const Color backdropBaseLight = Color.fromRGBO(255, 255, 255, 0.92);
const Color backdropMutedLight = Color.fromRGBO(255, 255, 255, 0.75);
const Color backdropFaintLight = Color.fromRGBO(255, 255, 255, 0.30);
@@ -207,7 +195,6 @@ const Color backdropBaseDark = Color.fromRGBO(0, 0, 0, 0.90);
const Color backdropMutedDark = Color.fromRGBO(0, 0, 0, 0.65);
const Color backdropFaintDark = Color.fromRGBO(0, 0, 0, 0.20);
-// Text Colors
const Color textBaseLight = Color.fromRGBO(0, 0, 0, 1);
const Color textMutedLight = Color.fromRGBO(0, 0, 0, 0.6);
const Color textFaintLight = Color.fromRGBO(0, 0, 0, 0.5);
@@ -216,7 +203,6 @@ const Color textBaseDark = Color.fromRGBO(255, 255, 255, 1);
const Color textMutedDark = Color.fromRGBO(255, 255, 255, 0.7);
const Color textFaintDark = Color.fromRGBO(255, 255, 255, 0.5);
-// Fill Colors
const Color fillBaseLight = Color.fromRGBO(0, 0, 0, 1);
const Color fillBasePressedLight = Color.fromRGBO(0, 0, 0, 0.87);
const Color fillMutedLight = Color.fromRGBO(0, 0, 0, 0.12);
@@ -229,7 +215,6 @@ const Color fillMutedDark = Color.fromRGBO(255, 255, 255, 0.16);
const Color fillFaintDark = Color.fromRGBO(255, 255, 255, 0.12);
const Color fillFaintPressedDark = Color.fromRGBO(255, 255, 255, 0.06);
-// Stroke Colors
const Color strokeBaseLight = Color.fromRGBO(0, 0, 0, 1);
const Color strokeMutedLight = Color.fromRGBO(0, 0, 0, 0.24);
const Color strokeFaintLight = Color.fromRGBO(0, 0, 0, 0.04);
@@ -246,8 +231,6 @@ const Color blurStrokeBaseDark = Color.fromRGBO(255, 255, 255, 0.90);
const Color blurStrokeFaintDark = Color.fromRGBO(255, 255, 255, 0.06);
const Color blurStrokePressedDark = Color.fromRGBO(255, 255, 255, 0.50);
-// Fixed Colors
-
const Color _primaryGreen = Color.fromRGBO(29, 185, 84, 1);
const Color _primary700 = Color(0xFF722ED1);
@@ -319,7 +302,6 @@ const List<Color> avatarDark = [
Color.fromRGBO(120, 181, 167, 1),
];
-// Tags
const Color _tagChipUnselectedColorLight = Color(0xFFFCF5FF);
const Color _tagChipUnselectedColorDark = Color(0xFF1C0F22);
const List<Color> _tagChipUnselectedGradientLight = [
@@ -343,7 +325,6 @@ const Color _tagTextUnselectedColor = Color(0xFF8232E1);
const Color _deleteTagIconColor = Color(0xFFF53434);
const Color _deleteTagTextColor = Color(0xFFF53434);
-// Code Widget
const Color _pinnedBgColorLight = Color(0xFFF9ECFF);
const Color _pinnedBgColorDark = Color(0xFF390C4F);
const Color _errorCodeProgressColor = Color(0xFFF53434);
@@ -357,7 +338,6 @@ const List<BoxShadow> _pinnedCardBoxShadow = [
BoxShadow(color: Color(0x2E000000), blurRadius: 1, offset: Offset(0, 0)),
];
-// Gradient Button
const Color _gradientButtonBgColor = Color(0xFF531DAB);
const List<Color> _gradientButtonBgColors = [
Color(0xFFB37FEB),
diff --git a/mobile/apps/auth/lib/theme/text_style.dart b/mobile/apps/auth/lib/theme/text_style.dart
index 3a2ab15f56..4e3d6207fd 100644
--- a/mobile/apps/auth/lib/theme/text_style.dart
+++ b/mobile/apps/auth/lib/theme/text_style.dart
@@ -86,7 +86,6 @@ class EnteTextTheme {
final TextStyle brandSmall;
final TextStyle brandMedium;
- // textMuted variants
final TextStyle h1Muted;
final TextStyle h2Muted;
final TextStyle h3Muted;
@@ -97,7 +96,6 @@ class EnteTextTheme {
final TextStyle miniBoldMuted;
final TextStyle tinyMuted;
- // textFaint variants
final TextStyle h1Faint;
final TextStyle h2Faint;
final TextStyle h3Faint;
diff --git a/mobile/apps/auth/lib/ui/code_timer_progress.dart b/mobile/apps/auth/lib/ui/code_timer_progress.dart
index 7302641eaa..6e2809c66a 100644
--- a/mobile/apps/auth/lib/ui/code_timer_progress.dart
+++ b/mobile/apps/auth/lib/ui/code_timer_progress.dart
@@ -24,7 +24,6 @@ class _CodeTimerProgressState extends State<CodeTimerProgress> {
late final ValueNotifier<double> _progress;
late final int _periodInMilii;
- // Reduce update frequency
final int _updateIntervalMs = (Platform.isAndroid || Platform.isIOS)
? 16
: 500; // approximately 60 FPS
@@ -43,7 +42,6 @@ class _CodeTimerProgressState extends State<CodeTimerProgress> {
}
void _updateTimeRemaining(int currentMilliSeconds) {
- // More efficient time calculation using modulo
final elapsed =
(currentMilliSeconds + widget.timeOffsetInMilliseconds) %
_periodInMilii;
diff --git a/mobile/apps/auth/lib/ui/code_widget.dart b/mobile/apps/auth/lib/ui/code_widget.dart
index 7ae137d360..bda90deef5 100644
--- a/mobile/apps/auth/lib/ui/code_widget.dart
+++ b/mobile/apps/auth/lib/ui/code_widget.dart
@@ -771,7 +771,6 @@ class _CodeWidgetState extends State<CodeWidget> {
final bool isMixedPinned = anyPinned && !allPinned;
if (isMixedPinned) {
- // Show both pin and unpin options for mixed state
entries.add(
MenuItem(
label: l10n.pinText,
@@ -787,7 +786,6 @@ class _CodeWidgetState extends State<CodeWidget> {
),
);
} else {
- // Show single toggle option for uniform state
entries.add(
MenuItem(
label: allPinned ? l10n.unpinText : l10n.pinText,
@@ -1142,7 +1140,6 @@ class _CodeWidgetState extends State<CodeWidget> {
String _getFormattedCode(String code) {
if (_hideCode) {
- // replace all digits with β€’
code = code.replaceAll(RegExp(r'\S'), 'β€’');
}
switch (code.length) {
diff --git a/mobile/apps/auth/lib/ui/common/gradient_button.dart b/mobile/apps/auth/lib/ui/common/gradient_button.dart
index 9c5722d0ff..63ee285a6e 100644
--- a/mobile/apps/auth/lib/ui/common/gradient_button.dart
+++ b/mobile/apps/auth/lib/ui/common/gradient_button.dart
@@ -6,13 +6,10 @@ import 'package:gradient_borders/box_borders/gradient_box_border.dart';
class GradientButton extends StatefulWidget {
final Function? onTap;
- // text is ignored if child is specified
final String text;
- // nullable
final IconData? iconData;
- // padding between the text and icon
final double paddingValue;
final double fontSize;
diff --git a/mobile/apps/auth/lib/ui/components/actions_bar_widget.dart b/mobile/apps/auth/lib/ui/components/actions_bar_widget.dart
index e26a0081fd..9ea37c3310 100644
--- a/mobile/apps/auth/lib/ui/components/actions_bar_widget.dart
+++ b/mobile/apps/auth/lib/ui/components/actions_bar_widget.dart
@@ -25,7 +25,6 @@ class _ActionBarWidgetState extends State<ActionBarWidget> {
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 8, 20, 8),
child: Column(
- // left align the text
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (widget.code.note.isNotEmpty)
diff --git a/mobile/apps/auth/lib/ui/components/bottom_action_bar_widget.dart b/mobile/apps/auth/lib/ui/components/bottom_action_bar_widget.dart
index 3ad1a644c0..8721a5ecd4 100644
--- a/mobile/apps/auth/lib/ui/components/bottom_action_bar_widget.dart
+++ b/mobile/apps/auth/lib/ui/components/bottom_action_bar_widget.dart
@@ -78,7 +78,6 @@ class BottomActionBarWidget extends StatelessWidget {
),
const DividerWidget(dividerType: DividerType.bottomBar),
ActionBarWidget(code: code, onCancel: onCancel),
- // const SizedBox(height: 2)
],
),
);
diff --git a/mobile/apps/auth/lib/ui/components/code_selection_actions_widget.dart b/mobile/apps/auth/lib/ui/components/code_selection_actions_widget.dart
index cbae33cf1a..90bdb7e869 100644
--- a/mobile/apps/auth/lib/ui/components/code_selection_actions_widget.dart
+++ b/mobile/apps/auth/lib/ui/components/code_selection_actions_widget.dart
@@ -36,7 +36,6 @@ class _CodeSelectionActionsWidgetState
extends State<CodeSelectionActionsWidget> {
late final scrollController = ScrollController();
- // static final _logger = Logger("CodeSelectionActionsWidget");
@override
void dispose() {
diff --git a/mobile/apps/auth/lib/ui/components/recovery_key_sheet.dart b/mobile/apps/auth/lib/ui/components/recovery_key_sheet.dart
index 3ddc5ae8f8..8d6b7fcbfb 100644
--- a/mobile/apps/auth/lib/ui/components/recovery_key_sheet.dart
+++ b/mobile/apps/auth/lib/ui/components/recovery_key_sheet.dart
@@ -38,7 +38,6 @@ class _RecoveryKeySheetState extends State<RecoveryKeySheet> {
@override
void dispose() {
- // Clean up temp file if it exists
if (_recoveryKeyFile.existsSync()) {
_recoveryKeyFile.deleteSync();
}
@@ -50,7 +49,6 @@ class _RecoveryKeySheetState extends State<RecoveryKeySheet> {
final colorScheme = getEnteColorScheme(context);
final textTheme = getEnteTextTheme(context);
- // Convert recovery key to mnemonic words
final String recoveryKeyMnemonic = bip39.entropyToMnemonic(
widget.recoveryKey,
);
diff --git a/mobile/apps/auth/lib/ui/home/add_tag_sheet.dart b/mobile/apps/auth/lib/ui/home/add_tag_sheet.dart
index de5efa2dcb..7ee6696ce8 100644
--- a/mobile/apps/auth/lib/ui/home/add_tag_sheet.dart
+++ b/mobile/apps/auth/lib/ui/home/add_tag_sheet.dart
@@ -37,7 +37,6 @@ class _AddTagSheetState extends State<AddTagSheet> {
Future<void> _loadInitialState() async {
final allTagsFromServer = await CodeDisplayStore.instance.getAllTags();
- // Calculate intersection: tags that exist in ALL selected codes
final initialTagsForSelection = widget.selectedCodes.isEmpty
? <String>{}
: widget.selectedCodes
diff --git a/mobile/apps/auth/lib/ui/home_page.dart b/mobile/apps/auth/lib/ui/home_page.dart
index d0ba76a9b1..7337071c4d 100644
--- a/mobile/apps/auth/lib/ui/home_page.dart
+++ b/mobile/apps/auth/lib/ui/home_page.dart
@@ -96,7 +96,6 @@ class _HomePageState extends State<HomePage> {
final Logger _logger = Logger("HomePage");
final scaffoldKey = GlobalKey<ScaffoldState>();
- // Used to request focus on the search box when clicked the search icon
late FocusNode searchBoxFocusNode;
final TextEditingController _textController = TextEditingController();
@@ -327,12 +326,10 @@ class _HomePageState extends State<HomePage> {
if (codesToUpdate.isEmpty) return;
try {
- // Determine the state of the current selection (pinned/unpinned)
final bool allArePinned = codesToUpdate.every((code) => code.isPinned);
final updatedCodes = <Code>[];
if (allArePinned) {
- // if all are pinned, unpin all
for (final code in codesToUpdate) {
updatedCodes.add(
code.copyWith(display: code.display.copyWith(pinned: false)),
@@ -356,7 +353,6 @@ class _HomePageState extends State<HomePage> {
int pinnedCount = 0;
for (final code in codesToUpdate) {
if (!code.isPinned) {
- // Only pin the codes that are currently unpinned
updatedCodes.add(
code.copyWith(display: code.display.copyWith(pinned: true)),
);
@@ -402,7 +398,6 @@ class _HomePageState extends State<HomePage> {
final updatedCodes = <Code>[];
for (final code in codesToUpdate) {
if (code.isPinned) {
- // only unpin the codes that are currently pinned
updatedCodes.add(
code.copyWith(display: code.display.copyWith(pinned: false)),
);
@@ -722,7 +717,6 @@ class _HomePageState extends State<HomePage> {
!allArePinned && !selectedCodes.every((code) => !code.isPinned);
if (isMixed) {
- // Mixed state: when selection contains both pinned and unpinned codes
return Row(
children: [
_buildActionButton(
@@ -766,7 +760,6 @@ class _HomePageState extends State<HomePage> {
],
);
} else {
- // When selection contains either only pinned OR only unpinned codes
return Row(
children: [
_buildActionButton(
@@ -994,7 +987,6 @@ class _HomePageState extends State<HomePage> {
bool _handleKeyEvent(KeyEvent event) {
if (!mounted) return false;
- // Always keep our pressed key state in sync.
if (event is KeyDownEvent) {
_pressedKeys.add(event.logicalKey);
} else if (event is KeyUpEvent) {
@@ -1246,7 +1238,6 @@ class _HomePageState extends State<HomePage> {
break;
}
if (sortKey != CodeSortKey.manual) {
- // move pinned codes to the using
int insertIndex = 0;
for (int i = 0; i < codes.length; i++) {
if (codes[i].isPinned) {
@@ -1301,7 +1292,6 @@ class _HomePageState extends State<HomePage> {
return;
}
await CodeStore.instance.addCode(newCode, shouldSync: false);
- // Focus the new code by searching
if (_shouldFocusAddedCode) {
_focusNewCode(newCode);
}
@@ -1342,7 +1332,6 @@ class _HomePageState extends State<HomePage> {
code,
shouldSync: result.fromGallery ? false : true,
);
- // Focus the new code by searching
if (_shouldFocusAddedCode) {
_focusNewCode(code);
}
@@ -1515,7 +1504,6 @@ class _HomePageState extends State<HomePage> {
},
onSubmitted: (_) {
if (_filteredCodes.isNotEmpty) {
- // Move focus to the first item in the grid
_firstItemFocusNode.requestFocus();
}
},
@@ -1982,7 +1970,6 @@ class _HomePageState extends State<HomePage> {
late final AppLinks _appLinks = AppLinks();
Future<bool> _initDeepLinks() async {
- // Platform messages may fail, so we use a try/catch PlatformException.
bool hadInitialLink = false;
try {
if (!mounted) return false;
@@ -1998,7 +1985,6 @@ class _HomePageState extends State<HomePage> {
_logger.severe("PlatformException thrown while getting initial link");
}
- // Always attach a listener for future deep links
if (!kIsWeb && !Platform.isLinux) {
_deepLinkSubscription = _appLinks.stringLinkStream.listen(
(link) {
diff --git a/mobile/apps/auth/lib/ui/settings/data/export_widget.dart b/mobile/apps/auth/lib/ui/settings/data/export_widget.dart
index e4bdbea3c3..56327b8a02 100644
--- a/mobile/apps/auth/lib/ui/settings/data/export_widget.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/export_widget.dart
@@ -93,7 +93,6 @@ Future<void> _requestForEncryptionPassword(
kekSalt,
);
String exportPlainText = await _getAuthDataForExport();
- // Encrypt the key with this derived key
final encResult = await CryptoUtil.encryptData(
utf8.encode(exportPlainText),
derivedKeyResult.key,
@@ -111,7 +110,6 @@ Future<void> _requestForEncryptionPassword(
),
);
if (!context.mounted) return;
- // get json value of data
await _exportCodes(
context,
jsonEncode(data.toJson()),
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/andotp_import.dart b/mobile/apps/auth/lib/ui/settings/data/import/andotp_import.dart
index 7377abbc41..e7a7dd3c6a 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import/andotp_import.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import/andotp_import.dart
@@ -60,13 +60,11 @@ Future<int?> _processAndOTPFile(
final Uint8List fileBytes = await readPickedImportFileAsBytes(path);
try {
- // Try to parse as JSON (plain text format)
final jsonString = utf8.decode(fileBytes);
entries = jsonDecode(jsonString) as List<dynamic>;
await dialog.show();
} catch (e) {
if (!context.mounted) return null;
- // If JSON parsing fails, assume it's encrypted
String? password;
try {
password = await promptForImportPassword(
@@ -107,7 +105,6 @@ Future<int?> _processAndOTPFile(
? (label.isNotEmpty ? '$issuer ($label)' : issuer)
: label;
- // Skip unsupported types (e.g., MOTP)
if (type != 'TOTP' && type != 'HOTP' && type != 'STEAM') {
_logger.warning('Skipping unsupported OTP type: $type for $displayName');
continue;
@@ -166,41 +163,34 @@ String _decryptAndOTPBackup(_DecryptParams params) {
throw Exception('Invalid andOTP encrypted file: file too small');
}
- // Extract iterations (4 bytes, big-endian)
final ByteData byteData = ByteData.sublistView(fileBytes, 0, intLength);
final int iterations = byteData.getInt32(0, Endian.big);
- // Extract salt (12 bytes)
final Uint8List salt = Uint8List.sublistView(
fileBytes,
intLength,
intLength + saltLength,
);
- // Extract encrypted payload (IV + ciphertext + auth tag)
final Uint8List encryptedPayload = Uint8List.sublistView(
fileBytes,
intLength + saltLength,
);
- // Extract IV from encrypted payload (first 12 bytes)
final Uint8List iv = Uint8List.sublistView(encryptedPayload, 0, ivLength);
- // Extract ciphertext + auth tag (remaining bytes)
final Uint8List ciphertextWithTag = Uint8List.sublistView(
encryptedPayload,
ivLength,
);
- // Derive key using PBKDF2 with HMAC-SHA1
- const int keyLength = 32; // 256 bits
+ const int keyLength = 32;
final pbkdf2 = PBKDF2KeyDerivator(HMac(SHA1Digest(), 64));
pbkdf2.init(Pbkdf2Parameters(salt, iterations, keyLength));
final Uint8List derivedKey = Uint8List(keyLength);
pbkdf2.deriveKey(Uint8List.fromList(utf8.encode(password)), 0, derivedKey, 0);
- // Decrypt using AES-GCM
final cipher = GCMBlockCipher(AESEngine())
..init(
false,
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/google_auth_qr_parser.dart b/mobile/apps/auth/lib/ui/settings/data/import/google_auth_qr_parser.dart
index 71ccf94ae3..a7f9a51309 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import/google_auth_qr_parser.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import/google_auth_qr_parser.dart
@@ -42,18 +42,14 @@ GoogleAuthMigration parseGoogleAuthMigration(String qrCodeData) {
base64Decoded,
);
for (var otpParameter in mPayload.otpParameters) {
- // Build the OTP URL
String otpUrl;
String issuer = otpParameter.issuer;
String account = otpParameter.name;
var counter = otpParameter.counter;
- // Create a list of bytes from the list of integers.
Uint8List bytes = Uint8List.fromList(otpParameter.secret);
- // Encode the bytes to base 32.
String base32String = base32.encode(bytes);
String secret = base32String;
- // identify digit count
int digits = 6;
int timer = 30; // default timer, no field in Google Auth
Algorithm algorithm = Algorithm.sha1;
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/lastpass_import.dart b/mobile/apps/auth/lib/ui/settings/data/import/lastpass_import.dart
index eb46a135e4..17ec8f31cb 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import/lastpass_import.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import/lastpass_import.dart
@@ -45,7 +45,6 @@ Future<int?> _processLastpassExportFile(
var secret = item['secret'];
var account = item['userName'];
- // Build the OTP URL
String otpUrl =
'otpauth://totp/$issuer:$account?secret=$secret&issuer=$issuer&algorithm=$algorithm&digits=$digits&period=$timer';
parsedCodes.add(Code.fromOTPAuthUrl(otpUrl));
diff --git a/mobile/apps/auth/lib/ui/settings/data/local_backup/local_backup_experience.dart b/mobile/apps/auth/lib/ui/settings/data/local_backup/local_backup_experience.dart
index e5050c353e..43ada7ebb5 100644
--- a/mobile/apps/auth/lib/ui/settings/data/local_backup/local_backup_experience.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/local_backup/local_backup_experience.dart
@@ -192,7 +192,6 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
if (!mounted) return;
_showSnackBar(context.strings.selectFolderToContinue);
}
- // Clear the path and prompt user to re-select
await prefs.remove('autoBackupPath');
if (mounted) {
setState(() {
@@ -568,7 +567,6 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
);
if (result?.action == ButtonAction.second) {
- // Use our native picker that creates bookmark immediately
final pickResult = await SecurityBookmarkService.instance
.pickDirectoryAndCreateBookmark();
if (!mounted) return false;
@@ -588,7 +586,6 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
}
if (Platform.isMacOS) {
- // On macOS, use DirUtils which creates a security-scoped bookmark
final picked = await DirUtils.instance.pickDirectory();
if (picked != null && picked.path.isNotEmpty && picked.bookmark != null) {
if (!mounted) return false;
@@ -601,7 +598,6 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
return false;
}
- // Other platforms (Windows, Linux, etc.)
final picked = await DirUtils.instance.pickDirectory();
if (picked != null && picked.path.isNotEmpty) {
if (!mounted) return false;
@@ -725,7 +721,6 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
}
return saved;
} else if (Platform.isIOS) {
- // On iOS, use our native picker that creates bookmark immediately
final result = await SecurityBookmarkService.instance
.pickDirectoryAndCreateBookmark();
if (result != null) {
@@ -749,7 +744,6 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
}
return false;
} else if (Platform.isMacOS) {
- // On macOS, use DirUtils which creates a security-scoped bookmark
final picked = await DirUtils.instance.pickDirectory();
if (picked != null && picked.path.isNotEmpty && picked.bookmark != null) {
if (!mounted) return false;
@@ -767,7 +761,6 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
}
return false;
} else {
- // Other platforms (Windows, Linux, etc.)
final picked = await DirUtils.instance.pickDirectory();
if (picked != null && picked.path.isNotEmpty) {
@@ -804,7 +797,6 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
final pickedDir = PickedDirectory(path: path, bookmark: bookmark);
try {
- // Start accessing using the bookmark
final accessResult = await dirUtils.startAccess(pickedDir);
if (accessResult == null || !accessResult.success) {
_logger.severe(
@@ -814,7 +806,6 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
}
try {
- // Write backup directly to the selected directory
await LocalBackupService.instance.writeBackupToDirectory(path);
} finally {
await dirUtils.stopAccess(pickedDir);
@@ -849,15 +840,12 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
Future<bool> savePath(String target) async {
try {
if (Platform.isIOS || Platform.isMacOS) {
- // On iOS/macOS, use native picker with bookmark via _persistLocationWithBookmark.
- // This path is only for non-native picker which won't have scoped access.
_logger.warning(
'${Platform.operatingSystem}: _persistLocation called without bookmark. '
'Use native picker for ${Platform.operatingSystem}.',
);
return false;
} else {
- // Non-iOS: just save the path directly
await Directory(target).create(recursive: true);
await prefs.setString('autoBackupPath', target);
await prefs.remove(_treeUriKey);
@@ -985,7 +973,6 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
if (!Platform.isIOS) return false;
if (path.isEmpty) return true;
- // Normalize the path
var normalized = path;
if (normalized.startsWith('file://')) {
normalized = normalized.substring(7);
@@ -1003,7 +990,6 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {
return true;
}
- // All other paths are valid (including user-created "File Provider Storage" folders)
return false;
}
}
diff --git a/mobile/apps/auth/lib/ui/utils/icon_utils.dart b/mobile/apps/auth/lib/ui/utils/icon_utils.dart
index ed9a36a07d..0870c1fd95 100644
--- a/mobile/apps/auth/lib/ui/utils/icon_utils.dart
+++ b/mobile/apps/auth/lib/ui/utils/icon_utils.dart
@@ -14,10 +14,8 @@ class IconUtils {
static final IconUtils instance = IconUtils._privateConstructor();
- // Map of icon-title to the color code in HEX
final Map<String, SimpleIconData> _simpleIcons = {};
final Map<String, CustomIconData> _customIcons = {};
- // Map of icon-color to its luminance
final Map<Color, double> _colorLuminance = {};
final List<String> _titleSplitCharacters = ['(', '.'];
diff --git a/mobile/apps/auth/lib/utils/date_time_util.dart b/mobile/apps/auth/lib/utils/date_time_util.dart
index daaacad6d9..816fe1ff7e 100644
--- a/mobile/apps/auth/lib/utils/date_time_util.dart
+++ b/mobile/apps/auth/lib/utils/date_time_util.dart
@@ -46,17 +46,14 @@ Map<int, String> _days = {
final currentYear = int.parse(DateTime.now().year.toString());
const searchStartYear = 1970;
-//Jun 2022
String getMonthAndYear(DateTime dateTime) {
return "${_months[dateTime.month]!} ${dateTime.year}";
}
-//Thu, 30 Jun
String getDayAndMonth(DateTime dateTime) {
return "${_days[dateTime.weekday]!}, ${dateTime.day} ${_months[dateTime.month]!}";
}
-//30 Jun, 2022
String getDateAndMonthAndYear(DateTime dateTime) {
return "${dateTime.day} ${_months[dateTime.month]!}, ${dateTime.year}";
}
@@ -77,7 +74,6 @@ String getAbbreviationOfYear(DateTime dateTime) {
return (dateTime.year % 100).toString();
}
-//14:32
String getTime(DateTime dateTime) {
final hours = dateTime.hour > 9
? dateTime.hour.toString()
@@ -88,17 +84,14 @@ String getTime(DateTime dateTime) {
return "$hours:$minutes";
}
-//11:22 AM
String getTimeIn12hrFormat(DateTime dateTime) {
return DateFormat.jm().format(dateTime);
}
-//Thu, Jun 30, 2022 - 14:32
String getFormattedTime(DateTime dateTime) {
return "${getDay(dateTime)}, ${getMonth(dateTime)} ${dateTime.day}, ${dateTime.year} - ${getTime(dateTime)}";
}
-//30 Jun'22
String getFormattedDate(DateTime dateTime) {
return "${dateTime.day} ${getMonth(dateTime)}'${getAbbreviationOfYear(dateTime)}";
}
diff --git a/mobile/apps/auth/lib/utils/dialog_util.dart b/mobile/apps/auth/lib/utils/dialog_util.dart
index 5bfbc23bb6..0b22b2d28b 100644
--- a/mobile/apps/auth/lib/utils/dialog_util.dart
+++ b/mobile/apps/auth/lib/utils/dialog_util.dart
@@ -106,7 +106,6 @@ String parseErrorForUI(
}
}
}
- // return generic error if the user is not internal and the error is not in debug mode
if (!kDebugMode) {
return genericError;
}
@@ -375,7 +374,6 @@ Future<ButtonResult?> showConfettiDialog<T>({
blastDirection: pi / 2,
emissionFrequency: 0,
numberOfParticles: 100,
- // a lot of particles at once
gravity: 1,
blastDirectionality: BlastDirectionality.explosive,
),
@@ -392,7 +390,6 @@ Future<ButtonResult?> showConfettiDialog<T>({
);
}
-//Can return ButtonResult? from ButtonWidget or Exception? from TextInputDialog
Future<dynamic> showTextInputDialog(
BuildContext context, {
required String title,
diff --git a/mobile/apps/auth/lib/utils/navigation_util.dart b/mobile/apps/auth/lib/utils/navigation_util.dart
index 418abc84dc..cc980668d2 100644
--- a/mobile/apps/auth/lib/utils/navigation_util.dart
+++ b/mobile/apps/auth/lib/utils/navigation_util.dart
@@ -54,7 +54,6 @@ class SwipeableRouteBuilder<T> extends PageRoute<T> {
final RoutePageBuilder pageBuilder;
final PageTransitionsBuilder matchingBuilder =
const CupertinoPageTransitionsBuilder(); // Default iOS/macOS (to get the swipe right to go back gesture)
- // final PageTransitionsBuilder matchingBuilder = const FadeUpwardsPageTransitionsBuilder(); // Default Android/Linux/Windows
SwipeableRouteBuilder({required this.pageBuilder});
diff --git a/mobile/apps/auth/lib/utils/toast_util.dart b/mobile/apps/auth/lib/utils/toast_util.dart
index caef095a16..c8f57fb5de 100644
--- a/mobile/apps/auth/lib/utils/toast_util.dart
+++ b/mobile/apps/auth/lib/utils/toast_util.dart
@@ -13,7 +13,6 @@ void showToast(
iOSDismissOnTap = true,
double mobileBottomMargin = 16,
}) async {
- // If on mobile render toast above the keyboard using FToast.
final bool isMobile = PlatformDetector.isMobile();
if (isMobile) {
@@ -68,7 +67,6 @@ void showToast(
return;
}
- // Default path (desktop)
try {
if (!context.mounted) return;
await Fluttertoast.cancel();
diff --git a/mobile/apps/auth/lib/utils/totp_util.dart b/mobile/apps/auth/lib/utils/totp_util.dart
index 53b68be5ff..339e6ffa3d 100644
--- a/mobile/apps/auth/lib/utils/totp_util.dart
+++ b/mobile/apps/auth/lib/utils/totp_util.dart
@@ -58,8 +58,6 @@ String getNextTotp(Code code) {
);
}
-// generateFutureTotpCodes generates future TOTP codes based on the current time.
-// It returns the start time and a list of future codes.
(int, List<String>) generateFutureTotpCodes(Code code, int count) {
final int startTime =
((millisecondsSinceEpoch() ~/ 1000) ~/ code.period) * code.period * 1000;
diff --git a/mobile/apps/auth/lib/utils/window_protocol_handler.dart b/mobile/apps/auth/lib/utils/window_protocol_handler.dart
index a1436ef01f..912d4b8304 100644
--- a/mobile/apps/auth/lib/utils/window_protocol_handler.dart
+++ b/mobile/apps/auth/lib/utils/window_protocol_handler.dart
@@ -46,9 +46,4 @@ class WindowsProtocolHandler {
free(txtData);
}
}
-
- // String _sanitize(String value) {
- // value = value.replaceAll(r'%s', '%1').replaceAll(r'"', '\\"');
- // return '"$value"';
- // }
}
diff --git a/mobile/apps/locker/lib/app.dart b/mobile/apps/locker/lib/app.dart
index 9276d7a095..70e6d946fa 100644
--- a/mobile/apps/locker/lib/app.dart
+++ b/mobile/apps/locker/lib/app.dart
@@ -161,8 +161,6 @@ class _AppState extends State<App> with WidgetsBindingObserver {
);
}
- // Wrap the app with MediaQuery to control text scaling and ensure
- // consistent font sizes across Android and iOS
return MediaQuery.withClampedTextScaling(
minScaleFactor: 0.8,
maxScaleFactor: 1.3,
diff --git a/mobile/apps/locker/lib/core/locale.dart b/mobile/apps/locker/lib/core/locale.dart
index b089b89471..e048e616ec 100644
--- a/mobile/apps/locker/lib/core/locale.dart
+++ b/mobile/apps/locker/lib/core/locale.dart
@@ -23,9 +23,6 @@ const List<Locale> appSupportedLocales = <Locale>[
];
Locale? autoDetectedLocale;
-// This function takes device locales and supported locales as input
-// and returns the best matching locale.
-// The device locales are sorted by priority, so the first one is the most preferred.
Locale localResolutionCallBack(
List<Locale>? onDeviceLocales,
Iterable<Locale> supportedLocales,
@@ -36,18 +33,15 @@ Locale localResolutionCallBack(
}
for (final deviceLocale in onDeviceLocales ?? const []) {
final locale = _normalizedLocale(deviceLocale);
- // check if exact local is supported, if yes, return it
if (appSupportedLocales.contains(locale)) {
autoDetectedLocale = locale;
return locale;
}
- // check if language code is supported, if yes, return it
if (languageSupport.contains(locale.languageCode)) {
autoDetectedLocale = locale;
return locale;
}
}
- // Return the first language code match or default to 'en'
return autoDetectedLocale ?? const Locale('en');
}
@@ -55,7 +49,6 @@ Future<Locale?> getLocale({bool noFallback = false}) async {
final String? savedValue = (await SharedPreferences.getInstance()).getString(
'locale',
);
- // if savedLocale is not null and is supported by the app, return it
if (savedValue != null) {
late Locale savedLocale;
if (savedValue.contains('_')) {
diff --git a/mobile/apps/locker/lib/main.dart b/mobile/apps/locker/lib/main.dart
index 05cfd65471..a498899109 100644
--- a/mobile/apps/locker/lib/main.dart
+++ b/mobile/apps/locker/lib/main.dart
@@ -56,7 +56,6 @@ void main() async {
await _runInForeground();
if (Platform.isAndroid) {
FlutterDisplayMode.setHighRefreshRate().ignore();
- // Make the navigation bar transparent so the app theme can take over
SystemChrome.setSystemUIOverlayStyle(
const SystemUiOverlayStyle(
systemNavigationBarColor: Color(0x00000000),
diff --git a/mobile/apps/locker/lib/models/info/info_item.dart b/mobile/apps/locker/lib/models/info/info_item.dart
index 3172f270bd..f022074eb5 100644
--- a/mobile/apps/locker/lib/models/info/info_item.dart
+++ b/mobile/apps/locker/lib/models/info/info_item.dart
@@ -1,10 +1,7 @@
import 'dart:convert';
-// Enum for different information types
enum InfoType { note, physicalRecord, accountCredential, emergencyContact }
-// Extension to convert enum to string and vice versa.
-//
// Locker file metadata currently uses the enum's camelCase name on the wire.
// Keep parsing tolerant of the older hyphenated representation so any
// previously serialized JSON can still be read safely.
@@ -41,7 +38,6 @@ extension InfoTypeExtension on InfoType {
}
}
-// Base class for all information data
abstract class InfoData {
Map<String, dynamic> toJson();
@@ -59,7 +55,6 @@ abstract class InfoData {
}
}
-// Personal Note Data Model
class PersonalNoteData extends InfoData {
final String title;
final String content;
@@ -79,7 +74,6 @@ class PersonalNoteData extends InfoData {
}
}
-// Physical Record Data Model
class PhysicalRecordData extends InfoData {
final String name;
final String location;
@@ -105,7 +99,6 @@ class PhysicalRecordData extends InfoData {
}
}
-// Account Credential Data Model
class AccountCredentialData extends InfoData {
final String name;
final String username;
@@ -139,7 +132,6 @@ class AccountCredentialData extends InfoData {
}
}
-// Emergency Contact Data Model
class EmergencyContactData extends InfoData {
final String name;
final String contactDetails;
@@ -169,7 +161,6 @@ class EmergencyContactData extends InfoData {
}
}
-// Main Information Item wrapper
class InfoItem {
final InfoType type;
final InfoData data;
@@ -212,7 +203,6 @@ class InfoItem {
return InfoItem.fromJson(jsonDecode(jsonString));
}
- // Create a copy with updated data
InfoItem copyWith({
InfoType? type,
InfoData? data,
@@ -227,7 +217,6 @@ class InfoItem {
);
}
- // Update with new data and timestamp
InfoItem update(InfoData newData) {
return copyWith(data: newData, updatedAt: DateTime.now());
}
diff --git a/mobile/apps/locker/lib/services/collections/collections_api_client.dart b/mobile/apps/locker/lib/services/collections/collections_api_client.dart
index ac5587f821..2e6d7a8581 100644
--- a/mobile/apps/locker/lib/services/collections/collections_api_client.dart
+++ b/mobile/apps/locker/lib/services/collections/collections_api_client.dart
@@ -245,7 +245,6 @@ class CollectionApiClient {
params["fromCollectionID"] = fromCollection.id;
params["toCollectionID"] = toCollection.id;
- // Process files in batches
const batchSize = 100;
final batchedFiles = <List<EnteFile>>[];
for (int i = 0; i < files.length; i += batchSize) {
@@ -268,7 +267,6 @@ class CollectionApiClient {
fileCollectionKey,
);
- // Update file's collectionID to the destination (like Photos does)
file.collectionID = toCollection.id;
// Re-encrypt the file key with the destination collection's key
@@ -552,7 +550,6 @@ class CollectionApiClient {
collection.id,
prop,
);
- // remove existing url information
collection.publicURLs.clear();
collection.publicURLs.add(PublicURL.fromMap(response.data["result"]));
await _updateCollectionInDB(collection);
diff --git a/mobile/apps/locker/lib/services/collections/collections_service.dart b/mobile/apps/locker/lib/services/collections/collections_service.dart
index 0bda5a3f34..76129985cf 100644
--- a/mobile/apps/locker/lib/services/collections/collections_service.dart
+++ b/mobile/apps/locker/lib/services/collections/collections_service.dart
@@ -34,7 +34,6 @@ class CollectionService {
static final CollectionService instance =
CollectionService._privateConstructor();
- // Fixed set of suggested collection names
static const Set<String> _suggestedCollectionNames = {
'Personal',
'Work',
@@ -95,7 +94,6 @@ class CollectionService {
return;
}
await _db.updateCollections(updatedCollections);
- // Update the cache with new/updated collections
for (final collection in updatedCollections) {
_collectionIDToCollections[collection.id] = collection;
}
@@ -180,16 +178,12 @@ class CollectionService {
final collection = await _apiClient.create(name, type);
_logger.info("Created collection: ${collection.id}");
- // Cache in memory
_collectionIDToCollections[collection.id] = collection;
- // Add to local database immediately
await _db.updateCollections([collection]);
- // Fire event to update UI
Bus.instance.fire(CollectionsUpdatedEvent('collection_created'));
- // Sync to ensure we have the latest state
await sync();
return collection;
@@ -308,14 +302,11 @@ class CollectionService {
"Added file (ID: ${file.uploadedFileID}) to collection ${collection.id}",
);
- // Update local database immediately
await _db.addFilesToCollection(collection, [file]);
- // Fire event to update UI
Bus.instance.fire(CollectionsUpdatedEvent('add_to_collection'));
if (runSync) {
- // Also sync to ensure we have the latest state from server
await sync();
}
} catch (e, stackTrace) {
@@ -351,7 +342,6 @@ class CollectionService {
try {
await _apiClient.rename(collection, newName);
_logger.info("Renamed collection ${collection.id}");
- // Let sync update the local state
await sync();
} catch (e, s) {
_logger.severe("failed to rename collection", e, s);
@@ -451,10 +441,8 @@ class CollectionService {
}
try {
- // Call API to move files on server
await _apiClient.move(files, from, to);
- // Update collectionID for all files
for (final file in files) {
file.collectionID = to.id;
}
@@ -464,7 +452,6 @@ class CollectionService {
await _db.addFilesToCollection(to, files);
await _db.deleteFilesFromCollection(from, files);
- // Let sync update the local state to ensure consistency
if (runSync) {
await sync();
}
@@ -574,8 +561,6 @@ class CollectionService {
split.ownedByOtherUsers,
);
} else if (!isCollectionOwner && split.ownedByCurrentUser.isNotEmpty) {
- // collection is not owned by the user, just remove files owned
- // by current user and return
await _apiClient.removeFromCollection(
collection.id,
split.ownedByCurrentUser,
@@ -590,13 +575,7 @@ class CollectionService {
return;
}
- // pendingAssignMap keeps a track of files which are yet to be assigned to
- // to destination collection.
final Map<int, EnteFile> pendingAssignMap = {};
- // destCollectionToFilesMap contains the destination collection and
- // files entry which needs to be moved in destination.
- // After the end of mapping logic, the number of files entries in
- // pendingAssignMap should be equal to files in destCollectionToFilesMap
final Map<int, List<EnteFile>> destCollectionToFilesMap = {};
final List<int> uploadedIDs = [];
for (EnteFile f in split.ownedByCurrentUser) {
@@ -622,10 +601,7 @@ class CollectionService {
}
final Collection? targetCollection = await getCollectionByID(entry.key);
if (targetCollection != null) {
- // for each file which already exist in the destination collection
- // add entries in the moveDestCollectionToFiles map
for (EnteFile file in entry.value) {
- // Check if the uploaded file is still waiting to be mapped
if (pendingAssignMap.containsKey(file.uploadedFileID)) {
if (!destCollectionToFilesMap.containsKey(targetCollection.id)) {
destCollectionToFilesMap[targetCollection.id] = <EnteFile>[];
@@ -638,7 +614,6 @@ class CollectionService {
}
}
}
- // Move the remaining files to uncategorized collection
if (pendingAssignMap.isNotEmpty) {
late final int toCollectionID;
@@ -659,7 +634,6 @@ class CollectionService {
}
}
- // Verify that all files are mapped.
int mappedFilesCount = 0;
destCollectionToFilesMap.forEach((key, value) {
mappedFilesCount += value.length;
@@ -688,11 +662,6 @@ class CollectionService {
}
}
- // This method returns true if the given destination collection is a good
- // target to moving files during file remove or delete collection but keep
- // photos action. Uncategorized or favorite type of collections are not
- // good auto-move candidates. Uncategorized will be fall back for all files
- // which could not be mapped to a potential target collection
Future<bool> _isAutoMoveCandidate(
int fromCollectionID,
toCollectionID,
@@ -704,8 +673,6 @@ class CollectionService {
final Collection? targetCollection = await getCollectionByID(
toCollectionID,
);
- // ignore non-cached, deleted, uncategorized and favorite collections,
- // and collections ignored by others
if (targetCollection == null ||
targetCollection.isDeleted ||
(CollectionType.uncategorized == targetCollection.type ||
@@ -727,13 +694,10 @@ class CollectionService {
_logger.info("Setting up default collections...");
- // Create uncategorized collection if it doesn't exist
await getOrCreateUncategorizedCollection();
- // Create important (favorites) collection if it doesn't exist
await getOrCreateImportantCollection();
- // Create Documents collection if it doesn't exist
await _getOrCreateDocumentsCollection();
_logger.info("Default collections setup completed.");
@@ -849,7 +813,6 @@ class CollectionService {
}
}
- // getActiveCollections returns list of collections which are not deleted yet
List<Collection> getActiveCollections() {
return _collectionIDToCollections.values
.toList()
@@ -871,14 +834,11 @@ class CollectionService {
for (final c in getActiveCollections()) {
if (c.owner.id == ownerID) {
- // Collaborators and viewers of collections owned by user
for (final User u in c.sharees) {
add(u.email, userID: u.id);
}
} else if (c.owner.email.isNotEmpty) {
- // Add owners of collections shared with user
add(c.owner.email, userID: c.owner.id);
- // Collaborators of collections in which user participates
final participates = c.sharees.any(
(u) => u.email == ownerEmail && (u.isCollaborator || u.isViewer),
);
@@ -915,7 +875,6 @@ class CollectionService {
_defaultSetupInFlight = null;
}
- // Methods for managing collection cache
void updateCollectionCache(Collection collection) {
_collectionIDToCollections[collection.id] = collection;
}
diff --git a/mobile/apps/locker/lib/services/collections/models/collection.dart b/mobile/apps/locker/lib/services/collections/models/collection.dart
index 9376c7e2fc..c5843a4ded 100644
--- a/mobile/apps/locker/lib/services/collections/models/collection.dart
+++ b/mobile/apps/locker/lib/services/collections/models/collection.dart
@@ -81,13 +81,10 @@ class Collection {
sharedMagicMetadata.visibility == archiveVisibility;
}
- // hasLink returns true if there's any link attached to the collection
- // including expired links
bool get hasLink => publicURLs.isNotEmpty;
bool get hasCover => (pubMagicMetadata.coverID ?? 0) > 0;
- // hasSharees returns true if the collection is shared with other ente users
bool get hasSharees => sharees.isNotEmpty;
bool get isPinned => (magicMetadata.order ?? 0) != 0;
diff --git a/mobile/apps/locker/lib/services/collections/models/collection_magic.dart b/mobile/apps/locker/lib/services/collections/models/collection_magic.dart
index 6ffa2af957..8f5ad2ecee 100644
--- a/mobile/apps/locker/lib/services/collections/models/collection_magic.dart
+++ b/mobile/apps/locker/lib/services/collections/models/collection_magic.dart
@@ -2,11 +2,9 @@ import 'dart:convert';
import "package:locker/services/files/sync/models/common_keys.dart";
-// Collection SubType Constants
const subTypeDefaultHidden = 1;
const subTypeSharedFilesCollection = 2;
-// key for collection subType
const subTypeKey = 'subType';
const muteKey = "mute";
@@ -59,10 +57,8 @@ class CollectionMagicMetadata {
}
class CollectionPubMagicMetadata {
- // sort order while showing collection
bool? asc;
- // cover photo id for the collection
int? coverID;
CollectionPubMagicMetadata({this.asc, this.coverID});
diff --git a/mobile/apps/locker/lib/services/collections/models/collection_view_type.dart b/mobile/apps/locker/lib/services/collections/models/collection_view_type.dart
index 1264899dce..38adb23e85 100644
--- a/mobile/apps/locker/lib/services/collections/models/collection_view_type.dart
+++ b/mobile/apps/locker/lib/services/collections/models/collection_view_type.dart
@@ -34,7 +34,6 @@ extension CollectionViewTypeActions on CollectionViewType {
CollectionViewType getCollectionViewType(Collection c, int userID) {
if (!c.isOwner(userID)) {
- // Check if user is collaborator or viewer
final role = c.getRole(userID);
if (role == CollectionParticipantRole.collaborator) {
return CollectionViewType.sharedCollectionCollaborator;
diff --git a/mobile/apps/locker/lib/services/collections/models/public_url.dart b/mobile/apps/locker/lib/services/collections/models/public_url.dart
index b6bfde12b8..5c9e2037b1 100644
--- a/mobile/apps/locker/lib/services/collections/models/public_url.dart
+++ b/mobile/apps/locker/lib/services/collections/models/public_url.dart
@@ -40,7 +40,6 @@ class PublicURL {
bool get hasExpiry => validTill != 0;
- // isExpired indicates whether the link has expired or not
bool get isExpired =>
hasExpiry && validTill < DateTime.now().microsecondsSinceEpoch;
diff --git a/mobile/apps/locker/lib/services/configuration.dart b/mobile/apps/locker/lib/services/configuration.dart
index 4b47d69074..253da06b11 100644
--- a/mobile/apps/locker/lib/services/configuration.dart
+++ b/mobile/apps/locker/lib/services/configuration.dart
@@ -22,8 +22,6 @@ class Configuration extends BaseConfiguration
);
@override
- // Provide all secure storage keys that should be wiped on logout.
- // Locker app uses the standard keys defined in BaseConfiguration.
List<String> get secureStorageKeys =>
BaseConfiguration.accountSecureStorageKeys;
diff --git a/mobile/apps/locker/lib/services/db/locker_db.dart b/mobile/apps/locker/lib/services/db/locker_db.dart
index 701102e1dc..176b22c6a5 100644
--- a/mobile/apps/locker/lib/services/db/locker_db.dart
+++ b/mobile/apps/locker/lib/services/db/locker_db.dart
@@ -499,7 +499,6 @@ class LockerDB extends EnteBaseDatabase {
final Map<int, List<EnteFile>> collectionToFilesMap = {};
- // Query to get all collection mappings for the given file IDs
final placeholders = List.filled(uploadedFileIDs.length, '?').join(',');
final result = await _db.rawQuery('''
SELECT
@@ -510,7 +509,6 @@ class LockerDB extends EnteBaseDatabase {
WHERE cf.uploaded_file_id IN ($placeholders)
''', uploadedFileIDs);
- // Group files by collection ID
for (final row in result) {
final collectionId = row['mapping_collection_id'] as int;
final file = await _mapFromRow(row)
diff --git a/mobile/apps/locker/lib/services/favorites_service.dart b/mobile/apps/locker/lib/services/favorites_service.dart
index 284066816a..dd06e578e1 100644
--- a/mobile/apps/locker/lib/services/favorites_service.dart
+++ b/mobile/apps/locker/lib/services/favorites_service.dart
@@ -33,7 +33,6 @@ class FavoritesService {
_collectionUpdatesSubscription = Bus.instance
.on<CollectionsUpdatedEvent>()
.listen((event) {
- // When collections are updated, refresh our cache
_warmUpCache();
});
await _warmUpCache();
@@ -94,7 +93,6 @@ class FavoritesService {
}
Future<bool> isFavorite(EnteFile file) async {
- // Use cache for better performance
if (file.uploadedFileID != null) {
bool isFav = false;
if (file.ownerID != _config.getUserID() && file.hash != null) {
@@ -172,12 +170,9 @@ class FavoritesService {
} else {
final Collection? favCollection = await getFavoritesCollection();
for (final file in files) {
- // Get current collections for file
final currentCollections = await _collectionService
.getCollectionsForFile(file);
- // If file is in multiple collections, move it to the first non-favorite one
- // Otherwise, move to uncategorized
Collection? targetCollection;
for (final col in currentCollections) {
if (col.id != favCollection!.id) {
@@ -186,7 +181,6 @@ class FavoritesService {
}
}
- // If no other collection found, move to uncategorized
targetCollection ??= await _collectionService
.getOrCreateUncategorizedCollection();
@@ -203,8 +197,6 @@ class FavoritesService {
} else {
final Collection? favCollection = await getFavoritesCollection();
- // The file might be part of another collection. For unfav, we need to
- // move file from the fav collection.
if (file.ownerID != _config.getUserID() &&
file.hash != null &&
_cachedFavFileHashes.containsKey(file.hash!)) {
@@ -225,13 +217,10 @@ class FavoritesService {
file = favFile;
}
- // Get current collections for file
final currentCollections = await _collectionService.getCollectionsForFile(
file,
);
- // If file is in multiple collections, move it to the first non-favorite one
- // Otherwise, move to uncategorized
Collection? targetCollection;
for (final col in currentCollections) {
if (col.id != favCollection.id) {
@@ -240,7 +229,6 @@ class FavoritesService {
}
}
- // If no other collection found, move to uncategorized
targetCollection ??= await _collectionService
.getOrCreateUncategorizedCollection();
diff --git a/mobile/apps/locker/lib/services/files/download/manager.dart b/mobile/apps/locker/lib/services/files/download/manager.dart
index 3df8011a0c..c9a99b579a 100644
--- a/mobile/apps/locker/lib/services/files/download/manager.dart
+++ b/mobile/apps/locker/lib/services/files/download/manager.dart
@@ -14,10 +14,8 @@ class DownloadManager {
final Dio _dio;
- // In-memory storage for download tasks
final Map<int, DownloadTask> _tasks = {};
- // Active downloads with their completers and streams
final Map<int, Completer<DownloadResult>> _completers = {};
final Map<int, StreamController<DownloadTask>> _streams = {};
final Map<int, CancelToken> _cancelTokens = {};
@@ -40,7 +38,6 @@ class DownloadManager {
String filename,
int totalBytes,
) async {
- // If already downloading, return existing future
if (_completers.containsKey(fileId)) {
return _completers[fileId]!.future;
}
@@ -48,18 +45,14 @@ class DownloadManager {
final completer = Completer<DownloadResult>();
_completers[fileId] = completer;
- // Get or create task
final existingTask = _tasks[fileId];
var task =
existingTask ??
DownloadTask(id: fileId, filename: filename, totalBytes: totalBytes);
- // Store task in memory
_tasks[fileId] = task;
- // Don't restart if already completed
if (task.isCompleted) {
- // ensure that the file exists
final filePath = task.filePath;
if (filePath == null || !(await File(filePath).exists())) {
_logger.warning(
@@ -97,7 +90,6 @@ class DownloadManager {
_updateTask(task.copyWith(status: DownloadStatus.paused));
}
- // Clean up streams if no listeners
final stream = _streams[fileId];
if (stream != null && !stream.hasListener) {
await stream.close();
@@ -138,7 +130,6 @@ class DownloadManager {
final directory = Configuration.instance.getTempDirectory();
final basePath = '$directory${task.id}.encrypted';
- // Check existing chunks and calculate progress
final totalChunks = (task.totalBytes / downloadChunkSize).ceil();
final existingChunks = await _validateExistingChunks(
basePath,
@@ -186,7 +177,6 @@ class DownloadManager {
}
} catch (e) {
if (e is DioException && e.type == DioExceptionType.cancel) {
- // Complete future with current task state (paused or cancelled)
final currentTask = _tasks[task.id];
if (currentTask != null && !completer.isCompleted) {
completer.complete(DownloadResult(currentTask, false));
@@ -284,7 +274,6 @@ class DownloadManager {
_notifyProgress(updatedTask);
},
);
- // Update progress after chunk completion
final chunkFileSize = await File(chunkPath).length();
task = task.copyWith(
bytesDownloaded: (chunkIndex) * downloadChunkSize + chunkFileSize,
@@ -354,7 +343,6 @@ class DownloadManager {
final finalFile = File(basePath);
if (await finalFile.exists()) await finalFile.delete();
- // Delete chunk files
final totalChunks = (task.totalBytes / downloadChunkSize).ceil();
for (int i = 1; i <= totalChunks; i++) {
final chunkFile = File(_getChunkPath(basePath, i));
diff --git a/mobile/apps/locker/lib/services/files/download/service_locator.dart b/mobile/apps/locker/lib/services/files/download/service_locator.dart
index ca65319ff2..bcad4e422e 100644
--- a/mobile/apps/locker/lib/services/files/download/service_locator.dart
+++ b/mobile/apps/locker/lib/services/files/download/service_locator.dart
@@ -9,7 +9,6 @@ class ServiceLocator {
late final Dio nonEnteDio;
late final PackageInfo packageInfo;
- // instance
ServiceLocator._privateConstructor();
static final ServiceLocator instance = ServiceLocator._privateConstructor();
diff --git a/mobile/apps/locker/lib/services/files/sync/metadata_updater_service.dart b/mobile/apps/locker/lib/services/files/sync/metadata_updater_service.dart
index a16ee6a525..576280332c 100644
--- a/mobile/apps/locker/lib/services/files/sync/metadata_updater_service.dart
+++ b/mobile/apps/locker/lib/services/files/sync/metadata_updater_service.dart
@@ -110,9 +110,6 @@ class MetadataUpdaterService {
} else if (file.ownerID != ownerID) {
throw AssertionError("cannot modify memories not owned by you");
}
- // read the existing magic metadata and apply new updates to existing data
- // current update is simple replace. This will be enhanced in the future,
- // as required.
final newUpdates = metadataUpdateMap != null
? metadataUpdateMap[file.uploadedFileID]
: newMetadataUpdate;
@@ -127,7 +124,6 @@ class MetadataUpdaterService {
jsonToUpdate[key] = value;
});
- // update the local information so that it's reflected on UI
file.pubMmdEncodedJson = jsonEncode(jsonToUpdate);
file.pubMagicMetadata = PubMagicMetadata.fromJson(jsonToUpdate);
diff --git a/mobile/apps/locker/lib/services/files/sync/models/common_keys.dart b/mobile/apps/locker/lib/services/files/sync/models/common_keys.dart
index 44dbf1665e..6370e588f3 100644
--- a/mobile/apps/locker/lib/services/files/sync/models/common_keys.dart
+++ b/mobile/apps/locker/lib/services/files/sync/models/common_keys.dart
@@ -1,6 +1,5 @@
const magicKeyVisibility = 'visibility';
-// Visibility Constants
const visibleVisibility = 0;
const archiveVisibility = 1;
diff --git a/mobile/apps/locker/lib/services/files/upload/file_upload_service.dart b/mobile/apps/locker/lib/services/files/upload/file_upload_service.dart
index c609d7a13a..a32f3e3b77 100644
--- a/mobile/apps/locker/lib/services/files/upload/file_upload_service.dart
+++ b/mobile/apps/locker/lib/services/files/upload/file_upload_service.dart
@@ -51,18 +51,11 @@ class FileUploader {
LinkedHashMap<String, BackupItem> get allBackups => _allBackups;
- // Maintains the count of files in the current upload session.
- // Upload session is the period between the first entry into the _queue and last entry out of the _queue
int _totalCountInUploadSession = 0;
- // _uploadCounter indicates number of uploads which are currently in progress
int _uploadCounter = 0;
late SharedPreferences _prefs;
- // _hasInitiatedForceUpload is used to track if user attempted force upload
- // where files are uploaded directly (without adding them to DB). In such
- // cases, we don't want to clear the stale upload files. See #removeStaleFiles
- // as it can result in clearing files which are still being force uploaded.
final bool _hasInitiatedForceUpload = false;
FileUploader._privateConstructor();
@@ -104,10 +97,8 @@ class FileUploader {
_checkIfWithinFileCountLimit();
- // Generate a file key for encryption
final fileKey = CryptoUtil.generateKey();
- // Create metadata for the info file
final Map<String, dynamic> metadata = infoFile.metadata;
final encryptedMetadataResult = await CryptoUtil.encryptData(
utf8.encode(jsonEncode(metadata)),
@@ -121,7 +112,6 @@ class FileUploader {
encryptedMetadataResult.header!,
);
- // Encrypt the file key with collection key
final encryptedFileKeyData = CryptoUtil.encryptSync(
fileKey,
CryptoHelper.instance.getCollectionKey(collection),
@@ -137,7 +127,6 @@ class FileUploader {
'info': infoFile.pubMagicMetadata.info,
}, fileKey);
- // Upload as metadata-only file (no file content or thumbnail)
final uploadedFile = await _uploadInfoFileMetadata(
infoFile,
collection.id,
@@ -205,7 +194,6 @@ class FileUploader {
void _pollQueue() {
if (_queue.isEmpty) {
- // Upload session completed
_totalCountInUploadSession = 0;
return;
}
@@ -274,8 +262,6 @@ class FileUploader {
}
try {
final String dir = Configuration.instance.getTempDirectory();
- // delete all files in the temp directory that start with upload_ and
- // ends with .encrypted. Fetch files in async manner
final files = await Directory(dir).list().toList();
final filesToDelete = files.where((file) {
return file.path.contains(uploadTempFilePrefix) &&
@@ -316,8 +302,6 @@ class FileUploader {
late final int encFileSize;
var uploadCompleted = false;
- // This flag is used to decide whether to clear the iOS origin file cache
- // or not.
var uploadHardFailure = false;
try {
_logger.info('starting ${forcedUpload ? 'forced' : ''} upload');
@@ -326,11 +310,9 @@ class FileUploader {
final encryptedFileExists = File(encryptedFilePath).existsSync();
if (encryptedFileExists) {
- // otherwise just delete the file for singlepart upload
await File(encryptedFilePath).delete();
}
- // Validate source file before encryption
final sourceFileSize = await file.length();
if (sourceFileSize == 0) {
throw Exception('Source file is empty (0 bytes)');
@@ -362,7 +344,6 @@ class FileUploader {
);
final encThumbSize = await encryptedThumbnailFile.length();
- // Validate file sizes before upload
if (encFileSize == 0) {
throw Exception('Encrypted file size is 0');
}
@@ -370,11 +351,9 @@ class FileUploader {
throw Exception('Encrypted thumbnail size is 0');
}
- // Calculate MD5 hashes for checksum verification
final thumbnailMd5 = await computeMd5(encryptedThumbnailPath);
final fileMd5 = fileAttributes.fileMd5;
- // Validate that MD5 was calculated during encryption
if (fileMd5 == null || fileMd5.isEmpty) {
throw Exception('File MD5 hash is null or empty');
}
@@ -476,7 +455,6 @@ class FileUploader {
e is FileTooLargeForPlanError ||
e is NoActiveSubscriptionError ||
e is FileLimitReachedError)) {
- // file upload can not be retried in such cases without user intervention
uploadHardFailure = true;
}
rethrow;
@@ -503,7 +481,6 @@ class FileUploader {
jsonToUpdate[key] = value;
});
- // update the local information so that it's reflected on UI
file.pubMmdEncodedJson = jsonEncode(jsonToUpdate);
file.pubMagicMetadata = PubMagicMetadata.fromJson(jsonToUpdate);
final encryptedMMd = await CryptoUtil.encryptData(
@@ -534,13 +511,6 @@ class FileUploader {
}
}
- /*
- _checkIfWithinFileCountLimit verifies if the user has reached their file count
- limit. It throws FileLimitReachedError if the limit is reached. For family
- plan users, it checks the combined family file count against the shared limit.
- This check is best effort and may not be completely accurate due to UserDetail
- cache.
- */
void _checkIfWithinFileCountLimit() {
try {
final userDetails = UserService.instance.getCachedUserDetails();
@@ -576,22 +546,14 @@ class FileUploader {
return currentLimit;
}
- /*
- _checkIfWithinStorageLimit verifies if the file size for encryption and upload
- is within the storage limit. It throws StorageLimitExceededError if the limit
- is exceeded. This check is best effort and may not be completely accurate
- due to UserDetail cache. It prevents infinite loops when clients attempt to
- upload files that exceed the server's storage limit + buffer.
- Note: Local storageBuffer is 20MB, server storageBuffer is 50MB, and an
- additional 30MB is reserved for thumbnails and encryption overhead.
- */
+ // Keep the client buffer 30 MB below the server buffer for thumbnail and
+ // encryption overhead. Cached user details make this check best-effort.
Future<void> _checkIfWithinStorageLimit(File fileToBeUploaded) async {
try {
final userDetails = UserService.instance.getCachedUserDetails();
if (userDetails == null) {
return;
}
- // add k20MBStorageBuffer to the free storage
final num freeStorage = userDetails.getFreeStorage() + k20MBStorageBuffer;
final num fileSize = await fileToBeUploaded.length();
if (fileSize > freeStorage) {
@@ -706,7 +668,6 @@ class FileUploader {
}
}
- // Fetch a fresh upload URL for each file with content length and MD5
Future<UploadURL> _getUploadURL({
required int contentLength,
required String md5,
diff --git a/mobile/apps/locker/lib/services/info_file_service.dart b/mobile/apps/locker/lib/services/info_file_service.dart
index afc72ab030..7f7a2b778e 100644
--- a/mobile/apps/locker/lib/services/info_file_service.dart
+++ b/mobile/apps/locker/lib/services/info_file_service.dart
@@ -18,27 +18,22 @@ class InfoFileService {
required Collection collection,
}) async {
try {
- // Create EnteFile object directly without a physical file
final enteFile = EnteFile();
enteFile.fileType = FileType.info;
enteFile.collectionID = collection.id;
- // Set the title based on info type and data
enteFile.title = getInfoFileTitle(infoItem);
- // Set creation and modification times
final now = DateTime.now().millisecondsSinceEpoch;
enteFile.creationTime = now;
enteFile.modificationTime = now;
- // Create public magic metadata with info data
final pubMagicMetadata = PubMagicMetadata(
info: {'type': infoItem.type.name, 'data': infoItem.data.toJson()},
- noThumb: true, // No thumbnail for info files
+ noThumb: true,
);
enteFile.pubMagicMetadata = pubMagicMetadata;
- // Upload the file using the special info file upload method
final uploadedFile = await _uploadInfoFile(enteFile, collection);
_logger.info(
@@ -56,13 +51,11 @@ class InfoFileService {
required InfoItem updatedInfoItem,
}) async {
try {
- // Prepare the info data structure
final infoData = {
'type': updatedInfoItem.type.name,
'data': updatedInfoItem.data.toJson(),
};
- // Prepare metadata updates - only update info and name/time if needed
final Map<String, dynamic> metadataUpdates = {infoKey: infoData};
// Update title if it's different from current display name
@@ -73,7 +66,6 @@ class InfoFileService {
metadataUpdates[editTimeKey] = DateTime.now().millisecondsSinceEpoch;
}
- // Update metadata using the simple metadata updater service
final success = await MetadataUpdaterService.instance.updateFileMetadata(
existingFile,
metadataUpdates,
@@ -178,7 +170,6 @@ class InfoFileService {
EnteFile enteFile,
Collection collection,
) async {
- // Use the FileUploader's special method for info files
return await FileUploader.instance.uploadInfoFile(enteFile, collection);
}
}
diff --git a/mobile/apps/locker/lib/services/trash/trash_service.dart b/mobile/apps/locker/lib/services/trash/trash_service.dart
index 0d40754f23..93c770f72c 100644
--- a/mobile/apps/locker/lib/services/trash/trash_service.dart
+++ b/mobile/apps/locker/lib/services/trash/trash_service.dart
@@ -203,7 +203,6 @@ class TrashService {
await _enteDio.post("/trash/delete", data: params);
await _db.deleteTrashFiles(uniqueFileIds);
await _db.deleteFilesByUploadedFileIDs(uniqueFileIds);
- // no need to await on syncing trash from remote
unawaited(syncTrash());
}
@@ -252,7 +251,6 @@ class TrashService {
}
await _enteDio.post("/collections/restore-files", data: params);
await _db.deleteTrashFiles(files.map((e) => e.uploadedFileID!).toList());
- // Refresh collections so restored files are immediately available in UI
await CollectionService.instance.sync();
Bus.instance.fire(CollectionsUpdatedEvent("file_restore"));
Bus.instance.fire(UserDetailsRefreshEvent());
diff --git a/mobile/apps/locker/lib/ui/components/item_list_view.dart b/mobile/apps/locker/lib/ui/components/item_list_view.dart
index af4dd052c8..fb62e88b41 100644
--- a/mobile/apps/locker/lib/ui/components/item_list_view.dart
+++ b/mobile/apps/locker/lib/ui/components/item_list_view.dart
@@ -269,7 +269,6 @@ class _FileListItem extends _ListItem {
@override
String get name {
- // For info files, try to extract the title from the info data
if (_file.fileType == FileType.info) {
return InfoFileService.instance.getFileTitleFromFile(_file) ??
_file.displayName;
diff --git a/mobile/apps/locker/lib/ui/components/recents_section_widget.dart b/mobile/apps/locker/lib/ui/components/recents_section_widget.dart
index 04ffb3e62d..5e1c0cd7b8 100644
--- a/mobile/apps/locker/lib/ui/components/recents_section_widget.dart
+++ b/mobile/apps/locker/lib/ui/components/recents_section_widget.dart
@@ -45,7 +45,6 @@ class _RecentsSectionWidgetState extends State<RecentsSectionWidget> {
super.initState();
_originalCollectionOrder = List.from(widget.collections);
_availableCollections = List.from(widget.collections);
- // Update notifier with initial displayed files after first frame
WidgetsBinding.instance.addPostFrameCallback((_) {
_updateDisplayedFilesNotifier();
});
@@ -71,7 +70,6 @@ class _RecentsSectionWidgetState extends State<RecentsSectionWidget> {
}
});
_updateFilteredFiles();
- // Update notifier when source files change and no filters are active
if (!_hasActiveFilters) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_updateDisplayedFilesNotifier();
@@ -253,7 +251,6 @@ class _RecentsSectionWidgetState extends State<RecentsSectionWidget> {
_availableCollections = List.from(widget.collections);
});
- // Update notifier when filters are cleared
WidgetsBinding.instance.addPostFrameCallback((_) {
_updateDisplayedFilesNotifier();
});
@@ -309,7 +306,6 @@ class _RecentsSectionWidgetState extends State<RecentsSectionWidget> {
_availableCollections = availableCollections;
});
- // Update notifier with the new displayed files
WidgetsBinding.instance.addPostFrameCallback((_) {
_updateDisplayedFilesNotifier();
});
@@ -329,7 +325,6 @@ class _RecentsSectionWidgetState extends State<RecentsSectionWidget> {
if (refresh) {
_fileCollectionsCache.remove(fileId);
- // Drop any in-flight request so a fresh fetch is triggered.
final _ = _fileCollectionsRequests.remove(fileId);
}
diff --git a/mobile/apps/locker/lib/ui/components/recovery_key_sheet.dart b/mobile/apps/locker/lib/ui/components/recovery_key_sheet.dart
index a04d53ed64..ca4b5940a4 100644
--- a/mobile/apps/locker/lib/ui/components/recovery_key_sheet.dart
+++ b/mobile/apps/locker/lib/ui/components/recovery_key_sheet.dart
@@ -36,7 +36,6 @@ class _RecoveryKeySheetState extends State<RecoveryKeySheet> {
@override
void dispose() {
- // Clean up temp file if it exists
if (_recoveryKeyFile.existsSync()) {
_recoveryKeyFile.deleteSync();
}
@@ -47,7 +46,6 @@ class _RecoveryKeySheetState extends State<RecoveryKeySheet> {
Widget build(BuildContext context) {
final colors = context.componentColors;
- // Convert recovery key to mnemonic words
final String recoveryKeyMnemonic = bip39.entropyToMnemonic(
widget.recoveryKey,
);
diff --git a/mobile/apps/locker/lib/ui/components/search_result_view.dart b/mobile/apps/locker/lib/ui/components/search_result_view.dart
index 43e2d4e767..0fac755fcf 100644
--- a/mobile/apps/locker/lib/ui/components/search_result_view.dart
+++ b/mobile/apps/locker/lib/ui/components/search_result_view.dart
@@ -27,7 +27,6 @@ class SearchResultView extends StatelessWidget {
Widget build(BuildContext context) {
final displayCollections = showCollections ? collections : <Collection>[];
- // For non-home pages, show search everywhere option
return Padding(
padding: const EdgeInsets.only(left: 16, right: 16),
child: Column(
diff --git a/mobile/apps/locker/lib/ui/mixins/search_mixin.dart b/mobile/apps/locker/lib/ui/mixins/search_mixin.dart
index 44bc29bd9d..2d1bf5467d 100644
--- a/mobile/apps/locker/lib/ui/mixins/search_mixin.dart
+++ b/mobile/apps/locker/lib/ui/mixins/search_mixin.dart
@@ -212,7 +212,6 @@ mixin SearchMixin<T extends StatefulWidget> on State<T> {
bool handleKeyEvent(KeyEvent event) {
if (event is KeyDownEvent) {
- // Clear search or close search on ESC
if (event.logicalKey == LogicalKeyboardKey.escape) {
if (_isSearchActive) {
if (_searchQuery.isNotEmpty) {
@@ -223,7 +222,6 @@ mixin SearchMixin<T extends StatefulWidget> on State<T> {
return true;
}
}
- // Activate search on Ctrl+F (Cmd+F on Mac)
else if (event.logicalKey == LogicalKeyboardKey.keyF &&
(HardwareKeyboard.instance.isMetaPressed ||
HardwareKeyboard.instance.isControlPressed)) {
@@ -253,7 +251,6 @@ mixin SearchMixin<T extends StatefulWidget> on State<T> {
onSearchStateChanged(true);
unawaited(_performSearch(query));
- // Focus the search field after the widget is built
WidgetsBinding.instance.addPostFrameCallback((_) {
_searchFocusNode.requestFocus();
});
diff --git a/mobile/apps/locker/lib/ui/pages/base_info_page.dart b/mobile/apps/locker/lib/ui/pages/base_info_page.dart
index 6b127ab89c..0f6ff3d199 100644
--- a/mobile/apps/locker/lib/ui/pages/base_info_page.dart
+++ b/mobile/apps/locker/lib/ui/pages/base_info_page.dart
@@ -54,22 +54,18 @@ abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>
@protected
bool get isInEditMode => _currentMode == InfoPageMode.edit;
- // Current data state (can be updated after saving)
T? _currentData;
- // Collection selection state
List<Collection> _availableCollections = [];
Set<int> _selectedCollectionIds = {};
Set<int> _initialSelectedCollectionIds = {};
bool _hasLoadedCollectionSelection = false;
- // Getter for current data - prioritizes updated data over existing file data
T? get currentData {
if (_currentData != null) {
return _currentData;
}
- // Extract data from existing file if available
if (widget.existingFile != null) {
final infoItem = InfoFileService.instance.extractInfoFromFile(
widget.existingFile!,
@@ -80,13 +76,8 @@ abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>
return null;
}
- // Override this method in subclasses to refresh UI when data changes
- void refreshUIWithCurrentData() {
- // Default implementation does nothing
- // Subclasses should override this to update their controllers/state
- }
+ void refreshUIWithCurrentData() {}
- // Abstract methods that subclasses must implement
String get pageTitle;
String get submitButtonText;
InfoType get infoType;
@@ -209,9 +200,7 @@ abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>
loadExistingData();
}
- void loadExistingData() {
- // Override in subclasses if needed
- }
+ void loadExistingData() {}
Future<void> _loadCollections() async {
try {
@@ -264,7 +253,6 @@ abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>
}
try {
- // Create InfoItem using the subclass implementation
final infoData = createInfoData();
final infoItem = InfoItem(
type: infoType,
@@ -273,17 +261,14 @@ abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>
);
if (widget.existingFile != null) {
- // Update existing file
await _updateExistingFile(infoItem);
} else {
- // Create new file
await _createNewFile(infoItem);
}
if (mounted && widget.existingFile != null) {
_captureEditSessionState();
- // Switch to view mode with updated data
setState(() {
_currentMode = InfoPageMode.view;
});
@@ -315,7 +300,6 @@ abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>
Future<void> _updateExistingFile(InfoItem infoItem) async {
if (widget.existingFile == null) return;
- // Use InfoFileService to handle the update logic
final success = await InfoFileService.instance.updateInfoFile(
existingFile: widget.existingFile!,
updatedInfoItem: infoItem,
@@ -325,18 +309,14 @@ abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>
throw Exception('Failed to update file metadata');
}
- // Handle collection membership changes
await _updateCollectionMembership();
if (!mounted) return;
- // Update the local data to reflect the changes in the UI
- // Use the infoItem data directly since it contains the updated values
setState(() {
_currentData = infoItem.data as T?;
});
- // Refresh UI with updated data
refreshUIWithCurrentData();
// The info file service already performs a sync, so we don't need to sync again
@@ -346,20 +326,16 @@ abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>
if (widget.existingFile == null) return;
if (!_hasLoadedCollectionSelection) return;
- // Get current collections for the file
final currentCollections = await CollectionService.instance
.getCollectionsForFile(widget.existingFile!);
- // Fetch all collections to ensure we have the latest state
final allCollections = await CollectionService.instance.getCollections();
- // Get the favorites/important collection for special handling
final favoriteCollection = await CollectionService.instance
.getOrCreateImportantCollection();
final currentCollectionIds = currentCollections.map((c) => c.id).toSet();
- // Check if favorites status changed
final wasFavorite = currentCollectionIds.contains(favoriteCollection.id);
final isFavoriteNow = _selectedCollectionIds.contains(
favoriteCollection.id,
@@ -387,7 +363,6 @@ abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>
regularSelectedIds,
);
- // If all regular collections are deselected, move to uncategorized
if (regularSelectedIds.isEmpty && collectionsToRemove.isNotEmpty) {
for (final collectionId in collectionsToRemove) {
try {
@@ -406,7 +381,6 @@ abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>
}
}
} else {
- // Add to new collections
for (final collectionId in collectionsToAdd) {
try {
final collection = allCollections.firstWhere(
@@ -422,7 +396,6 @@ abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>
}
}
- // Remove from deselected collections
for (final collectionId in collectionsToRemove) {
try {
final collection = allCollections.firstWhere(
@@ -455,13 +428,11 @@ abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>
selectedCollections.add(uncategorizedCollection);
}
- // Upload to the first collection
final uploadedFile = await InfoFileService.instance.createAndUploadInfoFile(
infoItem: infoItem,
collection: selectedCollections.first,
);
- // Add to additional collections if multiple were selected
for (int i = 1; i < selectedCollections.length; i++) {
await CollectionService.instance.addToCollection(
selectedCollections[i],
@@ -470,13 +441,11 @@ abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>
);
}
- // Trigger sync after successful save
await CollectionService.instance.sync();
Bus.instance.fire(UserDetailsRefreshEvent());
if (!mounted) return;
- // Show success message
final collectionCount = selectedCollections.length;
final message = collectionCount == 1
? context.strings.recordSavedSuccessfully
@@ -484,13 +453,11 @@ abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>
count: collectionCount,
);
- // Navigate to home page and clear all previous routes
await Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (context) => const HomePage()),
(route) => false,
);
- // Show success message after navigation
Future.delayed(const Duration(milliseconds: 100), () {
if (mounted) {
showToast(context, message);
diff --git a/mobile/apps/locker/lib/ui/pages/home_page.dart b/mobile/apps/locker/lib/ui/pages/home_page.dart
index 3b698fdd2a..c36fe6322a 100644
--- a/mobile/apps/locker/lib/ui/pages/home_page.dart
+++ b/mobile/apps/locker/lib/ui/pages/home_page.dart
@@ -238,10 +238,8 @@ class _HomePageState extends UploaderPageState<HomePage>
_loadCollections();
- // Initialize sharing functionality to handle shared files
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
- // Add a small delay to ensure the app is fully loaded
Future.delayed(const Duration(milliseconds: 1000), () {
if (mounted) {
initializeSharing();
@@ -252,11 +250,9 @@ class _HomePageState extends UploaderPageState<HomePage>
_initDeepLinks();
- // Activate search if initial query is provided (after collections are loaded)
if (widget.initialSearchQuery != null &&
widget.initialSearchQuery!.isNotEmpty) {
WidgetsBinding.instance.addPostFrameCallback((_) {
- // Wait a bit more to ensure collections are loaded
Future.delayed(const Duration(milliseconds: 100), () {
if (mounted) {
activateSearchWithQuery(widget.initialSearchQuery!);
@@ -494,7 +490,6 @@ class _HomePageState extends UploaderPageState<HomePage>
if (collections.isEmpty && hasCompletedFirstSync) {
_logger.info("No collections found after sync, setting up defaults");
await CollectionService.instance.ensureDefaultCollections();
- // Reload collections after setup
collections = await CollectionService.instance.getCollections();
await _loadRecentFiles(collections);
}
@@ -571,7 +566,6 @@ class _HomePageState extends UploaderPageState<HomePage>
}
void _handleClearSearch() {
- // Clear text and unfocus before dismissing search
searchController.clear();
searchFocusNode.unfocus();
diff --git a/mobile/apps/locker/lib/ui/pages/onboarding_page.dart b/mobile/apps/locker/lib/ui/pages/onboarding_page.dart
index 1e3374f0a1..288a4f3c82 100644
--- a/mobile/apps/locker/lib/ui/pages/onboarding_page.dart
+++ b/mobile/apps/locker/lib/ui/pages/onboarding_page.dart
@@ -270,19 +270,15 @@ class _OnboardingPageState extends State<OnboardingPage> {
if (Configuration.instance.getEncryptedToken() == null) {
page = EmailEntryPage(Configuration.instance);
} else {
- // No key
if (Configuration.instance.getKeyAttributes() == null) {
- // Never had a key
page = PasswordEntryPage(
Configuration.instance,
PasswordEntryMode.set,
const HomePage(),
);
} else if (Configuration.instance.getKey() == null) {
- // Yet to decrypt the key
page = PasswordReentryPage(Configuration.instance, const HomePage());
} else {
- // All is well
page = const HomePage();
}
}
@@ -300,20 +296,15 @@ class _OnboardingPageState extends State<OnboardingPage> {
if (Configuration.instance.getEncryptedToken() == null) {
page = LoginPage(Configuration.instance);
} else {
- // No key
if (Configuration.instance.getKeyAttributes() == null) {
- // Never had a key
page = PasswordEntryPage(
Configuration.instance,
PasswordEntryMode.set,
const HomePage(),
);
} else if (Configuration.instance.getKey() == null) {
- // Yet to decrypt the key
page = PasswordReentryPage(Configuration.instance, const HomePage());
} else {
- // All is well, user just has not subscribed
- // page = getSubscriptionPage(isOnBoarding: true);
page = const HomePage();
}
}
diff --git a/mobile/apps/locker/lib/ui/pages/uploader_page.dart b/mobile/apps/locker/lib/ui/pages/uploader_page.dart
index 3df7e6cc9e..07286600a3 100644
--- a/mobile/apps/locker/lib/ui/pages/uploader_page.dart
+++ b/mobile/apps/locker/lib/ui/pages/uploader_page.dart
@@ -72,7 +72,6 @@ abstract class UploaderPageState<T extends UploaderPage> extends State<T> {
return false;
}
- // Navigate to upload screen to get collection selection
final uploadResult = await Navigator.of(context)
.push<FileUploadScreenResult>(
MaterialPageRoute(
@@ -84,7 +83,6 @@ abstract class UploaderPageState<T extends UploaderPage> extends State<T> {
),
);
- // Handle both regular collections and uncategorized (empty set)
final isUncategorizedUpload =
uploadResult != null && uploadResult.selectedCollections.isEmpty;
final isRegularUpload =
@@ -93,7 +91,6 @@ abstract class UploaderPageState<T extends UploaderPage> extends State<T> {
if (isUncategorizedUpload || isRegularUpload) {
didUpload = true;
if (isUncategorizedUpload) {
- // Get the uncategorized collection for upload
final uncategorizedCollection = await CollectionService.instance
.getOrCreateUncategorizedCollection();
uploadResult.selectedCollections.add(uncategorizedCollection);
@@ -135,7 +132,6 @@ abstract class UploaderPageState<T extends UploaderPage> extends State<T> {
}
final postUploadFutures = <Future<dynamic>>[];
- // Add to additional collections if multiple were selected
for (
int cIndex = 1;
cIndex < uploadResult.selectedCollections.length;
diff --git a/mobile/apps/locker/lib/ui/sharing/pickers/link_expiry_picker_page.dart b/mobile/apps/locker/lib/ui/sharing/pickers/link_expiry_picker_page.dart
index 6351f30ef2..a498f2045e 100644
--- a/mobile/apps/locker/lib/ui/sharing/pickers/link_expiry_picker_page.dart
+++ b/mobile/apps/locker/lib/ui/sharing/pickers/link_expiry_picker_page.dart
@@ -42,7 +42,6 @@ class ItemsWidget extends StatefulWidget {
}
class _ItemsWidgetState extends State<ItemsWidget> {
- // index, title, milliseconds in future post which link should expire (when >0)
late final List<Tuple2<String, int>> _expiryOptions = [
Tuple2(context.strings.never, 0),
Tuple2(context.strings.after1Hour, const Duration(hours: 1).inMicroseconds),
@@ -81,7 +80,6 @@ class _ItemsWidgetState extends State<ItemsWidget> {
onTap: () async {
int newValidTill = -1;
final int expireAfterInMicroseconds = expiryOption.item2;
- // need to manually select time
if (expireAfterInMicroseconds < 0) {
final now = DateTime.now();
final DateTime? picked = await showDateTimePickerSheet(
@@ -94,7 +92,6 @@ class _ItemsWidgetState extends State<ItemsWidget> {
newValidTill = timeInMicrosecondsFromEpoch;
}
} else if (expireAfterInMicroseconds == 0) {
- // no expiry
newValidTill = 0;
} else {
newValidTill =
diff --git a/mobile/apps/locker/lib/utils/collection_actions.dart b/mobile/apps/locker/lib/utils/collection_actions.dart
index 12127c34c8..08ca0a60e8 100644
--- a/mobile/apps/locker/lib/utils/collection_actions.dart
+++ b/mobile/apps/locker/lib/utils/collection_actions.dart
@@ -65,7 +65,6 @@ class CollectionActions {
return null;
}
- // Shows a dialog to edit/rename a collection
static Future<void> editCollection(
BuildContext context,
Collection collection, {
@@ -97,10 +96,8 @@ class CollectionActions {
showToast(context, l10n.collectionRenamedSuccessfully);
}
- // Update the collection name locally
collection.setName(newName);
- // Call success callback if provided
onSuccess?.call();
} catch (error) {
await progressDialog.hide();
@@ -258,7 +255,6 @@ class CollectionActions {
showToast(context, l10n.collectionDeletedSuccessfully);
}
- // Call success callback if provided
onSuccess?.call();
} catch (error) {
await progressDialog?.hide();
@@ -293,8 +289,6 @@ class CollectionActions {
}
try {
- // If deleteFromAllCollections is true β†’ keepFiles should be false (move files to trash)
- // If deleteFromAllCollections is false β†’ keepFiles should be true (keep files in other collections)
await CollectionService.instance.trashCollection(
context.mounted ? context : null,
collection,
@@ -307,7 +301,6 @@ class CollectionActions {
showToast(context, l10n.collectionDeletedSuccessfully);
}
- // Call success callback if provided
onSuccess?.call();
} catch (error) {
await progressDialog?.hide();
@@ -483,8 +476,6 @@ class CollectionActions {
}
return false;
}
- // getPublicKey can return null when no user is associated with given
- // email id
if (publicKey == null || publicKey == '') {
// todo: neeraj replace this as per the design where a new screen
// is used for error. Do this change along with handling of network errors
@@ -497,7 +488,6 @@ class CollectionActions {
}
}
- // addEmailToCollection returns true if add operation was successful
Future<bool> addEmailToCollection(
BuildContext? context,
Collection collection,
@@ -552,8 +542,6 @@ class CollectionActions {
}
return false;
}
- // getPublicKey can return null when no user is associated with given
- // email id
if (publicKey == null || publicKey == '') {
await dialog?.hide();
if (context != null && context.mounted) {
@@ -588,7 +576,6 @@ class CollectionActions {
}
}
- // removeParticipant remove the user from a share album
Future<bool> removeParticipant(
BuildContext context,
Collection collection,
diff --git a/mobile/apps/locker/lib/utils/collection_sort_util.dart b/mobile/apps/locker/lib/utils/collection_sort_util.dart
index 19767f3189..b2184f4fd4 100644
--- a/mobile/apps/locker/lib/utils/collection_sort_util.dart
+++ b/mobile/apps/locker/lib/utils/collection_sort_util.dart
@@ -3,7 +3,6 @@ import 'package:locker/services/collections/models/collection.dart';
class CollectionSortUtil {
static void sortCollections(List<Collection> collections) {
collections.sort((a, b) {
- // Important collection (favorites) should come first
if (a.type == CollectionType.favorites &&
b.type != CollectionType.favorites) {
return -1;
@@ -12,7 +11,6 @@ class CollectionSortUtil {
a.type != CollectionType.favorites) {
return 1;
}
- // For other collections, sort alphabetically by name
final nameA = a.name ?? a.name ?? '';
final nameB = b.name ?? b.name ?? '';
return nameA.toLowerCase().compareTo(nameB.toLowerCase());
@@ -39,7 +37,6 @@ class CollectionSortUtil {
}
static int compareCollections(Collection a, Collection b) {
- // Important collection (favorites) should come first
if (a.type == CollectionType.favorites &&
b.type != CollectionType.favorites) {
return -1;
@@ -48,7 +45,6 @@ class CollectionSortUtil {
a.type != CollectionType.favorites) {
return 1;
}
- // For other collections, sort alphabetically by name
final nameA = a.name ?? a.name ?? '';
final nameB = b.name ?? b.name ?? '';
return nameA.toLowerCase().compareTo(nameB.toLowerCase());
@@ -59,7 +55,6 @@ class CollectionSortUtil {
Collection b,
bool ascending,
) {
- // Important collection (favorites) should always come first regardless of sort direction
if (a.type == CollectionType.favorites &&
b.type != CollectionType.favorites) {
return -1;
@@ -68,7 +63,6 @@ class CollectionSortUtil {
a.type != CollectionType.favorites) {
return 1;
}
- // For other collections, use normal comparison
return ascending ? compareCollections(a, b) : compareCollections(b, a);
}
@@ -77,7 +71,6 @@ class CollectionSortUtil {
Collection b,
bool ascending,
) {
- // Important collection (favorites) should always come first regardless of sort direction
if (a.type == CollectionType.favorites &&
b.type != CollectionType.favorites) {
return -1;
@@ -86,7 +79,6 @@ class CollectionSortUtil {
a.type != CollectionType.favorites) {
return 1;
}
- // For other collections, sort by modification time
final dateA = DateTime.fromMicrosecondsSinceEpoch(a.updationTime);
final dateB = DateTime.fromMicrosecondsSinceEpoch(b.updationTime);
return ascending ? dateA.compareTo(dateB) : dateB.compareTo(dateA);
diff --git a/mobile/apps/locker/lib/utils/file_icon_utils.dart b/mobile/apps/locker/lib/utils/file_icon_utils.dart
index 99b173e78f..0816c1550d 100644
--- a/mobile/apps/locker/lib/utils/file_icon_utils.dart
+++ b/mobile/apps/locker/lib/utils/file_icon_utils.dart
@@ -17,7 +17,6 @@ class FileIconConfig {
}
class FileIconUtils {
- // Centralized configuration - change icons and colors here only
static const Map<String, FileIconConfig> _fileTypeConfigs = {
'pdf': FileIconConfig(
extensions: {'.pdf'},
@@ -52,7 +51,7 @@ class FileIconUtils {
final lastDotIndex = lowerFileName.lastIndexOf('.');
if (lastDotIndex == -1) {
- return _defaultConfig; // No extension found
+ return _defaultConfig;
}
final extension = lowerFileName.substring(lastDotIndex);
diff --git a/mobile/apps/locker/lib/utils/info_item_utils.dart b/mobile/apps/locker/lib/utils/info_item_utils.dart
index 514adeb8a4..d16c09fa03 100644
--- a/mobile/apps/locker/lib/utils/info_item_utils.dart
+++ b/mobile/apps/locker/lib/utils/info_item_utils.dart
@@ -14,7 +14,6 @@ class InfoIconConfig {
}
class InfoItemUtils {
- // Centralized configuration - change icons and colors here only
static const Map<InfoType, InfoIconConfig> _infoTypeConfigs = {
InfoType.note: InfoIconConfig(
icon: HugeIcons.strokeRoundedNote,
diff --git a/mobile/apps/photos/integration_test/app_init_test.dart b/mobile/apps/photos/integration_test/app_init_test.dart
index 356a1d4242..9a6b3ffaa0 100644
--- a/mobile/apps/photos/integration_test/app_init_test.dart
+++ b/mobile/apps/photos/integration_test/app_init_test.dart
@@ -18,7 +18,7 @@ void main() {
() async {
bool skipLogin = false;
- ///Ignore exceptions thrown by the app for the test to pass
+ // Ignore exceptions thrown by the app for the test to pass.
WidgetsFlutterBinding.ensureInitialized();
FlutterError.onError = (FlutterErrorDetails errorDetails) {
FlutterError.dumpErrorToConsole(errorDetails);
@@ -39,7 +39,6 @@ void main() {
await tester.pumpAndSettle();
final emailInputField = find.byType(TextFormField);
final logInButton = find.byKey(const ValueKey("logInButton"));
- //Fill email id here
await tester.enterText(emailInputField, "*enter email here*");
await tester.pumpAndSettle(const Duration(seconds: 1));
await tester.tap(logInButton);
@@ -50,7 +49,6 @@ void main() {
final verifyPasswordButton = find.byKey(
const ValueKey("verifyPasswordButton"),
);
- //Fill password here
await tester.enterText(
passwordInputField,
"*enter password here*",
@@ -70,7 +68,6 @@ void main() {
await tester.pumpAndSettle(const Duration(seconds: 1));
await tester.pumpAndSettle(const Duration(seconds: 3));
- //Automatically skips backup
final skipBackupButton = find.byKey(
const ValueKey("skipBackupButton"),
);
@@ -91,40 +88,3 @@ Future<void> dismissUpdateAppDialog(WidgetTester tester) async {
await tester.tapAt(const Offset(0, 0));
await tester.pumpAndSettle();
}
-
-///Use this widget as floating action buttom in HomeWidget so that frames
-///are built and rendered continuously so that timeline trace has continuous
-///data. Change the duraiton in `_startTimer()` to control the duraiton of
-///test on app init.
-
-// class TempWidget extends StatefulWidget {
-// const TempWidget({super.key});
-
-// @override
-// TempWidgetState createState() => TempWidgetState();
-// }
-
-// class TempWidgetState extends State<TempWidget> {
-// bool _isLoading = true;
-
-// @override
-// void initState() {
-// super.initState();
-// _startTimer();
-// }
-
-// void _startTimer() {
-// Future.delayed(const Duration(seconds: 20), () {
-// setState(() {
-// _isLoading = false;
-// });
-// });
-// }
-
-// @override
-// Widget build(BuildContext context) {
-// return _isLoading
-// ? const CircularProgressIndicator()
-// : const SizedBox.shrink();
-// }
-// }
diff --git a/mobile/apps/photos/integration_test/home_gallery_scroll_test.dart b/mobile/apps/photos/integration_test/home_gallery_scroll_test.dart
index dfcc7a1a11..cc7d63589b 100644
--- a/mobile/apps/photos/integration_test/home_gallery_scroll_test.dart
+++ b/mobile/apps/photos/integration_test/home_gallery_scroll_test.dart
@@ -19,7 +19,7 @@ void main() {
await runZonedGuarded(
() async {
- ///Ignore exceptions thrown by the app for the test to pass
+ // Ignore exceptions thrown by the app for the test to pass.
WidgetsFlutterBinding.ensureInitialized();
FlutterError.onError = (FlutterErrorDetails errorDetails) {
FlutterError.dumpErrorToConsole(errorDetails);
@@ -37,7 +37,6 @@ void main() {
final emailInputField = find.byType(TextFormField);
final logInButton = find.byKey(const ValueKey("logInButton"));
- //Fill email id here
await tester.enterText(emailInputField, "enter email here");
await tester.pumpAndSettle(const Duration(seconds: 1));
await tester.tap(logInButton);
@@ -49,7 +48,6 @@ void main() {
final verifyPasswordButton = find.byKey(
const ValueKey("verifyPasswordButton"),
);
- //Fill password here
await tester.enterText(passwordInputField, "enter password here");
await tester.pumpAndSettle(const Duration(seconds: 1));
await tester.tap(verifyPasswordButton);
@@ -66,7 +64,6 @@ void main() {
await tester.pumpAndSettle(const Duration(seconds: 1));
await tester.pumpAndSettle(const Duration(seconds: 3));
- //Automatically skips backup
final skipBackupButton = find.byKey(
const ValueKey("skipBackupButton"),
);
@@ -74,7 +71,6 @@ void main() {
await tester.pumpAndSettle(const Duration(seconds: 2));
await binding.traceAction(() async {
- //scroll gallery
final scrollablePositionedList = find.byType(
ScrollablePositionedList,
);
diff --git a/mobile/apps/photos/integration_test/video_editor_test.dart b/mobile/apps/photos/integration_test/video_editor_test.dart
index c6e02c4ef9..8b72cc4463 100644
--- a/mobile/apps/photos/integration_test/video_editor_test.dart
+++ b/mobile/apps/photos/integration_test/video_editor_test.dart
@@ -23,7 +23,6 @@ import 'package:photos/ui/tools/editor/video_editor/crop_value.dart';
import 'package:photos/ui/tools/editor/video_editor/video_editor_controller.dart';
import 'package:shared_preferences/shared_preferences.dart';
-/// Trim configuration
class TrimConfig {
final String label;
final Duration? duration;
@@ -41,12 +40,9 @@ class TrimConfig {
String toString() => label;
}
-/// Trim configuration factory
class TrimConfigs {
static const noTrim = TrimConfig(label: "no-trim", duration: null);
- /// Create a trim config from seconds
- /// Example: TrimConfigs.fromSeconds(15) β†’ trim to 15 seconds
static TrimConfig fromSeconds(int seconds) {
return TrimConfig(
label: "trim-${seconds}s",
@@ -54,14 +50,11 @@ class TrimConfigs {
);
}
- /// Create a trim config from duration
- /// Example: TrimConfigs.fromDuration(Duration(minutes: 1, seconds: 30))
static TrimConfig fromDuration(Duration duration) {
final totalSeconds = duration.inSeconds;
return TrimConfig(label: "trim-${totalSeconds}s", duration: duration);
}
- /// Create a trim config from start offset and length
static TrimConfig fromRange({
required int startSeconds,
required int lengthSeconds,
@@ -74,7 +67,6 @@ class TrimConfigs {
}
}
-/// Validation failure details
class ValidationFailure {
final String fileId;
final String description;
@@ -93,14 +85,12 @@ class ValidationFailure {
});
}
-/// Result of processing a video iteration
class IterationResult {
final List<ValidationFailure> validationFailures;
IterationResult({required this.validationFailures});
}
-/// Configuration for one or more files to test with the same combinations
class TestFileConfig {
final List<int> fileIds;
final int? collectionId;
@@ -122,53 +112,9 @@ class TestFileConfig {
int get totalIterations => totalIterationsPerFile * fileIds.length;
}
-/// Video Editor Integration Test
-///
-/// Tests native video editor by processing videos through all combinations
-/// of trim/crop/rotate. Validates exported video duration and dimensions.
-///
-/// CONFIGURATION:
-/// Update testFiles list below. Each TestFileConfig can have:
-/// - fileIds: [123, 456] - One or more video file IDs to test
-/// - collectionId: null (uses source's collection) or specific ID
-/// - trimOptions: [TrimConfigs.noTrim, TrimConfigs.fromSeconds(1), TrimConfigs.fromSeconds(15), ...]
-/// - cropOptions: ["None", "1:1", "16:9", "9:16", "3:4", "4:3"]
-/// - rotateOptions: [0, 90, 180, 270]
-///
-/// EXAMPLES:
-/// // Single file, full test
-/// TestFileConfig(
-/// fileIds: [123],
-/// trimOptions: [TrimConfigs.noTrim, TrimConfigs.fromSeconds(1)],
-/// cropOptions: ["None", "1:1"],
-/// rotateOptions: [0, 90],
-/// ) // 2 Γ— 2 Γ— 2 = 8 iterations
-///
-/// // Multiple files, same combinations
-/// TestFileConfig(
-/// fileIds: [123, 456, 789],
-/// trimOptions: [TrimConfigs.fromSeconds(2)],
-/// cropOptions: ["1:1"],
-/// rotateOptions: [0],
-/// ) // 1 Γ— 1 Γ— 1 Γ— 3 files = 3 iterations
-///
-/// // Custom trim durations
-/// TestFileConfig(
-/// fileIds: [123],
-/// trimOptions: [TrimConfigs.fromSeconds(30), TrimConfigs.fromDuration(Duration(minutes: 2))],
-/// cropOptions: ["None"],
-/// rotateOptions: [0],
-/// )
-///
-/// RUN:
-/// flutter drive --driver=test_driver/integration_test.dart \
-/// --target=integration_test/video_editor_test.dart --flavor independent
-///
-/// VALIDATION:
-/// - Duration check: Β±100ms tolerance
-/// - Width/Height check: Β±2px tolerance
-/// - Failures are grouped by type (export vs validation) in the final report
-/// - Tests native editor only (no FFmpeg fallback)
+// Run:
+// flutter drive --driver=test_driver/integration_test.dart \
+// --target=integration_test/video_editor_test.dart --flavor independent
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
@@ -179,7 +125,6 @@ void main() {
print('[${record.level.name}] ${record.time}: ${record.message}');
});
- // TEST CONFIGURATION - Update this list with your files and combinations
final testFiles = [
TestFileConfig(
// TODO: Update with the generated file IDs available on the test device.
@@ -192,25 +137,15 @@ void main() {
cropOptions: ["1:1", "9:16", "16:9", "3:4", "4:3"],
rotateOptions: [0, 90, 180, 270],
),
- // Add more configurations with different combinations:
- // TestFileConfig(
- // fileIds: [456, 789, 101], // Multiple files with same combinations
- // collectionId: 999, // Save to specific collection
- // trimOptions: [TrimConfigs.fromSeconds(2), TrimConfigs.fromSeconds(5)],
- // cropOptions: ["None", "1:1"],
- // rotateOptions: [0, 90],
- // ),
];
group('Video Editor Integration Test', () {
testWidgets('Process videos with all trim/crop/rotate combinations', (
WidgetTester tester,
) async {
- // Initialize global singletons that the app normally sets up on startup.
final prefs = await SharedPreferences.getInstance();
final packageInfo = await PackageInfo.fromPlatform();
- // Initialize network clients before service locator (mirrors app bootstrap).
await NetworkClient.instance.init(packageInfo, prefs);
ServiceLocator.instance.init(
@@ -222,7 +157,6 @@ void main() {
);
await Configuration.instance.init(prefs);
- // Verify configuration
expect(
testFiles,
isNotEmpty,
@@ -243,7 +177,6 @@ void main() {
}
}
- // Calculate total files and iterations
final totalFiles = testFiles.fold(
0,
(sum, config) => sum + config.fileIds.length,
@@ -264,7 +197,6 @@ void main() {
final failedExports = <String, String>{};
final validationFailures = <ValidationFailure>[];
- // Process each configuration
for (int configIndex = 0; configIndex < testFiles.length; configIndex++) {
final config = testFiles[configIndex];
@@ -281,7 +213,6 @@ void main() {
'β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•\n',
);
- // Process each file in this configuration
for (
int fileIndex = 0;
fileIndex < config.fileIds.length;
@@ -295,7 +226,6 @@ void main() {
);
logger.info('─────────────────────────────────────────────────────');
- // Load source file
logger.info('Loading source file with ID: $fileId');
final sourceFile = await FilesDB.instance.getAnyUploadedFile(fileId);
expect(
@@ -342,7 +272,6 @@ void main() {
logger.info('Source file loaded: ${sourceFile.title}');
logger.info('Video path: ${sourceIoFile.path}\n');
- // Iterate through all combinations for this file
int fileIterationCount = 0;
for (final trimOption in config.trimOptions) {
for (final cropOption in config.cropOptions) {
@@ -407,7 +336,6 @@ void main() {
);
}
- // Print final summary
logger.info(
'\n╔═══════════════════════════════════════════════════════╗',
);
@@ -443,7 +371,6 @@ void main() {
'β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•',
);
- // Group by failure type
final groupedFailures = <String, List<ValidationFailure>>{};
for (final failure in validationFailures) {
groupedFailures
@@ -468,7 +395,6 @@ void main() {
logger.info('═══════════════════════════════════════════════════════\n');
- // Fail test if any iteration failed or had validation errors
final totalFailures = failedExports.length + validationFailures.length;
expect(
totalFailures,
@@ -480,8 +406,6 @@ void main() {
});
}
-/// Process a single video iteration with the specified settings.
-/// Returns any validation failures detected for the exported video.
Future<IterationResult> _processVideoIteration({
required EnteFile sourceFile,
required File sourceIoFile,
@@ -498,7 +422,6 @@ Future<IterationResult> _processVideoIteration({
CropCalculation? cropCalc;
try {
- // Step 1: Initialize video editor controller
logger.info(' β†’ Initializing video editor controller...');
controller = VideoEditorController.file(
sourceIoFile,
@@ -518,11 +441,9 @@ Future<IterationResult> _processVideoIteration({
' - Original size: ${originalSize.width.toInt()}x${originalSize.height.toInt()}',
);
- // Track expected dimensions (will be updated after crop)
var expectedWidth = originalSize.width.toInt();
var expectedHeight = originalSize.height.toInt();
- // Step 2: Apply trim settings
Duration? expectedDuration;
if (trimOption.shouldTrim) {
final startOffset = trimOption.startOffset;
@@ -554,11 +475,9 @@ Future<IterationResult> _processVideoIteration({
logger.info(' β†’ No trim applied');
}
- // Step 3: Apply crop settings
if (cropOption != "None") {
logger.info(' β†’ Applying crop: $cropOption...');
- // Map crop option to CropValue and apply aspect ratio
CropValue? cropValue;
switch (cropOption) {
case "1:1":
@@ -585,7 +504,6 @@ Future<IterationResult> _processVideoIteration({
}
}
- // Calculate expected dimensions after crop
try {
cropCalc = VideoCropUtil.calculateFileSpaceCrop(controller: controller);
expectedWidth = cropCalc.width;
@@ -601,16 +519,13 @@ Future<IterationResult> _processVideoIteration({
logger.info(' β†’ No crop applied');
}
- // Step 4: Apply rotation
if (rotateOption != 0) {
logger.info(' β†’ Applying rotation: $rotateOptionΒ°...');
- // Reset rotation to 0 first
while (controller.rotation != 0) {
controller.rotate90Degrees(VideoRotationDirection.left);
}
- // Apply the desired rotation (from video_rotate_page.dart)
switch (rotateOption) {
case 90:
controller.rotate90Degrees(VideoRotationDirection.right);
@@ -629,10 +544,8 @@ Future<IterationResult> _processVideoIteration({
logger.info(' β†’ No rotation applied');
}
- // Step 5: Export video using native editor (no FFmpeg fallback)
logger.info(' β†’ Exporting video with native editor...');
- // Create temp output path
final tempDir = Directory.systemTemp.createTempSync('video_export_test');
final outputPath = path_helper.join(
tempDir.path,
@@ -643,7 +556,6 @@ Future<IterationResult> _processVideoIteration({
controller: controller,
outputPath: outputPath,
onProgress: (progress) {
- // Log progress at 25% intervals
if ((progress * 100).round() % 25 == 0) {
logger.info(
' - Progress: ${(progress * 100).toStringAsFixed(0)}%',
@@ -662,7 +574,6 @@ Future<IterationResult> _processVideoIteration({
tempOutputFile = exportedFile;
logger.info(' β†’ Export completed: ${exportedFile.path}');
- // Step 6: Save to gallery
logger.info(' β†’ Saving to gallery...');
final suffixBuffer = StringBuffer();
if (trimOption.shouldTrim) {
@@ -691,12 +602,10 @@ Future<IterationResult> _processVideoIteration({
);
logger.info(' β†’ Saved to gallery: $fileName');
- // Step 7: Create EnteFile entry
logger.info(' β†’ Creating file entry in database...');
final newFile = fileFromAsset(sourceFile.deviceFolder ?? '', newAsset);
newFile.creationTime = sourceFile.creationTime;
- // Use provided collectionId, or source file's collection if null/0
newFile.collectionID = (collectionId == null || collectionId == 0)
? sourceFile.collectionID
: collectionId;
@@ -718,7 +627,6 @@ Future<IterationResult> _processVideoIteration({
);
}
- // Step 8: Validate exported video
logger.info(' β†’ Validating exported video...');
try {
final videoInfo = await NativeVideoEditor.inspectVideo(
@@ -733,7 +641,7 @@ Future<IterationResult> _processVideoIteration({
);
logger.info(' - Actual size: ${actualWidth}x$actualHeight');
- // Validate duration (allow 100ms tolerance for encoding variations)
+ // Allow 100ms for encoding variation.
final durationDiff =
(actualDuration.inMilliseconds - expectedDuration.inMilliseconds)
.abs();
@@ -753,22 +661,19 @@ Future<IterationResult> _processVideoIteration({
);
}
- // Validate dimensions (accounting for crop and rotation)
final expectedRotation = rotateOption;
final isRotated = expectedRotation % 180 != 0;
- // expectedWidth and expectedHeight already account for crop
- // Just swap if rotation is 90/270 degrees
var finalExpectedWidth = expectedWidth;
var finalExpectedHeight = expectedHeight;
if (isRotated) {
- // Swap dimensions for 90/270 rotation
final temp = finalExpectedWidth;
finalExpectedWidth = finalExpectedHeight;
finalExpectedHeight = temp;
}
+ // Allow 2px for encoding variation.
bool widthOk = (actualWidth - finalExpectedWidth).abs() <= 2;
bool heightOk = (actualHeight - finalExpectedHeight).abs() <= 2;
@@ -788,7 +693,6 @@ Future<IterationResult> _processVideoIteration({
}
}
- // Check width (allow some tolerance for encoding)
if (!widthOk) {
failures.add(
ValidationFailure(
@@ -804,7 +708,6 @@ Future<IterationResult> _processVideoIteration({
);
}
- // Check height (allow some tolerance for encoding)
if (!heightOk) {
failures.add(
ValidationFailure(
@@ -830,11 +733,8 @@ Future<IterationResult> _processVideoIteration({
// Non-fatal - continue
}
- // Step 9: Update description with test parameters
logger.info(' β†’ Updating video description...');
- // Only update if file is uploaded (has uploadedFileID)
- // For local-only files, we skip the metadata update
if (newFile.uploadedFileID != null) {
try {
await FileMagicService.instance.updatePublicMagicMetadata(
@@ -844,7 +744,6 @@ Future<IterationResult> _processVideoIteration({
logger.info(' β†’ Description set: "$description"');
} catch (e) {
logger.warning(' - Failed to update description (non-fatal): $e');
- // Don't fail the test if description update fails
}
} else {
logger.info(
@@ -852,7 +751,6 @@ Future<IterationResult> _processVideoIteration({
);
}
- // Cleanup temp file
if (tempOutputFile.existsSync()) {
tempOutputFile.deleteSync();
}
@@ -860,7 +758,6 @@ Future<IterationResult> _processVideoIteration({
await PhotoManager.startChangeNotify();
}
} finally {
- // Cleanup
controller?.dispose();
if (tempOutputFile != null && tempOutputFile.existsSync()) {
try {
diff --git a/mobile/apps/photos/lib/data/holidays.dart b/mobile/apps/photos/lib/data/holidays.dart
index 1df4ccc415..617587f08f 100644
--- a/mobile/apps/photos/lib/data/holidays.dart
+++ b/mobile/apps/photos/lib/data/holidays.dart
@@ -41,91 +41,61 @@ List<HolidayData> _defaultHolidays = [
Map<String, List<HolidayData>> localeToHolidays = {
'it': [
HolidayData('Capodanno', month: 1, day: 1),
- // New Year's Day
HolidayData('Epifania', month: 1, day: 6),
- // Epiphany
HolidayData('San Valentino', month: 2, day: 14),
- // Valentine's Day
HolidayData('Festa della Liberazione', month: 4, day: 25),
- // Liberation Day
HolidayData('Primo Maggio', month: 5, day: 1),
- // Labor Day
HolidayData('Festa della Repubblica', month: 6, day: 2),
- // Republic Day
HolidayData('Ferragosto', month: 8, day: 15),
- // Assumption of Mary
HolidayData('Halloween', month: 10, day: 31),
- // Halloween
HolidayData('Ognissanti', month: 11, day: 1),
- // All Saints' Day
HolidayData('Immacolata Concezione', month: 12, day: 8),
- // Immaculate Conception
HolidayData('Natale', month: 12, day: 25),
- // Christmas Day
HolidayData('Vigilia di Capodanno', month: 12, day: 31),
- // New Year's Eve
],
'fr': [
- HolidayData('Jour de l\'An', month: 1, day: 1), // New Year's Day
- HolidayData('FΓͺte du Travail', month: 5, day: 1), // Labour Day
- HolidayData('FΓͺte Nationale', month: 7, day: 14), // Bastille Day
- HolidayData('Assomption', month: 8, day: 15), // Assumption of Mary
- HolidayData('Halloween', month: 10, day: 31), // Halloween
- HolidayData('Toussaint', month: 11, day: 1), // All Saints' Day
- HolidayData('Jour de l\'Armistice', month: 11, day: 11), // Armistice Day
- HolidayData('NoΓ«l', month: 12, day: 25), // Christmas
- HolidayData('Lendemain de NoΓ«l', month: 12, day: 26), // Boxing Day
- HolidayData('Saint-Sylvestre', month: 12, day: 31), // New Year's Eve
+ HolidayData('Jour de l\'An', month: 1, day: 1),
+ HolidayData('FΓͺte du Travail', month: 5, day: 1),
+ HolidayData('FΓͺte Nationale', month: 7, day: 14),
+ HolidayData('Assomption', month: 8, day: 15),
+ HolidayData('Halloween', month: 10, day: 31),
+ HolidayData('Toussaint', month: 11, day: 1),
+ HolidayData('Jour de l\'Armistice', month: 11, day: 11),
+ HolidayData('NoΓ«l', month: 12, day: 25),
+ HolidayData('Lendemain de NoΓ«l', month: 12, day: 26),
+ HolidayData('Saint-Sylvestre', month: 12, day: 31),
],
'de': [
HolidayData('Neujahrstag', month: 1, day: 1),
- // New Year
HolidayData('Valentinstag', month: 2, day: 14),
- // Valentine's Day
HolidayData('Tag der Arbeit', month: 5, day: 1),
- // Labor Day
HolidayData('Tag der Deutschen Einheit', month: 10, day: 3),
- // German Unity Day
HolidayData('Halloween', month: 10, day: 31),
- // Halloween
HolidayData('Erster Weihnachtstag', month: 12, day: 25),
- // First Christmas Day
HolidayData('Zweiter Weihnachtstag', month: 12, day: 26),
- // Second Christmas Day (Boxing Day)
HolidayData('Silvester', month: 12, day: 31),
- // New Year's Eve
],
'nl': [
- HolidayData('Nieuwjaarsdag', month: 1, day: 1), // New Year's Day
- HolidayData('Valentijnsdag', month: 2, day: 14), // Valentine's Day
- HolidayData('Koningsdag', month: 4, day: 27), // King's Day
- HolidayData('Bevrijdingsdag', month: 5, day: 5), // Liberation Day
- HolidayData('Halloween', month: 10, day: 31), // Halloween
- HolidayData('Sinterklaas', month: 12, day: 5), // Sinterklaas
- HolidayData('Eerste Kerstdag', month: 12, day: 25), // First Christmas Day
- HolidayData('Tweede Kerstdag', month: 12, day: 26), // Second Christmas Day
- HolidayData('Oudejaarsdag', month: 12, day: 31), // New Year's Eve
+ HolidayData('Nieuwjaarsdag', month: 1, day: 1),
+ HolidayData('Valentijnsdag', month: 2, day: 14),
+ HolidayData('Koningsdag', month: 4, day: 27),
+ HolidayData('Bevrijdingsdag', month: 5, day: 5),
+ HolidayData('Halloween', month: 10, day: 31),
+ HolidayData('Sinterklaas', month: 12, day: 5),
+ HolidayData('Eerste Kerstdag', month: 12, day: 25),
+ HolidayData('Tweede Kerstdag', month: 12, day: 26),
+ HolidayData('Oudejaarsdag', month: 12, day: 31),
],
'es': [
HolidayData('AΓ±o Nuevo', month: 1, day: 1),
- // New Year's Day
HolidayData('San ValentΓ­n', month: 2, day: 14),
- // Valentine's Day
HolidayData('DΓ­a del Trabajador', month: 5, day: 1),
- // Labor Day
HolidayData('DΓ­a de la Hispanidad', month: 10, day: 12),
- // Hispanic Day
HolidayData('Halloween', month: 10, day: 31),
- // Halloween
HolidayData('DΓ­a de Todos los Santos', month: 11, day: 1),
- // All Saints' Day
HolidayData('DΓ­a de la ConstituciΓ³n', month: 12, day: 6),
- // Constitution Day
HolidayData('La Inmaculada ConcepciΓ³n', month: 12, day: 8),
- // Immaculate Conception
HolidayData('Navidad', month: 12, day: 25),
- // Christmas Day
HolidayData('Nochevieja', month: 12, day: 31),
- // New Year's Eve
],
};
diff --git a/mobile/apps/photos/lib/main.dart b/mobile/apps/photos/lib/main.dart
index 665e3b9bea..5d019047f8 100644
--- a/mobile/apps/photos/lib/main.dart
+++ b/mobile/apps/photos/lib/main.dart
@@ -301,13 +301,11 @@ Future<void> _runMinimally(
await Configuration.instance.init(prefs);
_logger.info("(for debugging) Configuration done $tlog");
- // App LifeCycle
AppLifecycleService.instance.init(prefs);
AppLifecycleService.instance.onAppInBackground(
'init via: WorkManager $tlog',
);
- // Crypto rel.
await Computer.shared().turnOn(workersCount: 4);
CryptoUtil.init();
@@ -320,7 +318,6 @@ Future<void> _runMinimally(
await CollectionsService.instance.init(prefs);
_logger.info("(for debugging) CollectionsService init done $tlog");
- // Upload & Sync Related
await FileUploader.instance.init(prefs, true);
LocalFileUpdateService.instance.init(prefs);
await LocalSyncService.instance.init(prefs);
@@ -328,13 +325,10 @@ Future<void> _runMinimally(
await SyncService.instance.init(prefs);
_isSyncInitialized = true;
- // Misc Services
await UserService.instance.init();
SocialNotificationCoordinator.instance.init(prefs);
await NotificationService.instance.initializeForBackground();
- // Begin Execution
- // only runs for android
_logger.info("[BG TASK] update notification");
updateService.showUpdateNotification().ignore();
_logger.info("[BG TASK] sync starting");
@@ -344,7 +338,6 @@ Future<void> _runMinimally(
_logger.info("[BG TASK] locale fetch");
final locale = await getLocale();
await initializeDateFormatting(locale?.languageCode ?? "en");
- // only runs for android
_logger.info("[BG TASK] home widget sync");
if (!isLocalGalleryMode &&
hasGrantedMLConsent &&
@@ -434,7 +427,6 @@ Future<void> _init(
} else {
AppLifecycleService.instance.onAppInForeground('init via: $via $tlog');
}
- // Start workers asynchronously. No need to wait for them to start
Computer.shared().turnOn(workersCount: 4).ignore();
CryptoUtil.init();
@@ -708,23 +700,19 @@ Future<void> _scheduleFGSync(String caller) async {
}
Future<void> _handleBackgroundPush(Object message) async {
- final bool isRunningInFG = await isForegroundEngineActive(); // hb
+ final bool isRunningInFG = await isForegroundEngineActive();
final bool isInForeground = AppLifecycleService.instance.isForeground;
if (isRunningInFG) {
_logger.info(
"Background push received when app is alive and runningInFG: $isRunningInFG inForeground: $isInForeground",
);
if (PushService.shouldSync(message)) {
- // FG is active, let it handle the sync
_logger.info("Foreground is active, skipping background sync from push");
- // Could optionally trigger a sync event that FG can handle
}
} else {
- // App is dead or FG is not active
runWithLogs(() async {
_logger.info("Background push received, no active foreground");
- // Mark BG as active before starting
final prefs = await SharedPreferences.getInstance();
await prefs.setInt(
kLastBGTaskHeartBeatTime,
diff --git a/mobile/apps/photos/lib/theme/colors.dart b/mobile/apps/photos/lib/theme/colors.dart
index 934b3be675..5333f6716e 100644
--- a/mobile/apps/photos/lib/theme/colors.dart
+++ b/mobile/apps/photos/lib/theme/colors.dart
@@ -3,23 +3,19 @@ import 'dart:ui';
import 'package:flutter/material.dart';
class EnteColorScheme {
- // Background Colors
final Color backgroundColour;
final Color backgroundElevated;
final Color backgroundElevated2;
- // Backdrop Colors
final Color backdropBase;
final Color backdropMuted;
final Color backdropFaint;
- // Text Colors
final Color textBase;
final Color textMuted;
final Color textFaint;
final Color blurTextBase;
- // Fill Colors
final Color fillBase;
final Color fillBasePressed;
final Color fillStrong;
@@ -28,7 +24,6 @@ class EnteColorScheme {
final Color fillFaintPressed;
final Color fillBaseGrey;
- // Stroke Colors
final Color strokeBase;
final Color strokeMuted;
final Color strokeFaint;
@@ -37,27 +32,22 @@ class EnteColorScheme {
final Color blurStrokeFaint;
final Color blurStrokePressed;
- // Fixed Colors
final Color primary700;
final Color primary500;
final Color primary400;
final Color primary300;
- //warning colors
final Color warning700;
final Color warning500;
final Color warning400;
final Color warning800;
final Color caution500;
- //golden colors
final Color golden700;
final Color golden500;
- //other colors
final Color tabIcon;
- // Menu item icon stroke color
final Color menuItemIconStroke;
final Color fill;
@@ -256,7 +246,6 @@ const EnteColorScheme darkScheme = EnteColorScheme(
redLightDark,
);
-// Background
const Color backgroundColorLight = Color.fromRGBO(244, 244, 244, 1);
const Color backgroundColorDark = Color.fromRGBO(22, 22, 22, 1);
@@ -266,7 +255,6 @@ const Color backgroundElevated2Light = Color.fromRGBO(251, 251, 251, 1);
const Color backgroundElevatedDark = Color.fromRGBO(27, 27, 27, 1);
const Color backgroundElevated2Dark = Color.fromRGBO(37, 37, 37, 1);
-// Backdrop Colors
const Color backdropBaseLight = Color.fromRGBO(255, 255, 255, 0.92);
const Color backdropMutedLight = Color.fromRGBO(255, 255, 255, 0.75);
const Color backdropFaintLight = Color.fromRGBO(255, 255, 255, 0.30);
@@ -275,7 +263,6 @@ const Color backdropBaseDark = Color.fromRGBO(0, 0, 0, 0.90);
const Color backdropMutedDark = Color.fromRGBO(0, 0, 0, 0.65);
const Color backdropFaintDark = Color.fromRGBO(0, 0, 0, 0.20);
-// Text Colors
const Color textBaseLight = Color.fromRGBO(0, 0, 0, 1);
const Color textMutedLight = Color.fromRGBO(0, 0, 0, 0.6);
const Color textFaintLight = Color.fromRGBO(0, 0, 0, 0.5);
@@ -286,7 +273,6 @@ const Color textMutedDark = Color.fromRGBO(255, 255, 255, 0.7);
const Color textFaintDark = Color.fromRGBO(255, 255, 255, 0.5);
const Color blurTextBaseDark = Color.fromRGBO(255, 255, 255, 0.95);
-// Fill Colors
const Color fillBaseLight = Color.fromRGBO(0, 0, 0, 1);
const Color fillBasePressedLight = Color.fromRGBO(0, 0, 0, 0.87);
const Color fillStrongLight = Color.fromRGBO(0, 0, 0, 0.24);
@@ -303,7 +289,6 @@ const Color fillFaintDark = Color.fromRGBO(255, 255, 255, 0.12);
const Color fillFaintPressedDark = Color.fromRGBO(255, 255, 255, 0.06);
const Color fillBaseGreyDark = Color.fromRGBO(66, 66, 66, 1);
-// Stroke Colors
const Color strokeBaseLight = Color.fromRGBO(0, 0, 0, 1);
const Color strokeMutedLight = Color.fromRGBO(0, 0, 0, 0.24);
const Color strokeFaintLight = Color.fromRGBO(0, 0, 0, 0.12);
@@ -320,21 +305,17 @@ const Color blurStrokeBaseDark = Color.fromRGBO(255, 255, 255, 0.90);
const Color blurStrokeFaintDark = Color.fromRGBO(255, 255, 255, 0.06);
const Color blurStrokePressedDark = Color.fromRGBO(255, 255, 255, 0.50);
-// Other colors
const Color tabIconLight = Color.fromRGBO(0, 0, 0, 0.85);
const Color tabIconDark = Color.fromRGBO(255, 255, 255, 0.80);
-// Menu item icon stroke colors
const Color menuItemIconStrokeLight = Color(0xFF979797);
const Color menuItemIconStrokeDark = Color.fromRGBO(255, 255, 255, 1);
-// Fixed Colors
-
const Color fixedStrokeMutedWhite = Color.fromRGBO(255, 255, 255, 0.50);
const Color strokeSolidMutedLight = Color.fromRGBO(147, 147, 147, 1);
const Color strokeSolidFaintLight = Color.fromRGBO(221, 221, 221, 1);
-// QR Code specific - always light for scanability
+// Keep light for scanability.
const Color qrBoxColor = Color.fromRGBO(245, 245, 247, 1);
const Color _primary700 = Color.fromRGBO(0, 179, 60, 1);
@@ -353,7 +334,6 @@ const Color _caution500 = Color.fromRGBO(255, 194, 71, 1);
const Color _golden700 = Color(0xFFFDB816);
const Color _golden500 = Color(0xFFFFC336);
-// Green Colors
const Color green = Color.fromRGBO(8, 194, 37, 1);
const Color greenLightLight = Color.fromRGBO(231, 246, 233, 1);
const Color greenLightDark = Color.fromRGBO(33, 33, 33, 1);
@@ -362,14 +342,12 @@ const Color greenDarker = Color.fromRGBO(5, 124, 24, 1);
const Color greenStrokeLight = Color.fromRGBO(186, 236, 194, 1);
const Color greenStrokeDark = Color.fromRGBO(28, 65, 34, 1);
-// Red Colors
const Color red = Color.fromRGBO(246, 58, 58, 1);
const Color redLightLight = Color.fromRGBO(250, 235, 235, 1);
const Color redLightDark = Color.fromRGBO(33, 33, 33, 1);
const Color redDark = Color.fromRGBO(221, 52, 52, 1);
const Color redDarker = Color.fromRGBO(197, 46, 46, 1);
-// Fill Colors
const Color fillLight = Color.fromRGBO(255, 255, 255, 1);
const Color fillDark = Color.fromRGBO(33, 33, 33, 1);
@@ -385,7 +363,6 @@ const Color fillDarkestDark = Color.fromRGBO(41, 41, 41, 1);
const Color fillReverseLight = Color.fromRGBO(0, 0, 0, 1);
const Color fillReverseDark = Color.fromRGBO(255, 255, 255, 1);
-// Content Colors
const Color contentLight = Color.fromRGBO(0, 0, 0, 1);
const Color contentDark = Color.fromRGBO(255, 255, 255, 1);
@@ -407,7 +384,6 @@ const Color contentLightestDark = Color.fromRGBO(10, 10, 10, 1);
const Color contentReverseLight = Color.fromRGBO(255, 255, 255, 1);
const Color contentReverseDark = Color.fromRGBO(0, 0, 0, 1);
-// Stroke Colors
const Color strokeLight = Color.fromRGBO(235, 235, 235, 1);
const Color strokeDark = Color.fromRGBO(20, 20, 20, 1);
diff --git a/mobile/apps/photos/plugins/ente_crypto/lib/src/crypto.dart b/mobile/apps/photos/plugins/ente_crypto/lib/src/crypto.dart
index 63d0f44be1..8dfd04f9f8 100644
--- a/mobile/apps/photos/plugins/ente_crypto/lib/src/crypto.dart
+++ b/mobile/apps/photos/plugins/ente_crypto/lib/src/crypto.dart
@@ -13,7 +13,6 @@ import "package:flutter_sodium/flutter_sodium.dart";
import "package:logging/logging.dart";
const int encryptionChunkSize = 4 * 1024 * 1024;
-// 17 bytes of overhead per chunk
final int decryptionChunkSize =
encryptionChunkSize + Sodium.cryptoSecretstreamXchacha20poly1305Abytes;
const int hashChunkSize = 4 * 1024 * 1024;
@@ -53,7 +52,6 @@ Uint8List cryptoKdfDeriveFromKey(Map<String, dynamic> args) {
);
}
-// Returns the hash for a given file
Future<Uint8List> cryptoGenericHash(Map<String, dynamic> args) async {
final file = File(args["sourceFilePath"]);
final state = Sodium.cryptoGenerichashInit(
@@ -86,10 +84,6 @@ EncryptionResult chachaEncryptData(Map<String, dynamic> args) {
);
}
-// chachaEncryptFileV2 does chucked encryption similar to chachaEncryptFile.
-// This implementation is refactored to simplify the logic to make it easier to
-// maintain and reason about.
-// Rolling out this version 2 in phases to ensure stability
Future<FileEncryptResult> chachaEncryptFileV2(Map<String, dynamic> args) async {
final encryptionStartTime = DateTime.now().millisecondsSinceEpoch;
final logger = Logger("chachaEncryptFileV2");
@@ -116,7 +110,6 @@ Future<FileEncryptResult> chachaEncryptFileV2(Map<String, dynamic> args) async {
? (sourceFileLength - bytesRead)
: encryptionChunkSize;
- // Read until we have the full chunk size (or reach EOF)
final buffer = BytesBuilder();
while (buffer.length < chunkSize) {
final remainingBytes = chunkSize - buffer.length;
@@ -132,7 +125,6 @@ Future<FileEncryptResult> chachaEncryptFileV2(Map<String, dynamic> args) async {
"V2 $kPartialReadErrorTag $chunkSize bytes, but got ${bufferBytes.length} bytes, sourceFileLength: $sourceFileLength",
);
}
- // Set final tag only after confirming we've read all expected data
if (isLastChunk) {
if (bytesRead == sourceFileLength) {
tag = Sodium.cryptoSecretstreamXchacha20poly1305TagFinal;
@@ -161,7 +153,6 @@ Future<FileEncryptResult> chachaEncryptFileV2(Map<String, dynamic> args) async {
return FileEncryptResult(key: key, header: initPushResult.header);
}
-// Encrypts a given file, in chunks of encryptionChunkSize
Future<FileEncryptResult> chachaEncryptFile(Map<String, dynamic> args) async {
final encryptionStartTime = DateTime.now().millisecondsSinceEpoch;
final logger = Logger("ChaChaEncryptV1");
@@ -209,7 +200,6 @@ Future<FileEncryptResult> chachaEncryptFile(Map<String, dynamic> args) async {
return FileEncryptResult(key: key, header: initPushResult.header);
}
-// Encrypts a file with MD5 calculation and real-time verification
Future<FileEncryptResult> chachaEncryptFileWithVerification(
Map<String, dynamic> args,
) async {
@@ -225,10 +215,7 @@ Future<FileEncryptResult> chachaEncryptFileWithVerification(
logger.info("Using multipart chunk size: $multiPartChunkSizeInBytes bytes");
}
- // Use openSync for simpler, predictable chunk reading
final inputFile = sourceFile.openSync(mode: FileMode.read);
-
- // Use streaming write
final outSink = destinationFile.openWrite(mode: FileMode.writeOnly);
final key = args["key"] ?? Sodium.cryptoSecretstreamXchacha20poly1305Keygen();
@@ -236,13 +223,11 @@ Future<FileEncryptResult> chachaEncryptFileWithVerification(
key,
);
- // Initialize verification state
final verifyPullState = Sodium.cryptoSecretstreamXchacha20poly1305InitPull(
initPushResult.header,
key,
);
- // MD5 setup
AccumulatorSink<Digest>? fullAccumulator;
ChunkedConversionSink<List<int>>? fullMd5Sink;
AccumulatorSink<Digest>? partAccumulator;
@@ -282,7 +267,6 @@ Future<FileEncryptResult> chachaEncryptFileWithVerification(
bytesRead += chunkSize;
- // Encrypt
final encryptedData = Sodium.cryptoSecretstreamXchacha20poly1305Push(
initPushResult.state,
buffer,
@@ -290,7 +274,6 @@ Future<FileEncryptResult> chachaEncryptFileWithVerification(
tag,
);
- // Verify with optimized comparison
try {
final pullResult = Sodium.cryptoSecretstreamXchacha20poly1305Pull(
verifyPullState,
@@ -298,7 +281,6 @@ Future<FileEncryptResult> chachaEncryptFileWithVerification(
null,
);
- // Use fast comparison
if (!_uint8listEquals(pullResult.m, buffer)) {
throw Exception(
"$kBitFlipErrorTag Data corruption detected at chunk $chunkIndex",
@@ -322,28 +304,23 @@ Future<FileEncryptResult> chachaEncryptFileWithVerification(
);
}
- // Handle MD5 calculation and disk writes
totalEncryptedBytes += encryptedData.length;
if (multiPartChunkSizeInBytes == null) {
- // Single-part: stream MD5 and write directly
fullMd5Sink!.add(encryptedData);
outSink.add(encryptedData);
} else {
- // Multi-part: buffer data and flush at exact part boundaries
partBuffer.add(encryptedData);
final bool isLastChunk =
tag == Sodium.cryptoSecretstreamXchacha20poly1305TagFinal;
- // Flush complete parts from buffer
while (partBuffer.length >= multiPartChunkSizeInBytes) {
final partBytes = partBuffer.toBytes().sublist(
0,
multiPartChunkSizeInBytes,
);
- // Calculate MD5 for this part
partMd5Sink!.add(partBytes);
partMd5Sink.close();
final digest = partAccumulator!.events.single;
@@ -353,34 +330,28 @@ Future<FileEncryptResult> chachaEncryptFileWithVerification(
"Part ${partMd5s.length}: $multiPartChunkSizeInBytes bytes",
);
- // Write to disk
outSink.add(partBytes);
- // Keep remaining bytes for next part
final remaining = partBuffer.toBytes().sublist(
multiPartChunkSizeInBytes,
);
partBuffer.clear();
partBuffer.add(remaining);
- // Start new MD5 for next part (if not last)
if (!isLastChunk || partBuffer.isNotEmpty) {
partAccumulator = AccumulatorSink<Digest>();
partMd5Sink = md5.startChunkedConversion(partAccumulator);
}
}
- // Handle last chunk (remaining data < partSize)
if (isLastChunk && partBuffer.isNotEmpty) {
final lastPartBytes = partBuffer.toBytes();
- // Calculate MD5 for last part
partMd5Sink!.add(lastPartBytes);
partMd5Sink.close();
final digest = partAccumulator!.events.single;
partMd5s.add(base64.encode(digest.bytes));
- // Write to disk
outSink.add(lastPartBytes);
partBuffer.clear();
}
@@ -389,7 +360,6 @@ Future<FileEncryptResult> chachaEncryptFileWithVerification(
await inputFile.close();
- // Finalize MD5
String? finalFileMd5;
if (multiPartChunkSizeInBytes == null && fullMd5Sink != null) {
fullMd5Sink.close();
@@ -398,7 +368,6 @@ Future<FileEncryptResult> chachaEncryptFileWithVerification(
logger.info("File MD5: $finalFileMd5");
}
- // Ensure all data is written
await outSink.flush();
await outSink.close();
@@ -439,7 +408,6 @@ Future<FileEncryptResult> chachaEncryptFileWithVerification(
}
}
-// Fast equality check for Uint8List
bool _uint8listEquals(Uint8List a, Uint8List b) {
if (identical(a, b)) return true;
if (a.length != b.length) return false;
@@ -447,7 +415,6 @@ bool _uint8listEquals(Uint8List a, Uint8List b) {
final len = a.length;
int i = 0;
- // Compare 8 bytes at a time for speed
while (i + 7 < len) {
final va = a.buffer.asByteData().getUint64(
a.offsetInBytes + i,
@@ -461,7 +428,6 @@ bool _uint8listEquals(Uint8List a, Uint8List b) {
i += 8;
}
- // Remaining bytes
while (i < len) {
if (a[i] != b[i]) return false;
i++;
@@ -533,7 +499,6 @@ Uint8List chachaDecryptData(Map<String, dynamic> args) {
Future<void> chachaVerifyFile(Map<String, dynamic> args) async {
try {
- // Step 1: Decrypt the file key using collection key
final encryptedKey = Sodium.base642bin(args["encFileKey"]);
final nonce = Sodium.base642bin(args["encFileNonce"]);
final fileKey = Sodium.cryptoSecretboxOpenEasy(
@@ -542,7 +507,6 @@ Future<void> chachaVerifyFile(Map<String, dynamic> args) async {
args["parentCollectionKey"],
);
- // Step 2: Verify file can be decrypted
final header = Sodium.base642bin(args["encFileHeaders"]);
final encFile = File(args["encFilePath"]);
@@ -560,44 +524,38 @@ Future<void> chachaVerifyFile(Map<String, dynamic> args) async {
final inputFile = encFile.openSync(mode: FileMode.read);
try {
- // Initialize decryption
final pullState = Sodium.cryptoSecretstreamXchacha20poly1305InitPull(
header,
fileKey,
);
- // Determine number of chunks to verify
- // -1 means verify entire file
final int chunkLimit = args["chunkLimit"] ?? 1;
final bool verifyEntireFile = chunkLimit == -1;
final chunksToVerify = verifyEntireFile
? 999999999
- : chunkLimit; // Large number for entire file
+ : chunkLimit;
var bytesRead = 0;
var chunksVerified = 0;
while (chunksVerified < chunksToVerify) {
- // Calculate chunk size
final remainingBytes = encFileLength - bytesRead;
if (remainingBytes <= 0) {
- break; // No more data to verify
+ break;
}
final chunkSize = remainingBytes < decryptionChunkSize
? remainingBytes
: decryptionChunkSize;
- // Read chunk
final buffer = await inputFile.read(chunkSize);
if (buffer.isEmpty) {
- break; // End of file
+ break;
}
bytesRead += buffer.length;
chunksVerified++;
- // Attempt to decrypt - this will throw if decryption fails
try {
final pullResult = Sodium.cryptoSecretstreamXchacha20poly1305Pull(
pullState,
@@ -605,13 +563,11 @@ Future<void> chachaVerifyFile(Map<String, dynamic> args) async {
null,
);
- // If this was the final tag, we've verified the entire file
if (pullResult.tag ==
Sodium.cryptoSecretstreamXchacha20poly1305TagFinal) {
break;
}
} catch (e) {
- // Crypto error during pull operation
throw Exception(
"$kVerificationErrorTag: Decryption verification failed at chunk $chunksVerified. "
"File cannot be decrypted with the provided keys. "
@@ -623,17 +579,14 @@ Future<void> chachaVerifyFile(Map<String, dynamic> args) async {
inputFile.closeSync();
}
} catch (e) {
- // If it's already tagged, just rethrow
if (e.toString().contains(kVerificationErrorTag)) {
rethrow;
}
- // For key decryption errors
if (e.toString().contains("crypto_secretbox_open_easy")) {
throw Exception(
"$kVerificationErrorTag: Failed to decrypt file key. Invalid collection key or corrupted key data.",
);
}
- // For other unexpected errors
throw Exception("$kVerificationErrorTag: Verification failed: $e");
}
}
@@ -671,11 +624,7 @@ class CryptoUtil {
return Sodium.hex2bin(hex);
}
- // Encrypts the given source, with the given key and a randomly generated
- // nonce, using XSalsa20 (w Poly1305 MAC).
- // This function runs on the same thread as the caller, so should be used only
- // for small amounts of data where thread switching can result in a degraded
- // user experience
+ // Runs on the caller thread; use only for small inputs.
static EncryptionResult encryptSync(Uint8List source, Uint8List key) {
final nonce = Sodium.randombytesBuf(Sodium.cryptoSecretboxNoncebytes);
@@ -691,8 +640,6 @@ class CryptoUtil {
);
}
- // Decrypts the given cipher, with the given key and nonce using XSalsa20
- // (w Poly1305 MAC).
static Future<Uint8List> decrypt(
Uint8List cipher,
Uint8List key,
@@ -709,11 +656,7 @@ class CryptoUtil {
);
}
- // Decrypts the given cipher, with the given key and nonce using XSalsa20
- // (w Poly1305 MAC).
- // This function runs on the same thread as the caller, so should be used only
- // for small amounts of data where thread switching can result in a degraded
- // user experience
+ // Runs on the caller thread; use only for small inputs.
static Uint8List decryptSync(
Uint8List cipher,
Uint8List key,
@@ -726,9 +669,6 @@ class CryptoUtil {
return cryptoSecretboxOpenEasy(args);
}
- // Encrypts the given source, with the given key and a randomly generated
- // nonce, using XChaCha20 (w Poly1305 MAC).
- // This function runs on the isolate pool held by `_computer`.
// TODO: Remove "ChaCha", an implementation detail from the function name
static Future<EncryptionResult> encryptChaCha(
Uint8List source,
@@ -744,8 +684,6 @@ class CryptoUtil {
);
}
- // Decrypts the given source, with the given key and header using XChaCha20
- // (w Poly1305 MAC).
// TODO: Remove "ChaCha", an implementation detail from the function name
static Future<Uint8List> decryptChaCha(
Uint8List source,
@@ -763,10 +701,6 @@ class CryptoUtil {
);
}
- // Encrypts the file at sourceFilePath, with the key (if provided) and a
- // randomly generated nonce using XChaCha20 (w Poly1305 MAC), and writes it
- // to the destinationFilePath.
- // If a key is not provided, one is generated and returned.
static Future<FileEncryptResult> encryptFile(
String sourceFilePath,
String destinationFilePath, {
@@ -785,10 +719,6 @@ class CryptoUtil {
.unwrapExceptionInComputer();
}
- // Encrypts the file at sourceFilePath, with the key (if provided) and a
- // randomly generated nonce using XChaCha20 (w Poly1305 MAC), and writes it
- // to the destinationFilePath.
- // If a key is not provided, one is generated and returned.
static Future<FileEncryptResult> encryptFileV2(
String sourceFilePath,
String destinationFilePath, {
@@ -805,7 +735,6 @@ class CryptoUtil {
);
}
- // Encrypts the file with MD5 calculation and real-time verification
static Future<FileEncryptResult> encryptFileWithMD5(
String sourceFilePath,
String destinationFilePath, {
@@ -828,8 +757,6 @@ class CryptoUtil {
.unwrapExceptionInComputer();
}
- // Decrypts the file at sourceFilePath, with the given key and header using
- // XChaCha20 (w Poly1305 MAC), and writes it to the destinationFilePath.
static Future<void> decryptFile(
String sourceFilePath,
String destinationFilePath,
@@ -873,23 +800,18 @@ class CryptoUtil {
.unwrapExceptionInComputer();
}
- // Generates and returns a 256-bit key.
static Uint8List generateKey() {
return Sodium.cryptoSecretboxKeygen();
}
- // Generates and returns a random byte buffer of length
- // crypto_pwhash_SALTBYTES (16)
static Uint8List getSaltToDeriveKey() {
return Sodium.randombytesBuf(Sodium.cryptoPwhashSaltbytes);
}
- // Generates and returns a secret key and the corresponding public key.
static Future<KeyPair> generateKeyPair() async {
return Sodium.cryptoBoxKeypair();
}
- // Decrypts the input using the given publicKey-secretKey pair
static Uint8List openSealSync(
Uint8List input,
Uint8List publicKey,
@@ -898,19 +820,10 @@ class CryptoUtil {
return Sodium.cryptoBoxSealOpen(input, publicKey, secretKey);
}
- // Encrypts the input using the given publicKey
static Uint8List sealSync(Uint8List input, Uint8List publicKey) {
return Sodium.cryptoBoxSeal(input, publicKey);
}
- // Derives a key for a given password and salt using Argon2id, v1.3.
- // The function first attempts to derive a key with both memLimit and opsLimit
- // set to their Sensitive variants.
- // If this fails, say on a device with insufficient RAM, we retry by halving
- // the memLimit and doubling the opsLimit, while ensuring that we stay within
- // the min and max limits for both parameters.
- // At all points, we ensure that the product of these two variables (the area
- // under the graph that determines the amount of work required) is a constant.
static Future<DerivedKeyResult> deriveSensitiveKey(
Uint8List password,
Uint8List salt,
@@ -919,20 +832,13 @@ class CryptoUtil {
final int desiredStrength =
Sodium.cryptoPwhashMemlimitSensitive *
Sodium.cryptoPwhashOpslimitSensitive;
- // When sensitive memLimit (1 GB) is used, on low spec device the OS might
- // kill the app with OOM. To avoid that, start with 256 MB and
- // corresponding ops limit (16).
- // This ensures that the product of these two variables
- // (the area under the graph that determines the amount of work required)
- // stays the same
- // SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE: 1073741824
- // SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE: 268435456
- // SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE: 4
+ // Start at 256 MiB to avoid OOM kills, then trade memory for operations
+ // while keeping their product constant.
int memLimit = Sodium.cryptoPwhashMemlimitModerate;
final factor =
Sodium.cryptoPwhashMemlimitSensitive ~/
- Sodium.cryptoPwhashMemlimitModerate; // = 4
- int opsLimit = Sodium.cryptoPwhashOpslimitSensitive * factor; // = 16
+ Sodium.cryptoPwhashMemlimitModerate;
+ int opsLimit = Sodium.cryptoPwhashOpslimitSensitive * factor;
if (memLimit * opsLimit != desiredStrength) {
throw UnsupportedError(
"unexpcted values for memLimit $memLimit and opsLimit: $opsLimit",
@@ -961,11 +867,8 @@ class CryptoUtil {
throw UnsupportedError("Cannot perform this operation on this device");
}
- // Derives a key for the given password and salt, using Argon2id, v1.3
- // with memory and ops limit hardcoded to their Interactive variants
- // NOTE: This is only used while setting passwords for shared links, as an
- // extra layer of authentication (atop the access token and collection key).
- // More details @ https://ente.com/blog/building-shareable-links/
+ // Used only for shared-link passwords, after the access token and collection
+ // key.
static Future<DerivedKeyResult> deriveInteractiveKey(
Uint8List password,
Uint8List salt,
@@ -976,8 +879,6 @@ class CryptoUtil {
return DerivedKeyResult(key, memLimit, opsLimit);
}
- // Derives a key for a given password, salt, memLimit and opsLimit using
- // Argon2id, v1.3.
static Future<Uint8List> deriveKey(
Uint8List password,
Uint8List salt,
@@ -1004,9 +905,6 @@ class CryptoUtil {
}
}
- // derives a Login key as subKey from the given key by applying KDF
- // (Key Derivation Function) with the `loginSubKeyId` and
- // `loginSubKeyLen` and `loginSubKeyContext` as context
static Future<Uint8List> deriveLoginKey(Uint8List key) async {
try {
final Uint8List derivedKey = await _computer.compute(
@@ -1019,7 +917,6 @@ class CryptoUtil {
},
taskName: "deriveLoginKey",
);
- // return the first 16 bytes of the derived key
return derivedKey.sublist(0, 16);
} catch (e, s) {
Logger("deriveLoginKey").severe("loginKeyDerivation failed", e, s);
@@ -1027,7 +924,6 @@ class CryptoUtil {
}
}
- // Computes and returns the hash of the source file
static Future<Uint8List> getHash(File source) {
return _computer.compute(
cryptoGenericHash,
@@ -1036,8 +932,6 @@ class CryptoUtil {
);
}
- /// Estimates the encrypted size for a given plaintext size.
- /// Takes into account the ChaCha20-Poly1305 overhead per chunk.
static int estimateEncryptedSize(int plainTextSize) {
if (plainTextSize <= 0) {
return 0;
@@ -1055,11 +949,6 @@ class CryptoUtil {
return estimatedSize;
}
- /// Validates that the plaintext and ciphertext sizes match for streaming encryption.
- /// Returns true if the sizes are valid for chunked ChaCha20-Poly1305 encryption.
- ///
- /// Each chunk adds 17 bytes (Sodium.cryptoSecretstreamXchacha20poly1305Abytes) overhead.
- /// For a 4MB chunk size, the encrypted size is 4MB + 17 bytes per chunk.
static bool validateStreamEncryptionSizes(
int plainTextSize,
int cipherTextSize,
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 8ce2b2fae1..8726efc265 100644
--- a/mobile/apps/photos/test/services/memories/photo_selector_test.dart
+++ b/mobile/apps/photos/test/services/memories/photo_selector_test.dart
@@ -11,14 +11,8 @@ import "package:photos/models/ml/face/face_with_embedding.dart";
import "package:photos/models/ml/vector.dart";
import "package:photos/services/memories/photo_selector.dart";
-// ---------------------------------------------------------------------------
-// Test helpers
-// ---------------------------------------------------------------------------
-
-/// Dimension of the fake CLIP embedding vectors used in tests.
const _embDim = 16;
-/// Creates a minimal [EnteFile] with the given properties.
EnteFile _file({
required int uploadedFileID,
required int creationTime,
@@ -34,12 +28,10 @@ EnteFile _file({
return f;
}
-/// Shorthand: wraps an [EnteFile] into a [Memory] with unseen state.
Memory _mem(EnteFile f) => Memory(f, -1);
-/// Creates a deterministic "random" embedding for the given [fileID].
-/// Vectors created with distinct seeds will have low cosine similarity;
-/// vectors with the same seed will be identical (similarity = 1).
+// Equal seeds produce identical vectors; distinct seeds have low cosine
+// similarity.
EmbeddingVector _emb(int fileID, {int? seed}) {
final s = seed ?? fileID;
final rng = Random(s);
@@ -52,10 +44,9 @@ EmbeddingVector _emb(int fileID, {int? seed}) {
);
}
-/// Creates an embedding that is *nearly identical* to [base] (similarity > 0.80).
+// Produces an embedding above the 0.80 near-duplicate threshold.
EmbeddingVector _nearDuplicateEmb(int fileID, EmbeddingVector base) {
final baseList = base.vector.toList();
- // Add a tiny perturbation – keeps cosine similarity > 0.99.
final perturbed = baseList
.map((v) => v + (Random(fileID).nextDouble() - 0.5) * 0.01)
.toList();
@@ -66,38 +57,28 @@ EmbeddingVector _nearDuplicateEmb(int fileID, EmbeddingVector base) {
);
}
-/// A unit vector used as the "positive text vector" for nostalgia scoring.
Vector get _positiveTextVector {
final raw = List<double>.generate(_embDim, (i) => (i + 1).toDouble());
final norm = Vector.fromList(raw).norm();
return Vector.fromList(raw.map((v) => v / norm).toList());
}
-/// Microseconds per hour – handy for spacing creation times.
const _hour = 3600 * 1000 * 1000;
-/// Base timestamp: 2023-06-15 12:00 UTC in microseconds since epoch.
final _baseTime = DateTime.utc(2023, 6, 15, 12).microsecondsSinceEpoch;
-/// Returns a creation time [hours] after [_baseTime], in the given [year].
int _timeInYear(int year, {int hours = 0}) {
return DateTime.utc(year, 6, 15, 12 + hours).microsecondsSinceEpoch;
}
-/// Builds the standard embedding map from a list of [EmbeddingVector]s.
Map<int, EmbeddingVector> _embMap(List<EmbeddingVector> embeddings) {
return {for (final e in embeddings) e.fileID: e};
}
-/// Creates a simple [FaceWithoutEmbedding] for testing.
FaceWithoutEmbedding _face(String faceID, int fileID) {
return FaceWithoutEmbedding(faceID, fileID, 0.9, Detection.empty(), 50.0);
}
-// ---------------------------------------------------------------------------
-// Utility function tests
-// ---------------------------------------------------------------------------
-
void main() {
group('PhotoSelector utilities', () {
test(
@@ -196,10 +177,6 @@ void main() {
});
});
- // -------------------------------------------------------------------------
- // bestSelection – single-year path
- // -------------------------------------------------------------------------
-
group('PhotoSelector.bestSelection (single year)', () {
test('returns input when count <= targetSize', () async {
final memories = List.generate(5, (i) {
@@ -219,12 +196,10 @@ void main() {
fileIDToImageEmbedding: _embMap(embeddings),
clipPositiveTextVector: _positiveTextVector,
);
- // Should return all 5 as-is (5 <= default target of 10).
expect(result.length, equals(5));
});
test('limits output to targetSize', () async {
- // 20 photos, all same year, target = 10
final memories = List.generate(20, (i) {
return _mem(
_file(uploadedFileID: i, creationTime: _baseTime + i * _hour),
@@ -272,9 +247,7 @@ void main() {
});
test('no two selected photos are within minimumMemoryTimeGap', () async {
- // Create 30 photos, some very close in time
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));
});
@@ -334,13 +307,11 @@ void main() {
);
test('prioritizes files with named faces', () async {
- // 20 photos, file 0 has a named face, others don't
final memories = List.generate(20, (i) {
return _mem(
_file(uploadedFileID: i, creationTime: _baseTime + i * _hour),
);
});
- // All files get the same CLIP embedding so CLIP score is equal
final sharedEmb = _emb(0, seed: 42);
final embeddings = memories.map((m) {
return EmbeddingVector(
@@ -348,7 +319,6 @@ void main() {
embedding: sharedEmb.vector.toList(),
);
}).toList();
- // File 0 has a named face
final fileIdToFaces = <int, List<FaceWithoutEmbedding>>{
0: [_face('face_0', 0)],
};
@@ -362,7 +332,6 @@ void main() {
fileIDToImageEmbedding: _embMap(embeddings),
clipPositiveTextVector: _positiveTextVector,
);
- // File 0 should be in the result because named faces are heavily prioritized
expect(
result.any((m) => m.file.uploadedFileID == 0),
isTrue,
@@ -371,7 +340,6 @@ void main() {
});
test('excludes near-duplicate photos', () async {
- // 20 photos: file 0 and file 1 are near-duplicates
final e0 = _emb(0, seed: 100);
final e1 = _nearDuplicateEmb(1, e0);
final embeddings = <EmbeddingVector>[e0, e1];
@@ -392,7 +360,6 @@ void main() {
fileIDToImageEmbedding: _embMap(embeddings),
clipPositiveTextVector: _positiveTextVector,
);
- // Both 0 and 1 should not both be in the result
final hasZero = result.any((m) => m.file.uploadedFileID == 0);
final hasOne = result.any((m) => m.file.uploadedFileID == 1);
expect(
@@ -403,13 +370,8 @@ void main() {
});
});
- // -------------------------------------------------------------------------
- // bestSelection – multi-year path
- // -------------------------------------------------------------------------
-
group('PhotoSelector.bestSelection (multi year)', () {
test('represents each year', () async {
- // 3 years, 10 photos each
final memories = <Memory>[];
final embeddings = <EmbeddingVector>[];
int id = 0;
@@ -445,7 +407,6 @@ void main() {
});
test('adjusts targetSize for many years', () async {
- // 7 years (7*2 = 14 > 10), so targetSize becomes 7*3 = 21
final memories = <Memory>[];
final embeddings = <EmbeddingVector>[];
int id = 0;
@@ -463,7 +424,6 @@ void main() {
embeddings.add(_emb(fileID));
}
}
- // 35 photos, 7 years. targetSize should be 21 when prefferedSize is null.
final result = await PhotoSelector.bestSelection(
memories,
isLocalGalleryMode: false,
@@ -473,14 +433,12 @@ void main() {
fileIDToImageEmbedding: _embMap(embeddings),
clipPositiveTextVector: _positiveTextVector,
);
- // Should select more than default 10 since targetSize was raised
expect(result.length, greaterThan(10));
});
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>>{};
@@ -572,7 +530,6 @@ 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>[];
@@ -600,8 +557,6 @@ void main() {
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();
@@ -617,7 +572,6 @@ void main() {
for (final year in [2020, 2021, 2022]) {
for (int i = 0; i < 10; i++) {
final fileID = id++;
- // Alternate close-in-time and spread
final offset = i.isEven ? i * _hour : (i - 1) * _hour + 60000000;
memories.add(
_mem(
@@ -656,10 +610,6 @@ void main() {
});
});
- // -------------------------------------------------------------------------
- // bestSelectionPeople
- // -------------------------------------------------------------------------
-
group('PhotoSelector.bestSelectionPeople', () {
test('returns input when count <= targetSize', () async {
final memories = List.generate(5, (i) {
@@ -764,7 +714,6 @@ void main() {
});
test('distributes selection across the time range', () async {
- // 30 photos spanning 30 hours
final memories = List.generate(30, (i) {
return _mem(
_file(uploadedFileID: i, creationTime: _baseTime + i * _hour),
@@ -779,7 +728,6 @@ void main() {
fileIDToImageEmbedding: _embMap(embeddings),
clipPositiveTextVector: _positiveTextVector,
);
- // Check that selected photos span at least 80% of the original time range
final times = result.map((m) => m.file.creationTime!).toList()..sort();
final selectedRange = times.last - times.first;
const totalRange = 29 * _hour;
@@ -791,8 +739,6 @@ void main() {
});
test('prefers geographically diverse photos', () async {
- // 30 photos: 20 in New York, 10 in Tokyo. Target = 10.
- // The algorithm should include some Tokyo photos for diversity.
const nyLoc = Location(latitude: 40.7128, longitude: -74.0060);
const tokyoLoc = Location(latitude: 35.6762, longitude: 139.6503);
final memories = <Memory>[];
@@ -841,12 +787,12 @@ void main() {
});
test('handles photos without embeddings (littleEmbeddings path)', () async {
- // 20 photos, but only 3 have embeddings (< 50% threshold)
final memories = List.generate(20, (i) {
return _mem(
_file(uploadedFileID: i, creationTime: _baseTime + i * _hour),
);
});
+ // Three embeddings keep this below the 50% threshold.
final embeddings = [_emb(0), _emb(5), _emb(15)];
final result = await PhotoSelector.bestSelectionPeople(
memories,
@@ -854,7 +800,6 @@ void main() {
fileIDToImageEmbedding: _embMap(embeddings),
clipPositiveTextVector: _positiveTextVector,
);
- // Should still produce a result (doesn't crash or return empty)
expect(result.length, greaterThan(0));
expect(result.length, lessThanOrEqualTo(10));
});
@@ -862,7 +807,6 @@ void main() {
test('filters memories without creationTime', () async {
final memories = <Memory>[
_mem(_file(uploadedFileID: 0, creationTime: _baseTime)),
- // This one has no creation time
_mem(
EnteFile()
..uploadedFileID = 1
@@ -887,15 +831,10 @@ void main() {
fileIDToImageEmbedding: _embMap(embeddings),
clipPositiveTextVector: _positiveTextVector,
);
- // File 1 (no creationTime) should not be in result
expect(result.any((m) => m.file.uploadedFileID == 1), isFalse);
});
});
- // -------------------------------------------------------------------------
- // Deterministic equivalence tests – verify exact output for fixed input
- // -------------------------------------------------------------------------
-
group('Deterministic equivalence (bestSelection)', () {
test('single-year: produces same output on repeated calls', () async {
final memories = List.generate(20, (i) {
@@ -1025,10 +964,6 @@ void main() {
);
});
- // -------------------------------------------------------------------------
- // Unified select() API tests
- // -------------------------------------------------------------------------
-
group('PhotoSelector.select (unified API)', () {
test('returns input when count <= targetSize', () async {
final memories = List.generate(5, (i) {
@@ -1063,7 +998,6 @@ void main() {
.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(),
@@ -1081,7 +1015,6 @@ void main() {
),
);
expect(result.length, lessThanOrEqualTo(10));
- // Should prefer higher-scored files
expect(
result.any((m) => m.file.uploadedFileID == 19),
isTrue,
@@ -1117,14 +1050,12 @@ void main() {
),
);
expect(result.length, lessThanOrEqualTo(10));
- // Check reverse chronological sort
for (int i = 1; i < result.length; i++) {
expect(
result[i].file.creationTime!,
lessThanOrEqualTo(result[i - 1].file.creationTime!),
);
}
- // Check time spread
final times = result.map((m) => m.file.creationTime!).toList()..sort();
if (times.length > 1) {
final selectedRange = times.last - times.first;
diff --git a/mobile/apps/photos/test/services/video_preview_service_test.dart b/mobile/apps/photos/test/services/video_preview_service_test.dart
index 171679b12c..4e2c8cf2d0 100644
--- a/mobile/apps/photos/test/services/video_preview_service_test.dart
+++ b/mobile/apps/photos/test/services/video_preview_service_test.dart
@@ -30,7 +30,6 @@ void main() {
group('calcStatus Logic Tests', () {
test('should handle mixed processed and unprocessed files', () async {
- // Arrange
final files = [
EnteFile()
..uploadedFileID = 1
@@ -55,12 +54,10 @@ void main() {
final status = await videoPreviewService.calcStatus(files, previewIds);
- // Assert
- expect(status, closeTo(0.33, 0.01)); // 1/3 β‰ˆ 0.33
+ expect(status, closeTo(0.33, 0.01));
});
test('should handle all files processed', () async {
- // Arrange
final files = [
EnteFile()
..uploadedFileID = 1
@@ -79,12 +76,10 @@ void main() {
final status = await videoPreviewService.calcStatus(files, previewIds);
- // Assert
- expect(status, equals(1.0)); // 100% processed
+ expect(status, equals(1.0));
});
test('should handle no files processed', () async {
- // Arrange
final files = [
EnteFile()
..uploadedFileID = 1
@@ -100,12 +95,10 @@ void main() {
final status = await videoPreviewService.calcStatus(files, previewIds);
- // Assert
- expect(status, equals(0.0)); // 0% processed
+ expect(status, equals(0.0));
});
test('should skip files with sv=1 from total count', () async {
- // Arrange
final files = [
EnteFile()
..uploadedFileID = 1
@@ -125,12 +118,10 @@ void main() {
final status = await videoPreviewService.calcStatus(files, previewIds);
- // Assert
- expect(status, equals(0.0)); // 0% processed
+ expect(status, equals(0.0));
});
test('should handle processed files with sv=1', () async {
- // Arrange
final files = [
EnteFile()
..uploadedFileID = 1
@@ -157,28 +148,19 @@ void main() {
final status = await videoPreviewService.calcStatus(files, previewIds);
- // Assert
- // Logic:
- // file 2 is processed -> goes to processed set (processed = {2})
- // All files except sv=1 go to total: file 1 -> total, file 2 -> total, file 3 -> total
- // So: processed = {2}, total = {1,2,3}
- // netProcessedItems = processed.length / total.length = 1/3 β‰ˆ 0.33
expect(status, closeTo(0.33, 0.01));
});
test('should handle empty file list', () async {
- // Arrange
final files = <EnteFile>[];
final previewIds = <int, PreviewInfo>{};
final status = await videoPreviewService.calcStatus(files, previewIds);
- // Assert
- expect(status, equals(1.0)); // Empty = 100% complete
+ expect(status, equals(1.0));
});
test('should handle complex scenario', () async {
- // Arrange
final files = [
EnteFile()
..uploadedFileID = 1
@@ -217,20 +199,10 @@ void main() {
final status = await videoPreviewService.calcStatus(files, previewIds);
- // Assert
- // File 1: processed -> add to processed {1}, then add to total {1}
- // File 2: not processed, sv=1 -> skip (continue)
- // File 3: processed -> add to processed {1,3}, then add to total {1,3}
- // File 4: not processed, sv!=1 -> add to total {1,3,4}
- // File 5: processed -> add to processed {1,3,5}, then add to total {1,3,4,5}
- //
- // Result: processed = {1,3,5}, total = {1,3,4,5}
- // netProcessedItems = 3/4 = 0.75
expect(status, equals(0.75));
});
test('should handle null pubMagicMetadata', () async {
- // Arrange
final files = [
EnteFile()
..uploadedFileID = 1
@@ -248,12 +220,10 @@ void main() {
final status = await videoPreviewService.calcStatus(files, previewIds);
- // Assert
- expect(status, equals(0.5)); // 1/2 = 0.5
+ expect(status, equals(0.5));
});
test('should handle large numbers correctly', () async {
- // Arrange - Create 1000 files, 750 processed
final files = List.generate(
1000,
(index) => EnteFile()
@@ -263,19 +233,16 @@ void main() {
);
final previewIds = <int, PreviewInfo>{};
- // Make first 750 files processed
for (int i = 1; i <= 750; i++) {
previewIds[i] = PreviewInfo(objectId: 'obj$i', objectSize: 1000);
}
final status = await videoPreviewService.calcStatus(files, previewIds);
- // Assert
- expect(status, equals(0.75)); // 750/1000 = 0.75
+ expect(status, equals(0.75));
});
test('should handle edge case - all files have sv=1', () async {
- // Arrange
final files = [
EnteFile()
..uploadedFileID = 1
@@ -294,13 +261,10 @@ void main() {
final status = await videoPreviewService.calcStatus(files, previewIds);
- // Assert
- // All files have sv=1, so total set is empty, netProcessedItems should be 1.0
- expect(status, equals(1.0)); // Empty total = 100% complete
+ expect(status, equals(1.0));
});
test('should handle percentage calculation precision', () async {
- // Arrange - Test precise percentage calculations
final files = List.generate(
7,
(index) => EnteFile()
@@ -316,8 +280,6 @@ void main() {
final status = await videoPreviewService.calcStatus(files, previewIds);
- // Assert
- // 2 out of 7 files processed = 2/7 β‰ˆ 0.2857
expect(status, closeTo(0.2857, 0.0001));
});
});
diff --git a/mobile/apps/photos/test/utils/date_query_parsing_test.dart b/mobile/apps/photos/test/utils/date_query_parsing_test.dart
index efeab55d8c..69c5798acd 100644
--- a/mobile/apps/photos/test/utils/date_query_parsing_test.dart
+++ b/mobile/apps/photos/test/utils/date_query_parsing_test.dart
@@ -2,12 +2,9 @@ import 'package:photos/services/date_parse_service.dart';
import 'package:test/test.dart';
void main() {
- // Get an instance of the service
final DateParseService dateParseService = DateParseService.instance;
- // --- Natural Language Date Parsing ---
group('Natural Language Date Parsing', () {
- // Relative dates: today, tomorrow, yesterday
test('should parse "today" correctly', () {
final DateTime now = DateTime.now();
final PartialDate expectedDate = PartialDate(
@@ -88,7 +85,6 @@ void main() {
);
});
- // Month names: Full (February), abbreviated (Feb), and partial (Febr)
test('should parse full month name "February 2025"', () {
final PartialDate parsedDate = dateParseService.parse('February 2025');
expect(parsedDate.day, isNull);
@@ -124,7 +120,6 @@ void main() {
expect(parsedDate.year, 2025);
});
- // Ordinal numbers: 25th, 22nd, 3rd, 1st
test('should parse ordinal number "25th Jan 2024"', () {
final PartialDate parsedDate = dateParseService.parse('25th Jan 2024');
expect(parsedDate.day, 25);
@@ -160,7 +155,6 @@ void main() {
expect(parsedDate.year, isNull);
});
- // Flexible combinations
test('should parse "25th Feb" (generic date)', () {
final PartialDate parsedDate = dateParseService.parse('25th Feb');
expect(parsedDate.day, 25);
@@ -185,9 +179,7 @@ void main() {
});
});
- // --- Structured Date Format Support ---
group('Structured Date Format Support', () {
- // ISO format: 2025-02-25, 2025/02/25
test('should parse ISO format "2025-02-25"', () {
final PartialDate parsedDate = dateParseService.parse('2025-02-25');
expect(parsedDate.day, 25);
@@ -202,10 +194,7 @@ void main() {
expect(parsedDate.year, 2025);
});
- // Standard formats: 02/25/2025, 25/02/2025 (with MM/DD vs DD/MM detection)
test('should parse standard MM/DD/YYYY format "02/25/2025"', () {
- // Your parser assumes MM/DD if ambiguous (e.g., both parts <= 12)
- // but for 02/25/2025, 25 > 12, so it correctly interprets 02 as month and 25 as day.
final PartialDate parsedDate = dateParseService.parse('02/25/2025');
expect(parsedDate.day, 25);
expect(parsedDate.month, 2);
@@ -213,7 +202,6 @@ void main() {
});
test('should parse standard DD/MM/YYYY format "25/02/2025"', () {
- // Your parser handles DD/MM explicitly when day part > 12
final PartialDate parsedDate = dateParseService.parse('25/02/2025');
expect(parsedDate.day, 25);
expect(parsedDate.month, 2);
@@ -221,14 +209,12 @@ void main() {
});
test('should parse ambiguous "01/02/2024" as DD/MM/YYYY (Feb 1)', () {
- // The parser prefers DD/MM when both day and month are plausible.
final PartialDate parsedDate = dateParseService.parse('01/02/2024');
expect(parsedDate.day, 1);
expect(parsedDate.month, 2);
expect(parsedDate.year, 2024);
});
- // Dot notation: 25.02.2025, 25.02.25
test('should parse dot notation "25.02.2025"', () {
final PartialDate parsedDate = dateParseService.parse('25.02.2025');
expect(parsedDate.day, 25);
@@ -237,14 +223,12 @@ void main() {
});
test('should parse dot notation with two-digit year "25.02.25"', () {
- // Assumes century detection (e.g., 25 -> 2025)
final PartialDate parsedDate = dateParseService.parse('25.02.25');
expect(parsedDate.day, 25);
expect(parsedDate.month, 2);
expect(parsedDate.year, 2025);
});
- // Compact format: 20250225
test('should parse compact format "20250225"', () {
final PartialDate parsedDate = dateParseService.parse('20250225');
expect(parsedDate.day, 25);
@@ -252,10 +236,6 @@ void main() {
expect(parsedDate.year, 2025);
});
- // Short formats: 02/25, 25/02 (your parser doesn't explicitly handle short yearless formats)
- // Based on your _standardFormatRegex: RegExp(r'^(\d{1,2})[\/-](\d{1,2})[\/-](\d{2,4})$');
- // and _parseTokenizedDate, "02/25" would be processed by _parseTokenizedDate.
- // Let's test how your current parser handles these.
test(
'should parse short MM/DD format "02/25" (no year, handled by tokenized)',
() {
@@ -269,7 +249,6 @@ void main() {
test(
'should parse short DD/MM format "25/02" (no year, handled by tokenized)',
() {
- // This will be parsed by _parseTokenizedDate
final PartialDate parsedDate = dateParseService.parse('25/02');
expect(parsedDate.day, 25);
expect(parsedDate.month, 2);
@@ -277,7 +256,6 @@ void main() {
},
);
- // Two-digit years: 25/02/25 (with century detection)
test('should parse two-digit year "25/02/25"', () {
final PartialDate parsedDate = dateParseService.parse('25/02/25');
expect(parsedDate.day, 25);
@@ -300,7 +278,6 @@ void main() {
});
});
- // --- Smart Query Types ---
group('Smart Query Types', () {
test('should parse year-only query "2025"', () {
final PartialDate parsedDate = dateParseService.parse('2025');
@@ -331,7 +308,6 @@ void main() {
});
});
- // --- Invalid Date Queries ---
group('Invalid Date Queries', () {
test(
'should parse "February 30000" as month-only (invalid year ignored)',
@@ -347,20 +323,17 @@ void main() {
},
);
- // Specific case to test if invalid day/month values are set to null
test('should return null for invalid day/month in tokenized parsing', () {
final PartialDate parsedDate = dateParseService.parse('32 Jan 2024');
expect(parsedDate.day, isNull, reason: 'Day should be null for 32');
expect(parsedDate.month, 1);
expect(parsedDate.year, 2024);
- // "Jan 13 2024" - This is a valid date (Jan 13, 2024), should parse completely.
final PartialDate parsedDate2 = dateParseService.parse('Jan 13 2024');
expect(parsedDate2.day, 13);
expect(parsedDate2.month, 1);
expect(parsedDate2.year, 2024);
- // "Feb 0 2024" - Day 0 should be null, but month and year are valid.
final PartialDate parsedDate3 = dateParseService.parse('Feb 0 2024');
expect(parsedDate3.day, isNull, reason: 'Day should be null for 0');
expect(parsedDate3.month, 2);
diff --git a/mobile/packages/ente_components/lib/theme/colors.dart b/mobile/packages/ente_components/lib/theme/colors.dart
index 83636db57e..3411d33839 100644
--- a/mobile/packages/ente_components/lib/theme/colors.dart
+++ b/mobile/packages/ente_components/lib/theme/colors.dart
@@ -428,7 +428,6 @@ const PrimaryColorTokens bluePrimaryTokensDark = PrimaryColorTokens(
primaryDarker: blueDarkerDark,
);
-// Green Colors
const Color greenLightLight = Color.fromRGBO(221, 238, 223, 1);
const Color greenLightDark = Color.fromRGBO(41, 41, 41, 1);
@@ -450,7 +449,6 @@ const Color greenDarkDark = Color.fromRGBO(6, 157, 30, 1);
const Color greenDarkerLight = Color.fromRGBO(5, 124, 24, 1);
const Color greenDarkerDark = Color.fromRGBO(5, 124, 24, 1);
-// Purple Colors
const Color purpleLightLight = Color.fromRGBO(244, 231, 252, 1);
const Color purpleLightDark = Color.fromRGBO(39, 28, 50, 1);
@@ -472,7 +470,6 @@ const Color purpleDarkDark = Color.fromRGBO(122, 12, 174, 1);
const Color purpleDarkerLight = Color.fromRGBO(93, 8, 132, 1);
const Color purpleDarkerDark = Color.fromRGBO(93, 8, 132, 1);
-// Blue Colors
const Color blueLightLight = Color.fromRGBO(231, 239, 250, 1);
const Color blueLightDark = Color.fromRGBO(41, 41, 41, 1);
@@ -494,7 +491,6 @@ const Color blueDarkDark = Color.fromRGBO(14, 95, 217, 1);
const Color blueDarkerLight = Color.fromRGBO(11, 76, 173, 1);
const Color blueDarkerDark = Color.fromRGBO(11, 76, 173, 1);
-// Warning Colors
const Color warningLightLight = Color.fromRGBO(250, 235, 235, 1);
const Color warningLightDark = Color.fromRGBO(41, 41, 41, 1);
@@ -507,14 +503,12 @@ const Color warningDarkDark = Color.fromRGBO(221, 52, 52, 1);
const Color warningDarkerLight = Color.fromRGBO(197, 46, 46, 1);
const Color warningDarkerDark = Color.fromRGBO(197, 46, 46, 1);
-// Caution Colors
const Color cautionLightLight = Color.fromRGBO(250, 244, 235, 1);
const Color cautionLightDark = Color.fromRGBO(41, 41, 41, 1);
const Color cautionDefaultLight = Color.fromRGBO(240, 138, 30, 1);
const Color cautionDefaultDark = Color.fromRGBO(240, 138, 30, 1);
-// Text Colors
const Color textLightLight = Color.fromRGBO(102, 102, 102, 1);
const Color textLightDark = Color.fromRGBO(153, 153, 153, 1);
@@ -536,15 +530,12 @@ const Color textLightestDark = Color.fromRGBO(65, 65, 65, 1);
const Color textReverseLight = Color.fromRGBO(255, 255, 255, 1);
const Color textReverseDark = Color.fromRGBO(0, 0, 0, 1);
-// Icon Colors
const Color iconColorLight = Color.fromRGBO(0, 0, 0, 0.75);
const Color iconColorDark = Color.fromRGBO(255, 255, 255, 1);
-// Background Colors
const Color backgroundBaseLight = Color.fromRGBO(244, 244, 244, 1);
const Color backgroundBaseDark = Color.fromRGBO(22, 22, 22, 1);
-// Fill Colors
const Color fillLightLight = Color.fromRGBO(255, 255, 255, 1);
const Color fillLightDark = Color.fromRGBO(33, 33, 33, 1);
@@ -560,14 +551,12 @@ const Color fillDarkerDark = Color.fromRGBO(20, 20, 20, 1);
const Color fillDarkestLight = Color.fromRGBO(210, 210, 210, 1);
const Color fillDarkestDark = Color.fromRGBO(41, 41, 41, 1);
-// Stroke Colors
const Color strokeDarkLight = Color.fromRGBO(224, 224, 224, 1);
const Color strokeDarkDark = Color.fromRGBO(62, 62, 62, 1);
const Color strokeFaintLight = Color.fromRGBO(235, 235, 235, 1);
const Color strokeFaintDark = Color.fromRGBO(42, 42, 42, 1);
-// Accent Colors
const Color accentOrangeLightLight = Color.fromRGBO(255, 247, 244, 1);
const Color accentOrangeLightDark = Color.fromRGBO(41, 41, 41, 1);
@@ -586,7 +575,6 @@ const Color accentPinkDefaultDark = Color.fromRGBO(223, 97, 187, 1);
const Color accentTealDefaultLight = Color.fromRGBO(95, 183, 187, 1);
const Color accentTealDefaultDark = Color.fromRGBO(95, 183, 187, 1);
-// Special Colors
const Color specialContentReverseLight = Color.fromRGBO(255, 255, 255, 1);
const Color specialContentReverseDark = Color.fromRGBO(0, 0, 0, 1);
diff --git a/mobile/packages/ente_qr/android/src/main/kotlin/io/ente/ente_qr/EnteQrPlugin.kt b/mobile/packages/ente_qr/android/src/main/kotlin/io/ente/ente_qr/EnteQrPlugin.kt
index 2f3eddb31a..53addb90cd 100644
--- a/mobile/packages/ente_qr/android/src/main/kotlin/io/ente/ente_qr/EnteQrPlugin.kt
+++ b/mobile/packages/ente_qr/android/src/main/kotlin/io/ente/ente_qr/EnteQrPlugin.kt
@@ -16,7 +16,6 @@ import io.flutter.plugin.common.MethodChannel.Result
import java.io.File
import java.util.concurrent.Executors
-/** EnteQrPlugin */
class EnteQrPlugin: FlutterPlugin, MethodCallHandler {
private lateinit var channel : MethodChannel
private val executor = Executors.newSingleThreadExecutor()
@@ -82,19 +81,13 @@ class EnteQrPlugin: FlutterPlugin, MethodCallHandler {
}
}
- /**
- * Load a bitmap with efficient downsampling and EXIF orientation correction.
- * Uses two-pass decoding: first get dimensions, then load at target size.
- */
private fun loadBitmap(imagePath: String, maxDimension: Int? = 1024): Bitmap? {
- // Pass 1: get dimensions without loading pixels
val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(imagePath, opts)
val rawW = opts.outWidth
val rawH = opts.outHeight
if (rawW <= 0 || rawH <= 0) return null
- // Pass 2: load with downsampling
var sampleSize = 1
if (maxDimension != null) {
while (rawW / (sampleSize * 2) >= maxDimension ||
@@ -109,7 +102,6 @@ class EnteQrPlugin: FlutterPlugin, MethodCallHandler {
null
} ?: return null
- // Apply EXIF orientation
return try {
val exif = ExifInterface(imagePath)
val orientation = exif.getAttributeInt(
@@ -145,7 +137,6 @@ class EnteQrPlugin: FlutterPlugin, MethodCallHandler {
}
}
- // Fallback: try GlobalHistogram binarizer
options.binarizer = Binarizer.GLOBAL_HISTOGRAM
val fallbackResults = ZxingCpp.readBitmap(
bitmap, 0, 0, bitmap.width, bitmap.height, 0, options
@@ -171,8 +162,6 @@ class EnteQrPlugin: FlutterPlugin, MethodCallHandler {
}
}
- // ── Main scan methods ─────────────────────────────────────────────
-
private fun scanQrCode(
imagePath: String,
tryOriginalResolution: Boolean = false,
@@ -236,7 +225,6 @@ class EnteQrPlugin: FlutterPlugin, MethodCallHandler {
}
}
- // Fallback: try GlobalHistogram binarizer
options.binarizer = Binarizer.GLOBAL_HISTOGRAM
val fallbackResults = ZxingCpp.readBitmap(
bitmap, 0, 0, bitmap.width, bitmap.height, 0, options
diff --git a/mobile/packages/native_video_editor/android/build.gradle b/mobile/packages/native_video_editor/android/build.gradle
index 332fbdcc84..995c4620d0 100644
--- a/mobile/packages/native_video_editor/android/build.gradle
+++ b/mobile/packages/native_video_editor/android/build.gradle
@@ -60,13 +60,11 @@ dependencies {
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3"
testImplementation 'junit:junit:4.13.2'
- // Media3 Transformer for efficient video operations
implementation "androidx.media3:media3-transformer:$media3_version"
implementation "androidx.media3:media3-common:$media3_version"
implementation "androidx.media3:media3-effect:$media3_version"
implementation "androidx.media3:media3-extractor:$media3_version"
implementation "androidx.media3:media3-inspector-frame:$media3_version"
- // Guava for ImmutableList
implementation "com.google.guava:guava:31.1-android"
}
diff --git a/mobile/packages/rust/android/build.gradle b/mobile/packages/rust/android/build.gradle
index 4c107ae44e..1744815b9f 100644
--- a/mobile/packages/rust/android/build.gradle
+++ b/mobile/packages/rust/android/build.gradle
@@ -1,5 +1,3 @@
-// The Android Gradle Plugin builds the native code with the Android NDK.
-
group 'com.flutter_rust_bridge.ente_rust'
version '1.0'
@@ -10,7 +8,6 @@ buildscript {
}
dependencies {
- // The Android Gradle Plugin knows how to build native code with the NDK.
classpath 'com.android.tools.build:gradle:7.3.0'
}
}
@@ -33,10 +30,6 @@ android {
// to bump the version in their app.
compileSdkVersion 33
- // Use the NDK version
- // declared in /android/app/build.gradle file of the Flutter project.
- // Replace it with a version number if this plugin requires a specfic NDK version.
- // (e.g. ndkVersion "23.1.7779620")
ndkVersion "28.2.13676358"
compileOptions {
diff --git a/mobile/packages/scoped_dir_access/ios/Classes/DirUtilsPlugin.swift b/mobile/packages/scoped_dir_access/ios/Classes/DirUtilsPlugin.swift
index 58fa96a4bd..1d2f1bf7e1 100644
--- a/mobile/packages/scoped_dir_access/ios/Classes/DirUtilsPlugin.swift
+++ b/mobile/packages/scoped_dir_access/ios/Classes/DirUtilsPlugin.swift
@@ -38,8 +38,6 @@ public class DirUtilsPlugin: NSObject, FlutterPlugin {
}
}
- // MARK: - Directory Picker
-
private func handlePickDirectory(result: @escaping FlutterResult) {
guard let viewController = UIApplication.shared.windows.first?.rootViewController else {
result(FlutterError(code: "NO_VIEW_CONTROLLER", message: "Could not find root view controller", details: nil))
@@ -60,8 +58,6 @@ public class DirUtilsPlugin: NSObject, FlutterPlugin {
viewController.present(picker, animated: true)
}
- // MARK: - Security-Scoped Access
-
private func handleStartAccess(call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let args = call.arguments as? [String: Any],
let base64Bookmark = args["bookmark"] as? String,
@@ -125,8 +121,6 @@ public class DirUtilsPlugin: NSObject, FlutterPlugin {
}
}
- // MARK: - File Operations
-
private func handleWriteFile(call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let args = call.arguments as? [String: Any],
let path = args["path"] as? String,
@@ -243,7 +237,6 @@ public class DirUtilsPlugin: NSObject, FlutterPlugin {
}
}
-// MARK: - UIDocumentPickerDelegate
extension DirUtilsPlugin: UIDocumentPickerDelegate {
public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let result = pendingResult else { return }
@@ -254,7 +247,6 @@ extension DirUtilsPlugin: UIDocumentPickerDelegate {
return
}
- // Start accessing the security-scoped resource
let didStartAccessing = url.startAccessingSecurityScopedResource()
defer {
diff --git a/mobile/packages/scoped_dir_access/macos/Classes/DirUtilsPlugin.swift b/mobile/packages/scoped_dir_access/macos/Classes/DirUtilsPlugin.swift
index 668c240fd4..c0f2eab434 100644
--- a/mobile/packages/scoped_dir_access/macos/Classes/DirUtilsPlugin.swift
+++ b/mobile/packages/scoped_dir_access/macos/Classes/DirUtilsPlugin.swift
@@ -34,10 +34,7 @@ public class DirUtilsPlugin: NSObject, FlutterPlugin {
}
}
- // MARK: - Bookmark Creation
-
- /// Creates a security-scoped bookmark from a path that was obtained from a file picker.
- /// This must be called while the app still has access (during the same session as the picker).
+ // Must run while picker access is still active.
private func handleCreateBookmarkFromPath(call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let args = call.arguments as? [String: Any],
let path = args["path"] as? String else {
@@ -71,8 +68,6 @@ public class DirUtilsPlugin: NSObject, FlutterPlugin {
}
}
- // MARK: - Security-Scoped Access
-
private func handleStartAccess(call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let args = call.arguments as? [String: Any],
let base64Bookmark = args["bookmark"] as? String,
@@ -138,8 +133,6 @@ public class DirUtilsPlugin: NSObject, FlutterPlugin {
}
}
- // MARK: - File Operations
-
private func handleWriteFile(call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let args = call.arguments as? [String: Any],
let path = args["path"] as? String,
diff --git a/mobile/packages/strings/lib/ente_strings.dart b/mobile/packages/strings/lib/ente_strings.dart
index 179b6333dd..8156897ced 100644
--- a/mobile/packages/strings/lib/ente_strings.dart
+++ b/mobile/packages/strings/lib/ente_strings.dart
@@ -1,8 +1,8 @@
export 'extensions.dart';
export 'l10n/strings_localizations.dart';
-/// Marks user-visible copy that should move to localized ARB after it settles.
+// User-visible copy that should move to localized ARB after it settles.
String pendingTranslation(String s) => s;
-/// Marks user-visible copy that intentionally should not be translated.
+// User-visible copy that intentionally should not be translated.
String untranslated(String s) => s;
diff --git a/mobile/packages/strings/lib/extensions.dart b/mobile/packages/strings/lib/extensions.dart
index e60e135535..91a31b4c03 100644
--- a/mobile/packages/strings/lib/extensions.dart
+++ b/mobile/packages/strings/lib/extensions.dart
@@ -1,11 +1,8 @@
import 'package:ente_strings/l10n/strings_localizations.dart';
import 'package:flutter/widgets.dart';
-// Re-export the localizations for convenience
export 'l10n/strings_localizations.dart';
-/// Extension to easily access shared strings from any BuildContext
extension EnteStringsExtension on BuildContext {
- /// Get the shared strings localizations for the current locale
StringsLocalizations get strings => StringsLocalizations.of(this);
}
diff --git a/mobile/packages/ui/lib/components/buttons/models/button_type.dart b/mobile/packages/ui/lib/components/buttons/models/button_type.dart
index a6cb8d95eb..595cefc710 100644
--- a/mobile/packages/ui/lib/components/buttons/models/button_type.dart
+++ b/mobile/packages/ui/lib/components/buttons/models/button_type.dart
@@ -50,7 +50,6 @@ enum ButtonType {
return Colors.transparent;
}
- //Returning null to fallback to default color
Color? pressedButtonColor(EnteColorScheme colorScheme) {
if (isPrimary) {
return colorScheme.primary700;
@@ -67,7 +66,6 @@ enum ButtonType {
return null;
}
- //Returning null to fallback to default color
Color? disabledButtonColor(
EnteColorScheme colorScheme,
ButtonSize buttonSize,
@@ -91,7 +89,6 @@ enum ButtonType {
return Colors.transparent;
}
- //Returning null to fallback to default color
Color? pressedBorderColor({
required EnteColorScheme colorScheme,
required ButtonSize buttonSize,
@@ -102,7 +99,6 @@ enum ButtonType {
return null;
}
- //Returning null to fallback to default color
Color? disabledBorderColor(
EnteColorScheme colorScheme,
ButtonSize buttonSize,
@@ -126,11 +122,9 @@ enum ButtonType {
if (this == ButtonType.tertiaryCritical) {
return colorScheme.warning500;
}
- //fallback
return colorScheme.strokeBase;
}
- //Returning null to fallback to default color
Color? pressedIconColor(EnteColorScheme colorScheme, ButtonSize buttonSize) {
if (this == ButtonType.tertiaryCritical) {
return colorScheme.warning700;
@@ -141,7 +135,6 @@ enum ButtonType {
return null;
}
- //Returning null to fallback to default color
Color? disabledIconColor(EnteColorScheme colorScheme, ButtonSize buttonSize) {
if (isPrimary ||
isSecondary ||
@@ -168,11 +161,9 @@ enum ButtonType {
if (this == ButtonType.tertiaryCritical) {
return textTheme.bodyBold.copyWith(color: warning500);
}
- //fallback
return textTheme.bodyBold;
}
- //Returning null to fallback to default color
TextStyle? pressedLabelStyle(
EnteTextTheme textTheme,
EnteColorScheme colorScheme,
@@ -187,7 +178,6 @@ enum ButtonType {
return null;
}
- //Returning null to fallback to default color
TextStyle? disabledLabelStyle(
EnteTextTheme textTheme,
EnteColorScheme colorScheme,
@@ -195,7 +185,6 @@ enum ButtonType {
return textTheme.bodyBold.copyWith(color: colorScheme.textFaint);
}
- //Returning null to fallback to default color
Color? checkIconColor(EnteColorScheme colorScheme) {
if (isSecondary) {
return colorScheme.primary500;
diff --git a/mobile/packages/ui/lib/components/menu_item_child_widgets.dart b/mobile/packages/ui/lib/components/menu_item_child_widgets.dart
index d90a3468ce..24bb90c499 100644
--- a/mobile/packages/ui/lib/components/menu_item_child_widgets.dart
+++ b/mobile/packages/ui/lib/components/menu_item_child_widgets.dart
@@ -128,7 +128,6 @@ class LeadingWidget extends StatelessWidget {
final Color? leadingIconColor;
final Widget? leadingIconWidget;
- // leadIconSize deafult value is 20.
final double leadingIconSize;
const LeadingWidget({
super.key,
diff --git a/mobile/packages/ui/lib/components/menu_item_widget_v2.dart b/mobile/packages/ui/lib/components/menu_item_widget_v2.dart
index 513cef6bdc..2bcb4e85eb 100644
--- a/mobile/packages/ui/lib/components/menu_item_widget_v2.dart
+++ b/mobile/packages/ui/lib/components/menu_item_widget_v2.dart
@@ -15,7 +15,6 @@ class MenuItemWidgetV2 extends StatefulWidget {
final Widget? leadingIconWidget;
- // leadIconSize deafult value is 24.
final double leadingIconSize;
final IconData? trailingIcon;
@@ -30,10 +29,6 @@ class MenuItemWidgetV2 extends StatefulWidget {
final Color? menuItemColor;
final bool alignCaptionedTextToLeft;
- // singleBorderRadius is applied to the border when it's a standalone menu item.
- // Widget will apply singleBorderRadius if value of both isTopBorderRadiusRemoved
- // and isBottomBorderRadiusRemoved is false. Otherwise, multipleBorderRadius will
- // be applied
final double singleBorderRadius;
final double multipleBorderRadius;
final Color? pressedColor;
@@ -309,7 +304,6 @@ class LeadingWidgetV2 extends StatelessWidget {
final Color? leadingIconColor;
final Widget? leadingIconWidget;
- // leadIconSize deafult value is 24.
final double leadingIconSize;
const LeadingWidgetV2({
super.key,
diff --git a/mobile/packages/ui/lib/components/progress_dialog.dart b/mobile/packages/ui/lib/components/progress_dialog.dart
index df46084147..37e72c9e02 100644
--- a/mobile/packages/ui/lib/components/progress_dialog.dart
+++ b/mobile/packages/ui/lib/components/progress_dialog.dart
@@ -268,7 +268,6 @@ class _BodyState extends State<_Body> {
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
- // row body
Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
diff --git a/mobile/packages/ui/lib/components/separators.dart b/mobile/packages/ui/lib/components/separators.dart
index bc4b1346ad..791edba8f7 100644
--- a/mobile/packages/ui/lib/components/separators.dart
+++ b/mobile/packages/ui/lib/components/separators.dart
@@ -1,5 +1,3 @@
-//This method returns a newly declared list with separators. It will not
-//modify the original list
import 'package:flutter/widgets.dart';
List<Widget> addSeparators(List<Widget> listOfWidgets, Widget separator) {
diff --git a/mobile/packages/ui/lib/theme/colors.dart b/mobile/packages/ui/lib/theme/colors.dart
index 5a01b75e7a..e772c46635 100644
--- a/mobile/packages/ui/lib/theme/colors.dart
+++ b/mobile/packages/ui/lib/theme/colors.dart
@@ -58,29 +58,24 @@ class EnteColorScheme extends ThemeExtension<EnteColorScheme> {
);
}
- // Background Colors
final Color backgroundBase;
final Color backgroundElevated;
final Color backgroundElevated2;
- // Backdrop Colors
final Color backdropBase;
final Color backdropBaseMute;
final Color backdropFaint;
- // Text Colors
final Color textBase;
final Color textMuted;
final Color textFaint;
- // Fill Colors
final Color fillBase;
final Color fillBasePressed;
final Color fillMuted;
final Color fillFaint;
final Color fillFaintPressed;
- // Stroke Colors
final Color strokeBase;
final Color strokeMuted;
final Color strokeFaint;
@@ -89,7 +84,6 @@ class EnteColorScheme extends ThemeExtension<EnteColorScheme> {
final Color blurStrokeFaint;
final Color blurStrokePressed;
- // Fixed Colors
final Color primary700;
final Color primary500;
final Color primary400;
@@ -104,11 +98,9 @@ class EnteColorScheme extends ThemeExtension<EnteColorScheme> {
final Color caution500;
- // Gradient Button
final Color gradientButtonBgColor;
final List<Color> gradientButtonBgColors;
- // Additional colors from ente_theme_data
final Color fabForegroundColor;
final Color fabBackgroundColor;
final Color boxSelectColor;
@@ -143,10 +135,8 @@ class EnteColorScheme extends ThemeExtension<EnteColorScheme> {
final Color primaryColor;
final Color surface;
- //other colors
final List<Color> avatarColors;
- //golden colors
final Color golden700;
final Color golden500;
@@ -601,7 +591,6 @@ const EnteColorScheme darkScheme = EnteColorScheme(
avatarDark,
);
-// Background Colors
const Color backgroundBaseLight = Color.fromRGBO(250, 250, 250, 1);
const Color backgroundElevatedLight = Color.fromRGBO(0, 0, 0, 0.04);
const Color backgroundElevated2Light = Color.fromRGBO(250, 250, 250, 1);
@@ -610,7 +599,6 @@ const Color backgroundBaseDark = Color.fromRGBO(0, 0, 0, 1);
const Color backgroundElevatedDark = Color.fromRGBO(255, 255, 255, 0.04);
const Color backgroundElevated2Dark = Color.fromRGBO(26, 26, 26, 1);
-// Backdrop Colors
const Color backdropBaseLight = Color.fromRGBO(255, 255, 255, 0.92);
const Color backdropMutedLight = Color.fromRGBO(255, 255, 255, 0.75);
const Color backdropFaintLight = Color.fromRGBO(255, 255, 255, 0.30);
@@ -619,7 +607,6 @@ const Color backdropBaseDark = Color.fromRGBO(33, 33, 33, 1);
const Color backdropMutedDark = Color.fromRGBO(0, 0, 0, 0.65);
const Color backdropFaintDark = Color.fromRGBO(0, 0, 0, 0.20);
-// Text Colors
const Color textBaseLight = Color.fromRGBO(0, 0, 0, 1);
const Color textMutedLight = Color.fromRGBO(0, 0, 0, 0.6);
const Color textFaintLight = Color.fromRGBO(0, 0, 0, 0.5);
@@ -628,7 +615,6 @@ const Color textBaseDark = Color.fromRGBO(255, 255, 255, 1);
const Color textMutedDark = Color.fromRGBO(255, 255, 255, 0.7);
const Color textFaintDark = Color.fromRGBO(255, 255, 255, 0.5);
-// Fill Colors
const Color fillBaseLight = Color.fromRGBO(0, 0, 0, 1);
const Color fillBasePressedLight = Color.fromRGBO(0, 0, 0, 0.87);
const Color fillMutedLight = Color.fromRGBO(0, 0, 0, 0.12);
@@ -641,7 +627,6 @@ const Color fillMutedDark = Color.fromRGBO(255, 255, 255, 0.16);
const Color fillFaintDark = Color.fromRGBO(255, 255, 255, 0.12);
const Color fillFaintPressedDark = Color.fromRGBO(255, 255, 255, 0.06);
-// Stroke Colors
const Color strokeBaseLight = Color.fromRGBO(0, 0, 0, 1);
const Color strokeMutedLight = Color.fromRGBO(0, 0, 0, 0.24);
const Color strokeFaintLight = Color.fromRGBO(0, 0, 0, 0.04);
@@ -658,23 +643,19 @@ const Color blurStrokeBaseDark = Color.fromRGBO(255, 255, 255, 0.90);
const Color blurStrokeFaintDark = Color.fromRGBO(255, 255, 255, 0.06);
const Color blurStrokePressedDark = Color.fromRGBO(255, 255, 255, 0.50);
-// Default Primary Colors
const Color _defaultPrimary700 = Color.fromRGBO(0, 122, 255, 1);
const Color _defaultPrimary500 = Color.fromRGBO(52, 152, 255, 1);
const Color _defaultPrimary400 = Color.fromRGBO(102, 178, 255, 1);
const Color _defaultPrimary300 = Color.fromRGBO(153, 204, 255, 1);
-// Default Gradient Colors
const Color _defaultGradientButtonBgColor = Color.fromRGBO(0, 122, 255, 1);
const List<Color> _defaultGradientButtonBgColors = [
Color.fromRGBO(0, 122, 255, 1),
Color.fromRGBO(52, 152, 255, 1),
];
-// Default Icon Button Color
const Color _defaultIconButtonColor = Color.fromRGBO(0, 122, 255, 1);
-// Warning Colors
const Color _warning700 = Color.fromRGBO(245, 52, 52, 1);
const Color _warning500 = Color.fromRGBO(255, 101, 101, 1);
const Color _warning800 = Color(0xFFF53434);
@@ -682,31 +663,23 @@ const Color warning500 = Color.fromRGBO(255, 101, 101, 1);
// ignore: unused_element
const Color _warning400 = Color.fromRGBO(255, 111, 111, 1);
-// Caution Colors
const Color _caution500 = Color.fromRGBO(255, 194, 71, 1);
-// Additional default colors from ente_theme_data
const Color _defaultPrimaryColor = Color(0xFF9610D6);
-// FAB Colors - based on brightness-dependent logic from ente_theme_data
const Color _defaultFabForegroundColor = Color.fromRGBO(255, 255, 255, 1);
const Color _defaultFabBackgroundColor = Color.fromRGBO(40, 40, 40, 1);
-// Box selection colors
const Color _defaultBoxSelectColor = Color.fromRGBO(67, 186, 108, 1);
const Color _defaultBoxUnSelectColor = Color.fromRGBO(240, 240, 240, 1);
-// Alternative color
const Color _defaultAlternativeColor = Color.fromARGB(255, 152, 77, 244);
-// Dynamic FAB colors
const Color _defaultDynamicFABBackgroundColor = Color.fromRGBO(0, 0, 0, 1);
const Color _defaultDynamicFABTextColor = Color.fromRGBO(255, 255, 255, 1);
-// Recovery key box color
const Color _defaultRecoveryKeyBoxColor = Color.fromARGB(51, 150, 0, 220);
-// Frosty blur backdrop filter color
const Color _defaultFrostyBlurBackdropFilterColor = Color.fromRGBO(
238,
238,
@@ -714,16 +687,12 @@ const Color _defaultFrostyBlurBackdropFilterColor = Color.fromRGBO(
0.5,
);
-// Default Icon Color
const Color _defaultIconColor = Color.fromRGBO(0, 0, 0, 0.75);
-// Default Background Color For Questions
const Color _defaultBgColorForQuestions = Color.fromRGBO(255, 255, 255, 1);
-// Default Green Text Color
const Color _defaultGreenText = Color.fromARGB(255, 40, 190, 113);
-// Default Cupertino Picker Top Color
const Color _defaultCupertinoPickerTopColor = Color.fromARGB(
255,
238,
@@ -731,7 +700,6 @@ const Color _defaultCupertinoPickerTopColor = Color.fromARGB(
238,
);
-// Default Step Progress Unselected Color
const Color _defaultStepProgressUnselectedColor = Color.fromRGBO(
196,
196,
@@ -739,13 +707,11 @@ const Color _defaultStepProgressUnselectedColor = Color.fromRGBO(
0.6,
);
-// Default Navigation Colors
const Color _defaultGNavBackgroundColor = Color.fromRGBO(196, 196, 196, 0.6);
const Color _defaultGNavBarActiveColor = Color.fromRGBO(255, 255, 255, 0.6);
const Color _defaultGNavIconColor = Color.fromRGBO(0, 0, 0, 0.8);
const Color _defaultGNavActiveIconColor = Color.fromRGBO(0, 0, 0, 0.8);
-// Default Gallery Thumb Colors
const Color _defaultGalleryThumbBackgroundColor = Color.fromRGBO(
240,
240,
@@ -754,24 +720,18 @@ const Color _defaultGalleryThumbBackgroundColor = Color.fromRGBO(
);
const Color _defaultGalleryThumbDrawColor = Color.fromRGBO(0, 0, 0, 0.8);
-// Default Backup Enabled Background Color
const Color _defaultBackupEnabledBgColor = Color.fromRGBO(230, 230, 230, 0.95);
-// Default Dots Indicator Colors
const Color _defaultDotsIndicatorActiveColor = Color.fromRGBO(0, 0, 0, 0.5);
const Color _defaultDotsIndicatorInactiveColor = Color.fromRGBO(0, 0, 0, 0.12);
-// Default Toast Colors
const Color _defaultToastTextColor = Color.fromRGBO(255, 255, 255, 1);
const Color _defaultToastBackgroundColor = Color.fromRGBO(24, 24, 24, 0.95);
-// Default Sub Text Color
const Color _defaultSubTextColor = Color.fromRGBO(180, 180, 180, 1);
-// Default Theme Switch Inactive Icon Color
const Color _defaultThemeSwitchInactiveIconColor = Color.fromRGBO(0, 0, 0, 0.5);
-// Default Search Results Colors
const Color _defaultSearchResultsColor = Color.fromRGBO(245, 245, 245, 1.0);
const Color _defaultMutedTextColor = Color.fromRGBO(80, 80, 80, 1);
const Color _defaultSearchResultsBackgroundColor = Color.fromRGBO(
@@ -781,7 +741,6 @@ const Color _defaultSearchResultsBackgroundColor = Color.fromRGBO(
0.32,
);
-// Default Code Card Background Color
const Color _defaultCodeCardBackgroundColor = Color.fromRGBO(246, 246, 246, 1);
const Color _golden700 = Color(0xFFFDB816);
@@ -791,7 +750,6 @@ class ColorSchemeBuilder {
static ({EnteColorScheme light, EnteColorScheme dark}) fromPrimaryColor(
Color primaryColor,
) {
- // Calculate different shades of the primary color
final HSLColor hsl = HSLColor.fromColor(primaryColor);
final primary700 = hsl
@@ -805,7 +763,6 @@ class ColorSchemeBuilder {
.withLightness((hsl.lightness + 0.2).clamp(0.0, 1.0))
.toColor();
- // Create gradient colors from the primary color
final gradientColors = [primary700, primary500];
final lightScheme = EnteColorScheme.light(
diff --git a/mobile/packages/ui/lib/theme/ente_theme_data.dart b/mobile/packages/ui/lib/theme/ente_theme_data.dart
index 5ff8ef2754..21ff26bc13 100644
--- a/mobile/packages/ui/lib/theme/ente_theme_data.dart
+++ b/mobile/packages/ui/lib/theme/ente_theme_data.dart
@@ -33,7 +33,6 @@ final lightThemeData = ThemeData(
iconTheme: const IconThemeData(color: Colors.black),
elevation: 0,
),
- //https://api.flutter.dev/flutter/material/TextTheme-class.html
textTheme: _buildTextTheme(const Color.fromRGBO(0, 0, 0, 1)),
primaryTextTheme: const TextTheme().copyWith(
bodyMedium: const TextStyle(color: Colors.yellow),
@@ -496,7 +495,6 @@ ElevatedButtonThemeData buildElevatedButtonThemeData({
);
}
-// Helper function to create ThemeData that works with the new color system
ThemeData createAppThemeData({
required Brightness brightness,
EnteColorScheme? colorScheme,
@@ -509,7 +507,6 @@ ThemeData createAppThemeData({
? lightThemeData
: darkThemeData;
- // Create platform-specific typography to ensure consistent font sizes
final typography = Typography.material2021(
platform:
TargetPlatform.android, // Force Android typography for consistency
diff --git a/mobile/packages/ui/lib/theme/multi_app_demo.dart b/mobile/packages/ui/lib/theme/multi_app_demo.dart
index d9e3846563..8d839e378e 100644
--- a/mobile/packages/ui/lib/theme/multi_app_demo.dart
+++ b/mobile/packages/ui/lib/theme/multi_app_demo.dart
@@ -1,6 +1,3 @@
-// Demo: Complete working example showing multi-app theme compatibility
-// This file demonstrates how the reusable theme system works for different apps
-
import 'package:ente_ui/theme/colors.dart';
import 'package:ente_ui/theme/ente_theme.dart';
import 'package:ente_ui/theme/ente_theme_data.dart';
@@ -189,7 +186,6 @@ class DemoHomePage extends StatelessWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- // App Selector
Text(
'Switch App Theme:',
style: TextStyle(
@@ -221,7 +217,6 @@ class DemoHomePage extends StatelessWidget {
),
const SizedBox(height: 32),
- // UI Components Demo
Text(
'UI Components:',
style: TextStyle(
@@ -232,7 +227,6 @@ class DemoHomePage extends StatelessWidget {
),
const SizedBox(height: 16),
- // Background colors demo
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
@@ -265,7 +259,6 @@ class DemoHomePage extends StatelessWidget {
),
const SizedBox(height: 16),
- // Buttons demo
Row(
children: [
Expanded(
@@ -294,7 +287,6 @@ class DemoHomePage extends StatelessWidget {
),
const SizedBox(height: 16),
- // Gradient button demo
Container(
width: double.infinity,
height: 48,
@@ -319,7 +311,6 @@ class DemoHomePage extends StatelessWidget {
),
const SizedBox(height: 16),
- // Warning demo
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
@@ -342,7 +333,6 @@ class DemoHomePage extends StatelessWidget {
),
const SizedBox(height: 32),
- // Color palette display
Text(
'Color Palette:',
style: TextStyle(
@@ -410,7 +400,6 @@ class DemoHomePage extends StatelessWidget {
}
}
-// Example of how to use this in main.dart:
void main() {
runApp(const MultiAppThemeDemo());
}
diff --git a/mobile/packages/ui/lib/theme/text_style.dart b/mobile/packages/ui/lib/theme/text_style.dart
index f8b8caad7b..5a8ae31af6 100644
--- a/mobile/packages/ui/lib/theme/text_style.dart
+++ b/mobile/packages/ui/lib/theme/text_style.dart
@@ -87,7 +87,6 @@ class EnteTextTheme {
final TextStyle brandSmall;
final TextStyle brandMedium;
- // textMuted variants
final TextStyle h1Muted;
final TextStyle h2Muted;
final TextStyle h3Muted;
@@ -98,7 +97,6 @@ class EnteTextTheme {
final TextStyle miniBoldMuted;
final TextStyle tinyMuted;
- // textFaint variants
final TextStyle h1Faint;
final TextStyle h2Faint;
final TextStyle h3Faint;
diff --git a/mobile/packages/ui/lib/utils/file_icon_utils.dart b/mobile/packages/ui/lib/utils/file_icon_utils.dart
index bc1f238200..9f3166a863 100644
--- a/mobile/packages/ui/lib/utils/file_icon_utils.dart
+++ b/mobile/packages/ui/lib/utils/file_icon_utils.dart
@@ -13,7 +13,6 @@ class FileIconConfig {
}
class FileIconUtils {
- // Centralized configuration - change icons and colors here only
static const Map<String, FileIconConfig> _fileTypeConfigs = {
'pdf': FileIconConfig(
extensions: {'.pdf'},