Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mob][photos] add internal contact editing flow

Neeraj Gupta19af49f58aaf
diff --git a/mobile/apps/photos/lib/emergency/emergency_page.dart b/mobile/apps/photos/lib/emergency/emergency_page.dart
index 0223f4bb1e..b03531e487 100644
--- a/mobile/apps/photos/lib/emergency/emergency_page.dart
+++ b/mobile/apps/photos/lib/emergency/emergency_page.dart
@@ -11,6 +11,7 @@ import "package:photos/emergency/other_contact_page.dart";
import "package:photos/emergency/select_contact_page.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/l10n/l10n.dart";
+import "package:photos/services/contacts/contact_identity_resolver.dart";
import "package:photos/theme/ente_theme.dart";
import "package:photos/ui/common/loading_widget.dart";
import "package:photos/ui/components/alert_bottom_sheet.dart";
@@ -116,15 +117,16 @@ class _EmergencyPageState extends State<EmergencyPage> {
final recoverSession = info!.recoverSessions[listIndex];
final isLastItem =
listIndex == info!.recoverSessions.length - 1;
+ final emergencyUser = recoverSession.emergencyContact;
return _buildGroupedMenuItem(
listIndex: listIndex,
isLastItem: isLastItem,
child: MenuItemWidgetNew(
- title: recoverSession.emergencyContact.email,
+ title: resolveDisplayName(emergencyUser),
titleColor: colorScheme.warning500,
leadingIconSize: 24,
leadingIconWidget: UserAvatarWidget(
- recoverSession.emergencyContact,
+ emergencyUser,
type: AvatarType.md,
currentUserID: currentUserID,
),
@@ -164,17 +166,18 @@ class _EmergencyPageState extends State<EmergencyPage> {
final contact = trustedContacts[listIndex];
final isLastItem =
listIndex == trustedContacts.length - 1;
+ final emergencyUser = contact.emergencyContact;
return _buildGroupedMenuItem(
listIndex: listIndex,
isLastItem: isLastItem,
child: MenuItemWidgetNew(
- title: contact.emergencyContact.email,
+ title: resolveDisplayName(emergencyUser),
titleColor: contact.isPendingInvite()
? colorScheme.warning500
: textTheme.small.color,
leadingIconSize: 24,
leadingIconWidget: UserAvatarWidget(
- contact.emergencyContact,
+ emergencyUser,
type: AvatarType.md,
currentUserID: currentUserID,
),
@@ -273,17 +276,18 @@ class _EmergencyPageState extends State<EmergencyPage> {
final listIndex = index - 1;
final currentUser = othersTrustedContacts[listIndex];
final isLastItem = index == othersTrustedContacts.length;
+ final emergencyUser = currentUser.user;
return _buildGroupedMenuItem(
listIndex: listIndex,
isLastItem: isLastItem,
child: MenuItemWidgetNew(
- title: currentUser.user.email,
+ title: resolveDisplayName(emergencyUser),
titleColor: currentUser.isPendingInvite()
? colorScheme.warning500
: textTheme.small.color,
leadingIconSize: 24,
leadingIconWidget: UserAvatarWidget(
- currentUser.user,
+ emergencyUser,
type: AvatarType.md,
currentUserID: currentUserID,
),
diff --git a/mobile/apps/photos/lib/emergency/select_contact_page.dart b/mobile/apps/photos/lib/emergency/select_contact_page.dart
index 0528cce427..701702b104 100644
--- a/mobile/apps/photos/lib/emergency/select_contact_page.dart
+++ b/mobile/apps/photos/lib/emergency/select_contact_page.dart
@@ -10,6 +10,7 @@ import "package:photos/l10n/l10n.dart";
import "package:photos/models/api/collection/user.dart";
import "package:photos/services/account/user_service.dart";
import 'package:photos/services/collections_service.dart';
+import "package:photos/services/contacts/contact_identity_resolver.dart";
import 'package:photos/theme/ente_theme.dart';
import "package:photos/ui/components/alert_bottom_sheet.dart";
import "package:photos/ui/components/base_bottom_sheet.dart";
@@ -124,7 +125,7 @@ class _AddContactSheetState extends State<AddContactSheet> {
listIndex: index,
isLastItem: isLastItem,
child: MenuItemWidgetNew(
- title: user.email,
+ title: resolveDisplayName(user),
titleColor: colorScheme.textMuted,
leadingIconWidget: UserAvatarWidget(
user,
diff --git a/mobile/apps/photos/lib/events/contacts_changed_event.dart b/mobile/apps/photos/lib/events/contacts_changed_event.dart
new file mode 100644
index 0000000000..ae1e60a2b5
--- /dev/null
+++ b/mobile/apps/photos/lib/events/contacts_changed_event.dart
@@ -0,0 +1,16 @@
+import 'package:photos/events/event.dart';
+
+class ContactsChangedEvent extends Event {
+ final Set<int>? contactUserIds;
+
+ ContactsChangedEvent({
+ this.contactUserIds,
+ });
+
+ bool matchesContactUserId(int? userId) {
+ if (userId == null) {
+ return false;
+ }
+ return contactUserIds == null ? true : contactUserIds!.contains(userId);
+ }
+}
diff --git a/mobile/apps/photos/lib/main.dart b/mobile/apps/photos/lib/main.dart
index f8c35d8198..63d224c961 100644
--- a/mobile/apps/photos/lib/main.dart
+++ b/mobile/apps/photos/lib/main.dart
@@ -5,6 +5,7 @@ import "package:adaptive_theme/adaptive_theme.dart";
import "package:computer/computer.dart";
import 'package:ente_crypto/ente_crypto.dart';
import "package:ente_pure_utils/ente_pure_utils.dart";
+import "package:ente_rust/ente_rust.dart";
import "package:ffmpeg_kit_flutter/ffmpeg_kit_config.dart";
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
@@ -39,6 +40,7 @@ import 'package:photos/services/machine_learning/semantic_search/semantic_search
import 'package:photos/services/memory_lane/memory_lane_service.dart';
import 'package:photos/services/memory_share_service.dart';
import "package:photos/services/notification_service.dart";
+import "package:photos/services/photos_contacts_service.dart";
import 'package:photos/services/push_service.dart';
import 'package:photos/services/search_service.dart';
import 'package:photos/services/social_notification_coordinator.dart';
@@ -383,6 +385,9 @@ Future<void> _init(bool isBackground, {String via = ''}) async {
unawaited(MLService.instance.init());
PersonService.init(entityService, MLDataDB.instance, preferences);
await PersonService.instance.refreshPersonCache();
+ if (!isBackground && flagService.internalUser) {
+ unawaited(_warmContactsCacheInBackground());
+ }
EnteWakeLockService.instance.init(preferences);
wrappedService.scheduleInitialLoad();
logLocalSettings();
@@ -395,6 +400,14 @@ Future<void> _init(bool isBackground, {String via = ''}) async {
}
}
+Future<void> _warmContactsCacheInBackground() async {
+ try {
+ await PhotosContactsService.instance.ensureReady();
+ } catch (e, s) {
+ _logger.warning("Deferred contacts warm-up failed", e, s);
+ }
+}
+
Future<void> _ensureRustInitialized({required String via}) async {
if (_isRustInitialized) {
return;
@@ -405,8 +418,10 @@ Future<void> _ensureRustInitialized({required String via}) async {
return;
}
- _logger.info("Initializing Rust bridge via $via");
- final initFuture = EntePhotosRust.init();
+ final initFuture = Future.wait([
+ EntePhotosRust.init(),
+ EnteRust.init(),
+ ]);
_rustInitFuture = initFuture;
try {
await initFuture;
diff --git a/mobile/apps/photos/lib/models/search/hierarchical/contacts_filter.dart b/mobile/apps/photos/lib/models/search/hierarchical/contacts_filter.dart
index 5e7d72e471..01f34a63bc 100644
--- a/mobile/apps/photos/lib/models/search/hierarchical/contacts_filter.dart
+++ b/mobile/apps/photos/lib/models/search/hierarchical/contacts_filter.dart
@@ -1,8 +1,8 @@
import "package:flutter/material.dart";
-import "package:photos/extensions/user_extension.dart";
import "package:photos/models/api/collection/user.dart";
import "package:photos/models/file/file.dart";
import "package:photos/models/search/hierarchical/hierarchical_search_filter.dart";
+import "package:photos/services/contacts/contact_identity_resolver.dart";
class ContactsFilter extends HierarchicalSearchFilter {
final User user;
@@ -17,11 +17,7 @@ class ContactsFilter extends HierarchicalSearchFilter {
@override
String name() {
- final name = user.displayName;
- if (name == null || name.isEmpty) {
- return user.email;
- }
- return name;
+ return resolveDisplayName(user);
}
@override
diff --git a/mobile/apps/photos/lib/models/search/search_constants.dart b/mobile/apps/photos/lib/models/search/search_constants.dart
index c5d64a2645..d6de4ee3d2 100644
--- a/mobile/apps/photos/lib/models/search/search_constants.dart
+++ b/mobile/apps/photos/lib/models/search/search_constants.dart
@@ -3,5 +3,6 @@ const kPersonWidgetKey = 'person_widget_key';
const kPersonPinned = 'person_pinned';
const kClusterParamId = 'cluster_id';
const kFileID = 'file_id';
+const kContactUserId = 'contact_user_id';
const kContactEmail = 'contact_email';
const kContactCollections = 'contact_collections';
diff --git a/mobile/apps/photos/lib/models/search/search_types.dart b/mobile/apps/photos/lib/models/search/search_types.dart
index 4f48bbc1ef..56a69ddc9d 100644
--- a/mobile/apps/photos/lib/models/search/search_types.dart
+++ b/mobile/apps/photos/lib/models/search/search_types.dart
@@ -5,6 +5,7 @@ import "package:flutter/material.dart";
import "package:logging/logging.dart";
import "package:photos/core/event_bus.dart";
import "package:photos/events/collection_updated_event.dart";
+import "package:photos/events/contacts_changed_event.dart";
import "package:photos/events/event.dart";
import "package:photos/events/location_tag_updated_event.dart";
import "package:photos/events/magic_cache_updated_event.dart";
@@ -292,7 +293,10 @@ extension SectionTypeExtensions on SectionType {
case SectionType.face:
return [Bus.instance.on<PeopleChangedEvent>()];
case SectionType.contacts:
- return [Bus.instance.on<PeopleChangedEvent>()];
+ return [
+ Bus.instance.on<PeopleChangedEvent>(),
+ Bus.instance.on<ContactsChangedEvent>(),
+ ];
default:
return [];
}
@@ -311,7 +315,10 @@ extension SectionTypeExtensions on SectionType {
case SectionType.ritual:
return [];
case SectionType.contacts:
- return [Bus.instance.on<PeopleChangedEvent>()];
+ return [
+ Bus.instance.on<PeopleChangedEvent>(),
+ Bus.instance.on<ContactsChangedEvent>(),
+ ];
default:
return [];
}
diff --git a/mobile/apps/photos/lib/services/contacts/contact_identity_resolver.dart b/mobile/apps/photos/lib/services/contacts/contact_identity_resolver.dart
new file mode 100644
index 0000000000..62b013094e
--- /dev/null
+++ b/mobile/apps/photos/lib/services/contacts/contact_identity_resolver.dart
@@ -0,0 +1,58 @@
+import "package:photos/extensions/user_extension.dart";
+import "package:photos/models/api/collection/user.dart";
+import "package:photos/service_locator.dart" show flagService;
+import "package:photos/services/photos_contacts_service.dart";
+
+String resolveDisplayName(User user) {
+ final savedName = _savedContactName(user);
+ if (savedName != null) {
+ return savedName;
+ }
+
+ final personName = user.displayName?.trim();
+ if (personName != null && personName.isNotEmpty) {
+ return personName;
+ }
+
+ return resolveKnownEmail(user) ?? "Someone";
+}
+
+String? resolveKnownEmail(User user) {
+ if (flagService.internalUser && user.id != null && user.id! > 0) {
+ final savedEmail = _knownEmailOrNull(
+ PhotosContactsService.instance.getCachedResolvedEmailByUserId(user.id),
+ );
+ if (savedEmail != null) {
+ return savedEmail;
+ }
+ }
+
+ return _knownEmailOrNull(user.email);
+}
+
+String? _savedContactName(User user) {
+ if (!flagService.internalUser || user.id == null || user.id! <= 0) {
+ return null;
+ }
+
+ final savedName = PhotosContactsService.instance
+ .getCachedSavedNameByUserId(user.id)
+ ?.trim();
+ if (savedName == null || savedName.isEmpty) {
+ return null;
+ }
+ return savedName;
+}
+
+String? _knownEmailOrNull(String? email) {
+ if (email == null) {
+ return null;
+ }
+
+ final trimmed = email.trim();
+ if (trimmed.isEmpty || trimmed == "[email protected]") {
+ return null;
+ }
+
+ return trimmed.endsWith("@unknown.com") ? null : trimmed;
+}
diff --git a/mobile/apps/photos/lib/services/photos_contacts_service.dart b/mobile/apps/photos/lib/services/photos_contacts_service.dart
new file mode 100644
index 0000000000..45ef53cf95
--- /dev/null
+++ b/mobile/apps/photos/lib/services/photos_contacts_service.dart
@@ -0,0 +1,334 @@
+import "dart:typed_data";
+
+import "package:ente_contacts/contacts.dart" as contacts;
+import "package:logging/logging.dart";
+import "package:photos/core/configuration.dart";
+import "package:photos/core/event_bus.dart";
+import "package:photos/events/contacts_changed_event.dart";
+import "package:photos/service_locator.dart";
+
+class PhotosContactsService {
+ PhotosContactsService._privateConstructor()
+ : _contacts = contacts.ContactsService(
+ preferences: ServiceLocator.instance.prefs,
+ );
+
+ static final PhotosContactsService instance =
+ PhotosContactsService._privateConstructor();
+
+ final contacts.ContactsService _contacts;
+ final _logger = Logger("PhotosContactsService");
+ final Map<int, contacts.ContactRecord> _contactsByUserId = {};
+ final Map<int, Uint8List?> _profilePictureBytesByUserId = {};
+ final Set<int> _resolvedProfilePictureUserIds = {};
+ final Map<int, Future<Uint8List?>> _profilePictureLoadsByUserId = {};
+
+ Future<void>? _readyFuture;
+ String? _sessionKey;
+ String? _sessionAuthToken;
+ bool _hasHydratedCache = false;
+
+ bool get hasHydratedCache => _hasHydratedCache;
+
+ Future<void> ensureReady() async {
+ final config = Configuration.instance;
+ final authToken = config.getToken();
+ if (!flagService.internalUser) {
+ _resetSessionState(notify: true);
+ return;
+ }
+ final sessionKey = _buildSessionKey();
+ if (sessionKey == null) {
+ _resetSessionState(notify: true);
+ return;
+ }
+ if (_readyFuture != null && _sessionKey == sessionKey) {
+ await _readyFuture;
+ if (authToken != null && _sessionAuthToken != authToken) {
+ await _contacts.updateAuthToken(authToken);
+ _sessionAuthToken = authToken;
+ }
+ return;
+ }
+ if (_sessionKey != sessionKey) {
+ _resetSessionState(notify: true);
+ }
+ _sessionKey = sessionKey;
+ _sessionAuthToken = authToken;
+ late final Future<void> readyFuture;
+ readyFuture =
+ _openAndSync().catchError((Object error, StackTrace stackTrace) {
+ if (identical(_readyFuture, readyFuture)) {
+ _readyFuture = null;
+ }
+ throw error;
+ });
+ _readyFuture = readyFuture;
+ return readyFuture;
+ }
+
+ Future<contacts.ContactRecord?> getContactByUserId(int contactUserId) async {
+ final cached = getCachedContactByUserId(contactUserId);
+ if (cached != null) {
+ return cached;
+ }
+ return _runReadSafely(
+ () async {
+ await ensureReady();
+ final contact = await _contacts.getContactByUserId(contactUserId);
+ if (contact == null || contact.isDeleted) {
+ return null;
+ }
+ _cacheContact(contact);
+ return contact;
+ },
+ description: "load contact for user $contactUserId",
+ );
+ }
+
+ contacts.ContactRecord? getCachedContactByUserId(int? contactUserId) {
+ if (contactUserId == null) {
+ return null;
+ }
+ final contact = _contactsByUserId[contactUserId];
+ if (contact == null || contact.isDeleted) {
+ return null;
+ }
+ return contact;
+ }
+
+ String? getCachedSavedNameByUserId(int? contactUserId) {
+ return getCachedContactByUserId(contactUserId)?.data?.name;
+ }
+
+ String? getCachedResolvedEmailByUserId(int? contactUserId) {
+ return getCachedContactByUserId(contactUserId)?.email;
+ }
+
+ Uint8List? getCachedProfilePictureBytesByUserId(int? contactUserId) {
+ if (contactUserId == null ||
+ !_resolvedProfilePictureUserIds.contains(contactUserId)) {
+ return null;
+ }
+ return _profilePictureBytesByUserId[contactUserId];
+ }
+
+ bool hasResolvedProfilePictureByUserId(int? contactUserId) {
+ return contactUserId != null &&
+ _resolvedProfilePictureUserIds.contains(contactUserId);
+ }
+
+ Future<Uint8List?> getProfilePictureBytesByUserId(int? contactUserId) async {
+ if (contactUserId == null) {
+ return null;
+ }
+ if (_resolvedProfilePictureUserIds.contains(contactUserId)) {
+ return _profilePictureBytesByUserId[contactUserId];
+ }
+ final inflightLoad = _profilePictureLoadsByUserId[contactUserId];
+ if (inflightLoad != null) {
+ return inflightLoad;
+ }
+ final load = _loadProfilePictureBytesByUserId(contactUserId);
+ _profilePictureLoadsByUserId[contactUserId] = load;
+ return load.whenComplete(() {
+ _profilePictureLoadsByUserId.remove(contactUserId);
+ });
+ }
+
+ Future<Uint8List?> _loadProfilePictureBytesByUserId(int contactUserId) async {
+ final contact = await getContactByUserId(contactUserId);
+ final attachmentId = contact?.profilePictureAttachmentId;
+ if (contact == null || attachmentId == null) {
+ _profilePictureBytesByUserId.remove(contactUserId);
+ _resolvedProfilePictureUserIds.add(contactUserId);
+ return null;
+ }
+ final contactId = contact.id;
+ try {
+ final bytes = await _contacts.getProfilePicture(contactId);
+ final latestContact = _contactsByUserId[contactUserId];
+ if (latestContact == null ||
+ latestContact.isDeleted ||
+ latestContact.id != contactId ||
+ latestContact.profilePictureAttachmentId != attachmentId) {
+ return _profilePictureBytesByUserId[contactUserId];
+ }
+ _profilePictureBytesByUserId[contactUserId] = bytes;
+ _resolvedProfilePictureUserIds.add(contactUserId);
+ return bytes;
+ } catch (e, s) {
+ _logger.warning(
+ "Failed to load contact profile picture for user $contactUserId",
+ e,
+ s,
+ );
+ return null;
+ }
+ }
+
+ Future<contacts.ContactRecord> createOrUpdateContact({
+ required int contactUserId,
+ required String name,
+ String? birthDate,
+ }) async {
+ await ensureReady();
+ final trimmedName = name.trim();
+ final trimmedBirthDate = birthDate?.trim();
+ final normalizedBirthDate =
+ trimmedBirthDate == null || trimmedBirthDate.isEmpty
+ ? null
+ : trimmedBirthDate;
+ final existing = await _contacts.getContactByUserId(
+ contactUserId,
+ includeDeleted: true,
+ );
+ final data = contacts.ContactData(
+ contactUserId: contactUserId,
+ name: trimmedName,
+ birthDate: normalizedBirthDate,
+ );
+ final contact = existing == null
+ ? await _contacts.createContact(data)
+ : await _contacts.updateContact(existing.id, data);
+ _cacheContact(contact);
+ _notifyChanged(contact);
+ return contact;
+ }
+
+ Future<contacts.ContactRecord> setProfilePicture({
+ required String contactId,
+ required Uint8List bytes,
+ }) async {
+ await ensureReady();
+ final contact = await _contacts.setProfilePicture(contactId, bytes);
+ _cacheContact(contact);
+ _profilePictureBytesByUserId[contact.contactUserId] = bytes;
+ _resolvedProfilePictureUserIds.add(contact.contactUserId);
+ _notifyChanged(contact);
+ return contact;
+ }
+
+ String? _buildSessionKey() {
+ final config = Configuration.instance;
+ final userId = config.getUserID();
+ final accountKey = config.getKey();
+ if (config.getToken() == null || userId == null || accountKey == null) {
+ return null;
+ }
+ return "${config.getHttpEndpoint()}|$userId";
+ }
+
+ Future<void> _openAndSync() async {
+ final config = Configuration.instance;
+ final token = config.getToken();
+ final userId = config.getUserID();
+ final accountKey = config.getKey();
+ if (token == null || userId == null || accountKey == null) {
+ return;
+ }
+ final packageInfo = ServiceLocator.instance.packageInfo;
+ await _contacts.open(
+ contacts.ContactsSession(
+ baseUrl: config.getHttpEndpoint(),
+ authToken: token,
+ userId: userId,
+ accountKey: accountKey,
+ clientPackage: packageInfo.packageName,
+ clientVersion: packageInfo.version,
+ ),
+ );
+ final contactsDiff = await _contacts.sync();
+ for (final contact in contactsDiff) {
+ _invalidateProfilePictureCache(contact.contactUserId);
+ _cacheContact(contact);
+ }
+ final cachedUserIdsBeforeHydration = _contactsByUserId.keys.toSet();
+ final diffUserIds =
+ contactsDiff.map((contact) => contact.contactUserId).toSet();
+ final localContacts = await _hydrateCacheFromLocalDb();
+ _hasHydratedCache = true;
+ final newlyHydratedLocalUserIds = localContacts
+ .map((contact) => contact.contactUserId)
+ .where((userId) => !cachedUserIdsBeforeHydration.contains(userId))
+ .toSet();
+ final changedUserIds = {...diffUserIds, ...newlyHydratedLocalUserIds};
+ if (changedUserIds.isNotEmpty) {
+ _notifyContactsChanged(changedUserIds);
+ }
+ }
+
+ void _notifyChanged(contacts.ContactRecord contact) {
+ _notifyContactsChanged({contact.contactUserId});
+ }
+
+ void _notifyContactsChanged(Set<int>? contactUserIds) {
+ Bus.instance.fire(ContactsChangedEvent(contactUserIds: contactUserIds));
+ }
+
+ Future<T?> _runReadSafely<T>(
+ Future<T?> Function() task, {
+ required String description,
+ }) async {
+ try {
+ return await task();
+ } on StateError catch (e, s) {
+ if (_isRustInitializationError(e)) {
+ _logger.warning(
+ "Contacts integration unavailable while Rust bindings are not initialized during $description. Photos initializes EntePhotosRust in main.dart, but ente_contacts calls into package:ente_rust.",
+ e,
+ s,
+ );
+ return null;
+ }
+ rethrow;
+ } catch (e, s) {
+ _logger.warning("Failed to $description", e, s);
+ return null;
+ }
+ }
+
+ bool _isRustInitializationError(StateError error) {
+ return error.message
+ .contains("flutter_rust_bridge has not been initialized");
+ }
+
+ void _cacheContact(contacts.ContactRecord contact) {
+ final userId = contact.contactUserId;
+ if (contact.isDeleted) {
+ _contactsByUserId.remove(userId);
+ _invalidateProfilePictureCache(userId);
+ return;
+ }
+ _contactsByUserId[userId] = contact;
+ }
+
+ Future<List<contacts.ContactRecord>> _hydrateCacheFromLocalDb() async {
+ final localContacts = await _contacts.getContacts();
+ for (final contact in localContacts) {
+ _cacheContact(contact);
+ }
+ return localContacts;
+ }
+
+ void _resetSessionState({required bool notify}) {
+ final hadCachedContacts = _contactsByUserId.isNotEmpty;
+ _contactsByUserId.clear();
+ _profilePictureBytesByUserId.clear();
+ _resolvedProfilePictureUserIds.clear();
+ _profilePictureLoadsByUserId.clear();
+ _readyFuture = null;
+ _sessionKey = null;
+ _sessionAuthToken = null;
+ _hasHydratedCache = false;
+ if (notify && hadCachedContacts) {
+ _notifyContactsChanged(null);
+ }
+ }
+
+ void _invalidateProfilePictureCache(int contactUserId) {
+ _profilePictureBytesByUserId.remove(contactUserId);
+ _resolvedProfilePictureUserIds.remove(contactUserId);
+ _profilePictureLoadsByUserId.remove(contactUserId);
+ }
+}
diff --git a/mobile/apps/photos/lib/services/search_service.dart b/mobile/apps/photos/lib/services/search_service.dart
index 4c73e23ce4..a4d1e34459 100644
--- a/mobile/apps/photos/lib/services/search_service.dart
+++ b/mobile/apps/photos/lib/services/search_service.dart
@@ -50,12 +50,14 @@ import "package:photos/models/search/search_types.dart";
import "package:photos/service_locator.dart";
import "package:photos/services/account/user_service.dart";
import 'package:photos/services/collections_service.dart';
+import "package:photos/services/contacts/contact_identity_resolver.dart";
import "package:photos/services/date_parse_service.dart";
import "package:photos/services/filter/db_filters.dart";
import "package:photos/services/location_service.dart";
import "package:photos/services/machine_learning/face_ml/person/person_service.dart";
import 'package:photos/services/machine_learning/semantic_search/semantic_search_service.dart';
import "package:photos/services/memories_cache_service.dart";
+import "package:photos/services/photos_contacts_service.dart";
import "package:photos/states/location_screen_state.dart";
import "package:photos/ui/viewer/location/add_location_sheet.dart";
import "package:photos/ui/viewer/location/location_screen.dart";
@@ -101,6 +103,35 @@ class SearchService {
return CollectionsService.instance.getHiddenCollectionIds();
}
+ Map<String, dynamic> _contactSearchParams(
+ User user,
+ List<Collection> collections,
+ ) {
+ final params = <String, dynamic>{
+ kPersonParamID: user.linkedPersonID,
+ kContactUserId: user.id,
+ kContactEmail: resolveKnownEmail(user) ?? user.email,
+ kContactCollections: collections,
+ };
+ return params;
+ }
+
+ Future<void> _warmContactsCacheIfNeeded() async {
+ if (!flagService.internalUser ||
+ PhotosContactsService.instance.hasHydratedCache) {
+ return;
+ }
+ try {
+ await PhotosContactsService.instance.ensureReady();
+ } catch (e, s) {
+ _logger.warning(
+ "Failed to preload contacts cache; falling back to person/email results",
+ e,
+ s,
+ );
+ }
+ }
+
Future<List<EnteFile>> getAllFilesForSearch() async {
if (_cachedFilesFuture != null && _cachedFilesForSearch != null) {
return _cachedFilesForSearch!;
@@ -1634,6 +1665,7 @@ class SearchService {
if (isOfflineMode) {
return <GenericSearchResult>[];
}
+ await _warmContactsCacheIfNeeded();
final int ownerID = Configuration.instance.getUserID()!;
final lowerCaseQuery = query.toLowerCase();
final searchResults = <GenericSearchResult>[];
@@ -1664,11 +1696,12 @@ class SearchService {
}
}
- final relevantContactEmails =
- UserService.instance.getEmailIDsOfRelevantContacts();
+ final relevantContacts = UserService.instance.getRelevantContacts();
- for (final email in relevantContactEmails.difference(existingEmails)) {
- final user = User(email: email);
+ for (final user in relevantContacts) {
+ if (existingEmails.contains(user.email)) {
+ continue;
+ }
if (user.email.toLowerCase().contains(lowerCaseQuery) ||
((user.displayName?.toLowerCase().contains(lowerCaseQuery)) ??
false)) {
@@ -1688,30 +1721,27 @@ class SearchService {
}
}
- peopleToSharedFiles.forEach((key, value) {
- final user = key;
+ for (final entry in peopleToSharedFiles.entries) {
+ final user = entry.key;
+ final files = entry.value;
final collections = peopleToSharedAlbums[user.email] ?? [];
+ final name = resolveDisplayName(user);
+ final params = _contactSearchParams(user, collections);
searchResults.add(
GenericSearchResult(
ResultType.shared,
- key.displayName != null && key.displayName!.isNotEmpty
- ? key.displayName!
- : key.email,
- value,
+ name,
+ files,
hierarchicalSearchFilter: ContactsFilter(
- user: key,
+ user: user,
occurrence: kMostRelevantFilter,
- matchedUploadedIDs: filesToUploadedFileIDs(value),
+ matchedUploadedIDs: filesToUploadedFileIDs(files),
),
- params: {
- kPersonParamID: key.linkedPersonID,
- kContactEmail: key.email,
- kContactCollections: collections,
- },
+ params: params,
),
);
- });
+ }
return searchResults;
}
@@ -1720,6 +1750,7 @@ class SearchService {
int? limit,
) async {
try {
+ await _warmContactsCacheIfNeeded();
final int ownerID = Configuration.instance.getUserID()!;
final searchResults = <GenericSearchResult>[];
final allFiles = await getAllFilesForSearch();
@@ -1756,14 +1787,12 @@ class SearchService {
}
}
- final allRelevantEmails =
- UserService.instance.getEmailIDsOfRelevantContacts();
+ final allRelevantContacts = UserService.instance.getRelevantContacts();
- final emailsWithNoSharedFiles =
- allRelevantEmails.difference(existingEmails);
-
- for (final email in emailsWithNoSharedFiles) {
- final user = User(email: email);
+ for (final user in allRelevantContacts) {
+ if (existingEmails.contains(user.email)) {
+ continue;
+ }
peopleToSharedFiles[user] = [];
}
@@ -1781,16 +1810,16 @@ class SearchService {
return aName.compareTo(bName);
});
- final limitedEntries =
- limit != null ? sortedEntries.take(limit).toList() : sortedEntries;
+ final limitedEntries = limit != null
+ ? _preserveEmailOnlyContactsWithinLimit(sortedEntries, limit)
+ : sortedEntries;
for (var entry in limitedEntries) {
final user = entry.key;
final files = entry.value;
- final name = user.displayName != null && user.displayName!.isNotEmpty
- ? user.displayName!
- : user.email;
+ final name = resolveDisplayName(user);
final collections = peopleToSharedAlbums[user.email] ?? [];
+ final params = _contactSearchParams(user, collections);
searchResults.add(
GenericSearchResult(
ResultType.shared,
@@ -1801,11 +1830,7 @@ class SearchService {
occurrence: kMostRelevantFilter,
matchedUploadedIDs: filesToUploadedFileIDs(files),
),
- params: {
- kPersonParamID: user.linkedPersonID,
- kContactEmail: user.email,
- kContactCollections: collections,
- },
+ params: params,
),
);
}
@@ -1826,6 +1851,36 @@ class SearchService {
.toList();
}
+ List<MapEntry<User, List<EnteFile>>> _preserveEmailOnlyContactsWithinLimit(
+ List<MapEntry<User, List<EnteFile>>> sortedEntries,
+ int limit,
+ ) {
+ if (limit <= 0) {
+ return const [];
+ }
+ final limitedEntries = sortedEntries.take(limit).toList();
+ if (limitedEntries.length < limit ||
+ limitedEntries.any((entry) => entry.key.id == null)) {
+ return limitedEntries;
+ }
+
+ final includedEmails =
+ limitedEntries.map((entry) => entry.key.email).toSet();
+ MapEntry<User, List<EnteFile>>? overflowEmailOnly;
+ for (final entry in sortedEntries.skip(limit)) {
+ if (entry.key.id == null && !includedEmails.contains(entry.key.email)) {
+ overflowEmailOnly = entry;
+ break;
+ }
+ }
+ if (overflowEmailOnly == null) {
+ return limitedEntries;
+ }
+
+ limitedEntries[limitedEntries.length - 1] = overflowEmailOnly;
+ return limitedEntries;
+ }
+
Future<List<EnteFile>> _getFilesInYear(List<int> durationOfYear) async {
return await FilesDB.instance.getFilesCreatedWithinDurations(
[durationOfYear],
diff --git a/mobile/apps/photos/lib/ui/actions/collection/collection_sharing_actions.dart b/mobile/apps/photos/lib/ui/actions/collection/collection_sharing_actions.dart
index d62c9c6be3..6263a73e06 100644
--- a/mobile/apps/photos/lib/ui/actions/collection/collection_sharing_actions.dart
+++ b/mobile/apps/photos/lib/ui/actions/collection/collection_sharing_actions.dart
@@ -6,7 +6,6 @@ import 'package:logging/logging.dart';
import 'package:photos/core/configuration.dart';
import "package:photos/core/errors.dart";
import 'package:photos/db/files_db.dart';
-import "package:photos/extensions/user_extension.dart";
import 'package:photos/gateways/collections/models/create_request.dart';
import "package:photos/generated/l10n.dart";
import "package:photos/models/api/collection/user.dart";
@@ -17,6 +16,7 @@ import "package:photos/models/metadata/collection_magic.dart";
import "package:photos/models/metadata/common_keys.dart";
import 'package:photos/services/account/user_service.dart';
import 'package:photos/services/collections_service.dart';
+import 'package:photos/services/contacts/contact_identity_resolver.dart';
import 'package:photos/services/hidden_service.dart';
import 'package:photos/theme/colors.dart';
import 'package:photos/theme/ente_theme.dart';
@@ -195,7 +195,7 @@ class CollectionActions {
],
title: AppLocalizations.of(context).removeWithQuestionMark,
body: AppLocalizations.of(context)
- .removeParticipantBody(userEmail: user.displayName ?? user.email),
+ .removeParticipantBody(userEmail: resolveDisplayName(user)),
);
if (actionResult?.action != null) {
if (actionResult!.action == ButtonAction.error) {
diff --git a/mobile/apps/photos/lib/ui/sharing/add_participant_page.dart b/mobile/apps/photos/lib/ui/sharing/add_participant_page.dart
index e82d4934e4..6487a83d78 100644
--- a/mobile/apps/photos/lib/ui/sharing/add_participant_page.dart
+++ b/mobile/apps/photos/lib/ui/sharing/add_participant_page.dart
@@ -1,11 +1,11 @@
import 'package:email_validator/email_validator.dart';
import 'package:flutter/material.dart';
-import "package:photos/extensions/user_extension.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/models/api/collection/user.dart";
import 'package:photos/models/collection/collection.dart';
import "package:photos/services/account/user_service.dart";
import 'package:photos/services/collections_service.dart';
+import "package:photos/services/contacts/contact_identity_resolver.dart";
import 'package:photos/theme/ente_theme.dart';
import 'package:photos/ui/actions/collection/collection_sharing_actions.dart';
import 'package:photos/ui/components/buttons/button_widget.dart';
@@ -74,10 +74,10 @@ class _AddParticipantPage extends State<AddParticipantPage> {
Widget build(BuildContext context) {
final filterSuggestedUsers = _suggestedUsers
.where(
- (element) =>
- (element.displayName ?? element.email).toLowerCase().contains(
- _textController.text.trim().toLowerCase(),
- ),
+ (element) => _matchesUserQuery(
+ element,
+ _textController.text.trim().toLowerCase(),
+ ),
)
.toList();
isKeypadOpen = MediaQuery.viewInsetsOf(context).bottom > 100;
@@ -158,15 +158,15 @@ class _AddParticipantPage extends State<AddParticipantPage> {
);
}
final currentUser = filterSuggestedUsers[index];
+ final resolvedName = resolveDisplayName(currentUser);
return Column(
children: [
MenuItemWidget(
key: ValueKey(
- currentUser.displayName ?? currentUser.email,
+ '${currentUser.email}-$resolvedName',
),
captionedTextWidget: CaptionedTextWidget(
- title: currentUser.displayName ??
- currentUser.email,
+ title: resolvedName,
),
leadingIconSize: 24.0,
leadingIconWidget: UserAvatarWidget(
@@ -509,9 +509,10 @@ class _AddParticipantPage extends State<AddParticipantPage> {
if (_textController.text.trim().isNotEmpty) {
suggestedUsers.removeWhere(
- (element) => !(element.displayName ?? element.email)
- .toLowerCase()
- .contains(_textController.text.trim().toLowerCase()),
+ (element) => !_matchesUserQuery(
+ element,
+ _textController.text.trim().toLowerCase(),
+ ),
);
}
suggestedUsers.removeWhere(
@@ -535,4 +536,14 @@ class _AddParticipantPage extends State<AddParticipantPage> {
return AppLocalizations.of(context).addAdmin;
}
}
+
+ bool _matchesUserQuery(User user, String lowerCaseQuery) {
+ if (lowerCaseQuery.isEmpty) {
+ return true;
+ }
+ final resolvedName = resolveDisplayName(user).toLowerCase();
+ final resolvedEmail = (resolveKnownEmail(user) ?? user.email).toLowerCase();
+ return resolvedName.contains(lowerCaseQuery) ||
+ resolvedEmail.contains(lowerCaseQuery);
+ }
}
diff --git a/mobile/apps/photos/lib/ui/sharing/album_participants_page.dart b/mobile/apps/photos/lib/ui/sharing/album_participants_page.dart
index aa9e18e9b1..08e74e6cf8 100644
--- a/mobile/apps/photos/lib/ui/sharing/album_participants_page.dart
+++ b/mobile/apps/photos/lib/ui/sharing/album_participants_page.dart
@@ -2,11 +2,11 @@ import 'package:collection/collection.dart';
import 'package:ente_pure_utils/ente_pure_utils.dart';
import 'package:flutter/material.dart';
import 'package:photos/core/configuration.dart';
-import "package:photos/extensions/user_extension.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/models/api/collection/user.dart";
import 'package:photos/models/collection/collection.dart';
import 'package:photos/service_locator.dart';
+import 'package:photos/services/contacts/contact_identity_resolver.dart';
import 'package:photos/theme/ente_theme.dart';
import 'package:photos/ui/components/captioned_text_widget.dart';
import 'package:photos/ui/components/divider_widget.dart';
@@ -438,10 +438,6 @@ class _AlbumParticipantsPageState extends State<AlbumParticipantsPage> {
}
String _nameIfAvailableElseEmail(User user) {
- final name = user.displayName;
- if (name != null && name.isNotEmpty) {
- return name;
- }
- return user.email;
+ return resolveDisplayName(user);
}
}
diff --git a/mobile/apps/photos/lib/ui/sharing/manage_album_participant.dart b/mobile/apps/photos/lib/ui/sharing/manage_album_participant.dart
index a69139a1f5..9493fa7216 100644
--- a/mobile/apps/photos/lib/ui/sharing/manage_album_participant.dart
+++ b/mobile/apps/photos/lib/ui/sharing/manage_album_participant.dart
@@ -1,9 +1,9 @@
import 'package:flutter/material.dart';
-import "package:photos/extensions/user_extension.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/models/api/collection/user.dart";
import 'package:photos/models/collection/collection.dart';
import 'package:photos/services/collections_service.dart';
+import "package:photos/services/contacts/contact_identity_resolver.dart";
import 'package:photos/theme/colors.dart';
import 'package:photos/theme/ente_theme.dart';
import 'package:photos/ui/actions/collection/collection_sharing_actions.dart';
@@ -43,6 +43,7 @@ class _ManageIndividualParticipantState
final isAdmin = widget.user.isAdmin;
final isCollaborator = widget.user.isCollaborator;
final isViewer = widget.user.isViewer;
+ final resolvedName = resolveDisplayName(widget.user);
bool isConvertToViewSuccess = false;
return Scaffold(
appBar: AppBar(),
@@ -61,7 +62,7 @@ class _ManageIndividualParticipantState
title: AppLocalizations.of(context).manage,
),
Text(
- widget.user.displayName ?? widget.user.email,
+ resolvedName,
textAlign: TextAlign.left,
style: textTheme.small.copyWith(
color: colorScheme.textMuted,
@@ -152,7 +153,7 @@ class _ManageIndividualParticipantState
).yesConvertToViewer,
body: AppLocalizations.of(context)
.cannotAddMorePhotosAfterBecomingViewer(
- user: widget.user.displayName ?? widget.user.email,
+ user: resolvedName,
),
isCritical: true,
);
diff --git a/mobile/apps/photos/lib/ui/sharing/share_collection_page.dart b/mobile/apps/photos/lib/ui/sharing/share_collection_page.dart
index 9c219ba118..a7444477ec 100644
--- a/mobile/apps/photos/lib/ui/sharing/share_collection_page.dart
+++ b/mobile/apps/photos/lib/ui/sharing/share_collection_page.dart
@@ -2,11 +2,11 @@ import 'package:collection/collection.dart';
import 'package:ente_pure_utils/ente_pure_utils.dart';
import 'package:flutter/material.dart';
import 'package:photos/core/configuration.dart';
-import 'package:photos/extensions/user_extension.dart';
import 'package:photos/generated/l10n.dart';
import 'package:photos/models/api/collection/user.dart';
import 'package:photos/models/collection/collection.dart';
import 'package:photos/services/collections_service.dart';
+import 'package:photos/services/contacts/contact_identity_resolver.dart';
import 'package:photos/theme/ente_theme.dart';
import 'package:photos/ui/actions/collection/collection_sharing_actions.dart';
import 'package:photos/ui/components/captioned_text_widget.dart';
@@ -353,12 +353,13 @@ class EmailItemWidget extends StatelessWidget {
return const SizedBox.shrink();
} else if (collection.getSharees().length == 1) {
final User? user = collection.getSharees().firstOrNull;
+ final resolvedName = user == null ? '' : resolveDisplayName(user);
return Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
MenuItemWidget(
captionedTextWidget: CaptionedTextWidget(
- title: user?.displayName ?? user?.email ?? '',
+ title: resolvedName,
),
leadingIconWidget: UserAvatarWidget(
collection.getSharees().first,
diff --git a/mobile/apps/photos/lib/ui/sharing/user_avator_widget.dart b/mobile/apps/photos/lib/ui/sharing/user_avator_widget.dart
index 93644dc04f..30bb3fe070 100644
--- a/mobile/apps/photos/lib/ui/sharing/user_avator_widget.dart
+++ b/mobile/apps/photos/lib/ui/sharing/user_avator_widget.dart
@@ -1,14 +1,16 @@
import "dart:async";
+import "dart:typed_data";
import "package:ente_pure_utils/ente_pure_utils.dart";
import 'package:flutter/material.dart';
-import "package:logging/logging.dart";
import "package:photos/core/configuration.dart";
import "package:photos/core/event_bus.dart";
+import "package:photos/events/contacts_changed_event.dart";
import "package:photos/events/people_changed_event.dart";
-import "package:photos/extensions/user_extension.dart";
import "package:photos/models/api/collection/user.dart";
+import "package:photos/services/contacts/contact_identity_resolver.dart";
import "package:photos/services/machine_learning/face_ml/person/person_service.dart";
+import "package:photos/services/photos_contacts_service.dart";
import "package:photos/theme/colors.dart";
import 'package:photos/theme/ente_theme.dart';
import "package:photos/ui/viewer/people/person_face_widget.dart";
@@ -38,11 +40,13 @@ class UserAvatarWidget extends StatefulWidget {
}
class _UserAvatarWidgetState extends State<UserAvatarWidget> {
- Future<String?>? _personID;
+ String? _personId;
+ Uint8List? _contactPhotoBytes;
bool _canUsePersonFaceWidget = false;
+ int _photoLoadGeneration = 0;
int lastSyncTimeForKey = 0;
- final _logger = Logger("_UserAvatarWidgetState");
late final StreamSubscription<PeopleChangedEvent> _peopleChangedSubscription;
+ StreamSubscription<ContactsChangedEvent>? _contactsChangedSubscription;
final _debouncer = Debouncer(
const Duration(milliseconds: 250),
executionInterval: const Duration(seconds: 20),
@@ -60,12 +64,19 @@ class _UserAvatarWidgetState extends State<UserAvatarWidget> {
_reload();
}
});
+ _contactsChangedSubscription =
+ Bus.instance.on<ContactsChangedEvent>().listen((event) {
+ if (event.matchesContactUserId(widget.user.id)) {
+ _reload();
+ }
+ });
}
@override
void didUpdateWidget(covariant UserAvatarWidget oldWidget) {
super.didUpdateWidget(oldWidget);
- if (oldWidget.user.email != widget.user.email) {
+ if (oldWidget.user.email != widget.user.email ||
+ oldWidget.user.id != widget.user.id) {
_reload();
}
}
@@ -73,6 +84,7 @@ class _UserAvatarWidgetState extends State<UserAvatarWidget> {
@override
void dispose() {
_peopleChangedSubscription.cancel();
+ _contactsChangedSubscription?.cancel();
_debouncer.cancelDebounceTimer();
super.dispose();
}
@@ -85,12 +97,34 @@ class _UserAvatarWidgetState extends State<UserAvatarWidget> {
.instance.emailToPartialPersonDataMapCache[widget.user.email];
if (data != null && data.containsKey(PersonService.kPersonIDKey)) {
_canUsePersonFaceWidget = true;
- _personID = Future.value(data[PersonService.kPersonIDKey]);
+ _personId = data[PersonService.kPersonIDKey] as String;
lastSyncTimeForKey = PersonService.instance.lastRemoteSyncTime();
} else {
_canUsePersonFaceWidget = false;
- _personID = Future.value(null);
+ _personId = null;
}
+ _contactPhotoBytes = PhotosContactsService.instance
+ .getCachedProfilePictureBytesByUserId(widget.user.id);
+ });
+ final userId = widget.user.id;
+ if (userId == null ||
+ PhotosContactsService.instance.hasResolvedProfilePictureByUserId(
+ userId,
+ )) {
+ return;
+ }
+ final loadGeneration = ++_photoLoadGeneration;
+ final photoBytes =
+ await PhotosContactsService.instance.getProfilePictureBytesByUserId(
+ userId,
+ );
+ if (!mounted ||
+ loadGeneration != _photoLoadGeneration ||
+ widget.user.id != userId) {
+ return;
+ }
+ setState(() {
+ _contactPhotoBytes = photoBytes;
});
});
}
@@ -100,7 +134,35 @@ class _UserAvatarWidgetState extends State<UserAvatarWidget> {
final double size = getAvatarSize(widget.type);
final int cachedPixelWidth =
(size * MediaQuery.devicePixelRatioOf(context)).toInt();
- return _personID != null
+ if (_contactPhotoBytes != null) {
+ return Container(
+ padding: widget.addStroke ? const EdgeInsets.all(0.5) : EdgeInsets.zero,
+ decoration: widget.addStroke
+ ? BoxDecoration(
+ shape: BoxShape.circle,
+ border: Border.all(
+ color: widget.thumbnailView
+ ? strokeMutedDark
+ : getEnteColorScheme(context).strokeMuted,
+ width: UserAvatarWidget.strokeWidth,
+ strokeAlign: BorderSide.strokeAlignOutside,
+ ),
+ )
+ : null,
+ child: SizedBox(
+ height: size,
+ width: size,
+ child: ClipOval(
+ child: Image.memory(
+ _contactPhotoBytes!,
+ fit: BoxFit.cover,
+ gaplessPlayback: true,
+ ),
+ ),
+ ),
+ );
+ }
+ return _personId != null
? Container(
padding:
widget.addStroke ? const EdgeInsets.all(0.5) : EdgeInsets.zero,
@@ -119,55 +181,28 @@ class _UserAvatarWidgetState extends State<UserAvatarWidget> {
child: SizedBox(
height: size,
width: size,
- child: FutureBuilder(
- future: _personID,
- builder: (context, snapshot) {
- if (snapshot.hasData) {
- final personID = snapshot.data as String;
- return ClipOval(
- child: _canUsePersonFaceWidget
- ? PersonFaceWidget(
- key: ValueKey('$personID-$lastSyncTimeForKey'),
- personId: personID,
- cachedPixelWidth: cachedPixelWidth,
- onErrorCallback: () {
- if (mounted) {
- setState(() {
- _personID = null;
- _canUsePersonFaceWidget = false;
- });
- }
- },
- )
- : _FirstLetterCircularAvatar(
- user: widget.user,
- currentUserID: widget.currentUserID,
- thumbnailView: widget.thumbnailView,
- type: widget.type,
- addStroke: widget.addStroke,
- ),
- );
- } else if (snapshot.hasError) {
- _logger.severe("Error loading personID", snapshot.error);
- return _FirstLetterCircularAvatar(
- user: widget.user,
- currentUserID: widget.currentUserID,
- thumbnailView: widget.thumbnailView,
- type: widget.type,
- addStroke: widget.addStroke,
- );
- } else if (snapshot.connectionState == ConnectionState.done &&
- snapshot.data == null) {
- return _FirstLetterCircularAvatar(
- user: widget.user,
- currentUserID: widget.currentUserID,
- thumbnailView: widget.thumbnailView,
- type: widget.type,
- addStroke: widget.addStroke,
- );
- }
- return const SizedBox.shrink();
- },
+ child: ClipOval(
+ child: _canUsePersonFaceWidget
+ ? PersonFaceWidget(
+ key: ValueKey('$_personId-$lastSyncTimeForKey'),
+ personId: _personId!,
+ cachedPixelWidth: cachedPixelWidth,
+ onErrorCallback: () {
+ if (mounted) {
+ setState(() {
+ _personId = null;
+ _canUsePersonFaceWidget = false;
+ });
+ }
+ },
+ )
+ : _FirstLetterCircularAvatar(
+ user: widget.user,
+ currentUserID: widget.currentUserID,
+ thumbnailView: widget.thumbnailView,
+ type: widget.type,
+ addStroke: widget.addStroke,
+ ),
),
),
)
@@ -205,18 +240,18 @@ class _FirstLetterCircularAvatarState
@override
Widget build(BuildContext context) {
final colorScheme = getEnteColorScheme(context);
- final displayChar =
- (widget.user.displayName == null || widget.user.displayName!.isEmpty)
- ? ((widget.user.email.isEmpty)
- ? " "
- : widget.user.email.substring(0, 1))
- : widget.user.displayName!.substring(0, 1);
+ final resolvedDisplayName = resolveDisplayName(widget.user);
+ final displayChar = resolvedDisplayName.isEmpty
+ ? ((widget.user.email.isEmpty)
+ ? " "
+ : widget.user.email.substring(0, 1))
+ : resolvedDisplayName.substring(0, 1);
Color decorationColor;
if (widget.user.email == Configuration.instance.getEmail()) {
decorationColor = Colors.black;
} else {
final colorIndex = widget.user.email.contains("unknown.com")
- ? (widget.user.displayName?.length ?? 0)
+ ? resolvedDisplayName.length
: widget.user.email.length;
decorationColor = colorScheme
.avatarColors[colorIndex.remainder(colorScheme.avatarColors.length)];
@@ -322,15 +357,16 @@ class _FirstLetterUserAvatarState extends State<FirstLetterUserAvatar> {
@override
Widget build(BuildContext context) {
final colorScheme = getEnteColorScheme(context);
- final displayChar = (user.displayName == null || user.displayName!.isEmpty)
+ final resolvedDisplayName = resolveDisplayName(user);
+ final displayChar = resolvedDisplayName.isEmpty
? ((user.email.isEmpty) ? " " : user.email.substring(0, 1))
- : user.displayName!.substring(0, 1);
+ : resolvedDisplayName.substring(0, 1);
Color decorationColor;
if (user.email == currentUserEmail) {
decorationColor = Colors.black;
} else {
final colorIndex = user.email.contains("unknown.com")
- ? (user.displayName?.length ?? 0)
+ ? resolvedDisplayName.length
: user.email.length;
decorationColor = colorScheme
.avatarColors[colorIndex.remainder(colorScheme.avatarColors.length)];
diff --git a/mobile/apps/photos/lib/ui/social/comment_likes_bottom_sheet.dart b/mobile/apps/photos/lib/ui/social/comment_likes_bottom_sheet.dart
index 493a6075af..de27d79a73 100644
--- a/mobile/apps/photos/lib/ui/social/comment_likes_bottom_sheet.dart
+++ b/mobile/apps/photos/lib/ui/social/comment_likes_bottom_sheet.dart
@@ -1,6 +1,5 @@
import "package:ente_icons/ente_icons.dart";
import "package:flutter/material.dart";
-import "package:photos/extensions/user_extension.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/models/api/collection/user.dart";
import "package:photos/models/social/reaction.dart";
@@ -10,6 +9,7 @@ import "package:photos/theme/ente_theme.dart";
import "package:photos/ui/common/loading_widget.dart";
import "package:photos/ui/components/buttons/icon_button_widget.dart";
import "package:photos/ui/sharing/user_avator_widget.dart";
+import "package:photos/ui/social/widgets/resolved_social_user_name.dart";
const _shrinkWrapThreshold = 30;
@@ -202,19 +202,32 @@ class _CommentLikeListItem extends StatelessWidget {
),
const SizedBox(width: 12),
Expanded(
- child: Text(
- user.id == currentUserID
- ? youLabel
- : (user.displayName ?? user.email),
- style: TextStyle(
- fontSize: 14,
- fontWeight: FontWeight.w500,
- height: 20 / 14,
- letterSpacing: 14 * -0.02,
- color: colorScheme.textMuted,
- ),
- overflow: TextOverflow.ellipsis,
- ),
+ child: user.id == currentUserID
+ ? Text(
+ youLabel,
+ style: TextStyle(
+ fontSize: 14,
+ fontWeight: FontWeight.w500,
+ height: 20 / 14,
+ letterSpacing: 14 * -0.02,
+ color: colorScheme.textMuted,
+ ),
+ overflow: TextOverflow.ellipsis,
+ )
+ : ResolvedSocialUserName(
+ user: user,
+ builder: (context, resolvedName) => Text(
+ resolvedName,
+ style: TextStyle(
+ fontSize: 14,
+ fontWeight: FontWeight.w500,
+ height: 20 / 14,
+ letterSpacing: 14 * -0.02,
+ color: colorScheme.textMuted,
+ ),
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
),
const Icon(
EnteIcons.likeFilled,
diff --git a/mobile/apps/photos/lib/ui/social/likes_bottom_sheet.dart b/mobile/apps/photos/lib/ui/social/likes_bottom_sheet.dart
index cf76779de6..4c1b90f4e9 100644
--- a/mobile/apps/photos/lib/ui/social/likes_bottom_sheet.dart
+++ b/mobile/apps/photos/lib/ui/social/likes_bottom_sheet.dart
@@ -4,7 +4,6 @@ import "package:ente_icons/ente_icons.dart";
import "package:flutter/material.dart";
import "package:photos/core/configuration.dart";
import "package:photos/db/files_db.dart";
-import "package:photos/extensions/user_extension.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/models/api/collection/user.dart";
import "package:photos/models/collection/collection.dart";
@@ -17,6 +16,7 @@ import "package:photos/ui/common/loading_widget.dart";
import "package:photos/ui/components/buttons/icon_button_widget.dart";
import "package:photos/ui/sharing/user_avator_widget.dart";
import "package:photos/ui/social/widgets/collection_selector_widget.dart";
+import "package:photos/ui/social/widgets/resolved_social_user_name.dart";
const _shrinkWrapThreshold = 30;
@@ -432,19 +432,32 @@ class _LikeListItem extends StatelessWidget {
),
const SizedBox(width: 12),
Expanded(
- child: Text(
- user.id == currentUserID
- ? youLabel
- : (user.displayName ?? user.email),
- style: TextStyle(
- fontSize: 14,
- fontWeight: FontWeight.w500,
- height: 20 / 14,
- letterSpacing: 14 * -0.02,
- color: colorScheme.textMuted,
- ),
- overflow: TextOverflow.ellipsis,
- ),
+ child: user.id == currentUserID
+ ? Text(
+ youLabel,
+ style: TextStyle(
+ fontSize: 14,
+ fontWeight: FontWeight.w500,
+ height: 20 / 14,
+ letterSpacing: 14 * -0.02,
+ color: colorScheme.textMuted,
+ ),
+ overflow: TextOverflow.ellipsis,
+ )
+ : ResolvedSocialUserName(
+ user: user,
+ builder: (context, resolvedName) => Text(
+ resolvedName,
+ style: TextStyle(
+ fontSize: 14,
+ fontWeight: FontWeight.w500,
+ height: 20 / 14,
+ letterSpacing: 14 * -0.02,
+ color: colorScheme.textMuted,
+ ),
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
),
const Icon(
EnteIcons.likeFilled,
diff --git a/mobile/apps/photos/lib/ui/social/widgets/comment_bubble_widget.dart b/mobile/apps/photos/lib/ui/social/widgets/comment_bubble_widget.dart
index feb09eb4fe..b9ff45659e 100644
--- a/mobile/apps/photos/lib/ui/social/widgets/comment_bubble_widget.dart
+++ b/mobile/apps/photos/lib/ui/social/widgets/comment_bubble_widget.dart
@@ -6,7 +6,6 @@ import "package:flutter/services.dart";
import "package:logging/logging.dart";
import "package:photos/core/event_bus.dart";
import "package:photos/events/comment_deleted_event.dart";
-import "package:photos/extensions/user_extension.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/models/api/collection/user.dart";
import "package:photos/models/social/comment.dart";
@@ -21,6 +20,7 @@ import "package:photos/ui/social/comment_likes_bottom_sheet.dart";
import "package:photos/ui/social/widgets/comment_actions_popup.dart";
import "package:photos/ui/social/widgets/comment_like_count_capsule.dart";
import "package:photos/ui/social/widgets/delete_comment_confirmation_dialog.dart";
+import "package:photos/ui/social/widgets/resolved_social_user_name.dart";
import "package:photos/utils/social/relative_time_formatter.dart";
final _logger = Logger("CommentBubbleWidget");
@@ -635,11 +635,6 @@ class _InlineParentQuote extends StatelessWidget {
isParentDeleted ? l10n.deletedComment : parentComment!.data;
final parentUser =
parentComment != null ? userResolver(parentComment!) : null;
- final parentAuthor = parentComment != null
- ? (parentUser!.id == currentUserID
- ? l10n.you
- : (parentUser.displayName ?? parentUser.email))
- : null;
final isDarkMode = Theme.of(context).brightness == Brightness.dark;
final lineColor = isOwnComment
@@ -678,17 +673,31 @@ class _InlineParentQuote extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
- if (parentAuthor != null)
- Text(
- parentAuthor,
- style: textTheme.mini.copyWith(
- color: parentAuthorTextColor,
- height: 20 / 12,
- letterSpacing: -0.24,
- ),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
+ if (parentUser != null)
+ parentUser.id == currentUserID
+ ? Text(
+ l10n.you,
+ style: textTheme.mini.copyWith(
+ color: parentAuthorTextColor,
+ height: 20 / 12,
+ letterSpacing: -0.24,
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ )
+ : ResolvedSocialUserName(
+ user: parentUser,
+ builder: (context, resolvedName) => Text(
+ resolvedName,
+ style: textTheme.mini.copyWith(
+ color: parentAuthorTextColor,
+ height: 20 / 12,
+ letterSpacing: -0.24,
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
Text(
parentText,
style: textTheme.tiny.copyWith(
@@ -810,7 +819,6 @@ class _Header extends StatelessWidget {
Widget build(BuildContext context) {
final colorScheme = getEnteColorScheme(context);
final textTheme = getEnteTextTheme(context);
- final name = user.displayName ?? user.email;
final timestamp = formatRelativeTime(createdAt);
if (isOwnComment) {
@@ -833,40 +841,43 @@ class _Header extends StatelessWidget {
fontWeight: FontWeight.w500,
);
- final headerText = Text.rich(
- TextSpan(
- children: [
- TextSpan(text: name, style: baseNameStyle),
- WidgetSpan(
- alignment: PlaceholderAlignment.baseline,
- baseline: TextBaseline.alphabetic,
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 4),
- child: Text(
- 'β€’',
- style: baseNameStyle.copyWith(
- fontSize: (baseNameStyle.fontSize ?? 14) * 0.65,
- height: 1,
- fontWeight: FontWeight.w600,
+ final headerText = ResolvedSocialUserName(
+ user: user,
+ builder: (context, resolvedName) => Text.rich(
+ TextSpan(
+ children: [
+ TextSpan(text: resolvedName, style: baseNameStyle),
+ WidgetSpan(
+ alignment: PlaceholderAlignment.baseline,
+ baseline: TextBaseline.alphabetic,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 4),
+ child: Text(
+ 'β€’',
+ style: baseNameStyle.copyWith(
+ fontSize: (baseNameStyle.fontSize ?? 14) * 0.65,
+ height: 1,
+ fontWeight: FontWeight.w600,
+ ),
),
),
),
- ),
- TextSpan(
- text: timestamp,
- style: textTheme.tiny.copyWith(
- color: colorScheme.textMuted,
- height: 14 / 10,
- fontWeight: FontWeight.w500,
+ TextSpan(
+ text: timestamp,
+ style: textTheme.tiny.copyWith(
+ color: colorScheme.textMuted,
+ height: 14 / 10,
+ fontWeight: FontWeight.w500,
+ ),
),
- ),
- ],
- ),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- textHeightBehavior: const TextHeightBehavior(
- applyHeightToFirstAscent: false,
- applyHeightToLastDescent: false,
+ ],
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ textHeightBehavior: const TextHeightBehavior(
+ applyHeightToFirstAscent: false,
+ applyHeightToLastDescent: false,
+ ),
),
);
diff --git a/mobile/apps/photos/lib/ui/social/widgets/feed_item_widget.dart b/mobile/apps/photos/lib/ui/social/widgets/feed_item_widget.dart
index eec0b786e8..1642a69515 100644
--- a/mobile/apps/photos/lib/ui/social/widgets/feed_item_widget.dart
+++ b/mobile/apps/photos/lib/ui/social/widgets/feed_item_widget.dart
@@ -1,7 +1,6 @@
import "package:ente_icons/ente_icons.dart";
import "package:flutter/material.dart";
import "package:photos/db/files_db.dart";
-import "package:photos/extensions/user_extension.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/models/api/collection/user.dart";
import "package:photos/models/file/file.dart";
@@ -11,6 +10,7 @@ import "package:photos/theme/colors.dart";
import "package:photos/theme/ente_theme.dart";
import "package:photos/theme/text_style.dart";
import "package:photos/ui/sharing/user_avator_widget.dart";
+import "package:photos/ui/social/widgets/resolved_social_user_name.dart";
import "package:photos/ui/social/widgets/shared_photos_grid.dart";
import "package:photos/ui/viewer/file/thumbnail_widget.dart";
@@ -488,14 +488,20 @@ class _FeedTextContent extends StatelessWidget {
final textTheme = getEnteTextTheme(context);
final primaryUser = _getPrimaryUser();
- final primaryName = primaryUser.displayName ?? primaryUser.email;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
- // Username row
- _buildUsernameRow(context, primaryName, textTheme, colorScheme),
+ ResolvedSocialUserName(
+ user: primaryUser,
+ builder: (context, primaryName) => _buildUsernameRow(
+ context,
+ primaryName,
+ textTheme,
+ colorScheme,
+ ),
+ ),
const SizedBox(height: 2),
// Action description
Text.rich(
diff --git a/mobile/apps/photos/lib/ui/social/widgets/feed_preview_item_widget.dart b/mobile/apps/photos/lib/ui/social/widgets/feed_preview_item_widget.dart
index 4242d0945b..0e8726be8e 100644
--- a/mobile/apps/photos/lib/ui/social/widgets/feed_preview_item_widget.dart
+++ b/mobile/apps/photos/lib/ui/social/widgets/feed_preview_item_widget.dart
@@ -1,6 +1,5 @@
import "package:flutter/material.dart";
import "package:hugeicons/hugeicons.dart";
-import "package:photos/extensions/user_extension.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/models/api/collection/user.dart";
import "package:photos/models/social/feed_item.dart";
@@ -9,6 +8,7 @@ import "package:photos/theme/colors.dart";
import "package:photos/theme/ente_theme.dart";
import "package:photos/theme/text_style.dart";
import "package:photos/ui/sharing/user_avator_widget.dart";
+import "package:photos/ui/social/widgets/resolved_social_user_name.dart";
class FeedPreviewItemWidget extends StatelessWidget {
final FeedItem feedItem;
@@ -246,28 +246,27 @@ class _PreviewTextContent extends StatelessWidget {
@override
Widget build(BuildContext context) {
final primaryUser = _getPrimaryUser();
- final primaryName = primaryUser.displayName ?? primaryUser.email;
-
- return Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisSize: MainAxisSize.min,
- children: [
- // Username row with "and X other(s)"
- _buildUsernameRow(context, primaryName),
- const SizedBox(height: 2),
- // Action description
- Text.rich(
- _getActionDescriptionSpan(
- context,
- textTheme.small.copyWith(
- color: colorScheme.textMuted,
- fontWeight: FontWeight.w500,
+ return ResolvedSocialUserName(
+ user: primaryUser,
+ builder: (context, primaryName) => Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ _buildUsernameRow(context, primaryName),
+ const SizedBox(height: 2),
+ Text.rich(
+ _getActionDescriptionSpan(
+ context,
+ textTheme.small.copyWith(
+ color: colorScheme.textMuted,
+ fontWeight: FontWeight.w500,
+ ),
),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- ],
+ ],
+ ),
);
}
diff --git a/mobile/apps/photos/lib/ui/social/widgets/resolved_social_user_name.dart b/mobile/apps/photos/lib/ui/social/widgets/resolved_social_user_name.dart
new file mode 100644
index 0000000000..2562bd7fe4
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/social/widgets/resolved_social_user_name.dart
@@ -0,0 +1,67 @@
+import "dart:async";
+
+import "package:flutter/material.dart";
+import "package:photos/core/event_bus.dart";
+import "package:photos/events/contacts_changed_event.dart";
+import "package:photos/events/people_changed_event.dart";
+import "package:photos/models/api/collection/user.dart";
+import "package:photos/service_locator.dart" show flagService;
+import "package:photos/services/contacts/contact_identity_resolver.dart";
+
+typedef ResolvedSocialUserNameBuilder = Widget Function(
+ BuildContext context,
+ String resolvedName,
+);
+
+class ResolvedSocialUserName extends StatefulWidget {
+ final User user;
+ final ResolvedSocialUserNameBuilder builder;
+
+ const ResolvedSocialUserName({
+ required this.user,
+ required this.builder,
+ super.key,
+ });
+
+ @override
+ State<ResolvedSocialUserName> createState() => _ResolvedSocialUserNameState();
+}
+
+class _ResolvedSocialUserNameState extends State<ResolvedSocialUserName> {
+ StreamSubscription<ContactsChangedEvent>? _contactsChangedSubscription;
+ StreamSubscription<PeopleChangedEvent>? _peopleChangedSubscription;
+
+ @override
+ void initState() {
+ super.initState();
+ _contactsChangedSubscription =
+ Bus.instance.on<ContactsChangedEvent>().listen((event) {
+ if (mounted &&
+ event.matchesContactUserId(widget.user.id) &&
+ flagService.internalUser) {
+ setState(() {});
+ }
+ });
+ _peopleChangedSubscription =
+ Bus.instance.on<PeopleChangedEvent>().listen((_) {
+ if (mounted) {
+ setState(() {});
+ }
+ });
+ }
+
+ @override
+ void dispose() {
+ _contactsChangedSubscription?.cancel();
+ _peopleChangedSubscription?.cancel();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return widget.builder(
+ context,
+ resolveDisplayName(widget.user),
+ );
+ }
+}
diff --git a/mobile/apps/photos/lib/ui/viewer/file_details/added_by_widget.dart b/mobile/apps/photos/lib/ui/viewer/file_details/added_by_widget.dart
index 85c7eba453..762e293b4e 100644
--- a/mobile/apps/photos/lib/ui/viewer/file_details/added_by_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file_details/added_by_widget.dart
@@ -1,9 +1,9 @@
import "package:flutter/material.dart";
-import "package:photos/extensions/user_extension.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/models/file/extensions/file_props.dart";
import 'package:photos/models/file/file.dart';
import "package:photos/services/collections_service.dart";
+import "package:photos/services/contacts/contact_identity_resolver.dart";
import "package:photos/theme/ente_theme.dart";
class AddedByWidget extends StatelessWidget {
@@ -22,7 +22,7 @@ class AddedByWidget extends StatelessWidget {
} else {
final fileOwner = CollectionsService.instance
.getFileOwner(file.ownerID!, file.collectionID);
- addedBy = fileOwner.displayName ?? fileOwner.email;
+ addedBy = resolveDisplayName(fileOwner);
}
if (addedBy == null || addedBy.isEmpty) {
return const SizedBox.shrink();
diff --git a/mobile/apps/photos/lib/ui/viewer/people/person_selection_action_widgets.dart b/mobile/apps/photos/lib/ui/viewer/people/person_selection_action_widgets.dart
index fe1376b398..0013825787 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/person_selection_action_widgets.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/person_selection_action_widgets.dart
@@ -33,10 +33,17 @@ import "package:photos/utils/local_settings.dart";
import "package:photos/utils/people_sort_util.dart";
import "package:photos/utils/person_contact_linking_util.dart";
+enum PersonSelectionMode {
+ linkContact,
+ autofillContact,
+}
+
class LinkContactToPersonSelectionPage extends StatefulWidget {
final String? emailToLink;
+ final PersonSelectionMode mode;
const LinkContactToPersonSelectionPage({
this.emailToLink,
+ this.mode = PersonSelectionMode.linkContact,
super.key,
});
@@ -85,8 +92,12 @@ class _LinkContactToPersonSelectionPageState
final entries = <_PersonSelectionEntry>[];
for (final person in persons) {
- if ((person.data.email != null && person.data.email!.isNotEmpty) ||
- person.data.isIgnored) {
+ final isAlreadyLinked =
+ person.data.email != null && person.data.email!.isNotEmpty;
+ if (person.data.isIgnored) {
+ continue;
+ }
+ if (widget.mode == PersonSelectionMode.linkContact && isAlreadyLinked) {
continue;
}
final searchResult = resultsById[person.remoteID];
@@ -227,7 +238,11 @@ class _LinkContactToPersonSelectionPageState
builder: (context, snapshot) {
final slivers = <Widget>[
SearchableAppBar(
- title: Text(context.l10n.selectPersonToLink),
+ title: Text(
+ widget.mode == PersonSelectionMode.autofillContact
+ ? "Select a person"
+ : context.l10n.selectPersonToLink,
+ ),
onSearch: _updateSearchQuery,
onSearchClosed: _clearSearchQuery,
centerTitle: false,
@@ -315,6 +330,13 @@ class _LinkContactToPersonSelectionPageState
return _RoundedPersonFaceWidget(
key: ValueKey(results[index].personEntity.remoteID),
onTap: () async {
+ if (widget.mode ==
+ PersonSelectionMode.autofillContact) {
+ Navigator.of(
+ context,
+ ).pop(results[index].personEntity);
+ return;
+ }
try {
final updatedPerson = await linkPersonToContact(
context,
diff --git a/mobile/apps/photos/lib/ui/viewer/search/contact_avatar_widget.dart b/mobile/apps/photos/lib/ui/viewer/search/contact_avatar_widget.dart
new file mode 100644
index 0000000000..acff623ead
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/viewer/search/contact_avatar_widget.dart
@@ -0,0 +1,120 @@
+import "dart:async";
+import "dart:typed_data";
+
+import "package:flutter/material.dart";
+import "package:photos/core/event_bus.dart";
+import "package:photos/events/contacts_changed_event.dart";
+import "package:photos/models/api/collection/user.dart";
+import "package:photos/services/contacts/contact_identity_resolver.dart";
+import "package:photos/services/photos_contacts_service.dart";
+import "package:photos/ui/sharing/user_avator_widget.dart";
+import "package:photos/ui/viewer/people/face_thumbnail_squircle.dart";
+import "package:photos/ui/viewer/people/person_face_widget.dart";
+
+class ContactAvatarWidget extends StatefulWidget {
+ final int? contactUserId;
+ final String email;
+ final String? personId;
+ final double size;
+
+ const ContactAvatarWidget({
+ required this.contactUserId,
+ required this.email,
+ required this.size,
+ this.personId,
+ super.key,
+ });
+
+ @override
+ State<ContactAvatarWidget> createState() => _ContactAvatarWidgetState();
+}
+
+class _ContactAvatarWidgetState extends State<ContactAvatarWidget> {
+ late Future<Uint8List?> _photoFuture;
+ StreamSubscription<ContactsChangedEvent>? _contactsChangedSubscription;
+ bool _canUsePersonFaceWidget = true;
+
+ @override
+ void initState() {
+ super.initState();
+ _photoFuture = _loadPhoto();
+ _contactsChangedSubscription =
+ Bus.instance.on<ContactsChangedEvent>().listen((event) {
+ if (event.matchesContactUserId(widget.contactUserId)) {
+ setState(() {
+ _photoFuture = _loadPhoto();
+ });
+ }
+ });
+ }
+
+ @override
+ void didUpdateWidget(covariant ContactAvatarWidget oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (oldWidget.contactUserId != widget.contactUserId ||
+ oldWidget.email != widget.email ||
+ oldWidget.personId != widget.personId) {
+ _photoFuture = _loadPhoto();
+ _canUsePersonFaceWidget = true;
+ }
+ }
+
+ @override
+ void dispose() {
+ _contactsChangedSubscription?.cancel();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return SizedBox(
+ width: widget.size,
+ height: widget.size,
+ child: FaceThumbnailSquircleClip(
+ borderRadius: faceThumbnailSquircleBorderRadius(widget.size),
+ child: FutureBuilder<Uint8List?>(
+ future: _photoFuture,
+ builder: (context, snapshot) {
+ final photoBytes = snapshot.data;
+ if (photoBytes != null) {
+ return Image.memory(photoBytes, fit: BoxFit.cover);
+ }
+ final personId = widget.personId;
+ if (_canUsePersonFaceWidget &&
+ personId != null &&
+ personId.isNotEmpty) {
+ return PersonFaceWidget(
+ key: ValueKey(personId),
+ personId: personId,
+ onErrorCallback: () {
+ if (mounted) {
+ setState(() {
+ _canUsePersonFaceWidget = false;
+ });
+ }
+ },
+ );
+ }
+ return FirstLetterUserAvatar(_fallbackUser());
+ },
+ ),
+ ),
+ );
+ }
+
+ Future<Uint8List?> _loadPhoto() {
+ return PhotosContactsService.instance.getProfilePictureBytesByUserId(
+ widget.contactUserId,
+ );
+ }
+
+ User _fallbackUser() {
+ final baseUser = User(id: widget.contactUserId, email: widget.email);
+ return User(
+ id: widget.contactUserId,
+ email: resolveKnownEmail(baseUser) ?? widget.email,
+ // ignore: deprecated_member_use_from_same_package
+ name: resolveDisplayName(baseUser),
+ );
+ }
+}
diff --git a/mobile/apps/photos/lib/ui/viewer/search/result/contact_photo_adjust_page.dart b/mobile/apps/photos/lib/ui/viewer/search/result/contact_photo_adjust_page.dart
new file mode 100644
index 0000000000..2633aaec0c
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/viewer/search/result/contact_photo_adjust_page.dart
@@ -0,0 +1,126 @@
+import "package:flutter/material.dart";
+import "package:flutter/services.dart";
+import "package:photos/ente_theme_data.dart";
+import "package:photos/generated/l10n.dart";
+import "package:photos/theme/ente_theme.dart";
+import "package:pro_image_editor/pro_image_editor.dart";
+
+class ContactPhotoAdjustPage extends StatefulWidget {
+ final Uint8List imageBytes;
+
+ const ContactPhotoAdjustPage({
+ required this.imageBytes,
+ super.key,
+ });
+
+ @override
+ State<ContactPhotoAdjustPage> createState() => _ContactPhotoAdjustPageState();
+}
+
+class _ContactPhotoAdjustPageState extends State<ContactPhotoAdjustPage> {
+ bool _isReturningBytes = false;
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+ final isLightMode = Theme.of(context).brightness == Brightness.light;
+
+ return Scaffold(
+ backgroundColor: colorScheme.backgroundBase,
+ body: CropRotateEditor.memory(
+ widget.imageBytes,
+ initConfigs: CropRotateEditorInitConfigs(
+ theme: ThemeData(
+ scaffoldBackgroundColor: colorScheme.backgroundBase,
+ appBarTheme: AppBarTheme(
+ titleTextStyle: textTheme.body,
+ backgroundColor: colorScheme.backgroundBase,
+ ),
+ bottomAppBarTheme: BottomAppBarTheme(
+ color: colorScheme.backgroundBase,
+ ),
+ brightness: isLightMode ? Brightness.light : Brightness.dark,
+ ),
+ convertToUint8List: true,
+ callbacks: ProImageEditorCallbacks(
+ onImageEditingComplete: (bytes) async {
+ if (mounted) {
+ Navigator.of(context).pop(bytes);
+ }
+ },
+ ),
+ configs: ProImageEditorConfigs(
+ imageGeneration: const ImageGenerationConfigs(
+ jpegQuality: 100,
+ enableIsolateGeneration: true,
+ pngLevel: 0,
+ ),
+ cropRotateEditor: CropRotateEditorConfigs(
+ showRotateButton: false,
+ showFlipButton: false,
+ showAspectRatioButton: false,
+ showResetButton: false,
+ initAspectRatio: 1.0,
+ aspectRatios: const [
+ AspectRatioItem(text: "1*1", value: 1.0),
+ ],
+ style: CropRotateEditorStyle(
+ background: colorScheme.backgroundBase,
+ cropCornerColor:
+ Theme.of(context).colorScheme.imageEditorPrimaryColor,
+ ),
+ widgets: CropRotateEditorWidgets(
+ appBar: (editor, rebuildStream) => ReactiveAppbar(
+ stream: rebuildStream,
+ builder: (_) => AppBar(
+ elevation: 0,
+ automaticallyImplyLeading: false,
+ backgroundColor: colorScheme.backgroundBase,
+ titleSpacing: 0,
+ title: Row(
+ children: [
+ TextButton(
+ onPressed: () => Navigator.of(context).pop(),
+ child: Text(
+ AppLocalizations.of(context).cancel,
+ style: textTheme.body,
+ ),
+ ),
+ const Spacer(),
+ TextButton(
+ onPressed: _isReturningBytes
+ ? null
+ : () async {
+ setState(() {
+ _isReturningBytes = true;
+ });
+ await editor.done();
+ },
+ child: Text(
+ AppLocalizations.of(context).useSelectedPhoto,
+ style: textTheme.body.copyWith(
+ color: _isReturningBytes
+ ? colorScheme.textMuted
+ : Theme.of(context)
+ .colorScheme
+ .imageEditorPrimaryColor,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ bottomBar: (_, rebuildStream) => ReactiveWidget<Widget>(
+ stream: rebuildStream,
+ builder: (_) => const SizedBox.shrink(),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/apps/photos/lib/ui/viewer/search/result/contact_photo_picker_sheet.dart b/mobile/apps/photos/lib/ui/viewer/search/result/contact_photo_picker_sheet.dart
new file mode 100644
index 0000000000..969f406037
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/viewer/search/result/contact_photo_picker_sheet.dart
@@ -0,0 +1,120 @@
+import "package:flutter/material.dart";
+import "package:modal_bottom_sheet/modal_bottom_sheet.dart";
+import "package:photos/models/file/file.dart";
+import "package:photos/models/file_load_result.dart";
+import "package:photos/models/selected_files.dart";
+import "package:photos/theme/colors.dart";
+import "package:photos/theme/ente_theme.dart";
+import "package:photos/ui/components/bottom_of_title_bar_widget.dart";
+import "package:photos/ui/components/buttons/button_widget.dart";
+import "package:photos/ui/components/models/button_type.dart";
+import "package:photos/ui/components/title_bar_title_widget.dart";
+import "package:photos/ui/viewer/gallery/gallery.dart";
+import "package:photos/ui/viewer/gallery/state/gallery_files_inherited_widget.dart";
+
+Future<EnteFile?> showContactPhotoPickerSheet(
+ BuildContext context, {
+ required List<EnteFile> files,
+}) {
+ return showBarModalBottomSheet<EnteFile>(
+ context: context,
+ builder: (context) => _ContactPhotoPickerSheet(files: files),
+ shape: const RoundedRectangleBorder(
+ side: BorderSide(width: 0),
+ borderRadius: BorderRadius.vertical(top: Radius.circular(5)),
+ ),
+ topControl: const SizedBox.shrink(),
+ backgroundColor: getEnteColorScheme(context).backgroundElevated,
+ barrierColor: backdropFaintDark,
+ enableDrag: true,
+ );
+}
+
+class _ContactPhotoPickerSheet extends StatelessWidget {
+ final List<EnteFile> files;
+
+ const _ContactPhotoPickerSheet({required this.files});
+
+ @override
+ Widget build(BuildContext context) {
+ final isFileSelected = ValueNotifier(false);
+ final selectedFiles = SelectedFiles();
+ selectedFiles.addListener(() {
+ isFileSelected.value = selectedFiles.files.isNotEmpty;
+ });
+
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(0, 32, 0, 8),
+ child: SizedBox(
+ width: double.infinity,
+ child: Column(
+ mainAxisSize: MainAxisSize.max,
+ children: [
+ Expanded(
+ child: Column(
+ children: [
+ const BottomOfTitleBarWidget(
+ title: TitleBarTitleWidget(title: "Set a contact photo"),
+ showCloseButton: true,
+ ),
+ Expanded(
+ child: GalleryFilesState(
+ child: Gallery(
+ asyncLoader: (
+ creationStartTime,
+ creationEndTime, {
+ limit,
+ asc,
+ }) async =>
+ FileLoadResult(files, false),
+ tagPrefix: "pick_contact_photo_gallery",
+ selectedFiles: selectedFiles,
+ limitSelectionToOne: true,
+ showSelectAll: false,
+ disablePinnedGroupHeader: true,
+ disableVerticalPaddingForScrollbar: true,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ SafeArea(
+ child: Container(
+ decoration: BoxDecoration(
+ border: Border(
+ top: BorderSide(
+ color: getEnteColorScheme(context).strokeFaint,
+ ),
+ ),
+ ),
+ child: Center(
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 428),
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(16, 15, 16, 8),
+ child: ValueListenableBuilder<bool>(
+ valueListenable: isFileSelected,
+ builder: (context, value, _) {
+ return ButtonWidget(
+ key: ValueKey(value),
+ isDisabled: !value,
+ buttonType: ButtonType.neutral,
+ labelText: "Set selected photo",
+ onTap: () async {
+ Navigator.pop(context, selectedFiles.files.first);
+ },
+ );
+ },
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/apps/photos/lib/ui/viewer/search/result/contact_result_page.dart b/mobile/apps/photos/lib/ui/viewer/search/result/contact_result_page.dart
index 1a73d89f0b..144aa4d602 100644
--- a/mobile/apps/photos/lib/ui/viewer/search/result/contact_result_page.dart
+++ b/mobile/apps/photos/lib/ui/viewer/search/result/contact_result_page.dart
@@ -1,28 +1,36 @@
import "dart:async";
import "package:email_validator/email_validator.dart";
+import "package:ente_contacts/contacts.dart" as contacts;
import "package:ente_pure_utils/ente_pure_utils.dart";
-import 'package:flutter/material.dart';
-import 'package:photos/core/event_bus.dart';
-import 'package:photos/events/files_updated_event.dart';
-import 'package:photos/events/local_photos_updated_event.dart';
+import "package:flutter/material.dart";
+import "package:photos/core/constants.dart";
+import "package:photos/core/event_bus.dart";
+import "package:photos/events/contacts_changed_event.dart";
+import "package:photos/events/files_updated_event.dart";
+import "package:photos/events/local_photos_updated_event.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/l10n/l10n.dart";
import "package:photos/models/collection/collection.dart";
-import 'package:photos/models/file/file.dart';
-import 'package:photos/models/file_load_result.dart';
-import 'package:photos/models/gallery_type.dart';
+import "package:photos/models/file/file.dart";
+import "package:photos/models/file_load_result.dart";
+import "package:photos/models/gallery_type.dart";
import "package:photos/models/ml/face/person.dart";
import "package:photos/models/search/generic_search_result.dart";
import "package:photos/models/search/search_constants.dart";
-import 'package:photos/models/search/search_result.dart';
-import 'package:photos/models/selected_files.dart';
+import "package:photos/models/search/search_result.dart";
+import "package:photos/models/selected_files.dart";
+import "package:photos/service_locator.dart";
+import "package:photos/services/photos_contacts_service.dart";
+import "package:photos/theme/colors.dart";
import "package:photos/theme/ente_theme.dart";
import "package:photos/ui/collections/album/row_item.dart";
+import "package:photos/ui/common/loading_widget.dart";
import "package:photos/ui/components/end_to_end_banner.dart";
-import 'package:photos/ui/viewer/actions/file_selection_overlay_bar.dart';
-import 'package:photos/ui/viewer/gallery/gallery.dart';
-import 'package:photos/ui/viewer/gallery/gallery_app_bar_widget.dart';
+import "package:photos/ui/components/menu_item_widget/menu_item_widget_new.dart";
+import "package:photos/ui/viewer/actions/file_selection_overlay_bar.dart";
+import "package:photos/ui/viewer/gallery/empty_state.dart";
+import "package:photos/ui/viewer/gallery/gallery.dart";
import "package:photos/ui/viewer/gallery/hierarchical_search_gallery.dart";
import "package:photos/ui/viewer/gallery/state/boundary_reporter_mixin.dart";
import "package:photos/ui/viewer/gallery/state/gallery_boundaries_provider.dart";
@@ -30,7 +38,11 @@ import "package:photos/ui/viewer/gallery/state/gallery_files_inherited_widget.da
import "package:photos/ui/viewer/gallery/state/inherited_search_filter_data.dart";
import "package:photos/ui/viewer/gallery/state/search_filter_data_provider.dart";
import "package:photos/ui/viewer/gallery/state/selection_state.dart";
+import "package:photos/ui/viewer/hierarchicial_search/applied_filters_for_appbar.dart";
+import "package:photos/ui/viewer/hierarchicial_search/recommended_filters_for_appbar.dart";
import "package:photos/ui/viewer/people/person_selection_action_widgets.dart";
+import "package:photos/ui/viewer/search/contact_avatar_widget.dart";
+import "package:photos/ui/viewer/search/result/edit_contact_page.dart";
class ContactResultPage extends StatefulWidget {
final SearchResult searchResult;
@@ -56,17 +68,23 @@ class _ContactResultPageState extends State<ContactResultPage> {
late final List<EnteFile> files;
late final List<Collection> collections;
late final StreamSubscription<LocalPhotosUpdatedEvent> _filesUpdatedEvent;
+ StreamSubscription<ContactsChangedEvent>? _contactsChangedEvent;
late String _searchResultName;
+ late final String _contactEmail;
+ late final int? _contactUserId;
late final SearchFilterDataProvider _searchFilterDataProvider;
+ contacts.ContactRecord? _savedContact;
+ bool _resolvedSavedContact = false;
@override
void initState() {
super.initState();
+ final params = (widget.searchResult as GenericSearchResult).params;
files = widget.searchResult.resultFiles();
- collections = (widget.searchResult as GenericSearchResult)
- .params[kContactCollections] ??
- <Collection>[];
+ collections = params[kContactCollections] ?? <Collection>[];
_searchResultName = widget.searchResult.name();
+ _contactEmail = params[kContactEmail] as String? ?? _searchResultName;
+ _contactUserId = params[kContactUserId] as int?;
_filesUpdatedEvent =
Bus.instance.on<LocalPhotosUpdatedEvent>().listen((event) {
if (event.type == EventType.deletedFromDevice ||
@@ -83,11 +101,22 @@ class _ContactResultPageState extends State<ContactResultPage> {
_searchFilterDataProvider = SearchFilterDataProvider(
initialGalleryFilter: widget.searchResult.getHierarchicalSearchFilter(),
);
+
+ if (flagService.enableContact && _contactUserId != null) {
+ _refreshSavedContact();
+ _contactsChangedEvent =
+ Bus.instance.on<ContactsChangedEvent>().listen((event) {
+ if (event.matchesContactUserId(_contactUserId)) {
+ _refreshSavedContact();
+ }
+ });
+ }
}
@override
void dispose() {
_filesUpdatedEvent.cancel();
+ _contactsChangedEvent?.cancel();
super.dispose();
}
@@ -121,34 +150,10 @@ class _ContactResultPageState extends State<ContactResultPage> {
initialFiles: widget.searchResult.resultFiles().isNotEmpty
? [widget.searchResult.resultFiles().first]
: null,
- header: Column(
- children: [
- if (EmailValidator.validate(_searchResultName))
- Padding(
- padding: const EdgeInsets.only(top: 12, bottom: 8),
- child: EndToEndBanner(
- title: context.l10n.linkPerson,
- caption: context.l10n.linkPersonCaption,
- leadingIcon: Icons.person,
- onTap: () async {
- final PersonEntity? updatedPerson = await routeToPage(
- context,
- LinkContactToPersonSelectionPage(
- emailToLink: _searchResultName,
- ),
- );
- if (updatedPerson != null) {
- setState(() {
- _searchResultName = updatedPerson.data.name;
- });
- }
- },
- ),
- ),
- if (collections.isNotEmpty)
- _AlbumsSection(context: context, collections: collections),
- ],
- ),
+ header: _buildPageHeader(context),
+ emptyState: _shouldShowUnsavedContactEmptyState
+ ? _UnsavedContactEmptyState(email: _contactEmail)
+ : const EmptyState(),
);
return GalleryBoundariesProvider(
@@ -156,21 +161,20 @@ class _ContactResultPageState extends State<ContactResultPage> {
child: InheritedSearchFilterDataWrapper(
searchFilterDataProvider: _searchFilterDataProvider,
child: Scaffold(
+ backgroundColor: getEnteColorScheme(context).backgroundColour,
appBar: PreferredSize(
- preferredSize: const Size.fromHeight(90.0),
+ preferredSize: Size.fromHeight(
+ _ContactResultAppBar.preferredHeight(
+ isHierarchicalSearchable: true,
+ ),
+ ),
child: widget.enableGrouping
- ? GalleryAppBarWidget(
- key: ValueKey(_searchResultName),
- ContactResultPage.appBarType,
- _searchResultName,
- _selectedFiles,
+ ? const _ContactResultAppBar(
+ isHierarchicalSearchable: true,
)
- : _AppBarWithBoundary(
- child: GalleryAppBarWidget(
- key: ValueKey(_searchResultName),
- ContactResultPage.appBarType,
- _searchResultName,
- _selectedFiles,
+ : const _AppBarWithBoundary(
+ child: _ContactResultAppBar(
+ isHierarchicalSearchable: true,
),
),
),
@@ -208,6 +212,207 @@ class _ContactResultPageState extends State<ContactResultPage> {
),
);
}
+
+ Widget _buildContactHeader(BuildContext context) {
+ if (flagService.enableContact && _contactUserId != null) {
+ if (!_resolvedSavedContact) {
+ return const Padding(
+ padding: EdgeInsets.only(top: 20, bottom: 8),
+ child: SizedBox(
+ height: 88,
+ child: Center(child: EnteLoadingWidget()),
+ ),
+ );
+ }
+ if (_savedContact == null) {
+ return _UnsavedContactHeader(
+ email: _contactEmail,
+ itemCount: files.length,
+ onTap: _openEditContactPage,
+ );
+ }
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(16, 20, 16, 8),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ ContactAvatarWidget(
+ contactUserId: _contactUserId,
+ email: _contactEmail,
+ personId: (widget.searchResult as GenericSearchResult)
+ .params[kPersonParamID] as String?,
+ size: 36,
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ _savedContact?.data?.name ?? _searchResultName,
+ style: _contactHeaderTitleStyle(context),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ const SizedBox(height: 2),
+ Text(
+ _savedContact?.email ?? _contactEmail,
+ style: _contactHeaderSubtitleStyle(context),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(width: 12),
+ _ContactHeaderOverflowButton(onEdit: _openEditContactPage),
+ ],
+ ),
+ );
+ }
+
+ if (EmailValidator.validate(_searchResultName)) {
+ return Padding(
+ padding: const EdgeInsets.only(top: 12, bottom: 8),
+ child: EndToEndBanner(
+ title: context.l10n.linkPerson,
+ caption: context.l10n.linkPersonCaption,
+ leadingIcon: Icons.person,
+ onTap: () async {
+ final PersonEntity? updatedPerson = await routeToPage(
+ context,
+ LinkContactToPersonSelectionPage(
+ emailToLink: _searchResultName,
+ ),
+ );
+ if (updatedPerson != null && mounted) {
+ setState(() {
+ _searchResultName = updatedPerson.data.name;
+ });
+ }
+ },
+ ),
+ );
+ }
+
+ return const SizedBox.shrink();
+ }
+
+ Widget? _buildPageHeader(BuildContext context) {
+ final sections = <Widget>[
+ _buildContactHeader(context),
+ if (collections.isNotEmpty)
+ _AlbumsSection(context: context, collections: collections),
+ ].whereType<Widget>().toList();
+ if (sections.isEmpty) {
+ return null;
+ }
+ return Column(children: sections);
+ }
+
+ bool get _shouldShowUnsavedContactEmptyState =>
+ flagService.enableContact &&
+ _contactUserId != null &&
+ _resolvedSavedContact &&
+ _savedContact == null &&
+ files.isEmpty &&
+ collections.isEmpty;
+
+ Future<void> _refreshSavedContact() async {
+ final contactUserId = _contactUserId;
+ if (contactUserId == null) {
+ return;
+ }
+ final saved = await PhotosContactsService.instance.getContactByUserId(
+ contactUserId,
+ );
+ if (!mounted) {
+ return;
+ }
+ setState(() {
+ _savedContact = saved;
+ _resolvedSavedContact = true;
+ });
+ }
+
+ Future<void> _openEditContactPage() async {
+ final contactUserId = _contactUserId;
+ if (contactUserId == null) {
+ return;
+ }
+ final updated = await routeToPage(
+ context,
+ EditContactPage(
+ contactUserId: contactUserId,
+ email: _contactEmail,
+ files: files,
+ existingContact: _savedContact,
+ ),
+ );
+ if (updated is contacts.ContactRecord && mounted) {
+ setState(() {
+ _savedContact = updated;
+ });
+ }
+ }
+
+ TextStyle _contactHeaderTitleStyle(BuildContext context) {
+ return getEnteTextTheme(context).largeBold.copyWith(
+ fontSize: 20,
+ height: 28 / 20,
+ );
+ }
+
+ TextStyle _contactHeaderSubtitleStyle(BuildContext context) {
+ return getEnteTextTheme(context).mini.copyWith(
+ color: getEnteColorScheme(context).textMuted,
+ height: 16 / 12,
+ fontWeight: FontWeight.w500,
+ );
+ }
+}
+
+enum _ContactHeaderAction { edit }
+
+class _ContactHeaderOverflowButton extends StatelessWidget {
+ const _ContactHeaderOverflowButton({required this.onEdit});
+
+ final VoidCallback onEdit;
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ return Container(
+ decoration: BoxDecoration(
+ color: EnteTheme.isDark(context)
+ ? colorScheme.backgroundElevated2
+ : Colors.white,
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: colorScheme.strokeFainter),
+ ),
+ child: PopupMenuButton<_ContactHeaderAction>(
+ tooltip: "",
+ padding: const EdgeInsets.all(2),
+ iconSize: 18,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
+ color: colorScheme.fill,
+ icon: Icon(Icons.more_vert_rounded, color: colorScheme.textBase),
+ onSelected: (value) {
+ switch (value) {
+ case _ContactHeaderAction.edit:
+ onEdit();
+ }
+ },
+ itemBuilder: (context) => [
+ PopupMenuItem<_ContactHeaderAction>(
+ value: _ContactHeaderAction.edit,
+ child: Text(context.l10n.edit),
+ ),
+ ],
+ ),
+ );
+ }
}
class _AlbumsSection extends StatelessWidget {
@@ -222,31 +427,31 @@ class _AlbumsSection extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Padding(
- padding: const EdgeInsets.only(bottom: 24, top: 8),
+ padding: const EdgeInsets.only(bottom: 24, top: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
- padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 12),
child: Text(
AppLocalizations.of(context).albums,
- style: getEnteTextTheme(context).large,
+ style: getEnteTextTheme(context).largeBold,
),
),
Align(
alignment: Alignment.centerLeft,
child: SizedBox(
- height: 147,
+ height: 142,
child: ListView.separated(
- separatorBuilder: (context, index) => const SizedBox(width: 4),
+ separatorBuilder: (context, index) => const SizedBox(width: 10),
scrollDirection: Axis.horizontal,
itemCount: collections.length,
- padding: const EdgeInsets.symmetric(horizontal: 8),
+ padding: const EdgeInsets.symmetric(horizontal: 16),
itemBuilder: (context, index) {
final item = collections[index];
return AlbumRowItemWidget(
item,
- 120,
+ 108,
key: ValueKey('contact_result_${item.id}'),
showFileCount: false,
);
@@ -260,6 +465,194 @@ class _AlbumsSection extends StatelessWidget {
}
}
+class _UnsavedContactHeader extends StatelessWidget {
+ const _UnsavedContactHeader({
+ required this.email,
+ required this.itemCount,
+ required this.onTap,
+ });
+
+ final String email;
+ final int itemCount;
+ final Future<void> Function() onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ email,
+ style: textTheme.largeBold.copyWith(
+ fontSize: 20,
+ height: 28 / 20,
+ ),
+ ),
+ const SizedBox(height: 20),
+ MenuItemWidgetNew(
+ title: "Add a name and photo",
+ subText: AppLocalizations.of(context).itemCount(count: itemCount),
+ titleColor: colorScheme.textBase,
+ subTextStyle: textTheme.mini.copyWith(
+ color: colorScheme.textMuted,
+ height: 16 / 12,
+ ),
+ titleToSubTextSpacing: 4,
+ leadingIconWidget: _AddContactMenuIcon(colorScheme: colorScheme),
+ leadingIconSize: 36,
+ trailingIcon: Icons.chevron_right_rounded,
+ trailingIconIsMuted: true,
+ onTap: onTap,
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+class _AddContactMenuIcon extends StatelessWidget {
+ const _AddContactMenuIcon({required this.colorScheme});
+
+ final EnteColorScheme colorScheme;
+
+ @override
+ Widget build(BuildContext context) {
+ return Container(
+ width: 36,
+ height: 36,
+ decoration: BoxDecoration(
+ color: colorScheme.greenLight,
+ borderRadius: BorderRadius.circular(12),
+ ),
+ child: Icon(
+ Icons.person_add_alt_1_rounded,
+ size: 18,
+ color: colorScheme.greenBase,
+ ),
+ );
+ }
+}
+
+class _UnsavedContactEmptyState extends StatelessWidget {
+ const _UnsavedContactEmptyState({required this.email});
+
+ final String email;
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+ return Center(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 36),
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Image.asset(
+ "assets/ducky_share.png",
+ height: 180,
+ errorBuilder: (context, error, stackTrace) {
+ return const SizedBox(height: 180);
+ },
+ ),
+ const SizedBox(height: 12),
+ Text(
+ "Nothing to see here",
+ style: textTheme.largeBold.copyWith(
+ fontSize: 18,
+ height: 24 / 18,
+ ),
+ ),
+ const SizedBox(height: 4),
+ Text(
+ "Photos shared with or by $email will appear here.",
+ textAlign: TextAlign.center,
+ style: textTheme.mini.copyWith(
+ color: colorScheme.textMuted,
+ height: 16 / 12,
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+class _ContactResultAppBar extends StatelessWidget
+ implements PreferredSizeWidget {
+ static const _toolbarHeight = 56.0;
+ static const _bottomPadding = 8.0;
+
+ final bool isHierarchicalSearchable;
+
+ const _ContactResultAppBar({
+ required this.isHierarchicalSearchable,
+ });
+
+ static double preferredHeight({required bool isHierarchicalSearchable}) {
+ return isHierarchicalSearchable
+ ? _toolbarHeight + kFilterChipHeight + _bottomPadding + 1
+ : _toolbarHeight;
+ }
+
+ @override
+ Size get preferredSize => Size.fromHeight(
+ preferredHeight(isHierarchicalSearchable: isHierarchicalSearchable),
+ );
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ if (!isHierarchicalSearchable) {
+ return AppBar(
+ elevation: 0,
+ scrolledUnderElevation: 0,
+ backgroundColor: colorScheme.backgroundColour,
+ surfaceTintColor: Colors.transparent,
+ titleSpacing: 0,
+ );
+ }
+
+ final searchFilterData = InheritedSearchFilterData.of(context);
+ return ValueListenableBuilder(
+ valueListenable:
+ searchFilterData.searchFilterDataProvider!.isSearchingNotifier,
+ builder: (context, isSearching, _) {
+ return AppBar(
+ elevation: 0,
+ scrolledUnderElevation: 0,
+ backgroundColor: colorScheme.backgroundColour,
+ surfaceTintColor: Colors.transparent,
+ titleSpacing: 0,
+ bottom: isSearching
+ ? const PreferredSize(
+ preferredSize: Size.fromHeight(kFilterChipHeight + 1),
+ child: Padding(
+ padding: EdgeInsets.symmetric(horizontal: 12),
+ child: SizedBox(
+ height: kFilterChipHeight + 1,
+ child: AppliedFiltersForAppbar(),
+ ),
+ ),
+ )
+ : const PreferredSize(
+ preferredSize: Size.fromHeight(0),
+ child: Padding(
+ padding: EdgeInsets.symmetric(horizontal: 12),
+ child: Flexible(child: RecommendedFiltersForAppbar()),
+ ),
+ ),
+ );
+ },
+ );
+ }
+}
+
/// Wrapper widget that reports the app bar as top boundary for auto-scroll
/// when file grouping is disabled
class _AppBarWithBoundary extends StatefulWidget {
diff --git a/mobile/apps/photos/lib/ui/viewer/search/result/edit_contact_page.dart b/mobile/apps/photos/lib/ui/viewer/search/result/edit_contact_page.dart
new file mode 100644
index 0000000000..a86cf30b8f
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/viewer/search/result/edit_contact_page.dart
@@ -0,0 +1,882 @@
+import "dart:async";
+import "dart:typed_data";
+
+import "package:ente_contacts/contacts.dart" as contacts;
+import "package:ente_pure_utils/ente_pure_utils.dart";
+import "package:flutter/material.dart";
+import "package:intl/intl.dart";
+import "package:logging/logging.dart";
+import "package:photos/core/constants.dart";
+import "package:photos/db/files_db.dart";
+import "package:photos/db/ml/db.dart";
+import "package:photos/models/file/file.dart";
+import "package:photos/models/ml/face/person.dart";
+import "package:photos/models/search/generic_search_result.dart";
+import "package:photos/models/search/search_constants.dart";
+import "package:photos/services/machine_learning/face_ml/face_filtering/face_filtering_constants.dart";
+import "package:photos/services/machine_learning/face_ml/person/person_service.dart";
+import "package:photos/services/machine_learning/ml_result.dart";
+import "package:photos/services/photos_contacts_service.dart";
+import "package:photos/services/search_service.dart";
+import "package:photos/theme/ente_theme.dart";
+import "package:photos/ui/common/loading_widget.dart";
+import "package:photos/ui/components/menu_item_widget/menu_item_widget_new.dart";
+import "package:photos/ui/notification/toast.dart";
+import "package:photos/ui/viewer/people/face_thumbnail_squircle.dart";
+import "package:photos/ui/viewer/people/person_face_widget.dart";
+import "package:photos/ui/viewer/people/person_selection_action_widgets.dart";
+import "package:photos/ui/viewer/search/result/contact_photo_adjust_page.dart";
+import "package:photos/ui/viewer/search/result/contact_photo_picker_sheet.dart";
+import "package:photos/utils/dialog_util.dart";
+import "package:photos/utils/face/face_thumbnail_cache.dart";
+import "package:photos/utils/file_util.dart";
+import "package:photos/utils/thumbnail_util.dart";
+
+class EditContactPage extends StatefulWidget {
+ final int contactUserId;
+ final String email;
+ final List<EnteFile> files;
+ final contacts.ContactRecord? existingContact;
+
+ const EditContactPage({
+ required this.contactUserId,
+ required this.email,
+ required this.files,
+ required this.existingContact,
+ super.key,
+ });
+
+ @override
+ State<EditContactPage> createState() => _EditContactPageState();
+}
+
+class _EditContactPageState extends State<EditContactPage> {
+ static const _maxThumbnailCompressionAttempts = 2;
+ static const _avatarSize = 108.0;
+ static const _editBadgeSize = 32.0;
+ static const _avatarRadius = 20.0;
+
+ final _logger = Logger("EditContactPage");
+ late final TextEditingController _nameController;
+ String? _selectedBirthDate;
+ bool _isSaving = false;
+ bool _isLoadingPhoto = false;
+ bool _photoDirty = false;
+ bool _resolvedAutofillPeople = false;
+ Uint8List? _draftPhotoBytes;
+ PersonEntity? _autofillPerson;
+ List<PersonEntity> _autofillPreviewPeople = const [];
+ int _photoLoadGeneration = 0;
+
+ @override
+ void initState() {
+ super.initState();
+ _nameController = TextEditingController(
+ text: widget.existingContact?.data?.name ?? "",
+ )..addListener(() {
+ if (mounted) {
+ setState(() {});
+ }
+ });
+ _selectedBirthDate = widget.existingContact?.data?.birthDate;
+ _loadExistingPhoto();
+ unawaited(_loadAutofillPeoplePreview());
+ }
+
+ @override
+ void dispose() {
+ _nameController.dispose();
+ super.dispose();
+ }
+
+ bool get _canSave => !_isSaving && _nameController.text.trim().isNotEmpty;
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+
+ return Scaffold(
+ backgroundColor: colorScheme.backgroundColour,
+ appBar: AppBar(
+ elevation: 0,
+ scrolledUnderElevation: 0,
+ backgroundColor: colorScheme.backgroundColour,
+ surfaceTintColor: Colors.transparent,
+ title: Text(
+ "Edit contact",
+ style: textTheme.h3Bold.copyWith(
+ fontSize: 20,
+ height: 28 / 20,
+ ),
+ ),
+ centerTitle: false,
+ ),
+ body: Column(
+ children: [
+ Expanded(
+ child: ListView(
+ padding: const EdgeInsets.fromLTRB(24, 20, 24, 20),
+ children: [
+ Center(
+ child: GestureDetector(
+ onTap: _pickContactPhoto,
+ child: Stack(
+ clipBehavior: Clip.none,
+ children: [
+ _buildAvatar(context, size: _avatarSize),
+ Positioned(
+ right: 0,
+ bottom: 0,
+ child: _AvatarEditButton(
+ size: _editBadgeSize,
+ onTap: _pickContactPhoto,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(height: 32),
+ if (_showAutofillRow) ...[
+ MenuItemWidgetNew(
+ title: "Auto-fetch from people",
+ subText: "Use their name and photo",
+ titleToSubTextSpacing: 4,
+ subTextStyle: textTheme.mini.copyWith(
+ color: colorScheme.textMuted,
+ height: 16 / 12,
+ ),
+ leadingIconSize: 44,
+ leadingIconWidget: _AutofillLeadingWidget(
+ person: _autofillPerson,
+ previewPeople: _autofillPreviewPeople,
+ ),
+ trailingIcon: Icons.chevron_right_rounded,
+ onTap: _autoFillFromPeople,
+ ),
+ const SizedBox(height: 28),
+ ],
+ const _FieldLabel(text: "Email", isRequired: true),
+ const SizedBox(height: 8),
+ _InputShell(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 16,
+ vertical: 16,
+ ),
+ child: Text(
+ widget.email,
+ style: textTheme.body,
+ ),
+ ),
+ ),
+ const SizedBox(height: 24),
+ const _FieldLabel(text: "Name"),
+ const SizedBox(height: 8),
+ _InputShell(
+ child: TextField(
+ controller: _nameController,
+ textCapitalization: TextCapitalization.words,
+ style: textTheme.body,
+ decoration: InputDecoration(
+ hintText: "Enter a name",
+ hintStyle: textTheme.bodyFaint,
+ border: InputBorder.none,
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 16,
+ vertical: 16,
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(height: 24),
+ const _FieldLabel(text: "Birthday"),
+ const SizedBox(height: 8),
+ _BirthDateField(
+ value: _selectedBirthDate,
+ onTap: _pickBirthDate,
+ onClear: _selectedBirthDate == null
+ ? null
+ : () {
+ setState(() {
+ _selectedBirthDate = null;
+ });
+ },
+ hintText: "Enter date of birth",
+ ),
+ ],
+ ),
+ ),
+ SafeArea(
+ top: false,
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(24, 8, 24, 24),
+ child: _SaveContactButton(
+ isDisabled: !_canSave,
+ onTap: _canSave ? _saveContact : null,
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _buildAvatar(BuildContext context, {required double size}) {
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+ final trimmedName = _nameController.text.trim();
+ final initial = trimmedName.isNotEmpty
+ ? trimmedName.characters.first.toUpperCase()
+ : widget.email.characters.first.toUpperCase();
+ final avatarSeed = trimmedName.isNotEmpty ? trimmedName : widget.email;
+ final avatarColor = colorScheme.avatarColors[
+ avatarSeed.length.remainder(colorScheme.avatarColors.length)];
+
+ if (_isLoadingPhoto) {
+ return Container(
+ width: size,
+ height: size,
+ decoration: BoxDecoration(
+ color: colorScheme.fillFaint,
+ borderRadius: BorderRadius.circular(_avatarRadius),
+ ),
+ child: const Center(child: EnteLoadingWidget()),
+ );
+ }
+
+ if (_draftPhotoBytes != null) {
+ return ClipRRect(
+ borderRadius: BorderRadius.circular(_avatarRadius),
+ child: Image.memory(
+ _draftPhotoBytes!,
+ width: size,
+ height: size,
+ fit: BoxFit.cover,
+ ),
+ );
+ }
+
+ return Container(
+ width: size,
+ height: size,
+ decoration: BoxDecoration(
+ color: avatarColor,
+ borderRadius: BorderRadius.circular(_avatarRadius),
+ ),
+ child: Center(
+ child: Text(
+ initial,
+ style: textTheme.h1Bold.copyWith(
+ fontSize: 38.25,
+ height: 47.813 / 38.25,
+ color: Colors.white,
+ ),
+ ),
+ ),
+ );
+ }
+
+ Future<void> _loadExistingPhoto() async {
+ final existing = widget.existingContact;
+ if (existing?.profilePictureAttachmentId == null) {
+ return;
+ }
+ final loadGeneration = ++_photoLoadGeneration;
+ setState(() {
+ _isLoadingPhoto = true;
+ });
+ final bytes =
+ await PhotosContactsService.instance.getProfilePictureBytesByUserId(
+ widget.contactUserId,
+ );
+ if (!mounted || loadGeneration != _photoLoadGeneration) {
+ return;
+ }
+ if (_photoDirty || _draftPhotoBytes != null) {
+ setState(() {
+ _isLoadingPhoto = false;
+ });
+ return;
+ }
+ setState(() {
+ _draftPhotoBytes = bytes;
+ _isLoadingPhoto = false;
+ _photoDirty = false;
+ });
+ }
+
+ Future<void> _pickContactPhoto() async {
+ final pickerFiles = widget.files.isNotEmpty
+ ? widget.files
+ : await SearchService.instance.getAllFilesForGenericGallery();
+ if (pickerFiles.isEmpty) {
+ showShortToast(context, "No photos available to use");
+ return;
+ }
+ final selectedFile = await showContactPhotoPickerSheet(
+ context,
+ files: pickerFiles,
+ );
+ if (selectedFile == null) {
+ return;
+ }
+ setState(() {
+ _isLoadingPhoto = true;
+ });
+ final sourceBytes = await _loadEditablePhotoBytesFromFile(selectedFile);
+ if (!mounted) {
+ return;
+ }
+ setState(() {
+ _isLoadingPhoto = false;
+ });
+ if (sourceBytes == null) {
+ showShortToast(context, "Could not load selected photo");
+ return;
+ }
+ final croppedBytes = await routeToPage(
+ context,
+ ContactPhotoAdjustPage(imageBytes: sourceBytes),
+ );
+ if (croppedBytes is! Uint8List) {
+ return;
+ }
+ _photoLoadGeneration++;
+ setState(() {
+ _isLoadingPhoto = true;
+ });
+ final photoBytes = await _normalizeAttachmentBytes(croppedBytes);
+ if (!mounted) {
+ return;
+ }
+ setState(() {
+ _draftPhotoBytes = photoBytes;
+ _isLoadingPhoto = false;
+ _photoDirty = photoBytes != null;
+ _autofillPerson = null;
+ });
+ }
+
+ Future<void> _autoFillFromPeople() async {
+ final person = await routeToPage(
+ context,
+ const LinkContactToPersonSelectionPage(
+ mode: PersonSelectionMode.autofillContact,
+ ),
+ );
+ if (person is! PersonEntity || !mounted) {
+ return;
+ }
+ _photoLoadGeneration++;
+ _nameController.text = person.data.name;
+ setState(() {
+ _selectedBirthDate = person.data.birthDate;
+ _autofillPerson = person;
+ _isLoadingPhoto = true;
+ });
+ final photoBytes = await _buildAttachmentBytesFromPerson(person);
+ if (!mounted) {
+ return;
+ }
+ final shouldReloadExistingPhoto = photoBytes == null &&
+ _draftPhotoBytes == null &&
+ widget.existingContact?.profilePictureAttachmentId != null;
+ setState(() {
+ if (photoBytes != null) {
+ _draftPhotoBytes = photoBytes;
+ _photoDirty = true;
+ }
+ _isLoadingPhoto = false;
+ });
+ if (shouldReloadExistingPhoto) {
+ unawaited(_loadExistingPhoto());
+ }
+ }
+
+ Future<void> _saveContact() async {
+ setState(() {
+ _isSaving = true;
+ });
+ try {
+ var saved = await PhotosContactsService.instance.createOrUpdateContact(
+ contactUserId: widget.contactUserId,
+ name: _nameController.text.trim(),
+ birthDate: _selectedBirthDate,
+ );
+ if (_photoDirty && _draftPhotoBytes != null) {
+ saved = await PhotosContactsService.instance.setProfilePicture(
+ contactId: saved.id,
+ bytes: _draftPhotoBytes!,
+ );
+ }
+ if (!mounted) {
+ return;
+ }
+ Navigator.of(context).pop(saved);
+ } catch (e, s) {
+ _logger.severe("Failed to save contact", e, s);
+ if (!mounted) {
+ return;
+ }
+ await showGenericErrorDialog(context: context, error: e);
+ setState(() {
+ _isSaving = false;
+ });
+ }
+ }
+
+ Future<Uint8List?> _loadEditablePhotoBytesFromFile(EnteFile file) async {
+ return getThumbnail(file);
+ }
+
+ Future<Uint8List?> _normalizeAttachmentBytes(Uint8List sourceBytes) async {
+ var bytes = sourceBytes;
+ var attempts = 0;
+ while (bytes.length > thumbnailDataLimit &&
+ attempts < _maxThumbnailCompressionAttempts) {
+ bytes = await compressThumbnail(bytes);
+ attempts++;
+ }
+ return bytes;
+ }
+
+ Future<Uint8List?> _buildAttachmentBytesFromPerson(
+ PersonEntity person,
+ ) async {
+ try {
+ final hiddenFileIds = await SearchService.instance
+ .getHiddenFiles()
+ .then((files) => files.map((file) => file.uploadedFileID).toSet());
+ final faceIds = await MLDataDB.instance.getFaceIDsForPersonOrderedByScore(
+ person.remoteID,
+ );
+ EnteFile? sourceFile;
+ String? faceId = person.data.avatarFaceID;
+
+ if (faceId != null) {
+ final fileId = getFileIdFromFaceId<int>(faceId);
+ if (!hiddenFileIds.contains(fileId)) {
+ sourceFile = await FilesDB.instance.getAnyUploadedFile(fileId);
+ }
+ }
+
+ if (sourceFile == null) {
+ for (final candidateFaceId in faceIds) {
+ final fileId = getFileIdFromFaceId<int>(candidateFaceId);
+ if (hiddenFileIds.contains(fileId)) {
+ continue;
+ }
+ sourceFile = await FilesDB.instance.getAnyUploadedFile(fileId);
+ if (sourceFile != null) {
+ faceId = candidateFaceId;
+ break;
+ }
+ }
+ }
+
+ if (sourceFile == null || sourceFile.uploadedFileID == null) {
+ return null;
+ }
+
+ final face = await MLDataDB.instance.getCoverFaceForPerson(
+ recentFileID: sourceFile.uploadedFileID!,
+ avatarFaceId: faceId,
+ personID: person.remoteID,
+ );
+ if (face == null) {
+ return null;
+ }
+
+ final crops = await getCachedFaceCrops(
+ sourceFile,
+ [face],
+ useFullFile: true,
+ personOrClusterID: person.remoteID,
+ useTempCache: false,
+ );
+ final croppedBytes = crops?[face.faceID];
+ if (croppedBytes == null) {
+ return null;
+ }
+ return _normalizeAttachmentBytes(croppedBytes);
+ } catch (e, s) {
+ _logger.warning("Failed to build contact photo from person", e, s);
+ return null;
+ }
+ }
+
+ Future<void> _pickBirthDate() async {
+ final locale = Localizations.localeOf(context);
+ final lastDate = DateTime.now();
+ final initialDate = _selectedBirthDate == null
+ ? lastDate
+ : DateTime.tryParse(_selectedBirthDate!) ?? lastDate;
+ final picked = await showDatePicker(
+ context: context,
+ locale: locale,
+ initialDate: initialDate.isAfter(lastDate) ? lastDate : initialDate,
+ firstDate: DateTime(1900),
+ lastDate: lastDate,
+ );
+ if (picked == null || !mounted) {
+ return;
+ }
+ setState(() {
+ _selectedBirthDate = picked.toIso8601String().split("T").first;
+ });
+ }
+
+ bool get _showAutofillRow =>
+ _autofillPerson != null ||
+ (_resolvedAutofillPeople && _autofillPreviewPeople.isNotEmpty);
+
+ Future<void> _loadAutofillPeoplePreview() async {
+ try {
+ final persons = await PersonService.instance.getPersons();
+ final results = await SearchService.instance.getAllFace(
+ null,
+ minClusterSize: kMinimumClusterSizeAllFaces,
+ );
+ final resultsById = <String, GenericSearchResult>{};
+ for (final result in results) {
+ final personId = result.params[kPersonParamID] as String?;
+ if (personId == null || personId.isEmpty) {
+ continue;
+ }
+ resultsById[personId] = result;
+ }
+
+ final previewPeople = <PersonEntity>[];
+ for (final person in persons) {
+ if (person.data.isIgnored) {
+ continue;
+ }
+ if (!resultsById.containsKey(person.remoteID)) {
+ continue;
+ }
+ previewPeople.add(person);
+ if (previewPeople.length == 3) {
+ break;
+ }
+ }
+
+ if (!mounted) {
+ return;
+ }
+ setState(() {
+ _autofillPreviewPeople = previewPeople;
+ _resolvedAutofillPeople = true;
+ });
+ } catch (e, s) {
+ _logger.warning("Failed to load autofill people preview", e, s);
+ if (!mounted) {
+ return;
+ }
+ setState(() {
+ _autofillPreviewPeople = const [];
+ _resolvedAutofillPeople = true;
+ });
+ }
+ }
+}
+
+class _FieldLabel extends StatelessWidget {
+ final String text;
+ final bool isRequired;
+
+ const _FieldLabel({
+ required this.text,
+ this.isRequired = false,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final textTheme = getEnteTextTheme(context);
+ final colorScheme = getEnteColorScheme(context);
+
+ return RichText(
+ text: TextSpan(
+ style: textTheme.small.copyWith(fontWeight: FontWeight.w600),
+ children: [
+ TextSpan(text: text),
+ if (isRequired)
+ TextSpan(
+ text: " *",
+ style: textTheme.small.copyWith(
+ fontWeight: FontWeight.w600,
+ color: colorScheme.textBase,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+class _InputShell extends StatelessWidget {
+ final Widget child;
+
+ const _InputShell({required this.child});
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ final backgroundColor = EnteTheme.isDark(context)
+ ? colorScheme.backgroundElevated2
+ : Colors.white;
+
+ return DecoratedBox(
+ decoration: BoxDecoration(
+ color: backgroundColor,
+ borderRadius: BorderRadius.circular(16),
+ ),
+ child: child,
+ );
+ }
+}
+
+class _BirthDateField extends StatelessWidget {
+ final String? value;
+ final String hintText;
+ final VoidCallback onTap;
+ final VoidCallback? onClear;
+
+ const _BirthDateField({
+ required this.value,
+ required this.onTap,
+ required this.hintText,
+ this.onClear,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final textTheme = getEnteTextTheme(context);
+ final parsedDate = value == null ? null : DateTime.tryParse(value!);
+ final localeName = Localizations.localeOf(context).toLanguageTag();
+ final formattedDate = parsedDate == null
+ ? null
+ : DateFormat.yMMMd(localeName).format(parsedDate);
+
+ return InkWell(
+ onTap: onTap,
+ borderRadius: BorderRadius.circular(16),
+ child: _InputShell(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ formattedDate ?? hintText,
+ style: formattedDate == null
+ ? textTheme.bodyFaint
+ : textTheme.body,
+ ),
+ ),
+ if (onClear != null)
+ GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onClear,
+ child: Padding(
+ padding: const EdgeInsets.only(right: 8),
+ child: Icon(
+ Icons.close_rounded,
+ size: 18,
+ color: getEnteColorScheme(context).textMuted,
+ ),
+ ),
+ ),
+ Icon(
+ Icons.calendar_today_outlined,
+ size: 18,
+ color: getEnteColorScheme(context).textMuted,
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+class _AvatarEditButton extends StatelessWidget {
+ final double size;
+ final VoidCallback onTap;
+
+ const _AvatarEditButton({
+ required this.size,
+ required this.onTap,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ return Material(
+ color: getEnteColorScheme(context).primary500,
+ shape: const CircleBorder(),
+ child: InkWell(
+ onTap: onTap,
+ customBorder: const CircleBorder(),
+ child: SizedBox(
+ width: size,
+ height: size,
+ child: const Icon(
+ Icons.edit_outlined,
+ color: Colors.white,
+ size: 16,
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+class _AutofillLeadingWidget extends StatelessWidget {
+ final PersonEntity? person;
+ final List<PersonEntity> previewPeople;
+
+ const _AutofillLeadingWidget({
+ this.person,
+ this.previewPeople = const [],
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ final selectedPerson = person;
+
+ if (selectedPerson != null) {
+ return Stack(
+ clipBehavior: Clip.none,
+ children: [
+ SizedBox(
+ width: 32,
+ height: 32,
+ child: FaceThumbnailSquircleClip(
+ child: PersonFaceWidget(
+ personId: selectedPerson.remoteID,
+ useFullFile: false,
+ ),
+ ),
+ ),
+ Positioned(
+ right: -2,
+ bottom: -2,
+ child: Container(
+ width: 18,
+ height: 18,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: colorScheme.primary500,
+ border: Border.all(color: Colors.white, width: 1.5),
+ ),
+ child: const Icon(
+ Icons.edit_outlined,
+ size: 10,
+ color: Colors.white,
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+
+ Widget buildFace(double left, PersonEntity person) {
+ return Positioned(
+ left: left,
+ top: 3,
+ child: Container(
+ width: 26,
+ height: 26,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ border: Border.all(color: Colors.white, width: 1.5),
+ ),
+ child: ClipOval(
+ child: PersonFaceWidget(
+ personId: person.remoteID,
+ useFullFile: false,
+ ),
+ ),
+ ),
+ );
+ }
+
+ return SizedBox(
+ width: 44,
+ height: 32,
+ child: Stack(
+ clipBehavior: Clip.none,
+ children: [
+ for (final entry in previewPeople.take(3).indexed)
+ buildFace(entry.$1 * 11.0, entry.$2),
+ Positioned(
+ right: -2,
+ bottom: -2,
+ child: Container(
+ width: 18,
+ height: 18,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: colorScheme.primary500,
+ border: Border.all(color: Colors.white, width: 1.5),
+ ),
+ child: const Icon(
+ Icons.edit_outlined,
+ size: 10,
+ color: Colors.white,
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+class _SaveContactButton extends StatelessWidget {
+ const _SaveContactButton({
+ required this.isDisabled,
+ required this.onTap,
+ });
+
+ final bool isDisabled;
+ final Future<void> Function()? onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+ final backgroundColor =
+ isDisabled ? colorScheme.fillFaint : colorScheme.primary500;
+ final textColor =
+ isDisabled ? colorScheme.textFaint : colorScheme.contentReverse;
+
+ return Material(
+ color: Colors.transparent,
+ child: InkWell(
+ onTap: isDisabled ? null : onTap,
+ borderRadius: BorderRadius.circular(20),
+ child: Ink(
+ height: 48,
+ width: double.infinity,
+ decoration: BoxDecoration(
+ color: backgroundColor,
+ borderRadius: BorderRadius.circular(20),
+ ),
+ child: Center(
+ child: Text(
+ "Save contact",
+ style: textTheme.small.copyWith(
+ color: textColor,
+ fontWeight: FontWeight.w500,
+ height: 20 / 14,
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/apps/photos/lib/ui/viewer/search_tab/contacts_section.dart b/mobile/apps/photos/lib/ui/viewer/search_tab/contacts_section.dart
index 47a3feab59..b66308d975 100644
--- a/mobile/apps/photos/lib/ui/viewer/search_tab/contacts_section.dart
+++ b/mobile/apps/photos/lib/ui/viewer/search_tab/contacts_section.dart
@@ -3,18 +3,15 @@ import "dart:async";
import "package:dotted_border/dotted_border.dart";
import "package:ente_pure_utils/ente_pure_utils.dart";
import "package:flutter/material.dart";
-import "package:logging/logging.dart";
import "package:photos/core/constants.dart";
import "package:photos/events/event.dart";
import "package:photos/generated/l10n.dart";
-import "package:photos/models/api/collection/user.dart";
import "package:photos/models/search/generic_search_result.dart";
import "package:photos/models/search/recent_searches.dart";
import "package:photos/models/search/search_constants.dart";
import "package:photos/models/search/search_types.dart";
import "package:photos/theme/ente_theme.dart";
-import "package:photos/ui/sharing/user_avator_widget.dart";
-import "package:photos/ui/viewer/people/person_face_widget.dart";
+import "package:photos/ui/viewer/search/contact_avatar_widget.dart";
import "package:photos/ui/viewer/search/result/contact_result_page.dart";
import "package:photos/ui/viewer/search/search_section_cta.dart";
import "package:photos/ui/viewer/search_tab/section_header.dart";
@@ -152,30 +149,15 @@ class ContactRecommendation extends StatefulWidget {
}
class _ContactRecommendationState extends State<ContactRecommendation> {
- bool _canUsePersonFaceWidget = true;
- late String? _personID;
- final _logger = Logger("_ContactRecommendationState");
-
- @override
- void initState() {
- super.initState();
- _personID = widget.contactSearchResult.params[kPersonParamID];
- _canUsePersonFaceWidget = _personID != null;
- }
-
- @override
- void didUpdateWidget(covariant ContactRecommendation oldWidget) {
- super.didUpdateWidget(oldWidget);
- final newPersonID = widget.contactSearchResult.params[kPersonParamID];
- if (newPersonID != _personID) {
- _personID = newPersonID;
- _canUsePersonFaceWidget = newPersonID != null;
- }
- }
-
@override
Widget build(BuildContext context) {
final enteTextTheme = getEnteTextTheme(context);
+ final personId =
+ widget.contactSearchResult.params[kPersonParamID] as String?;
+ final contactUserId =
+ widget.contactSearchResult.params[kContactUserId] as int?;
+ final contactEmail =
+ widget.contactSearchResult.params[kContactEmail] as String;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 2.5),
child: GestureDetector(
@@ -207,26 +189,12 @@ class _ContactRecommendationState extends State<ContactRecommendation> {
child: SizedBox(
width: 67.75,
height: 67.75,
- child: _canUsePersonFaceWidget
- ? PersonFaceWidget(
- personId: _personID,
- onErrorCallback: () {
- if (mounted) {
- _logger.severe(
- "Failed to load face for person with ID: $_personID",
- );
- setState(() {
- _canUsePersonFaceWidget = false;
- });
- }
- },
- )
- : FirstLetterUserAvatar(
- User(
- email: widget
- .contactSearchResult.params[kContactEmail],
- ),
- ),
+ child: ContactAvatarWidget(
+ contactUserId: contactUserId,
+ email: contactEmail,
+ personId: personId,
+ size: 67.75,
+ ),
),
),
const SizedBox(height: 10.5),
diff --git a/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart b/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart
index 5993fa2dc3..bba6e318f5 100644
--- a/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart
+++ b/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart
@@ -57,6 +57,8 @@ class FlagService {
bool get internalOrBetaUser => internalUser || betaUser;
+ bool get enableContact => internalUser;
+
bool get enableStripe => Platform.isIOS ? false : flags.enableStripe;
bool get mapEnabled => flags.mapEnabled;