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 | |
| download | aves-src-master.tar.gz aves-src-master.zip | |
Diffstat (limited to 'lib/model/entry')
| -rw-r--r-- | lib/model/entry/cache.dart | 64 | ||||
| -rw-r--r-- | lib/model/entry/dirs.dart | 76 | ||||
| -rw-r--r-- | lib/model/entry/entry.dart | 502 | ||||
| -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 | ||||
| -rw-r--r-- | lib/model/entry/origins.dart | 6 | ||||
| -rw-r--r-- | lib/model/entry/sort.dart | 52 |
14 files changed, 1961 insertions, 0 deletions
diff --git a/lib/model/entry/cache.dart b/lib/model/entry/cache.dart new file mode 100644 index 0000000..ecb32d7 --- /dev/null +++ b/lib/model/entry/cache.dart @@ -0,0 +1,64 @@ +import 'dart:async'; + +import 'package:aves/image_providers/full_image_provider.dart'; +import 'package:aves/image_providers/thumbnail_provider.dart'; +import 'package:flutter/foundation.dart'; + +class EntryCache { + // ordered descending + static final thumbnailRequestExtents = <double>[]; + + static void markThumbnailExtent(double extent) { + if (!thumbnailRequestExtents.contains(extent)) { + thumbnailRequestExtents + ..add(extent) + ..sort((a, b) => b.compareTo(a)); + } + } + + static Future<void> evict( + String uri, + String mimeType, + int? dateModifiedMillis, + int rotationDegrees, + bool isFlipped, + bool isAnimated, + ) async { + debugPrint('Evict cached images for uri=$uri, mimeType=$mimeType, dateModifiedMillis=$dateModifiedMillis, rotationDegrees=$rotationDegrees, isFlipped=$isFlipped, isAnimated=$isAnimated'); + + // TODO TLAD provide pageId parameter for multi page items, if someday image editing features are added for them + int? pageId; + + // evict fullscreen image + await FullImage( + uri: uri, + mimeType: mimeType, + pageId: pageId, + rotationDegrees: rotationDegrees, + isFlipped: isFlipped, + isAnimated: isAnimated, + ).evict(); + + // evict low quality thumbnail (without specified extents) + await ThumbnailProvider(ThumbnailProviderKey( + uri: uri, + mimeType: mimeType, + pageId: pageId, + dateModifiedMillis: dateModifiedMillis ?? 0, + rotationDegrees: rotationDegrees, + isFlipped: isFlipped, + )).evict(); + + await Future.forEach<double>( + thumbnailRequestExtents, + (extent) => ThumbnailProvider(ThumbnailProviderKey( + uri: uri, + mimeType: mimeType, + pageId: pageId, + dateModifiedMillis: dateModifiedMillis ?? 0, + rotationDegrees: rotationDegrees, + isFlipped: isFlipped, + extent: extent, + )).evict()); + } +} diff --git a/lib/model/entry/dirs.dart b/lib/model/entry/dirs.dart new file mode 100644 index 0000000..6db7918 --- /dev/null +++ b/lib/model/entry/dirs.dart @@ -0,0 +1,76 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:aves/services/common/services.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:collection/collection.dart'; + +final entryDirRepo = EntryDirRepo._private(); + +class EntryDirRepo { + EntryDirRepo._private(); + + // mapping between the raw entry directory path to a resolvable directory + final Map<String?, EntryDir> _dirs = {}; + final StreamController<EntryDir> _ambiguousDirStreamController = StreamController.broadcast(); + + Stream<EntryDir> get ambiguousDirStream => _ambiguousDirStreamController.stream; + + // get a resolvable directory for a raw entry directory path + EntryDir getOrCreate(String? asIs) { + var entryDir = _dirs[asIs]; + if (entryDir != null) return entryDir; + + final asIsLower = asIs?.toLowerCase(); + entryDir = _dirs.values.firstWhereOrNull((dir) => dir.asIsLower == asIsLower); + if (entryDir != null && !entryDir.ambiguous) { + entryDir.ambiguous = true; + _ambiguousDirStreamController.add(entryDir); + } + + return _dirs.putIfAbsent(asIs, () => entryDir ?? EntryDir(asIs)); + } +} + +// Some directories are ambiguous because they use different cases, +// but the OS merge and present them as one directory. +// This class resolves ambiguous directories to get the directory path +// with the right case, as presented by the OS. +class EntryDir { + final String? asIs, asIsLower; + bool ambiguous = false; + String? _resolved; + + EntryDir(this.asIs) : asIsLower = asIs?.toLowerCase(); + + String? get resolved { + if (!ambiguous) return asIs; + if (asIs == null) return null; + + _resolved ??= _resolve(); + return _resolved; + } + + String? _resolve() { + final vrl = androidFileUtils.relativeDirectoryFromPath(asIs!); + if (vrl == null || vrl.relativeDir.isEmpty) return asIs; + + var resolved = vrl.volumePath; + final parts = pContext.split(vrl.relativeDir); + for (final part in parts) { + FileSystemEntity? found; + final dir = Directory(resolved); + if (dir.existsSync()) { + final partLower = part.toLowerCase(); + try { + final childrenDirs = dir.listSync().where((v) => v.absolute is Directory).toSet(); + found = childrenDirs.firstWhereOrNull((v) => pContext.basename(v.path).toLowerCase() == partLower); + } catch (error) { + // ignore, could be IO issue when listing directory + } + } + resolved = found?.path ?? '$resolved${pContext.separator}$part'; + } + return resolved; + } +} diff --git a/lib/model/entry/entry.dart b/lib/model/entry/entry.dart new file mode 100644 index 0000000..b6f7cbc --- /dev/null +++ b/lib/model/entry/entry.dart @@ -0,0 +1,502 @@ +import 'dart:async'; +import 'dart:ui'; + +import 'package:aves/model/entry/cache.dart'; +import 'package:aves/model/entry/dirs.dart'; +import 'package:aves/model/entry/extensions/keys.dart'; +import 'package:aves/model/metadata/address.dart'; +import 'package:aves/model/metadata/catalog.dart'; +import 'package:aves/model/metadata/trash.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/format.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:flutter/foundation.dart'; +import 'package:leak_tracker/leak_tracker.dart'; + +enum EntryDataType { basic, aspectRatio, catalog, address, references } + +class AvesEntry with AvesEntryBase { + @override + int id; + + @override + String uri; + + @override + int? pageId; + + @override + int? sizeBytes; + + String? _path, _filename, _extension, _sourceTitle; + EntryDir? _directory; + int? contentId; + final String sourceMimeType; + int width, height, sourceRotationDegrees; + int? dateAddedSecs, _dateModifiedMillis, sourceDateTakenMillis, _durationMillis; + bool trashed; + int origin; + + int? _catalogDateMillis; + CatalogMetadata? _catalogMetadata; + AddressDetails? _addressDetails; + TrashDetails? trashDetails; + + // synthetic stack of related entries, e.g. burst shots or raw/developed pairs + List<AvesEntry>? stackedEntries; + + @override + final AChangeNotifier visualChangeNotifier = AChangeNotifier(); + + final AChangeNotifier metadataChangeNotifier = AChangeNotifier(), addressChangeNotifier = AChangeNotifier(); + + AvesEntry({ + required int? id, + required this.uri, + required String? path, + required this.contentId, + required this.pageId, + required this.sourceMimeType, + required this.width, + required this.height, + required this.sourceRotationDegrees, + required this.sizeBytes, + required String? sourceTitle, + required this.dateAddedSecs, + required int? dateModifiedMillis, + required this.sourceDateTakenMillis, + required int? durationMillis, + required this.trashed, + required this.origin, + this.stackedEntries, + }) : id = id ?? 0 { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$AvesEntry', + object: this, + ); + } + this.path = path; + this.sourceTitle = sourceTitle; + this.dateModifiedMillis = dateModifiedMillis; + this.durationMillis = durationMillis; + } + + AvesEntry copyWith({ + int? id, + String? uri, + String? path, + int? contentId, + String? title, + int? dateAddedSecs, + int? dateModifiedMillis, + int? origin, + List<AvesEntry>? stackedEntries, + }) { + final copyEntryId = id ?? this.id; + final copied = AvesEntry( + id: copyEntryId, + uri: uri ?? this.uri, + path: path ?? this.path, + contentId: contentId ?? this.contentId, + pageId: null, + sourceMimeType: sourceMimeType, + width: width, + height: height, + sourceRotationDegrees: sourceRotationDegrees, + sizeBytes: sizeBytes, + sourceTitle: title ?? sourceTitle, + dateAddedSecs: dateAddedSecs ?? this.dateAddedSecs, + dateModifiedMillis: dateModifiedMillis ?? this.dateModifiedMillis, + sourceDateTakenMillis: sourceDateTakenMillis, + durationMillis: durationMillis, + trashed: trashed, + origin: origin ?? this.origin, + stackedEntries: stackedEntries ?? this.stackedEntries, + ) + ..catalogMetadata = _catalogMetadata?.copyWith(id: copyEntryId) + ..addressDetails = _addressDetails?.copyWith(id: copyEntryId) + ..trashDetails = trashDetails?.copyWith(id: copyEntryId); + + return copied; + } + + // from DB or platform source entry + factory AvesEntry.fromMap(Map map) { + return AvesEntry( + id: map[EntryFields.id] as int?, + uri: map[EntryFields.uri] as String, + path: map[EntryFields.path] as String?, + pageId: null, + contentId: map[EntryFields.contentId] as int?, + sourceMimeType: map[EntryFields.sourceMimeType] as String, + width: map[EntryFields.width] as int? ?? 0, + height: map[EntryFields.height] as int? ?? 0, + sourceRotationDegrees: map[EntryFields.sourceRotationDegrees] as int? ?? 0, + sizeBytes: map[EntryFields.sizeBytes] as int?, + sourceTitle: map[EntryFields.title] as String?, + dateAddedSecs: map[EntryFields.dateAddedSecs] as int?, + dateModifiedMillis: map[EntryFields.dateModifiedMillis] as int?, + sourceDateTakenMillis: map[EntryFields.sourceDateTakenMillis] as int?, + durationMillis: map[EntryFields.durationMillis] as int?, + trashed: (map[EntryFields.trashed] as int? ?? 0) != 0, + origin: map[EntryFields.origin] as int, + ); + } + + // for DB only + Map<String, dynamic> toDatabaseMap() { + return { + EntryFields.id: id, + EntryFields.uri: uri, + EntryFields.path: path, + EntryFields.contentId: contentId, + EntryFields.sourceMimeType: sourceMimeType, + EntryFields.width: width, + EntryFields.height: height, + EntryFields.sourceRotationDegrees: sourceRotationDegrees, + EntryFields.sizeBytes: sizeBytes, + EntryFields.title: sourceTitle, + EntryFields.dateAddedSecs: dateAddedSecs, + EntryFields.dateModifiedMillis: dateModifiedMillis, + EntryFields.sourceDateTakenMillis: sourceDateTakenMillis, + EntryFields.durationMillis: durationMillis, + EntryFields.trashed: trashed ? 1 : 0, + EntryFields.origin: origin, + }; + } + + Map<String, dynamic> toPlatformEntryMap() { + return { + EntryFields.uri: uri, + EntryFields.path: path, + EntryFields.pageId: pageId, + EntryFields.mimeType: mimeType, + EntryFields.width: width, + EntryFields.height: height, + EntryFields.rotationDegrees: rotationDegrees, + EntryFields.isFlipped: isFlipped, + EntryFields.dateModifiedMillis: dateModifiedMillis, + EntryFields.sizeBytes: sizeBytes, + EntryFields.trashed: trashed, + EntryFields.trashPath: trashDetails?.path, + EntryFields.origin: origin, + }; + } + + void dispose() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + visualChangeNotifier.dispose(); + metadataChangeNotifier.dispose(); + addressChangeNotifier.dispose(); + } + + // do not implement [Object.==] and [Object.hashCode] using mutable attributes (e.g. `uri`) + // so that we can reliably use instances in a `Set`, which requires consistent hash codes over time + + @override + String toString() => '$runtimeType#${shortHash(this)}{id=$id, uri=$uri, path=$path, pageId=$pageId}'; + + set path(String? path) { + _path = path; + _directory = null; + _filename = null; + _extension = null; + _bestTitle = null; + } + + @override + String? get path => _path; + + // directory path, without the trailing separator + String? get directory { + _directory ??= entryDirRepo.getOrCreate(path != null ? pContext.dirname(path!) : null); + return _directory!.resolved; + } + + String? get filenameWithoutExtension { + _filename ??= path != null ? pContext.basenameWithoutExtension(path!) : null; + return _filename; + } + + // file extension, including the `.` + String? get extension { + _extension ??= path != null ? pContext.extension(path!) : null; + return _extension; + } + + // the MIME type reported by the Media Store is unreliable + // so we use the one found during cataloguing if possible + @override + String get mimeType => _catalogMetadata?.mimeType ?? sourceMimeType; + + bool get isCatalogued => _catalogMetadata != null; + + DateTime? _bestDate; + + DateTime? get bestDate { + _bestDate ??= dateTimeFromMillis(_catalogDateMillis) ?? dateTimeFromMillis(sourceDateTakenMillis) ?? dateTimeFromMillis(dateModifiedMillis ?? 0); + return _bestDate; + } + + @override + bool get isAnimated => catalogMetadata?.isAnimated ?? false; + + bool get isHdr => _catalogMetadata?.isHdr ?? false; + + int get rating => _catalogMetadata?.rating ?? 0; + + @override + int get rotationDegrees => _catalogMetadata?.rotationDegrees ?? sourceRotationDegrees; + + set rotationDegrees(int rotationDegrees) { + sourceRotationDegrees = rotationDegrees; + _catalogMetadata?.rotationDegrees = rotationDegrees; + } + + bool get isFlipped => _catalogMetadata?.isFlipped ?? false; + + set isFlipped(bool isFlipped) => _catalogMetadata?.isFlipped = isFlipped; + + // Media Store size/rotation is inaccurate, e.g. a portrait FHD video is rotated according to its metadata, + // so it should be registered as width=1920, height=1080, orientation=90, + // but is incorrectly registered as width=1080, height=1920, orientation=0. + // Double-checking the width/height during loading or cataloguing is the proper solution, but it would take space and time. + // Comparing width and height can help with the portrait FHD video example, + // but it fails for a portrait screenshot rotated, which is landscape with width=1080, height=1920, orientation=90 + bool get isRotated => rotationDegrees % 180 == 90; + + @override + double get displayAspectRatio { + if (width == 0 || height == 0) return 1; + return isRotated ? height / width : width / height; + } + + @override + Size get displaySize { + final w = width.toDouble(); + final h = height.toDouble(); + return isRotated ? Size(h, w) : Size(w, h); + } + + String? get sourceTitle => _sourceTitle; + + set sourceTitle(String? sourceTitle) { + _sourceTitle = sourceTitle; + _bestTitle = null; + } + + int? get dateModifiedMillis => _dateModifiedMillis; + + set dateModifiedMillis(int? dateModifiedMillis) { + _dateModifiedMillis = dateModifiedMillis; + _bestDate = null; + } + + // TODO TLAD cache _monthTaken + DateTime? get monthTaken { + final d = bestDate; + return d == null ? null : DateTime(d.year, d.month); + } + + // TODO TLAD cache _dayTaken + DateTime? get dayTaken { + final d = bestDate; + return d == null ? null : DateTime(d.year, d.month, d.day); + } + + @override + int? get durationMillis => _durationMillis; + + set durationMillis(int? durationMillis) { + _durationMillis = durationMillis; + _durationText = null; + } + + String? _durationText; + + String get durationText { + _durationText ??= formatFriendlyDuration(Duration(milliseconds: durationMillis ?? 0)); + return _durationText!; + } + + // returns whether this entry has GPS coordinates + // (0, 0) coordinates are considered invalid, as it is likely a default value + bool get hasGps => (_catalogMetadata?.latitude ?? 0) != 0 || (_catalogMetadata?.longitude ?? 0) != 0; + + bool get hasAddress => _addressDetails != null; + + // has a place, or at least the full country name + // derived from Google reverse geocoding addresses + bool get hasFineAddress => _addressDetails?.place?.isNotEmpty == true || (_addressDetails?.countryName?.length ?? 0) > 3; + + Set<String>? _tags; + + Set<String> get tags { + _tags ??= _catalogMetadata?.xmpSubjects?.split(';').where((tag) => tag.isNotEmpty).toSet() ?? {}; + return _tags!; + } + + String? _bestTitle; + + @override + String? get bestTitle { + _bestTitle ??= _catalogMetadata?.xmpTitle?.isNotEmpty == true ? _catalogMetadata!.xmpTitle : (filenameWithoutExtension ?? sourceTitle); + return _bestTitle; + } + + int? get catalogDateMillis => _catalogDateMillis; + + set catalogDateMillis(int? dateMillis) { + _catalogDateMillis = dateMillis; + _bestDate = null; + } + + CatalogMetadata? get catalogMetadata => _catalogMetadata; + + set catalogMetadata(CatalogMetadata? newMetadata) { + final oldMimeType = mimeType; + final oldDateModifiedMillis = dateModifiedMillis; + final oldRotationDegrees = rotationDegrees; + final oldIsFlipped = isFlipped; + + catalogDateMillis = newMetadata?.dateMillis; + _catalogMetadata = newMetadata; + _bestTitle = null; + _tags = null; + metadataChangeNotifier.notify(); + + _onVisualFieldChanged(oldMimeType, oldDateModifiedMillis, oldRotationDegrees, oldIsFlipped); + } + + void clearMetadata() { + catalogMetadata = null; + addressDetails = null; + } + + AddressDetails? get addressDetails => _addressDetails; + + set addressDetails(AddressDetails? newAddress) { + _addressDetails = newAddress; + addressChangeNotifier.notify(); + } + + String get shortAddress { + // `admin area` examples: Seoul, Geneva, null + // `locality` examples: Mapo-gu, Geneva, Annecy + return { + _addressDetails?.countryName, + _addressDetails?.adminArea, + _addressDetails?.locality, + }.nonNulls.where((v) => v.isNotEmpty).join(', '); + } + + static void normalizeMimeTypeFields(Map fields) { + final mimeType = fields[EntryFields.mimeType] as String?; + if (mimeType != null) { + fields[EntryFields.mimeType] = MimeTypes.normalize(mimeType); + } + final sourceMimeType = fields[EntryFields.sourceMimeType] as String?; + if (sourceMimeType != null) { + fields[EntryFields.sourceMimeType] = MimeTypes.normalize(sourceMimeType); + } + } + + Future<void> applyNewFields(Map newFields, {required bool persist}) async { + final oldMimeType = mimeType; + final oldDateModifiedMillis = this.dateModifiedMillis; + final oldRotationDegrees = this.rotationDegrees; + final oldIsFlipped = this.isFlipped; + + final uri = newFields[EntryFields.uri]; + if (uri is String) this.uri = uri; + final path = newFields[EntryFields.path]; + if (path is String) this.path = path; + final contentId = newFields[EntryFields.contentId]; + if (contentId is int) this.contentId = contentId; + + final sourceTitle = newFields[EntryFields.title]; + if (sourceTitle is String) this.sourceTitle = sourceTitle; + final sourceRotationDegrees = newFields[EntryFields.sourceRotationDegrees]; + if (sourceRotationDegrees is int) this.sourceRotationDegrees = sourceRotationDegrees; + final sourceDateTakenMillis = newFields[EntryFields.sourceDateTakenMillis]; + if (sourceDateTakenMillis is int) this.sourceDateTakenMillis = sourceDateTakenMillis; + + final width = newFields[EntryFields.width]; + if (width is int) this.width = width; + final height = newFields[EntryFields.height]; + if (height is int) this.height = height; + final durationMillis = newFields[EntryFields.durationMillis]; + if (durationMillis is int) this.durationMillis = durationMillis; + + final sizeBytes = newFields[EntryFields.sizeBytes]; + if (sizeBytes is int) this.sizeBytes = sizeBytes; + final dateModifiedMillis = newFields[EntryFields.dateModifiedMillis]; + if (dateModifiedMillis is int) this.dateModifiedMillis = dateModifiedMillis; + final rotationDegrees = newFields[EntryFields.rotationDegrees]; + if (rotationDegrees is int) this.rotationDegrees = rotationDegrees; + final isFlipped = newFields[EntryFields.isFlipped]; + if (isFlipped is bool) this.isFlipped = isFlipped; + + if (persist) { + await localMediaDb.updateEntry(id, this); + if (catalogMetadata != null) await localMediaDb.saveCatalogMetadata({catalogMetadata!}); + } + + await _onVisualFieldChanged(oldMimeType, oldDateModifiedMillis, oldRotationDegrees, oldIsFlipped); + metadataChangeNotifier.notify(); + } + + Future<void> refresh({ + required bool background, + required bool persist, + required Set<EntryDataType> dataTypes, + }) async { + // clear derived fields + _bestDate = null; + _bestTitle = null; + _tags = null; + + if (persist) { + await localMediaDb.removeIds({id}, dataTypes: dataTypes); + } + + final updatedEntry = await mediaFetchService.getEntry(uri, mimeType); + if (updatedEntry != null) { + await applyNewFields(updatedEntry.toDatabaseMap(), persist: persist); + } + } + + Future<bool> delete() { + final opCompleter = Completer<bool>(); + mediaEditService.delete(entries: {this}).listen( + (event) => opCompleter.complete(event.success && !event.skipped), + onError: opCompleter.completeError, + onDone: () { + if (!opCompleter.isCompleted) { + opCompleter.complete(false); + } + }, + ); + return opCompleter.future; + } + + // when the MIME type or the image itself changed (e.g. after rotation) + Future<void> _onVisualFieldChanged( + String oldMimeType, + int? oldDateModifiedMillis, + int oldRotationDegrees, + bool oldIsFlipped, + ) async { + if ((!MimeTypes.refersToSameType(oldMimeType, mimeType) && !MimeTypes.isVideo(oldMimeType)) || oldDateModifiedMillis != dateModifiedMillis || oldRotationDegrees != rotationDegrees || oldIsFlipped != isFlipped) { + await EntryCache.evict(uri, oldMimeType, oldDateModifiedMillis, oldRotationDegrees, oldIsFlipped, isAnimated); + visualChangeNotifier.notify(); + } + } +} 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); +} diff --git a/lib/model/entry/origins.dart b/lib/model/entry/origins.dart new file mode 100644 index 0000000..efc3549 --- /dev/null +++ b/lib/model/entry/origins.dart @@ -0,0 +1,6 @@ +class EntryOrigins { + static const int mediaStoreContent = 0; + static const int unknownContent = 1; + static const int file = 2; + static const int vault = 3; +} diff --git a/lib/model/entry/sort.dart b/lib/model/entry/sort.dart new file mode 100644 index 0000000..e0e5573 --- /dev/null +++ b/lib/model/entry/sort.dart @@ -0,0 +1,52 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:collection/collection.dart'; + +class AvesEntrySort { + // compare by: + // 1) title ascending + // 2) extension ascending + static int compareByName(AvesEntry a, AvesEntry b) { + final c = compareAsciiUpperCaseNatural(a.bestTitle ?? '', b.bestTitle ?? ''); + return c != 0 ? c : compareAsciiUpperCase(a.extension ?? '', b.extension ?? ''); + } + + // compare by: + // 1) date descending + // 2) name descending + static int compareByDate(AvesEntry a, AvesEntry b) { + var c = (b.bestDate ?? epoch).compareTo(a.bestDate ?? epoch); + if (c != 0) return c; + return compareByName(b, a); + } + + // compare by: + // 1) rating descending + // 2) date descending + static int compareByRating(AvesEntry a, AvesEntry b) { + final c = b.rating.compareTo(a.rating); + return c != 0 ? c : compareByDate(a, b); + } + + // compare by: + // 1) size descending + // 2) date descending + static int compareBySize(AvesEntry a, AvesEntry b) { + final c = (b.sizeBytes ?? 0).compareTo(a.sizeBytes ?? 0); + return c != 0 ? c : compareByDate(a, b); + } + + // compare by: + // 1) duration descending + // 2) date descending + static int compareByDuration(AvesEntry a, AvesEntry b) { + final c = (b.durationMillis ?? 0).compareTo(a.durationMillis ?? 0); + return c != 0 ? c : compareByDate(a, b); + } + + // compare by: + // 1) path ascending + static int compareByPath(AvesEntry a, AvesEntry b) { + return compareAsciiUpperCase(a.path ?? '', b.path ?? ''); + } +} |
