π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Use contact avatars for linked people
Neeraj Gupta92aea86c08a4
diff --git a/mobile/apps/photos/lib/services/machine_learning/face_ml/person/person_service.dart b/mobile/apps/photos/lib/services/machine_learning/face_ml/person/person_service.dartindex 69b26393c3..5b4062d54a 100644--- a/mobile/apps/photos/lib/services/machine_learning/face_ml/person/person_service.dart+++ b/mobile/apps/photos/lib/services/machine_learning/face_ml/person/person_service.dart@@ -17,7 +17,9 @@ import "package:photos/models/ml/face/person.dart";import "package:photos/service_locator.dart";import "package:photos/services/entity_service.dart";import "package:photos/services/machine_learning/ml_result.dart";+import "package:photos/services/photos_contacts_service.dart";import "package:photos/settings/local_settings.dart";+import "package:photos/utils/contact_photo_util.dart";import "package:photos/utils/face/face_thumbnail_cache.dart";import "package:shared_preferences/shared_preferences.dart";@@ -581,6 +583,7 @@ class PersonService {}final person = (await getPerson(p.remoteID))!;+ await _updateLinkedContactAvatarBeforePerson(person, file, face);final updatedPerson = person.copyWith(data: person.data.copyWith(avatarFaceId: face.faceID),);@@ -589,6 +592,43 @@ class PersonService {return updatedPerson;}+ Future<void> _updateLinkedContactAvatarBeforePerson(+ PersonEntity person,+ EnteFile file,+ Face face,+ ) async {+ if (!flagService.enableContact) {+ return;+ }+ final contact = await PhotosContactsService.instance.getContact(+ contactUserId: person.data.userID,+ email: person.data.email,+ );+ if (contact == null || !flagService.enableContact) {+ return;+ }+ final Uint8List? bytes = await buildContactPhotoAttachmentBytesFromFace(+ file: file,+ face: face,+ );+ if (bytes == null) {+ throw StateError(+ "Failed to prepare contact avatar for linked person ${person.remoteID}",+ );+ }+ try {+ await PhotosContactsService.instance.setProfilePicture(+ contactId: contact.id,+ bytes: bytes,+ );+ } on StateError {+ if (!flagService.enableContact) {+ return;+ }+ rethrow;+ }+ }+Future<PersonEntity> updateAttributes(String id, {String? name,diff --git a/mobile/apps/photos/lib/services/photos_contacts_service.dart b/mobile/apps/photos/lib/services/photos_contacts_service.dartindex b9424c2ea6..2cfb0f4633 100644--- a/mobile/apps/photos/lib/services/photos_contacts_service.dart+++ b/mobile/apps/photos/lib/services/photos_contacts_service.dart@@ -32,6 +32,8 @@ class PhotosContactsService {final contacts.ContactsService Function()? _contactsServiceFactory;final _logger = Logger("PhotosContactsService");final Map<int, contacts.ContactRecord> _contactsByUserId = {};+ final Map<String, contacts.ContactRecord> _contactsByNormalizedEmail = {};+ final Map<int, String?> _normalizedEmailByUserId = {};final Map<int, Uint8List?> _profilePictureBytesByUserId = {};final Set<int> _resolvedProfilePictureUserIds = {};final Map<int, Future<Uint8List?>> _profilePictureLoadsByUserId = {};@@ -93,50 +95,74 @@ class PhotosContactsService {}Future<contacts.ContactRecord?> getContactByUserId(int contactUserId) async {+ return getContact(contactUserId: contactUserId);+ }++ Future<contacts.ContactRecord?> getContact({+ int? contactUserId,+ String? email,+ }) async {if (!flagService.enableContact) {return null;}- final cached = getCachedContactByUserId(contactUserId);+ final cached = _getCachedContact(+ contactUserId: contactUserId,+ email: email,+ );if (cached != null) {return cached;}return _runReadSafely(() async {await ensureReady();+ final hydratedCached = _getCachedContact(+ contactUserId: contactUserId,+ email: email,+ );+ if (hydratedCached != null) {+ return hydratedCached;+ }+ if (contactUserId == null) {+ return null;+ }final contacts = _activeContactsOrNull();if (contacts == null) {return null;}final contact = await contacts.getContactByUserId(contactUserId);- if (contact == null || contact.isDeleted) {- return null;+ if (contact != null) {+ _cacheContact(contact);}- _cacheContact(contact);- return contact;+ return _getCachedContact(contactUserId: contactUserId, email: email);}, description: "load contact for user $contactUserId");}contacts.ContactRecord? getCachedContactByUserId(int? contactUserId) {- if (contactUserId == null || _sessionKey == null) {- return null;- }- final contact = _contactsByUserId[contactUserId];- if (contact == null || contact.isDeleted) {- return null;- }- return contact;+ return _getCachedContact(contactUserId: contactUserId);}String? getCachedSavedNameByUserId(int? contactUserId) {- return getCachedContactByUserId(contactUserId)?.data?.name;+ final savedName = getCachedContactByUserId(contactUserId)?.data?.name;+ if (savedName == null) {+ return null;+ }+ final trimmed = savedName.trim();+ return trimmed.isEmpty ? null : trimmed;}String? getCachedResolvedEmailByUserId(int? contactUserId) {- return getCachedContactByUserId(contactUserId)?.email;+ final resolved = getCachedContactByUserId(contactUserId)?.email;+ if (resolved == null) {+ return null;+ }+ final trimmed = resolved.trim();+ return trimmed.isEmpty ? null : trimmed;}Uint8List? getCachedProfilePictureBytesByUserId(int? contactUserId) {+ if (_sessionKey == null) {+ return null;+ }if (contactUserId == null ||- _sessionKey == null ||!_resolvedProfilePictureUserIds.contains(contactUserId)) {return null;}@@ -159,23 +185,33 @@ class PhotosContactsService {if (hasResolvedProfilePictureByUserId(contactUserId)) {return _profilePictureBytesByUserId[contactUserId];}+ final contact = await getContact(contactUserId: contactUserId);+ if (contact == null) {+ if (_hasHydratedCache) {+ _profilePictureBytesByUserId.remove(contactUserId);+ _resolvedProfilePictureUserIds.add(contactUserId);+ }+ return null;+ }+ if (_resolvedProfilePictureUserIds.contains(contactUserId)) {+ return _profilePictureBytesByUserId[contactUserId];+ }final inflightLoad = _profilePictureLoadsByUserId[contactUserId];if (inflightLoad != null) {return inflightLoad;}- final load = _loadProfilePictureBytesByUserId(contactUserId);+ final load = _loadProfilePictureBytes(contact);_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) {- return null;- }+ Future<Uint8List?> _loadProfilePictureBytes(+ contacts.ContactRecord contact,+ ) async {+ final contactUserId = contact.contactUserId;+ final attachmentId = contact.profilePictureAttachmentId;if (attachmentId == null) {_profilePictureBytesByUserId.remove(contactUserId);_resolvedProfilePictureUserIds.add(contactUserId);@@ -418,12 +454,25 @@ class PhotosContactsService {void _cacheContact(contacts.ContactRecord contact) {final userId = contact.contactUserId;final existing = _contactsByUserId[userId];+ final previousEmail = _normalizedEmailByUserId[userId];+ if (previousEmail != null &&+ _contactsByNormalizedEmail[previousEmail]?.contactUserId == userId) {+ _contactsByNormalizedEmail.remove(previousEmail);+ }if (contact.isDeleted) {_contactsByUserId.remove(userId);+ _normalizedEmailByUserId.remove(userId);_invalidateProfilePictureCache(userId);return;}_contactsByUserId[userId] = contact;+ final normalizedEmail = _normalizeEmail(contact.email);+ if (normalizedEmail == null) {+ _normalizedEmailByUserId.remove(userId);+ } else {+ _contactsByNormalizedEmail[normalizedEmail] = contact;+ _normalizedEmailByUserId[userId] = normalizedEmail;+ }if (existing?.profilePictureAttachmentId !=contact.profilePictureAttachmentId) {_invalidateProfilePictureCache(userId);@@ -433,6 +482,8 @@ class PhotosContactsService {void _resetSessionState({required bool notify}) {final hadCachedContacts = _contactsByUserId.isNotEmpty;_contactsByUserId.clear();+ _contactsByNormalizedEmail.clear();+ _normalizedEmailByUserId.clear();_profilePictureBytesByUserId.clear();_resolvedProfilePictureUserIds.clear();_profilePictureLoadsByUserId.clear();@@ -452,6 +503,50 @@ class PhotosContactsService {_profilePictureLoadsByUserId.remove(contactUserId);}+ contacts.ContactRecord? _getCachedContact({+ int? contactUserId,+ String? email,+ }) {+ if (_sessionKey == null) {+ return null;+ }+ if (contactUserId != null) {+ return _contactByUserIdOrNull(contactUserId);+ }+ return _contactByEmailOrNull(email);+ }++ contacts.ContactRecord? _contactByUserIdOrNull(int? contactUserId) {+ if (contactUserId == null) {+ return null;+ }+ final contact = _contactsByUserId[contactUserId];+ if (contact == null || contact.isDeleted) {+ return null;+ }+ return contact;+ }++ contacts.ContactRecord? _contactByEmailOrNull(String? email) {+ final normalizedEmail = _normalizeEmail(email);+ if (normalizedEmail == null) {+ return null;+ }+ final contact = _contactsByNormalizedEmail[normalizedEmail];+ if (contact == null || contact.isDeleted) {+ return null;+ }+ return contact;+ }++ String? _normalizeEmail(String? email) {+ if (email == null) {+ return null;+ }+ final trimmed = email.trim().toLowerCase();+ return trimmed.isEmpty ? null : trimmed;+ }+void _attachSessionResetListeners() {Bus.instance.on<UserLoggedOutEvent>().listen((_) {_sessionGeneration += 1;diff --git a/mobile/apps/photos/lib/ui/viewer/people/person_face_widget.dart b/mobile/apps/photos/lib/ui/viewer/people/person_face_widget.dartindex adfb6186cd..526204768a 100644--- a/mobile/apps/photos/lib/ui/viewer/people/person_face_widget.dart+++ b/mobile/apps/photos/lib/ui/viewer/people/person_face_widget.dart@@ -1,17 +1,21 @@+import "dart:async";import "dart:typed_data";import "package:flutter/foundation.dart" show kDebugMode;import "package:flutter/material.dart";import "package:logging/logging.dart";+import "package:photos/core/event_bus.dart";import "package:photos/db/files_db.dart";import "package:photos/db/ml/db.dart";import "package:photos/db/offline_files_db.dart";+import "package:photos/events/contacts_changed_event.dart";import 'package:photos/models/file/file.dart';import "package:photos/models/ml/face/face.dart";import "package:photos/models/ml/face/person.dart";import "package:photos/service_locator.dart" show isLocalGalleryMode;import "package:photos/services/machine_learning/face_ml/person/person_service.dart";import "package:photos/services/machine_learning/ml_result.dart";+import "package:photos/services/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";@@ -58,11 +62,14 @@ class PersonFaceWidget extends StatefulWidget {class _PersonFaceWidgetState extends State<PersonFaceWidget>with AutomaticKeepAliveClientMixin {Future<Uint8List?>? faceCropFuture;- EnteFile? fileForFaceCrop;int? _faceCropFileId;String? _personName;bool _showingFallback = false;bool _fallbackEverUsed = false;+ bool _personHasContactLink = false;+ int? _linkedContactUserId;+ int _loadGeneration = 0;+ StreamSubscription<ContactsChangedEvent>? _contactsChangedSubscription;bool get isPerson => widget.personId != null;@@ -72,11 +79,27 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>@overridevoid initState() {super.initState();- faceCropFuture = _loadFaceCrop();+ _contactsChangedSubscription = Bus.instance+ .on<ContactsChangedEvent>()+ .listen(_onContactsChanged);+ faceCropFuture = _startFaceCropLoad();+ }++ @override+ void didUpdateWidget(covariant PersonFaceWidget oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (oldWidget.personId != widget.personId ||+ oldWidget.clusterID != widget.clusterID ||+ oldWidget.useFullFile != widget.useFullFile) {+ _personHasContactLink = false;+ _linkedContactUserId = null;+ faceCropFuture = _startFaceCropLoad();+ }}@overridevoid dispose() {+ _contactsChangedSubscription?.cancel();if (_faceCropFileId != null) {checkStopTryingToGenerateFaceThumbnails(_faceCropFileId!,@@ -92,6 +115,22 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>super.dispose();}+ void _onContactsChanged(ContactsChangedEvent event) {+ if (!isPerson || !mounted) {+ return;+ }+ if (!_personHasContactLink && _linkedContactUserId == null) {+ return;+ }+ if (event.contactUserIds == null ||+ _linkedContactUserId == null ||+ event.matchesContactUserId(_linkedContactUserId)) {+ setState(() {+ faceCropFuture = _startFaceCropLoad();+ });+ }+ }+@overrideWidget build(BuildContext context) {super.build(@@ -165,35 +204,50 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>);}- Future<Uint8List?> _loadFaceCrop() async {+ Future<Uint8List?> _startFaceCropLoad() {+ final generation = ++_loadGeneration;+ return _loadFaceCrop(generation);+ }++ Future<Uint8List?> _loadFaceCrop(int generation) async {+ final String personOrClusterId = widget.personId ?? widget.clusterID!;if (!widget.useFullFile) {final Uint8List? thumbnailCrop = await _getFaceCrop(+ generation: generation,useFullFile: widget.useFullFile,);- if (thumbnailCrop != null) {+ if (_isCurrentLoad(generation, personOrClusterId) &&+ thumbnailCrop != null) {_fallbackEverUsed = true;+ _showingFallback = false;}- _showingFallback = false;return thumbnailCrop;}final Uint8List? fullCrop = await _getFaceCrop(+ generation: generation,useFullFile: widget.useFullFile,);if (fullCrop != null) {- _showingFallback = false;+ if (_isCurrentLoad(generation, personOrClusterId)) {+ _showingFallback = false;+ }return fullCrop;}- final String personOrClusterId = widget.personId ?? widget.clusterID!;_logger.warning("Full face crop unavailable for $personOrClusterId, attempting thumbnail fallback.",);- final Uint8List? fallbackCrop = await _getFaceCrop(useFullFile: false);+ final Uint8List? fallbackCrop = await _getFaceCrop(+ generation: generation,+ useFullFile: false,+ );if (fallbackCrop != null) {- _showingFallback = true;- _fallbackEverUsed = true;+ if (_isCurrentLoad(generation, personOrClusterId)) {+ _showingFallback = true;+ _fallbackEverUsed = true;+ }return fallbackCrop;}@@ -203,13 +257,12 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>return null;}- Future<Uint8List?> _getFaceCrop({required bool useFullFile}) async {+ Future<Uint8List?> _getFaceCrop({+ required int generation,+ required bool useFullFile,+ }) async {try {final String personOrClusterId = widget.personId ?? widget.clusterID!;- final tryInMemoryCachedCrop = checkInMemoryCachedCropForPersonOrClusterID(- personOrClusterId,- );- if (tryInMemoryCachedCrop != null) return tryInMemoryCachedCrop;String? fixedFaceID;PersonEntity? personEntity;final mlDataDB = isLocalGalleryMode@@ -223,9 +276,28 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>);return null;}+ if (!_isCurrentLoad(generation, personOrClusterId)) {+ return null;+ }_personName = personEntity.data.name;+ _personHasContactLink = _hasContactLink(personEntity);+ final contactPhotoBytes = await _getLinkedContactPhotoBytes(+ personEntity,+ generation: generation,+ personOrClusterId: personOrClusterId,+ );+ if (contactPhotoBytes != null) {+ return contactPhotoBytes;+ }fixedFaceID = personEntity.data.avatarFaceID;+ } else {+ _personHasContactLink = false;+ _linkedContactUserId = null;}+ final tryInMemoryCachedCrop = checkInMemoryCachedCropForPersonOrClusterID(+ personOrClusterId,+ );+ if (tryInMemoryCachedCrop != null) return tryInMemoryCachedCrop;fixedFaceID ??= await checkUsedFaceIDForPersonOrClusterId(personOrClusterId,);@@ -388,8 +460,9 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>personOrClusterID: personOrClusterId,useTempCache: false,);- this.fileForFaceCrop = fileForFaceCrop;- _faceCropFileId = recentFileID;+ if (_isCurrentLoad(generation, personOrClusterId)) {+ _faceCropFileId = recentFileID;+ }final result = cropMap?[face.faceID];if (result == null) {_logger.severe(@@ -407,6 +480,43 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget>return null;}}++ bool _isCurrentLoad(int generation, String personOrClusterId) {+ return _loadGeneration == generation &&+ (widget.personId ?? widget.clusterID) == personOrClusterId;+ }++ bool _hasContactLink(PersonEntity personEntity) {+ final userId = personEntity.data.userID;+ final email = personEntity.data.email?.trim();+ return (userId != null && userId > 0) ||+ (email != null && email.isNotEmpty);+ }++ Future<Uint8List?> _getLinkedContactPhotoBytes(+ PersonEntity personEntity, {+ required int generation,+ required String personOrClusterId,+ }) async {+ if (!_personHasContactLink) {+ _linkedContactUserId = null;+ return null;+ }+ final contact = await PhotosContactsService.instance.getContact(+ contactUserId: personEntity.data.userID,+ email: personEntity.data.email,+ );+ if (!_isCurrentLoad(generation, personOrClusterId)) {+ return null;+ }+ _linkedContactUserId = contact?.contactUserId ?? personEntity.data.userID;+ if (contact == null) {+ return null;+ }+ return PhotosContactsService.instance.getProfilePictureBytesByUserId(+ contact.contactUserId,+ );+ }}class _EmptyPersonThumbnail extends StatelessWidget {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.dartindex d0efd7fc4d..a808540b20 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,10 +1,12 @@import "dart:async";import "package:email_validator/email_validator.dart";-import "package:ente_components/theme/text_styles.dart";+import "package:ente_components/components/app_bar_component.dart";+import "package:ente_components/components/buttons/icon_button_component.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:hugeicons/hugeicons.dart";import "package:photos/core/event_bus.dart";import "package:photos/events/contacts_changed_event.dart";import "package:photos/events/files_updated_event.dart";@@ -31,6 +33,7 @@ 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/gallery_app_bar_config.dart";import "package:photos/ui/viewer/gallery/gallery_app_bar_widget.dart";import "package:photos/ui/viewer/gallery/hierarchical_search_gallery.dart";import "package:photos/ui/viewer/gallery/state/gallery_boundaries_provider.dart";@@ -38,6 +41,7 @@ import "package:photos/ui/viewer/gallery/state/gallery_files_inherited_widget.daimport "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/app_bar_filter_chips.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";@@ -122,11 +126,7 @@ class _ContactResultPageState extends State<ContactResultPage> {@overrideWidget build(BuildContext context) {- final appBar = GalleryAppBarWidget.sliverConfig(- ContactResultPage.appBarType,- _searchResultName,- _selectedFiles,- );+ final appBar = _buildAppBarConfig();final gallery = Gallery(appBar: appBar,asyncLoader: (creationStartTime, creationEndTime, {limit, asc}) {@@ -201,7 +201,45 @@ class _ContactResultPageState extends State<ContactResultPage> {);}- Widget _buildContactHeader(BuildContext context) {+ GalleryAppBarConfig _buildAppBarConfig() {+ final contactUserId = _contactUserId;+ if (_savedContact != null && contactUserId != null) {+ return GalleryAppBarConfig(+ sliverBuilder: (_) => _SavedContactAppBar(+ title: _savedContactDisplayName,+ email: _savedContactEmail,+ contactUserId: contactUserId,+ personId: _personId,+ selectedFiles: _selectedFiles,+ onEdit: _openEditContactPage,+ ),+ geometryBuilder: (context) {+ final inheritedSearchFilterData = InheritedSearchFilterData.maybeOf(+ context,+ );+ final isHierarchicalSearchable =+ inheritedSearchFilterData?.isHierarchicalSearchable ?? false;+ final bottomHeight = isHierarchicalSearchable+ ? AppBarFilterChips.preferredHeight(context)+ : 0.0;+ return SliverAppBarComponent.resolveGeometry(+ context,+ subtitle: _savedContactEmail,+ collapsedHeight: GalleryAppBarWidget.toolbarHeight,+ bottomHeight: bottomHeight,+ );+ },+ );+ }++ return GalleryAppBarWidget.sliverConfig(+ ContactResultPage.appBarType,+ _searchResultName,+ _selectedFiles,+ );+ }++ Widget? _buildContactHeader(BuildContext context) {if (flagService.enableContact && _contactUserId != null) {if (!_resolvedSavedContact) {return const Padding(@@ -213,53 +251,9 @@ class _ContactResultPageState extends State<ContactResultPage> {);}if (_savedContact == null) {- return _UnsavedContactHeader(- email: _contactEmail,- itemCount: files.length,- onTap: _openEditContactPage,- );+ return _UnsavedContactHeader(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),- ],- ),- );+ return null;}if (EmailValidator.validate(_searchResultName)) {@@ -284,11 +278,11 @@ class _ContactResultPageState extends State<ContactResultPage> {);}- return const SizedBox.shrink();+ return null;}Widget? _buildPageHeader(BuildContext context) {- final sections = <Widget>[+ final sections = <Widget?>[_buildContactHeader(context),if (collections.isNotEmpty)_AlbumsSection(context: context, collections: collections),@@ -344,59 +338,111 @@ class _ContactResultPageState extends State<ContactResultPage> {}}- TextStyle _contactHeaderTitleStyle(BuildContext context) {- return getEnteTextTheme(- context,- ).largeBold.copyWith(fontSize: 20, height: 28 / 20);+ String? get _personId =>+ (widget.searchResult as GenericSearchResult).params[kPersonParamID]+ as String?;++ String get _savedContactDisplayName {+ final savedName = _savedContact?.data?.name.trim();+ if (savedName != null && savedName.isNotEmpty) {+ return savedName;+ }+ return _searchResultName;}- TextStyle _contactHeaderSubtitleStyle(BuildContext context) {- return getEnteTextTheme(context).mini.copyWith(- color: getEnteColorScheme(context).textMuted,- height: 16 / 12,- fontWeight: FontWeight.w500,- );+ String get _savedContactEmail {+ final savedEmail = _savedContact?.email?.trim();+ if (savedEmail != null && savedEmail.isNotEmpty) {+ return savedEmail;+ }+ return _contactEmail;}}-enum _ContactHeaderAction { edit }--class _ContactHeaderOverflowButton extends StatelessWidget {- const _ContactHeaderOverflowButton({required this.onEdit});+class _SavedContactAppBar extends StatelessWidget {+ const _SavedContactAppBar({+ required this.title,+ required this.email,+ required this.contactUserId,+ required this.personId,+ required this.selectedFiles,+ required this.onEdit,+ });- final VoidCallback onEdit;+ final String title;+ final String email;+ final int contactUserId;+ final String? personId;+ final SelectedFiles selectedFiles;+ final Future<void> Function() onEdit;@overrideWidget 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),+ final inheritedSearchFilterData = InheritedSearchFilterData.maybeOf(+ context,+ );+ final isHierarchicalSearchable =+ inheritedSearchFilterData?.isHierarchicalSearchable ?? false;++ if (!isHierarchicalSearchable) {+ return _buildSliverAppBar(context, isSearching: false);+ }++ return ValueListenableBuilder(+ valueListenable: inheritedSearchFilterData!+ .searchFilterDataProvider!+ .isSearchingNotifier,+ child: PreferredSize(+ preferredSize: Size.fromHeight(+ AppBarFilterChips.preferredHeight(context),+ ),+ child: const AppBarFilterChips(),),- 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),+ builder: (context, isSearching, child) {+ return _buildSliverAppBar(+ context,+ isSearching: isSearching,+ bottom: child as PreferredSizeWidget,+ );+ },+ );+ }++ Widget _buildSliverAppBar(+ BuildContext context, {+ required bool isSearching,+ PreferredSizeWidget? bottom,+ }) {+ return AnimatedBuilder(+ animation: selectedFiles,+ builder: (context, _) {+ return SliverAppBarComponent(+ title: title,+ subtitle: email,+ leading: Center(+ child: ContactAvatarWidget(+ contactUserId: contactUserId,+ email: email,+ personId: personId,+ size: 36,+ ),),- ],- ),+ actions: isSearching || selectedFiles.files.isNotEmpty+ ? const []+ : [+ IconButtonComponent(+ tooltip: context.l10n.edit,+ icon: const HugeIcon(icon: HugeIcons.strokeRoundedEdit03),+ variant: IconButtonComponentVariant.primary,+ shouldSurfaceExecutionStates: false,+ onTap: onEdit,+ ),+ ],+ bottom: bottom,+ collapsedHeight: GalleryAppBarWidget.toolbarHeight,+ backgroundColor: GalleryAppBarWidget.backgroundColor(context),+ );+ },);}}@@ -449,49 +495,24 @@ class _AlbumsSection extends StatelessWidget {}class _UnsavedContactHeader extends StatelessWidget {- const _UnsavedContactHeader({- required this.email,- required this.itemCount,- required this.onTap,- });+ const _UnsavedContactHeader({required this.onTap});- final String email;- final int itemCount;final Future<void> Function() onTap;@overrideWidget build(BuildContext context) {final colorScheme = getEnteColorScheme(context);- final textTheme = getEnteTextTheme(context);final l10n = AppLocalizations.of(context);return Padding(- padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(- email,- style: TextStyles.body.copyWith(color: colorScheme.textMuted),- maxLines: 1,- overflow: TextOverflow.ellipsis,- ),- const SizedBox(height: 12),- MenuItemWidgetNew(- title: l10n.addANameAndPhoto,- subText: l10n.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,- ),- ],+ padding: const EdgeInsets.fromLTRB(16, 24, 16, 8),+ child: MenuItemWidgetNew(+ title: l10n.addANameAndPhoto,+ titleColor: colorScheme.textBase,+ leadingIconWidget: _AddContactMenuIcon(colorScheme: colorScheme),+ leadingIconSize: 36,+ trailingIcon: Icons.chevron_right_rounded,+ trailingIconIsMuted: true,+ onTap: onTap,),);}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.dartindex 374ee83be0..7d5da6e8ee 100644--- 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@@ -1,40 +1,24 @@-import "dart:async";import "dart:typed_data";+import "package:ente_components/ente_components.dart";import "package:ente_contacts/contacts.dart" as contacts;import "package:ente_pure_utils/ente_pure_utils.dart";-import "package:figma_squircle/figma_squircle.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/generated/l10n.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/action_sheet_widget.dart";import "package:photos/ui/components/buttons/button_widget.dart";-import "package:photos/ui/components/menu_item_widget/menu_item_widget_new.dart";import "package:photos/ui/components/models/button_type.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/contact_photo_util.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 {@@ -54,22 +38,17 @@ class EditContactPage extends StatefulWidget {}class _EditContactPageState extends State<EditContactPage> {- static const _maxThumbnailCompressionAttempts = 2;static const _avatarSize = 108.0;static const _editBadgeSize = 32.0;- static const _avatarRadius = 20.0;- static const _avatarCornerSmoothing = 0.6;final _logger = Logger("EditContactPage");late final TextEditingController _nameController;- String? _selectedBirthDate;+ late final FocusNode _nameFocusNode;+ late final String? _birthDateToPreserve;bool _isSaving = false;bool _isLoadingPhoto = false;bool _photoDirty = false;- bool _resolvedAutofillPeople = false;Uint8List? _draftPhotoBytes;- PersonEntity? _autofillPerson;- List<PersonEntity> _autofillPreviewPeople = const [];int _photoLoadGeneration = 0;@override@@ -82,29 +61,31 @@ class _EditContactPageState extends State<EditContactPage> {setState(() {});}});- _selectedBirthDate = widget.existingContact?.data?.birthDate;+ _nameFocusNode = FocusNode()+ ..addListener(() {+ if (mounted) {+ setState(() {});+ }+ });+ _birthDateToPreserve = widget.existingContact?.data?.birthDate;_loadExistingPhoto();- unawaited(_loadAutofillPeoplePreview());}@overridevoid dispose() {_nameController.dispose();+ _nameFocusNode.dispose();super.dispose();}bool get _canSave => !_isSaving && _nameController.text.trim().isNotEmpty;String get _initialName => (widget.existingContact?.data?.name ?? "").trim();- String? get _initialBirthDate => widget.existingContact?.data?.birthDate;bool get _hasUnsavedChanges =>- _nameController.text.trim() != _initialName ||- _selectedBirthDate != _initialBirthDate ||- _photoDirty;+ _nameController.text.trim() != _initialName || _photoDirty;@overrideWidget build(BuildContext context) {- final colorScheme = getEnteColorScheme(context);- final textTheme = getEnteTextTheme(context);+ final colors = context.componentColors;final l10n = AppLocalizations.of(context);return PopScope(@@ -132,22 +113,20 @@ class _EditContactPageState extends State<EditContactPage> {}},child: Scaffold(- backgroundColor: colorScheme.backgroundColour,- appBar: AppBar(- elevation: 0,- scrolledUnderElevation: 0,- backgroundColor: colorScheme.backgroundColour,- surfaceTintColor: Colors.transparent,- title: Text(- l10n.editContact,- style: textTheme.h3Bold.copyWith(fontSize: 20, height: 28 / 20),- ),- centerTitle: false,- ),+ resizeToAvoidBottomInset: true,+ backgroundColor: colors.backgroundBase,body: Column(children: [+ _EditContactHeader(+ title: l10n.editContact,+ onBack: () {+ Navigator.of(context).maybePop();+ },+ ),Expanded(child: ListView(+ keyboardDismissBehavior:+ ScrollViewKeyboardDismissBehavior.onDrag,padding: const EdgeInsets.fromLTRB(24, 20, 24, 20),children: [Center(@@ -161,8 +140,8 @@ class _EditContactPageState extends State<EditContactPage> {children: [_buildAvatar(context, size: _avatarSize),Positioned(- right: -4,- bottom: -4,+ right: 0,+ bottom: 0,child: _AvatarEditButton(size: _editBadgeSize,onTap: _pickContactPhoto,@@ -173,82 +152,30 @@ class _EditContactPageState extends State<EditContactPage> {),),),- const SizedBox(height: 32),- if (_showAutofillRow) ...[- MenuItemWidgetNew(- title: l10n.autoFetchFromPeople,- subText: l10n.useTheirNameAndPhoto,- 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),- ],- _FieldLabel(text: l10n.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),- _FieldLabel(text: l10n.name),- const SizedBox(height: 8),- _InputShell(- child: TextField(- controller: _nameController,- textCapitalization: TextCapitalization.words,- style: textTheme.body,- decoration: InputDecoration(- hintText: l10n.enterName,- hintStyle: textTheme.bodyFaint,- border: InputBorder.none,- contentPadding: const EdgeInsets.symmetric(- horizontal: 16,- vertical: 16,- ),- ),- ),+ const SizedBox(height: 20),+ _ReadOnlyContactTextInput(+ label: l10n.email,+ value: widget.email,),- const SizedBox(height: 24),- _FieldLabel(text: l10n.birthday),- const SizedBox(height: 8),- _BirthDateField(- value: _selectedBirthDate,- onTap: _pickBirthDate,- onClear: _selectedBirthDate == null- ? null- : () {- setState(() {- _selectedBirthDate = null;- });- },- hintText: l10n.enterDateOfBirthHint,+ const SizedBox(height: 20),+ TextInputComponent(+ label: l10n.name,+ hintText: l10n.enterName,+ controller: _nameController,+ focusNode: _nameFocusNode,+ isRequired: true,+ textCapitalization: TextCapitalization.words,+ onSubmit: _canSave ? (_) => _saveContact() : null,),],),),- SafeArea(- top: false,- child: Padding(- padding: const EdgeInsets.fromLTRB(24, 8, 24, 24),- child: _SaveContactButton(- isDisabled: !_canSave,- onTap: _canSave ? _saveContact : null,- ),+ Padding(+ padding: const EdgeInsets.fromLTRB(24, 24, 24, 24),+ child: _ContactSaveButton(+ label: l10n.saveContact,+ isDisabled: !_canSave,+ onTap: _canSave ? _saveContact : null,),),],@@ -361,55 +288,17 @@ class _EditContactPageState extends State<EditContactPage> {setState(() {_isLoadingPhoto = true;});- final photoBytes = await _normalizeAttachmentBytes(croppedBytes);+ final photoBytes = await normalizeContactPhotoAttachmentBytes(croppedBytes);if (!mounted) {return;}setState(() {_draftPhotoBytes = photoBytes;_isLoadingPhoto = false;- _photoDirty = photoBytes != null;- _autofillPerson = null;+ _photoDirty = true;});}- 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;@@ -418,7 +307,7 @@ class _EditContactPageState extends State<EditContactPage> {var saved = await PhotosContactsService.instance.createOrUpdateContact(contactUserId: widget.contactUserId,name: _nameController.text.trim(),- birthDate: _selectedBirthDate,+ birthDate: _birthDateToPreserve,);if (_photoDirty && _draftPhotoBytes != null) {saved = await PhotosContactsService.instance.setProfilePicture(@@ -504,267 +393,159 @@ class _EditContactPageState extends State<EditContactPage> {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;- }- }- }+class _EditContactHeader extends StatelessWidget {+ const _EditContactHeader({required this.title, required this.onBack});- if (sourceFile == null || sourceFile.uploadedFileID == null) {- return null;- }+ final String title;+ final VoidCallback onBack;- final face = await MLDataDB.instance.getCoverFaceForPerson(- recentFileID: sourceFile.uploadedFileID!,- avatarFaceId: faceId,- personID: person.remoteID,- );- if (face == null) {- return null;- }+ @override+ Widget build(BuildContext context) {+ final topPadding = MediaQuery.paddingOf(context).top;+ final colors = context.componentColors;+ final height = topPadding + 76;- 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;- }+ return SizedBox(+ width: double.infinity,+ height: height,+ child: Padding(+ padding: EdgeInsets.only(top: topPadding),+ child: ColoredBox(+ color: colors.backgroundBase,+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: Spacing.lg),+ child: _expandedContent(context),+ ),+ ),+ ),+ );}- 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,+ Widget _expandedContent(BuildContext context) {+ return Padding(+ padding: const EdgeInsets.only(top: Spacing.lg),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ _BackButton(onBack: onBack),+ const SizedBox(height: 8),+ Text(title, style: _titleStyle(context)),+ ],+ ),);- 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;- });- }+ TextStyle _titleStyle(BuildContext context) {+ return TextStyles.display2.copyWith(+ color: context.componentColors.textBase,+ );}}-class _FieldLabel extends StatelessWidget {- final String text;- final bool isRequired;+class _BackButton extends StatelessWidget {+ const _BackButton({required this.onBack});- const _FieldLabel({required this.text, this.isRequired = false});+ final VoidCallback onBack;@overrideWidget 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,- ),+ final tooltip = MaterialLocalizations.of(context).backButtonTooltip;+ return Semantics(+ button: true,+ label: tooltip,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: onBack,+ child: SizedBox(+ width: 40,+ height: 20,+ child: Align(+ alignment: Alignment.centerLeft,+ child: Icon(+ Icons.arrow_back,+ size: 24,+ color: getEnteColorScheme(context).textBase,),- ],+ ),+ ),),);}}-class _InputShell extends StatelessWidget {- final Widget child;+class _ReadOnlyContactTextInput extends StatelessWidget {+ const _ReadOnlyContactTextInput({required this.label, required this.value});- const _InputShell({required this.child});+ final String label;+ final String value;@overrideWidget 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,+ final colors = context.componentColors;+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(label, style: TextStyles.body.copyWith(color: colors.textBase)),+ const SizedBox(height: 9),+ Container(+ height: 52,+ width: double.infinity,+ alignment: Alignment.centerLeft,+ padding: const EdgeInsets.symmetric(horizontal: Spacing.lg),+ decoration: BoxDecoration(+ color: colors.fillLight,+ borderRadius: BorderRadius.circular(Radii.lg),+ ),+ child: Text(+ value,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyles.body.copyWith(color: colors.textLightest),+ ),+ ),+ ],);}}-class _BirthDateField extends StatelessWidget {- final String? value;- final String hintText;- final VoidCallback onTap;- final VoidCallback? onClear;-- const _BirthDateField({- required this.value,+class _ContactSaveButton extends StatelessWidget {+ const _ContactSaveButton({+ required this.label,+ required this.isDisabled,required this.onTap,- required this.hintText,- this.onClear,});+ final String label;+ final bool isDisabled;+ final VoidCallback? onTap;+@overrideWidget 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,- ),- ],+ final colors = context.componentColors;+ final enabled = !isDisabled && onTap != null;+ return GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: enabled ? onTap : null,+ child: AnimatedContainer(+ duration: Motion.standard,+ curve: Curves.easeInOutCubic,+ width: double.infinity,+ height: 48,+ alignment: Alignment.center,+ padding: const EdgeInsets.symmetric(horizontal: Spacing.xxl),+ decoration: BoxDecoration(+ color: enabled ? colors.primary : colors.fillDark,+ borderRadius: BorderRadius.circular(Radii.button),+ ),+ child: Text(+ label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyles.body.copyWith(+ color: enabled ? colors.specialWhite : colors.textLightest,),),),@@ -813,11 +594,8 @@ class _ContactThumbnailShell extends StatelessWidget {return SizedBox(width: size,height: size,- child: ClipSmoothRect(- radius: SmoothBorderRadius(- cornerRadius: _EditContactPageState._avatarRadius,- cornerSmoothing: _EditContactPageState._avatarCornerSmoothing,- ),+ child: FaceThumbnailSquircleClip(+ borderRadius: faceThumbnailSquircleBorderRadius(size),child: ColoredBox(color: backgroundColor ?? Colors.transparent,child: SizedBox.expand(child: child),@@ -826,149 +604,3 @@ class _ContactThumbnailShell extends StatelessWidget {);}}--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 l10n = AppLocalizations.of(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(- l10n.saveContact,- style: textTheme.small.copyWith(- color: textColor,- fontWeight: FontWeight.w500,- height: 20 / 14,- ),- ),- ),- ),- ),- );- }-}diff --git a/mobile/apps/photos/lib/utils/contact_photo_util.dart b/mobile/apps/photos/lib/utils/contact_photo_util.dartnew file mode 100644index 0000000000..db80ccc25b--- /dev/null+++ b/mobile/apps/photos/lib/utils/contact_photo_util.dart@@ -0,0 +1,93 @@+import "dart:typed_data";++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/face.dart";+import "package:photos/models/ml/face/person.dart";+import "package:photos/services/machine_learning/ml_result.dart";+import "package:photos/services/search_service.dart";+import "package:photos/utils/face/face_thumbnail_cache.dart";+import "package:photos/utils/file_util.dart";++const _maxContactPhotoCompressionAttempts = 2;++Future<Uint8List> normalizeContactPhotoAttachmentBytes(+ Uint8List sourceBytes,+) async {+ var bytes = sourceBytes;+ var attempts = 0;+ while (bytes.length > thumbnailDataLimit &&+ attempts < _maxContactPhotoCompressionAttempts) {+ bytes = await compressThumbnail(bytes);+ attempts++;+ }+ return bytes;+}++Future<Uint8List?> buildContactPhotoAttachmentBytesFromFace({+ required EnteFile file,+ required Face face,+}) async {+ final crops = await getCachedFaceCrops(+ file,+ [face],+ useFullFile: true,+ useTempCache: false,+ );+ final croppedBytes = crops?[face.faceID];+ if (croppedBytes == null) {+ return null;+ }+ return normalizeContactPhotoAttachmentBytes(croppedBytes);+}++Future<Uint8List?> buildContactPhotoAttachmentBytesFromPerson(+ PersonEntity person,+) async {+ 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;+ }++ return buildContactPhotoAttachmentBytesFromFace(file: sourceFile, face: face);+}diff --git a/mobile/apps/photos/test/services/photos_contacts_service_test.dart b/mobile/apps/photos/test/services/photos_contacts_service_test.dartindex 1c9e8be5ad..a0728e6efc 100644--- a/mobile/apps/photos/test/services/photos_contacts_service_test.dart+++ b/mobile/apps/photos/test/services/photos_contacts_service_test.dart@@ -66,12 +66,23 @@ void main() {expect(service.hasHydratedCache, isTrue);expect(service.getCachedContactByUserId(7), isNotNull);+ expect((await service.getContact(email: '[email protected]'))?.id, 'ct_1');expect(service.getCachedSavedNameByUserId(7), 'Alice');expect(service.getCachedResolvedEmailByUserId(7), '[email protected]');expect(contactsService.openCalls, 1);expect(contactsService.syncCalls, 1);});+ test('user id lookup does not fall back to email', () async {+ await service.debugOpenAndSync(session);++ expect(+ await service.getContact(contactUserId: 99, email: '[email protected]'),+ isNull,+ );+ expect((await service.getContact(email: '[email protected]'))?.id, 'ct_1');+ });+test('stale in-flight debugOpenAndSync does not repopulate cache after session switch',() async {@@ -228,6 +239,43 @@ void main() {},);+ test('loads profile picture through linked email lookup', () async {+ contactsService = FakeContactsService(+ localContacts: const [+ contacts.ContactRecord(+ id: 'ct_1',+ contactUserId: 7,+ email: '[email protected]',+ data: contacts.ContactData(contactUserId: 7, name: 'Alice'),+ profilePictureAttachmentId: 'att_1',+ isDeleted: false,+ createdAt: 1,+ updatedAt: 2,+ ),+ ],+ );+ contactsService.profilePictureBytesByContactId['ct_1'] = Uint8List.fromList(+ [4, 5, 6],+ );+ service = PhotosContactsService.forTesting(+ contactsService: contactsService,+ );++ await service.debugOpenAndSync(session);++ final contact = await service.getContact(email: '[email protected]');+ expect(contact?.id, 'ct_1');+ expect(+ await service.getProfilePictureBytesByUserId(contact!.contactUserId),+ Uint8List.fromList([4, 5, 6]),+ );+ expect(+ service.getCachedProfilePictureBytesByUserId(7),+ Uint8List.fromList([4, 5, 6]),+ );+ expect(contactsService.getProfilePictureCalls, 1);+ });+test('logout event clears hydrated contact cache immediately', () async {await service.debugOpenAndSync(session);@@ -298,6 +346,20 @@ class FakeContactsService extends Fake implements contacts.ContactsService {return response;}+ @override+ Future<contacts.ContactRecord?> getContactByUserId(+ int contactUserId, {+ bool includeDeleted = false,+ }) async {+ for (final contact in localContacts) {+ if (contact.contactUserId == contactUserId &&+ (includeDeleted || !contact.isDeleted)) {+ return contact;+ }+ }+ return null;+ }+@overrideFuture<List<contacts.ContactRecord>> sync() async {syncCalls += 1;