diff options
| author | mirror <mirror@localhost> | 2026-11-22 08:41:00 +0900 |
|---|---|---|
| committer | mirror <mirror@localhost> | 2026-11-22 08:41:00 +0900 |
| commit | 449d8b74bd6d9dae98a07254cdfad677b920e7b0 (patch) | |
| tree | c131c3528c4d517f56e19b854a7453fedb097d40 /lib/model/entry/extensions | |
| download | aves-src-master.tar.gz aves-src-master.zip | |
Diffstat (limited to 'lib/model/entry/extensions')
| -rw-r--r-- | lib/model/entry/extensions/catalog.dart | 82 | ||||
| -rw-r--r-- | lib/model/entry/extensions/favourites.dart | 26 | ||||
| -rw-r--r-- | lib/model/entry/extensions/images.dart | 83 | ||||
| -rw-r--r-- | lib/model/entry/extensions/info.dart | 179 | ||||
| -rw-r--r-- | lib/model/entry/extensions/keys.dart | 28 | ||||
| -rw-r--r-- | lib/model/entry/extensions/location.dart | 90 | ||||
| -rw-r--r-- | lib/model/entry/extensions/metadata_edition.dart | 590 | ||||
| -rw-r--r-- | lib/model/entry/extensions/multipage.dart | 43 | ||||
| -rw-r--r-- | lib/model/entry/extensions/props.dart | 140 |
9 files changed, 1261 insertions, 0 deletions
diff --git a/lib/model/entry/extensions/catalog.dart b/lib/model/entry/extensions/catalog.dart new file mode 100644 index 0000000..593fadd --- /dev/null +++ b/lib/model/entry/extensions/catalog.dart @@ -0,0 +1,82 @@ +import 'dart:async'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/keys.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/media/geotiff.dart'; +import 'package:aves/model/media/video/metadata.dart'; +import 'package:aves/model/metadata/catalog.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/metadata/svg_metadata_service.dart'; +import 'package:flutter/foundation.dart'; + +extension ExtraAvesEntryCatalog on AvesEntry { + Future<void> catalog({required bool background, required bool force, required bool persist}) async { + if (isCatalogued && !force) return; + + final beforeAvailableHeapSize = await deviceService.getAvailableHeapSize(); + + if (isSvg) { + // vector image sizing is not essential, so we should not spend time for it during loading + // but it is useful anyway (for aspect ratios etc.) so we size them during cataloguing + final size = await SvgMetadataService.getSize(this); + if (size != null) { + final fields = { + EntryFields.width: size.width.ceil(), + EntryFields.height: size.height.ceil(), + }; + await applyNewFields(fields, persist: persist); + } + catalogMetadata = CatalogMetadata(id: id); + } else { + // pre-processing + if (isVideo || mimeType == MimeTypes.avif) { + // on initial loading, original source may report incorrect size, rotation or duration + final fields = await VideoMetadataFormatter.getLoadingMetadata(this); + // check size as the video interpreter may fail on some AVIF stills + final width = fields[EntryFields.width]; + final height = fields[EntryFields.height]; + final isValid = (width == null || width > 0) && (height == null || height > 0); + if (isValid) { + await applyNewFields(fields, persist: persist); + } + } + + // cataloguing on platform + catalogMetadata = await metadataFetchService.getCatalogMetadata(this, background: background); + + // post-processing + if ((isVideo && (catalogMetadata?.dateMillis ?? 0) == 0) || (mimeType == MimeTypes.avif && durationMillis != null)) { + final videoMetadata = await VideoMetadataFormatter.completeCatalogMetadata(this); + if (videoMetadata != null) { + catalogMetadata = videoMetadata; + } + } + if (isGeotiff && !hasGps) { + final info = await metadataFetchService.getGeoTiffInfo(this); + if (info != null) { + final center = GeoTiffCoordinateConverter( + info: info, + entry: this, + ).center; + if (center != null) { + catalogMetadata = catalogMetadata?.copyWith( + latitude: center.latitude, + longitude: center.longitude, + ); + } + } + } + } + + final afterAvailableHeapSize = await deviceService.getAvailableHeapSize(); + final diff = beforeAvailableHeapSize - afterAvailableHeapSize; + const largeHeapUsageThreshold = 15 * (1 << 20); // MB + + if (diff > largeHeapUsageThreshold) { + debugPrint('Large heap usage (${diff}B) from cataloguing entry=$this size=$sizeBytes'); + await deviceService.requestGarbageCollection(); + } + } +} diff --git a/lib/model/entry/extensions/favourites.dart b/lib/model/entry/extensions/favourites.dart new file mode 100644 index 0000000..22ca36f --- /dev/null +++ b/lib/model/entry/extensions/favourites.dart @@ -0,0 +1,26 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/favourites.dart'; + +extension ExtraAvesEntryFav on AvesEntry { + bool get isFavourite => favourites.isFavourite(this); + + Future<void> toggleFavourite() async { + if (isFavourite) { + await removeFromFavourites(); + } else { + await addToFavourites(); + } + } + + Future<void> addToFavourites() async { + if (!isFavourite) { + await favourites.add({this}); + } + } + + Future<void> removeFromFavourites() async { + if (isFavourite) { + await favourites.removeEntries({this}); + } + } +} diff --git a/lib/model/entry/extensions/images.dart b/lib/model/entry/extensions/images.dart new file mode 100644 index 0000000..8181bd5 --- /dev/null +++ b/lib/model/entry/extensions/images.dart @@ -0,0 +1,83 @@ +import 'dart:math'; + +import 'package:aves/image_providers/full_image_provider.dart'; +import 'package:aves/image_providers/region_provider.dart'; +import 'package:aves/image_providers/thumbnail_provider.dart'; +import 'package:aves/model/entry/cache.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/utils/math_utils.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/painting.dart'; + +extension ExtraAvesEntryImages on AvesEntry { + bool isThumbnailReady({double extent = 0}) => _isReady(_getThumbnailProviderKey(extent)); + + ThumbnailProvider getThumbnail({double extent = 0}) { + return ThumbnailProvider(_getThumbnailProviderKey(extent)); + } + + ThumbnailProviderKey _getThumbnailProviderKey(double extent) { + final requestExtent = extent.roundToDouble(); + EntryCache.markThumbnailExtent(requestExtent); + return ThumbnailProviderKey( + uri: uri, + mimeType: mimeType, + pageId: pageId, + rotationDegrees: rotationDegrees, + isFlipped: isFlipped, + dateModifiedMillis: dateModifiedMillis ?? -1, + extent: requestExtent, + ); + } + + RegionProvider getRegion({int sampleSize = 1, double scale = 1, required Rectangle<num> region}) { + return RegionProvider(RegionProviderKey( + uri: uri, + mimeType: mimeType, + pageId: pageId, + sizeBytes: sizeBytes, + rotationDegrees: rotationDegrees, + isFlipped: isFlipped, + sampleSize: sampleSize, + regionRect: Rectangle( + (region.left * scale).round(), + (region.top * scale).round(), + (region.width * scale).round(), + (region.height * scale).round(), + ), + imageSize: Size((width * scale).toDouble(), (height * scale).toDouble()), + )); + } + + Rectangle<double> get fullImageRegion => Rectangle<double>(.0, .0, width.toDouble(), height.toDouble()); + + FullImage get fullImage => FullImage( + uri: uri, + mimeType: mimeType, + pageId: pageId, + rotationDegrees: rotationDegrees, + isFlipped: isFlipped, + isAnimated: isAnimated, + sizeBytes: sizeBytes, + ); + + bool _isReady(Object providerKey) => imageCache.statusForKey(providerKey).keepAlive; + + List<ThumbnailProvider> get cachedThumbnails => EntryCache.thumbnailRequestExtents.map(_getThumbnailProviderKey).where(_isReady).map(ThumbnailProvider.new).toList(); + + ThumbnailProvider get bestCachedThumbnail { + final sizedThumbnailKey = EntryCache.thumbnailRequestExtents.map(_getThumbnailProviderKey).firstWhereOrNull(_isReady); + return sizedThumbnailKey != null ? ThumbnailProvider(sizedThumbnailKey) : getThumbnail(); + } + + static int sampleSizeForScale({ + required double magnifierScale, + required double devicePixelRatio, + }) { + var sample = 0; + if (0 < magnifierScale && magnifierScale < 1) { + sample = highestPowerOf2(1 / (magnifierScale * devicePixelRatio)); + } + return max<int>(1, sample); + } +} diff --git a/lib/model/entry/extensions/info.dart b/lib/model/entry/extensions/info.dart new file mode 100644 index 0000000..81fc0bf --- /dev/null +++ b/lib/model/entry/extensions/info.dart @@ -0,0 +1,179 @@ +import 'dart:async'; +import 'dart:collection'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/media/video/metadata.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/metadata/svg_metadata_service.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/format.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/widgets/viewer/info/metadata/metadata_dir.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +extension ExtraAvesEntryInfo on AvesEntry { + // directory names may contain the name of their parent directory (as prefix + '/') + // directory names may contain an index (as suffix in '[]') + static final directoryNamePattern = RegExp(r'^((?<parent>.*?)/)?(?<name>.*?)(\[(?<index>\d+)\])?$'); + + Future<List<MapEntry<String, MetadataDirectory>>> getMetadataDirectories(BuildContext context) async { + final rawMetadata = await (isSvg ? SvgMetadataService.getAllMetadata(this) : metadataFetchService.getAllMetadata(this)); + final directories = rawMetadata.entries.map((dirKV) { + var directoryName = dirKV.key as String; + + String? parent; + int? index; + final match = directoryNamePattern.firstMatch(directoryName); + if (match != null) { + parent = match.namedGroup('parent'); + final nameMatch = match.namedGroup('name'); + if (nameMatch != null) { + directoryName = nameMatch; + } + final indexMatch = match.namedGroup('index'); + if (indexMatch != null) { + index = int.tryParse(indexMatch); + } + } + + final rawTags = dirKV.value as Map; + return MetadataDirectory( + directoryName, + _toSortedTags(rawTags), + parent: parent, + index: index, + ); + }).toList(); + + if (isVideo || (mimeType == MimeTypes.heif && isMultiPage) || mimeType == MimeTypes.avif) { + directories.addAll(await _getStreamDirectories(context)); + } + + final titledDirectories = directories.map((dir) { + var title = dir.name; + if (directories.where((dir) => dir.name == title).length > 1 && dir.parent?.isNotEmpty == true) { + title = '${dir.parent}/$title'; + } + if (dir.index != null) { + title += ' ${dir.index}'; + } + return MapEntry(title, dir); + }).toList() + ..sort((a, b) => compareAsciiUpperCase(a.key, b.key)); + + return titledDirectories; + } + + Future<List<MetadataDirectory>> _getStreamDirectories(BuildContext context) async { + final directories = <MetadataDirectory>[]; + final mediaInfo = await videoMetadataFetcher.getMetadata(this); + if (!context.mounted) { + return directories; + } + + final formattedMediaTags = VideoMetadataFormatter.formatInfo(mediaInfo); + if (formattedMediaTags.isNotEmpty) { + // overwrite generic directory found from the platform side + directories.add(MetadataDirectory(MetadataDirectory.mediaDirectory, _toSortedTags(formattedMediaTags))); + } + + if (mediaInfo.containsKey(Keys.chapters)) { + final allChapters = (mediaInfo.remove(Keys.chapters) as List).cast<Map>(); + if (allChapters.isNotEmpty) { + allChapters.sortBy((v) => v[Keys.time] as num? ?? 0); + + final chapterTags = SplayTreeMap.of(Map.fromEntries(allChapters.mapIndexed((i, chapter) { + final chapterNumber = i + 1; + final time = Duration(seconds: (chapter[Keys.time] as num? ?? 0).round()); + final title = chapter[Keys.title] as String? ?? 'Chapter $chapterNumber'; + return MapEntry('$chapterNumber${AText.separator}${formatFriendlyDuration(time)}', title); + })), compareNatural); + directories.add(MetadataDirectory('Chapters', chapterTags)); + } + } + + if (mediaInfo.containsKey(Keys.streams)) { + String getTypeText(Map stream) { + final type = stream[Keys.streamType] ?? MediaStreamTypes.unknown; + switch (type) { + case MediaStreamTypes.attachment: + return 'Attachment'; + case MediaStreamTypes.audio: + return 'Audio'; + case MediaStreamTypes.metadata: + return 'Metadata'; + case MediaStreamTypes.subtitle: + case MediaStreamTypes.timedText: + return 'Text'; + case MediaStreamTypes.video: + return stream.containsKey(Keys.fpsDen) || stream.containsKey(Keys.fps) ? 'Video' : 'Image'; + case MediaStreamTypes.unknown: + default: + return 'Unknown'; + } + } + + final allStreams = (mediaInfo[Keys.streams] as List).cast<Map>(); + final attachmentStreams = allStreams.where((stream) => stream[Keys.streamType] == MediaStreamTypes.attachment).toList(); + final knownStreams = allStreams.whereNot(attachmentStreams.contains); + + // display known streams as separate directories (e.g. video, audio, subs) + if (knownStreams.isNotEmpty) { + final indexDigits = knownStreams.length.toString().length; + + final colors = context.read<AvesColorsData>(); + for (final stream in knownStreams) { + final index = (stream[Keys.index] ?? 0) + 1; + final typeText = getTypeText(stream); + final dirName = [ + 'Stream ${index.toString().padLeft(indexDigits, '0')}', + typeText, + ].join(AText.separator); + final formattedStreamTags = VideoMetadataFormatter.formatInfo(stream); + if (formattedStreamTags.isNotEmpty) { + final color = colors.fromString(typeText); + directories.add(MetadataDirectory(dirName, _toSortedTags(formattedStreamTags), color: color)); + } + } + } + + // group attachments by format (e.g. TTF fonts) + if (attachmentStreams.isNotEmpty) { + final formatCount = <String, List<String?>>{}; + for (final stream in attachmentStreams) { + final codec = (stream[Keys.codecName] as String? ?? 'unknown').toUpperCase(); + if (!formatCount.containsKey(codec)) { + formatCount[codec] = []; + } + formatCount[codec]!.add(stream[Keys.filename]); + } + if (formatCount.isNotEmpty) { + final rawTags = formatCount.map((key, value) { + final count = value.length; + // remove duplicate names, so number of displayed names may not match displayed count + final names = value.nonNulls.toSet().toList()..sort(compareAsciiUpperCase); + return MapEntry(key, '$count items: ${names.join(', ')}'); + }); + directories.add(MetadataDirectory('Attachments', _toSortedTags(rawTags))); + } + } + } + return directories; + } + + SplayTreeMap<String, String> _toSortedTags(Map rawTags) { + final tags = SplayTreeMap.of(Map.fromEntries(rawTags.entries.map((tagKV) { + var value = (tagKV.value as String? ?? '').trim(); + if (value.isEmpty) return null; + final tagName = tagKV.key as String; + return MapEntry(tagName, value); + }).nonNulls)); + return tags; + } +} diff --git a/lib/model/entry/extensions/keys.dart b/lib/model/entry/extensions/keys.dart new file mode 100644 index 0000000..d6eeafb --- /dev/null +++ b/lib/model/entry/extensions/keys.dart @@ -0,0 +1,28 @@ +// entry fields exported and imported from/to the platform side +// should match `EntryFields` on platform side +class EntryFields { + static const id = 'id'; // int + static const origin = 'origin'; // int + static const uri = 'uri'; // string + static const contentId = 'contentId'; // long + static const path = 'path'; // string + static const pageId = 'pageId'; // int + static const sourceMimeType = 'sourceMimeType'; // string + static const mimeType = 'mimeType'; // string + + static const width = 'width'; // int + static const height = 'height'; // int + static const sourceRotationDegrees = 'sourceRotationDegrees'; // int + static const rotationDegrees = 'rotationDegrees'; // int + static const isFlipped = 'isFlipped'; // boolean + + static const dateAddedSecs = 'dateAddedSecs'; // long + static const dateModifiedMillis = 'dateModifiedMillis'; // long + static const sourceDateTakenMillis = 'sourceDateTakenMillis'; // long + static const durationMillis = 'durationMillis'; // long + + static const sizeBytes = 'sizeBytes'; // long + static const trashed = 'trashed'; // boolean + static const trashPath = 'trashPath'; // string + static const title = 'title'; // string +} diff --git a/lib/model/entry/extensions/location.dart b/lib/model/entry/extensions/location.dart new file mode 100644 index 0000000..e33c4ab --- /dev/null +++ b/lib/model/entry/extensions/location.dart @@ -0,0 +1,90 @@ +import 'dart:async'; +import 'dart:ui'; + +import 'package:aves/geo/countries.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/metadata/address.dart'; +import 'package:aves/services/common/service_policy.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/geocoding_service.dart'; +import 'package:country_code/country_code.dart'; +import 'package:flutter/foundation.dart'; +import 'package:latlong2/latlong.dart'; + +extension ExtraAvesEntryLocation on AvesEntry { + static final _invalidLocalityPattern = RegExp(r'^[-+\dA-Z]+$'); + + LatLng? get latLng => hasGps ? LatLng(catalogMetadata!.latitude!, catalogMetadata!.longitude!) : null; + + Future<void> locate({required bool background, required bool force, required Locale geocoderLocale}) async { + if (hasGps) { + await _locateCountry(force: force); + if (await availability.canLocatePlaces) { + await locatePlace(background: background, force: force, geocoderLocale: geocoderLocale); + } + } else { + addressDetails = null; + } + } + + // quick reverse geocoding to find the country, using an offline asset + Future<void> _locateCountry({required bool force}) async { + if (!hasGps || (hasAddress && !force)) return; + final countryCode = await countryTopology.countryCode(latLng!); + setCountry(countryCode); + } + + void setCountry(CountryCode? countryCode) { + if (hasFineAddress || countryCode == null) return; + addressDetails = AddressDetails( + id: id, + countryCode: countryCode.alpha2, + countryName: countryCode.alpha3, + ); + } + + // full reverse geocoding, requiring Play Services and some connectivity + Future<void> locatePlace({required bool background, required bool force, required Locale geocoderLocale}) async { + if (!hasGps || (hasFineAddress && !force)) return; + try { + Future<List<Address>> call() => GeocodingService.getAddress(latLng!, geocoderLocale); + final addresses = await (background + ? servicePolicy.call( + call, + priority: ServiceCallPriority.getLocation, + ) + : call()); + if (addresses.isNotEmpty) { + final v = addresses.first; + var locality = v.locality ?? v.subLocality ?? v.featureName; + if (locality == null || _invalidLocalityPattern.hasMatch(locality) || {v.subThoroughfare, v.countryName}.contains(locality)) { + locality = v.subAdminArea; + } + addressDetails = AddressDetails( + id: id, + countryCode: v.countryCode?.toUpperCase(), + countryName: v.countryName, + adminArea: v.adminArea, + locality: locality, + ); + } + } catch (error, stack) { + debugPrint('$runtimeType locate failed with path=$path coordinates=$latLng error=$error\n$stack'); + } + } + + Future<String?> findAddressLine({required Locale geocoderLocale}) async { + if (!hasGps) return null; + + try { + final addresses = await GeocodingService.getAddress(latLng!, geocoderLocale); + if (addresses.isNotEmpty) { + final address = addresses.first; + return address.addressLine; + } + } catch (error, stack) { + debugPrint('$runtimeType findAddressLine failed with path=$path coordinates=$latLng error=$error\n$stack'); + } + return null; + } +} diff --git a/lib/model/entry/extensions/metadata_edition.dart b/lib/model/entry/extensions/metadata_edition.dart new file mode 100644 index 0000000..3c196d4 --- /dev/null +++ b/lib/model/entry/extensions/metadata_edition.dart @@ -0,0 +1,590 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:aves/convert/convert.dart'; +import 'package:aves/model/device.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/catalog.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/metadata/date_modifier.dart'; +import 'package:aves/ref/locales.dart'; +import 'package:aves/ref/metadata/exif.dart'; +import 'package:aves/ref/metadata/iptc.dart'; +import 'package:aves/ref/metadata/xmp.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/metadata/xmp.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:aves/utils/xmp_utils.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/foundation.dart'; +import 'package:intl/intl.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:xml/xml.dart'; + +extension ExtraAvesEntryMetadataEdition on AvesEntry { + static final _iso6709LatitudeFormatter = NumberFormat('00.0000', asciiLocale); + static final _iso6709LongitudeFormatter = NumberFormat('000.0000', asciiLocale); + + Future<Set<EntryDataType>> editDate(DateModifier userModifier) async { + final dataTypes = <EntryDataType>{}; + + final appliedModifier = await _applyDateModifierToEntry(userModifier); + if (appliedModifier == null) { + if (isValid && userModifier.action != DateEditAction.copyField) { + await reportService.recordError('failed to get date for modifier=$userModifier, entry=$this'); + } + return {}; + } + + if (isExifEditionSupported && appliedModifier.fields.any((v) => v.type == MetadataType.exif)) { + final newFields = await metadataEditService.editExifDate(this, appliedModifier); + if (newFields.isNotEmpty) { + dataTypes.addAll({ + EntryDataType.basic, + EntryDataType.catalog, + }); + } + } + + if (isXmpEditionSupported && appliedModifier.fields.any((v) => v.type == MetadataType.xmp)) { + final metadata = { + MetadataType.xmp: await _editXmp((descriptions) { + switch (appliedModifier.action) { + case DateEditAction.setCustom: + case DateEditAction.copyField: + case DateEditAction.copyItem: + case DateEditAction.extractFromTitle: + editCreateDateXmp(descriptions, appliedModifier.setDateTime); + case DateEditAction.shift: + final xmpDate = XMP.getString(descriptions, XmpAttributes.xmpCreateDate, namespace: XmpNamespaces.xmp); + if (xmpDate != null) { + final date = DateTime.tryParse(xmpDate); + if (date != null) { + // TODO TLAD [date] DateTime.tryParse converts to UTC time, losing the time zone offset + final shiftedDate = date.add(Duration(seconds: appliedModifier.shiftSeconds!)); + editCreateDateXmp(descriptions, shiftedDate); + } else { + reportService.recordError('failed to parse XMP date=$xmpDate'); + } + } + case DateEditAction.remove: + editCreateDateXmp(descriptions, null); + } + return true; + }), + }; + final newFields = await metadataEditService.editMetadata(this, metadata); + if (newFields.isNotEmpty) { + dataTypes.addAll({ + EntryDataType.basic, + EntryDataType.catalog, + }); + } + } + + return dataTypes; + } + + static const removalLocation = LatLng(0, 0); + + Future<Set<EntryDataType>> editLocation(LatLng? latLng) async { + final dataTypes = <EntryDataType>{}; + final metadata = <MetadataType, dynamic>{}; + + final missingDate = await _missingDateCheckAndExifEdit(dataTypes); + + if (isExifEditionSupported) { + // clear every GPS field + final exifFields = Map<MetadataField, dynamic>.fromEntries(MetadataFields.exifGpsFields.map((k) => MapEntry(k, null))); + // add latitude & longitude, if any + if (latLng != null && latLng != removalLocation) { + final latitude = latLng.latitude; + final longitude = latLng.longitude; + exifFields.addAll({ + MetadataField.exifGpsLatitude: latitude.abs(), + MetadataField.exifGpsLatitudeRef: latitude >= 0 ? Exif.latitudeNorth : Exif.latitudeSouth, + MetadataField.exifGpsLongitude: longitude.abs(), + MetadataField.exifGpsLongitudeRef: longitude >= 0 ? Exif.longitudeEast : Exif.longitudeWest, + }); + } + metadata[MetadataType.exif] = Map<String, dynamic>.fromEntries(exifFields.entries.map((kv) => MapEntry(kv.key.toPlatform!, kv.value))); + + if (isXmpEditionSupported && missingDate != null) { + metadata[MetadataType.xmp] = await _editXmp((descriptions) { + editCreateDateXmp(descriptions, missingDate); + return true; + }); + } + } + + if (mimeType == MimeTypes.mp4) { + final mp4Fields = <MetadataField, String?>{}; + + String? iso6709String; + if (latLng != null && latLng != removalLocation) { + final latitude = latLng.latitude; + final longitude = latLng.longitude; + final isoLat = '${latitude >= 0 ? '+' : '-'}${_iso6709LatitudeFormatter.format(latitude.abs())}'; + final isoLon = '${longitude >= 0 ? '+' : '-'}${_iso6709LongitudeFormatter.format(longitude.abs())}'; + iso6709String = '$isoLat$isoLon/'; + } + mp4Fields[MetadataField.mp4GpsCoordinates] = iso6709String; + + if (missingDate != null) { + final xmpParts = await _editXmp((descriptions) { + editCreateDateXmp(descriptions, missingDate); + return true; + }); + mp4Fields[MetadataField.mp4Xmp] = xmpParts[xmpCoreKey]; + } + + metadata[MetadataType.mp4] = Map<String, String?>.fromEntries(mp4Fields.entries.map((kv) => MapEntry(kv.key.toPlatform!, kv.value))); + } + + final newFields = await metadataEditService.editMetadata(this, metadata); + if (newFields.isNotEmpty) { + dataTypes.addAll({ + EntryDataType.catalog, + EntryDataType.address, + }); + } + return dataTypes; + } + + Future<Set<EntryDataType>> _changeExifOrientation(Future<Map<String, dynamic>> Function() apply) async { + final dataTypes = <EntryDataType>{}; + + await _missingDateCheckAndExifEdit(dataTypes); + + final newFields = await apply(); + // applying fields is only useful for a smoother visual change, + // as proper refreshing and persistence happens at the caller level + await applyNewFields(newFields, persist: false); + if (newFields.isNotEmpty) { + dataTypes.addAll({ + EntryDataType.basic, + EntryDataType.aspectRatio, + EntryDataType.catalog, + }); + } + return dataTypes; + } + + Future<Set<EntryDataType>> _rotateMp4(int rotationDegrees) async { + final dataTypes = <EntryDataType>{}; + + final missingDate = await _missingDateCheckAndExifEdit(dataTypes); + + final mp4Fields = <MetadataField, String?>{ + MetadataField.mp4RotationDegrees: rotationDegrees.toString(), + }; + + if (missingDate != null) { + final xmpParts = await _editXmp((descriptions) { + editCreateDateXmp(descriptions, missingDate); + return true; + }); + mp4Fields[MetadataField.mp4Xmp] = xmpParts[xmpCoreKey]; + } + + final metadata = <MetadataType, dynamic>{ + MetadataType.mp4: Map<String, String?>.fromEntries(mp4Fields.entries.map((kv) => MapEntry(kv.key.toPlatform!, kv.value))), + }; + + final newFields = await metadataEditService.editMetadata(this, metadata); + // applying fields is only useful for a smoother visual change, + // as proper refreshing and persistence happens at the caller level + await applyNewFields(newFields, persist: false); + if (newFields.isNotEmpty) { + dataTypes.addAll({ + EntryDataType.basic, + EntryDataType.aspectRatio, + EntryDataType.catalog, + }); + } + return dataTypes; + } + + Future<Set<EntryDataType>> rotate({required bool clockwise}) { + if (mimeType == MimeTypes.mp4) { + return _rotateMp4((rotationDegrees + (clockwise ? 90 : -90) + 360) % 360); + } else { + return _changeExifOrientation(() => metadataEditService.rotate(this, clockwise: clockwise)); + } + } + + Future<Set<EntryDataType>> flip() { + return _changeExifOrientation(() => metadataEditService.flip(this)); + } + + // write title: + // - IPTC / object-name, if IPTC exists + // - XMP / dc:title + // write description: + // - Exif / ImageDescription (clear field) + // - Exif / UserComment (clear field) + // - IPTC / caption-abstract, if IPTC exists + // - XMP / dc:description + Future<Set<EntryDataType>> editTitleDescription(Map<DescriptionField, String?> fields) async { + final dataTypes = <EntryDataType>{}; + final metadata = <MetadataType, dynamic>{}; + + final missingDate = await _missingDateCheckAndExifEdit(dataTypes); + + final editTitle = fields.keys.contains(DescriptionField.title); + final editDescription = fields.keys.contains(DescriptionField.description); + final title = fields[DescriptionField.title]; + final description = fields[DescriptionField.description]; + + if (isExifEditionSupported && editDescription) { + metadata[MetadataType.exif] = { + // clear field because it is subpar, with ASCII support only + MetadataField.exifImageDescription.toPlatform!: null, + // clear field because it is subpar, with ambiguous encoding + MetadataField.exifUserComment.toPlatform!: null, + }; + } + + if (isIptcEditionSupported) { + final iptc = await metadataFetchService.getIptc(this); + if (iptc != null) { + if (editTitle) { + editIptcValues(iptc, IPTC.applicationRecord, IPTC.objectName, {if (title != null) title}); + } + if (editDescription) { + editIptcValues(iptc, IPTC.applicationRecord, IPTC.captionAbstractTag, {if (description != null) description}); + } + metadata[MetadataType.iptc] = iptc; + } + } + + if (isXmpEditionSupported) { + metadata[MetadataType.xmp] = await _editXmp((descriptions) { + var modified = false; + if (editTitle) { + modified |= XMP.setAttribute( + descriptions, + XmpElements.dcTitle, + title, + namespace: XmpNamespaces.dc, + strat: XmpEditStrategy.always, + ); + } + if (editDescription) { + modified |= XMP.setAttribute( + descriptions, + XmpElements.dcDescription, + description, + namespace: XmpNamespaces.dc, + strat: XmpEditStrategy.always, + ); + } + if (modified && missingDate != null) { + editCreateDateXmp(descriptions, missingDate); + } + return modified; + }); + } + + final newFields = await metadataEditService.editMetadata(this, metadata); + if (newFields.isNotEmpty) { + dataTypes.addAll({ + EntryDataType.basic, + EntryDataType.catalog, + }); + } + + return dataTypes; + } + + // write: + // - IPTC / keywords, if IPTC exists + // - XMP / dc:subject + Future<Set<EntryDataType>> editTags(Set<String> tags) async { + final dataTypes = <EntryDataType>{}; + final metadata = <MetadataType, dynamic>{}; + + final missingDate = await _missingDateCheckAndExifEdit(dataTypes); + + if (isIptcEditionSupported) { + final iptc = await metadataFetchService.getIptc(this); + if (iptc != null) { + editIptcValues(iptc, IPTC.applicationRecord, IPTC.keywordsTag, tags); + metadata[MetadataType.iptc] = iptc; + } + } + + if (isXmpEditionSupported) { + metadata[MetadataType.xmp] = await _editXmp((descriptions) { + final modified = editTagsXmp(descriptions, tags); + if (modified && missingDate != null) { + editCreateDateXmp(descriptions, missingDate); + } + return modified; + }); + } + + final newFields = await metadataEditService.editMetadata(this, metadata); + if (newFields.isNotEmpty) { + dataTypes.add(EntryDataType.catalog); + } + return dataTypes; + } + + // write: + // - XMP / xmp:Rating + // update: + // - XMP / MicrosoftPhoto:Rating + // ignore (Windows tags, not part of Exif 2.32 spec): + // - Exif / Rating + // - Exif / RatingPercent + Future<Set<EntryDataType>> editRating(int? rating) async { + final dataTypes = <EntryDataType>{}; + final metadata = <MetadataType, dynamic>{}; + + final missingDate = await _missingDateCheckAndExifEdit(dataTypes); + + if (isXmpEditionSupported) { + metadata[MetadataType.xmp] = await _editXmp((descriptions) { + final modified = editRatingXmp(descriptions, rating); + if (modified && missingDate != null) { + editCreateDateXmp(descriptions, missingDate); + } + return modified; + }); + } + + final newFields = await metadataEditService.editMetadata(this, metadata); + if (newFields.isNotEmpty) { + dataTypes.add(EntryDataType.catalog); + } + return dataTypes; + } + + // remove: + // - trailer video + // - XMP / Container:Directory + // - XMP / GCamera:MicroVideo* + // - XMP / GCamera:MotionPhoto* + Future<Set<EntryDataType>> removeTrailerVideo() async { + final dataTypes = <EntryDataType>{}; + final metadata = <MetadataType, dynamic>{}; + + if (!isXmpEditionSupported) return dataTypes; + + final missingDate = await _missingDateCheckAndExifEdit(dataTypes); + + final newFields = await metadataEditService.removeTrailerVideo(this); + + metadata[MetadataType.xmp] = await _editXmp((descriptions) { + final modified = removeContainerXmp(descriptions); + if (modified && missingDate != null) { + editCreateDateXmp(descriptions, missingDate); + } + return modified; + }); + + newFields.addAll(await metadataEditService.editMetadata(this, metadata, autoCorrectTrailerOffset: false)); + if (newFields.isNotEmpty) { + dataTypes.add(EntryDataType.catalog); + } + return dataTypes; + } + + Future<Set<EntryDataType>> removeMetadata(Set<MetadataType> types) async { + final dataTypes = <EntryDataType>{}; + + final newFields = await metadataEditService.removeTypes(this, types); + if (newFields.isNotEmpty) { + dataTypes.addAll({ + EntryDataType.basic, + EntryDataType.aspectRatio, + EntryDataType.catalog, + EntryDataType.address, + }); + } + return dataTypes; + } + + static void editIptcValues(List<Map<String, dynamic>> iptc, int record, int tag, Set<String> values) { + iptc.removeWhere((v) => v['record'] == record && v['tag'] == tag); + iptc.add({ + 'record': record, + 'tag': tag, + 'values': values.map((v) => utf8.encode(v)).toList(), + }); + } + + @visibleForTesting + static bool editCreateDateXmp(List<XmlNode> descriptions, DateTime? date) { + return XMP.setAttribute( + descriptions, + XmpAttributes.xmpCreateDate, + date != null ? XMP.toXmpDate(date) : null, + namespace: XmpNamespaces.xmp, + strat: XmpEditStrategy.always, + ); + } + + @visibleForTesting + static bool editTagsXmp(List<XmlNode> descriptions, Set<String> tags) { + return XMP.setStringBag( + descriptions, + XmpElements.dcSubject, + tags, + namespace: XmpNamespaces.dc, + strat: XmpEditStrategy.always, + ); + } + + @visibleForTesting + static bool editRatingXmp(List<XmlNode> descriptions, int? rating) { + bool modified = false; + + modified |= XMP.setAttribute( + descriptions, + XmpElements.xmpRating, + (rating ?? 0) == 0 ? null : '$rating', + namespace: XmpNamespaces.xmp, + strat: XmpEditStrategy.always, + ); + + modified |= XMP.setAttribute( + descriptions, + XmpElements.msPhotoRating, + XMP.toMsPhotoRating(rating), + namespace: XmpNamespaces.microsoftPhoto, + strat: XmpEditStrategy.updateIfPresent, + ); + + return modified; + } + + @visibleForTesting + static bool removeContainerXmp(List<XmlNode> descriptions) { + bool modified = false; + + modified |= XMP.removeElements( + descriptions, + XmpElements.containerDirectory, + XmpNamespaces.gContainer, + ); + + modified |= [ + XmpAttributes.gCameraMicroVideo, + XmpAttributes.gCameraMicroVideoVersion, + XmpAttributes.gCameraMicroVideoOffset, + XmpAttributes.gCameraMicroVideoPresentationTimestampUs, + XmpAttributes.gCameraMotionPhoto, + XmpAttributes.gCameraMotionPhotoVersion, + XmpAttributes.gCameraMotionPhotoPresentationTimestampUs, + ].fold<bool>(modified, (prev, name) { + return prev |= XMP.removeElements( + descriptions, + name, + XmpNamespaces.gCamera, + ); + }); + + return modified; + } + + // convenience methods + + // This method checks whether the item already has a metadata date, + // and adds a date (the file modified date) via Exif if possible. + // It returns a date if the caller needs to add it via other metadata types (e.g. XMP). + Future<DateTime?> _missingDateCheckAndExifEdit(Set<EntryDataType> dataTypes) async { + if (path == null) return null; + + // make sure entry is catalogued before we check whether is has a metadata date + if (!isCatalogued) { + await catalog(background: false, force: false, persist: true); + } + final dateMillis = catalogMetadata?.dateMillis; + if (dateMillis != null && dateMillis > 0) return null; + + late DateTime date; + try { + date = await File(path!).lastModified(); + } on FileSystemException catch (_) { + return null; + } + + if (isExifEditionSupported) { + final newFields = await metadataEditService.editExifDate(this, DateModifier.setCustom(const {MetadataField.exifDateOriginal}, date)); + if (newFields.isNotEmpty) { + dataTypes.addAll({ + EntryDataType.basic, + EntryDataType.catalog, + }); + return null; + } + } + + return date; + } + + Future<DateModifier?> _applyDateModifierToEntry(DateModifier modifier) async { + Set<MetadataField> mainMetadataDate() => {isExifEditionSupported ? MetadataField.exifDateOriginal : MetadataField.xmpXmpCreateDate}; + + switch (modifier.action) { + case DateEditAction.copyField: + DateTime? date; + final source = modifier.copyFieldSource; + if (source != null) { + switch (source) { + case DateFieldSource.fileModifiedDate: + try { + if (path != null) { + final file = File(path!); + if (await file.exists()) { + date = await file.lastModified(); + } + } + } on FileSystemException catch (_) {} + default: + date = await metadataFetchService.getDate(this, source.toMetadataField()!); + } + } + return date != null ? DateModifier.setCustom(mainMetadataDate(), date) : null; + case DateEditAction.extractFromTitle: + final date = parseUnknownDateFormat(bestTitle); + return date != null ? DateModifier.setCustom(mainMetadataDate(), date) : null; + case DateEditAction.setCustom: + case DateEditAction.copyItem: + return DateModifier.setCustom(mainMetadataDate(), modifier.setDateTime!); + case DateEditAction.shift: + case DateEditAction.remove: + return modifier; + } + } + + static const xmpCoreKey = 'xmp'; + static const xmpExtendedKey = 'extendedXmp'; + + Future<Map<String, String?>> _editXmp(bool Function(List<XmlNode> descriptions) apply) async { + final xmp = await metadataFetchService.getXmp(this); + if (xmp == null) { + throw Exception('failed to get XMP'); + } + + final xmpString = xmp.xmpString; + final extendedXmpString = xmp.extendedXmpString; + + final editedXmpString = await XMP.edit( + xmpString, + 'Aves v${device.packageVersion}', + apply, + ); + + final editedXmp = AvesXmp(xmpString: editedXmpString, extendedXmpString: extendedXmpString); + return { + xmpCoreKey: editedXmp.xmpString, + xmpExtendedKey: editedXmp.extendedXmpString, + }; + } +} + +enum DescriptionField { title, description } diff --git a/lib/model/entry/extensions/multipage.dart b/lib/model/entry/extensions/multipage.dart new file mode 100644 index 0000000..6b32a8e --- /dev/null +++ b/lib/model/entry/extensions/multipage.dart @@ -0,0 +1,43 @@ +import 'dart:async'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/multipage.dart'; +import 'package:aves/ref/bursts.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:collection/collection.dart'; + +extension ExtraAvesEntryMultipage on AvesEntry { + bool get isMultiPage => isStack || ((catalogMetadata?.isMultiPage ?? false) && (isMotionPhoto || !isHdr)); + + bool get isStack => stackedEntries?.isNotEmpty == true; + + bool get isMotionPhoto => catalogMetadata?.isMotionPhoto ?? false; + + String? getBurstKey(List<String> patterns) { + final key = BurstPatterns.getKeyForName(filenameWithoutExtension, patterns); + return key != null ? '$directory/$key' : null; + } + + Future<MultiPageInfo?> getMultiPageInfo() async { + if (isStack) { + return MultiPageInfo( + mainEntry: this, + pages: stackedEntries! + .mapIndexed((index, entry) => SinglePageInfo( + index: index, + pageId: entry.id, + isDefault: index == 0, + uri: entry.uri, + mimeType: entry.mimeType, + width: entry.width, + height: entry.height, + rotationDegrees: entry.rotationDegrees, + durationMillis: entry.durationMillis, + )) + .toList(), + ); + } else { + return await metadataFetchService.getMultiPageInfo(this); + } + } +} diff --git a/lib/model/entry/extensions/props.dart b/lib/model/entry/extensions/props.dart new file mode 100644 index 0000000..ec21ab7 --- /dev/null +++ b/lib/model/entry/extensions/props.dart @@ -0,0 +1,140 @@ +import 'dart:io'; +import 'dart:ui'; + +import 'package:aves/model/app/support.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/trash.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/ref/unicode.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:intl/intl.dart'; + +extension ExtraAvesEntryProps on AvesEntry { + bool get isValid => !isMissingAtPath && sizeBytes != 0 && width > 0 && height > 0; + + // type + + String get mimeTypeAnySubtype => mimeType.replaceAll(RegExp('/.*'), '/*'); + + bool get canHaveAlpha => MimeTypes.canHaveAlpha(mimeType); + + bool get isSvg => mimeType == MimeTypes.svg; + + bool get isRaw => MimeTypes.isRaw(mimeType); + + bool get isImage => MimeTypes.isImage(mimeType); + + bool get isVideo => MimeTypes.isVideo(mimeType) || (mimeType == MimeTypes.avif && isAnimated); + + bool get isPureVideo => isVideo && !isAnimated; + + // size + + bool get useTiles => !isAnimated; + + bool get isSized => width > 0 && height > 0; + + Size videoDisplaySize(double? sar) { + final size = displaySize; + if (sar != null && sar != 1) { + final dar = displayAspectRatio * sar; + final w = size.width; + final h = size.height; + if (w >= h) return Size(w, w / dar); + if (h > w) return Size(h * dar, h); + } + return size; + } + + // text + + String getResolutionText(String locale) { + final dimensionFormatter = NumberFormat('0', locale); + final ws = dimensionFormatter.format(width); + final hs = dimensionFormatter.format(height); + return isRotated ? '$hs${AText.resolutionSeparator}$ws' : '$ws${AText.resolutionSeparator}$hs'; + } + + String get aspectRatioText { + const separator = UniChars.ratio; + if (width > 0 && height > 0) { + final gcd = width.gcd(height); + final w = width ~/ gcd; + final h = height ~/ gcd; + return isRotated ? '$h$separator$w' : '$w$separator$h'; + } else { + return '?$separator?'; + } + } + + // catalog + + bool get isGeotiff => catalogMetadata?.isGeotiff ?? false; + + bool get is360 => catalogMetadata?.is360 ?? false; + + // trash + + bool get isExpiredTrash { + final dateMillis = trashDetails?.dateMillis; + if (dateMillis == null) return false; + return DateTime.fromMillisecondsSinceEpoch(dateMillis).add(TrashMixin.binKeepDuration).isBefore(DateTime.now()); + } + + int? get trashDaysLeft { + final dateMillis = trashDetails?.dateMillis; + if (dateMillis == null) return null; + return DateTime.fromMillisecondsSinceEpoch(dateMillis).add(TrashMixin.binKeepDuration).difference(DateTime.now()).inHumanDays; + } + + // storage + + String? get storageDirectory => trashed ? pContext.dirname(trashDetails!.path) : directory; + + bool get isMissingAtPath { + final _storagePath = trashed ? trashDetails?.path : path; + return _storagePath != null && !File(_storagePath).existsSync(); + } + + // providers + + bool get _isVaultContent => path?.startsWith(androidFileUtils.vaultRoot) ?? false; + + bool get _isMediaStoreContent => uri.startsWith(AndroidFileUtils.mediaStoreUriRoot); + + bool get isMediaStoreMediaContent => _isMediaStoreContent && AndroidFileUtils.mediaUriPathRoots.any(uri.contains); + + // edition + + bool get canEdit => !settings.isReadOnly && path != null && !trashed && (_isMediaStoreContent || _isVaultContent); + + bool get canEditDate => canEdit && (isExifEditionSupported || isXmpEditionSupported); + + bool get canEditLocation => canEdit && (isExifEditionSupported || mimeType == MimeTypes.mp4); + + bool get canEditTitleDescription => canEdit && isXmpEditionSupported; + + bool get canEditRating => canEdit && isXmpEditionSupported; + + bool get canEditTags => canEdit && isXmpEditionSupported; + + bool get canRotate => canEdit && (isExifEditionSupported || mimeType == MimeTypes.mp4); + + bool get canFlip => canEdit && isExifEditionSupported; + + // app support + + bool get isDecodingSupported => AppSupport.canDecode(mimeType); + + bool get isExifEditionSupported => AppSupport.canEditExif(mimeType); + + bool get isIptcEditionSupported => AppSupport.canEditIptc(mimeType); + + bool get isXmpEditionSupported => AppSupport.canEditXmp(mimeType); + + bool get isMetadataRemovalSupported => AppSupport.canRemoveMetadata(mimeType); +} |
