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/services | |
| download | aves-src-master.tar.gz aves-src-master.zip | |
Diffstat (limited to 'lib/services')
30 files changed, 4019 insertions, 0 deletions
diff --git a/lib/services/accessibility_service.dart b/lib/services/accessibility_service.dart new file mode 100644 index 0000000..0361fb1 --- /dev/null +++ b/lib/services/accessibility_service.dart @@ -0,0 +1,80 @@ +import 'package:aves/services/common/channel.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/services.dart'; + +class AccessibilityService { + static const _platform = AvesMethodChannel('deckers.thibault/aves/accessibility'); + + static Future<bool> areAnimationsRemoved() async { + try { + final result = await _platform.invokeMethod('areAnimationsRemoved'); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + static Future<int> getLongPressTimeout() async { + try { + final result = await _platform.invokeMethod('getLongPressTimeout'); + if (result != null) return result as int; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return kLongPressTimeout.inMilliseconds; + } + + static bool? _hasRecommendedTimeouts; + + static Future<bool> hasRecommendedTimeouts() async { + if (_hasRecommendedTimeouts != null) return SynchronousFuture(_hasRecommendedTimeouts!); + try { + final result = await _platform.invokeMethod('hasRecommendedTimeouts'); + _hasRecommendedTimeouts = result as bool?; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return _hasRecommendedTimeouts ?? false; + } + + static Future<int> getRecommendedTimeToRead(Duration originalTimeoutDuration) async { + final originalTimeoutMillis = originalTimeoutDuration.inMilliseconds; + try { + final result = await _platform.invokeMethod('getRecommendedTimeoutMillis', <String, dynamic>{ + 'originalTimeoutMillis': originalTimeoutMillis, + 'content': ['icons', 'text'] + }); + if (result != null) return result as int; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return originalTimeoutMillis; + } + + static Future<int> getRecommendedTimeToTakeAction(Duration originalTimeoutDuration) async { + final originalTimeoutMillis = originalTimeoutDuration.inMilliseconds; + try { + final result = await _platform.invokeMethod('getRecommendedTimeoutMillis', <String, dynamic>{ + 'originalTimeoutMillis': originalTimeoutMillis, + 'content': ['controls', 'icons', 'text'] + }); + if (result != null) return result as int; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return originalTimeoutMillis; + } + + static Future<bool> shouldUseBoldFont() async { + try { + final result = await _platform.invokeMethod('shouldUseBoldFont'); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } +} diff --git a/lib/services/analysis_service.dart b/lib/services/analysis_service.dart new file mode 100644 index 0000000..d97abbb --- /dev/null +++ b/lib/services/analysis_service.dart @@ -0,0 +1,214 @@ +import 'dart:async'; +import 'dart:ui'; + +import 'package:aves/l10n/l10n.dart'; +import 'package:aves/model/device.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/analysis_controller.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/media_store_source.dart'; +import 'package:aves/services/common/channel.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:leak_tracker/leak_tracker.dart'; +import 'package:permission_handler/permission_handler.dart'; + +class AnalysisService { + static const _platform = AvesMethodChannel('deckers.thibault/aves/analysis'); + + static Future<void> registerCallback() async { + try { + await _platform.invokeMethod('registerCallback', <String, dynamic>{ + // callback needs to be annotated with `@pragma('vm:entry-point')` to work in release mode + 'callbackHandle': PluginUtilities.getCallbackHandle(_init)?.toRawHandle(), + }); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } + + static Future<void> startService({required bool force, List<int>? entryIds}) async { + // from Android 13 (API 33), notifications are off by default, + // so the user needs to grant the permission to see the service notification + unawaited(Permission.notification.request()); + + await reportService.log('Start analysis service${entryIds != null ? ' for ${entryIds.length} items' : ''}'); + try { + await _platform.invokeMethod('startAnalysis', <String, dynamic>{ + 'entryIds': entryIds, + 'force': force, + }); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } +} + +const _channel = AvesMethodChannel('deckers.thibault/aves/analysis_service_background'); + +@pragma('vm:entry-point') +Future<void> _init() async { + WidgetsFlutterBinding.ensureInitialized(); + initPlatformServices(); + await androidFileUtils.init(); + await localMediaDb.init(); + await device.init(); + await mobileServices.init(); + await settings.init(monitorPlatformSettings: false); + await reportService.init(); + videoMetadataFetcher.init(); + + final analyzer = Analyzer(); + _channel.setMethodCallHandler((call) { + switch (call.method) { + case 'start': + analyzer.start(call.arguments); + return Future.value(true); + case 'stop': + analyzer.stop(); + return Future.value(true); + default: + throw PlatformException(code: 'not-implemented', message: 'failed to handle method=${call.method}'); + } + }); + try { + await _channel.invokeMethod('initialized'); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } +} + +enum AnalyzerState { running, stopping, stopped } + +class Analyzer with WidgetsBindingObserver { + late AppLocalizations _l10n; + final ValueNotifier<AnalyzerState> _serviceStateNotifier = ValueNotifier<AnalyzerState>(AnalyzerState.stopped); + AnalysisController? _controller; + Timer? _notificationUpdateTimer; + final _source = MediaStoreSource(); + + AnalyzerState get serviceState => _serviceStateNotifier.value; + + bool get isRunning => serviceState == AnalyzerState.running; + + SourceState get sourceState => _source.state; + + static const notificationUpdateInterval = Duration(seconds: 1); + + Analyzer() { + debugPrint('$runtimeType create'); + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$Analyzer', + object: this, + ); + } + _serviceStateNotifier.addListener(_onServiceStateChanged); + _source.stateNotifier.addListener(_onSourceStateChanged); + WidgetsBinding.instance.addObserver(this); + } + + void dispose() { + debugPrint('$runtimeType dispose'); + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + _stopUpdateTimer(); + _controller?.dispose(); + WidgetsBinding.instance.removeObserver(this); + _serviceStateNotifier.removeListener(_onServiceStateChanged); + _source.stateNotifier.removeListener(_onSourceStateChanged); + _source.dispose(); + } + + @override + void didHaveMemoryPressure() { + super.didHaveMemoryPressure(); + reportService.log('Analyzer memory pressure'); + } + + Future<void> start(dynamic args) async { + List<int>? entryIds; + var force = false; + if (args is Map) { + entryIds = (args['entryIds'] as List?)?.cast<int>(); + force = args['force'] ?? false; + } + await reportService.log('Analyzer start for ${entryIds?.length ?? 'all'} entries'); + _controller?.dispose(); + _controller = AnalysisController( + canStartService: false, + entryIds: entryIds, + force: force, + ); + + settings.systemLocalesFallback = await deviceService.getLocales(); + _l10n = await AppLocalizations.delegate.load(settings.appliedLocale); + _serviceStateNotifier.value = AnalyzerState.running; + await _source.init(scope: CollectionSource.fullScope, analysisController: _controller); + + _notificationUpdateTimer = Timer.periodic(notificationUpdateInterval, (_) async { + if (!isRunning) return; + await _updateNotification(); + }); + } + + Future<void> stop() async { + await reportService.log('Analyzer stop'); + _serviceStateNotifier.value = AnalyzerState.stopped; + } + + void _stopUpdateTimer() => _notificationUpdateTimer?.cancel(); + + Future<void> _onServiceStateChanged() async { + switch (serviceState) { + case AnalyzerState.running: + break; + case AnalyzerState.stopping: + await _stopPlatformService(); + _serviceStateNotifier.value = AnalyzerState.stopped; + case AnalyzerState.stopped: + _controller?.enableStopSignal(); + _stopUpdateTimer(); + } + } + + void _onSourceStateChanged() { + if (_source.isReady) { + _serviceStateNotifier.value = AnalyzerState.stopping; + } + } + + Future<void> _updateNotification() async { + if (!isRunning) return; + + final title = sourceState.getName(_l10n); + if (title == null) return; + + final progress = _source.progressNotifier.value; + final progressive = progress.total != 0 && sourceState != SourceState.locatingCountries; + + try { + await _channel.invokeMethod('updateNotification', <String, dynamic>{ + 'title': title, + 'message': progressive ? '${progress.done}/${progress.total}' : null, + }); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } + + Future<void> _stopPlatformService() async { + try { + await _channel.invokeMethod('stop'); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } +} diff --git a/lib/services/android_debug_service.dart b/lib/services/android_debug_service.dart new file mode 100644 index 0000000..47ff17c --- /dev/null +++ b/lib/services/android_debug_service.dart @@ -0,0 +1,189 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/channel.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:flutter/services.dart'; + +class AndroidDebugService { + static const _platform = AvesMethodChannel('deckers.thibault/aves/debug'); + + static Future<void> crash() async { + try { + await _platform.invokeMethod('crash'); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } + + static Future<void> exception() async { + try { + await _platform.invokeMethod('exception'); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } + + static Future<void> safeException() async { + try { + await _platform.invokeMethod('safeException'); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } + + static Future<void> exceptionInCoroutine() async { + try { + await _platform.invokeMethod('exceptionInCoroutine'); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } + + static Future<void> safeExceptionInCoroutine() async { + try { + await _platform.invokeMethod('safeExceptionInCoroutine'); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } + + static Future<Map> getContextDirs() async { + try { + final result = await _platform.invokeMethod('getContextDirs'); + if (result != null) return result as Map; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + static Future<List<Map>> getCodecs() async { + try { + final result = await _platform.invokeMethod('getCodecs'); + if (result != null) return (result as List).cast<Map>(); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return []; + } + + static Future<Map> getEnv() async { + try { + final result = await _platform.invokeMethod('getEnv'); + if (result != null) return result as Map; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + static Future<Map> getBitmapFactoryInfo(AvesEntry entry) async { + try { + // returns map with all data available when decoding image bounds with `BitmapFactory` + final result = await _platform.invokeMethod('getBitmapFactoryInfo', <String, dynamic>{ + 'uri': entry.uri, + }); + if (result != null) return result as Map; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + static Future<Map> getContentResolverMetadata(AvesEntry entry) async { + try { + // returns map with all data available from the content resolver + final result = await _platform.invokeMethod('getContentResolverMetadata', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + }); + if (result != null) return result as Map; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + static Future<Map> getExifInterfaceMetadata(AvesEntry entry) async { + try { + // returns map with all data available from the `ExifInterface` library + final result = await _platform.invokeMethod('getExifInterfaceMetadata', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + }); + if (result != null) return result as Map; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + static Future<Map> getMediaMetadataRetrieverMetadata(AvesEntry entry) async { + try { + // returns map with all data available from `MediaMetadataRetriever` + final result = await _platform.invokeMethod('getMediaMetadataRetrieverMetadata', <String, dynamic>{ + 'uri': entry.uri, + }); + if (result != null) return result as Map; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + static Future<Map> getMetadataExtractorSummary(AvesEntry entry) async { + try { + // returns map with the MIME type and tag count for each directory found by `metadata-extractor` + final result = await _platform.invokeMethod('getMetadataExtractorSummary', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + }); + if (result != null) return result as Map; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + static Future<String?> getMp4ParserDump(AvesEntry entry) async { + try { + return await _platform.invokeMethod('getMp4ParserDump', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + }); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return null; + } + + static Future<Map> getPixyMetadata(AvesEntry entry) async { + try { + // returns map with all data available from the `PixyMeta` library + final result = await _platform.invokeMethod('getPixyMetadata', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + }); + if (result != null) return result as Map; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + static Future<Map> getTiffStructure(AvesEntry entry) async { + if (entry.mimeType != MimeTypes.tiff) return {}; + + try { + final result = await _platform.invokeMethod('getTiffStructure', <String, dynamic>{ + 'uri': entry.uri, + }); + if (result != null) return result as Map; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } +} diff --git a/lib/services/app_profile_service.dart b/lib/services/app_profile_service.dart new file mode 100644 index 0000000..c540bab --- /dev/null +++ b/lib/services/app_profile_service.dart @@ -0,0 +1,90 @@ +import 'dart:async'; + +import 'package:aves/services/common/channel.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:flutter/services.dart'; + +abstract class AppProfileService { + Future<bool> canInteractAcrossProfiles(); + + Future<bool> canRequestInteractAcrossProfiles(); + + Future<bool> requestInteractAcrossProfiles(); + + Future<String> getProfileSwitchingLabel(); + + Future<void> switchProfile(); + + Future<List<String>> getTargetUserProfiles(); +} + +class PlatformAppProfileService implements AppProfileService { + static const _platform = AvesMethodChannel('deckers.thibault/aves/app_profile'); + + @override + Future<bool> canInteractAcrossProfiles() async { + try { + final result = await _platform.invokeMethod('canInteractAcrossProfiles'); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + @override + Future<bool> canRequestInteractAcrossProfiles() async { + try { + final result = await _platform.invokeMethod('canRequestInteractAcrossProfiles'); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + @override + Future<bool> requestInteractAcrossProfiles() async { + try { + final result = await _platform.invokeMethod('requestInteractAcrossProfiles'); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + @override + Future<void> switchProfile() async { + try { + await _platform.invokeMethod('switchProfile'); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return; + } + + @override + Future<String> getProfileSwitchingLabel() async { + try { + final result = await _platform.invokeMethod('getProfileSwitchingLabel'); + return result as String; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return ''; + } + + @override + Future<List<String>> getTargetUserProfiles() async { + try { + final result = await _platform.invokeMethod('getTargetUserProfiles'); + if (result != null) { + return (result as List).cast<String>(); + } + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return []; + } +} diff --git a/lib/services/app_service.dart b/lib/services/app_service.dart new file mode 100644 index 0000000..da63602 --- /dev/null +++ b/lib/services/app_service.dart @@ -0,0 +1,268 @@ +import 'dart:async'; +import 'dart:ui' as ui; +import 'dart:ui'; + +import 'package:aves/geo/uri.dart'; +import 'package:aves/image_providers/thumbnail_provider.dart'; +import 'package:aves/model/app_inventory.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/services/common/channel.dart'; +import 'package:aves/services/common/decoding.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/painting.dart'; +import 'package:flutter/services.dart'; +import 'package:latlong2/latlong.dart'; + +abstract class AppService { + Future<Set<Package>> getPackages(); + + Future<ui.ImageDescriptor?> getAppIcon(String packageName, double size); + + Future<bool> copyToClipboard(String uri, String? label); + + Future<Map<String, dynamic>> edit(String uri, String mimeType); + + Future<bool> open(String uri, String mimeType, {required bool forceChooser}); + + Future<bool> openMap(LatLng latLng); + + Future<bool> setAs(String uri, String mimeType); + + Future<bool> shareEntries(Iterable<AvesEntry> entries); + + Future<bool> shareSingle(String uri, String mimeType); + + Future<void> pinToHomeScreen( + String label, + AvesEntry? coverEntry, { + required String route, + Set<CollectionFilter>? filters, + String? path, + String? viewUri, + String? geoUri, + }); +} + +class PlatformAppService implements AppService { + static const _platform = AvesMethodChannel('deckers.thibault/aves/app'); + static final _stream = AvesStreamsChannel('deckers.thibault/aves/activity_result_stream'); + + static final _knownAppDirs = { + 'com.google.android.apps.photos': {'Google Photos'}, + 'com.kakao.talk': {'KakaoTalkDownload'}, + 'com.sony.playmemories.mobile': {'Imaging Edge Mobile'}, + 'nekox.messenger': {'NekoX'}, + 'org.telegram.messenger': {'Telegram Images', 'Telegram Video'}, + 'com.whatsapp': {'WhatsApp Animated Gifs', 'WhatsApp Documents', 'WhatsApp Images', 'WhatsApp Video'} + }; + + @override + Future<Set<Package>> getPackages() async { + try { + final result = await _platform.invokeMethod('getPackages'); + final packages = (result as List).cast<Map>().map(Package.fromMap).toSet(); + // additional info for known directories + _knownAppDirs.forEach((packageName, dirs) { + final package = packages.firstWhereOrNull((package) => package.packageName == packageName); + if (package != null) { + package.ownedDirs.addAll(dirs); + } + }); + return packages; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + @override + Future<ui.ImageDescriptor?> getAppIcon(String packageName, double size) async { + try { + final result = await _platform.invokeMethod('getAppIcon', <String, dynamic>{ + 'packageName': packageName, + 'sizeDip': size, + }); + if (result != null) { + final bytes = result as Uint8List; + return InteropDecoding.rawBytesToDescriptor(bytes); + } + } on PlatformException catch (_) { + // ignore, as some packages legitimately do not have icons + } + return null; + } + + @override + Future<bool> copyToClipboard(String uri, String? label) async { + try { + final result = await _platform.invokeMethod('copyToClipboard', <String, dynamic>{ + 'uri': uri, + 'label': label, + }); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + @override + Future<Map<String, dynamic>> edit(String uri, String mimeType) async { + try { + final opCompleter = Completer<Map?>(); + _stream.receiveBroadcastStream(<String, dynamic>{ + 'op': 'edit', + 'uri': uri, + 'mimeType': mimeType, + }).listen( + (data) => opCompleter.complete(data as Map?), + onError: opCompleter.completeError, + onDone: () { + if (!opCompleter.isCompleted) opCompleter.complete({'error': 'cancelled'}); + }, + cancelOnError: true, + ); + // `await` here, so that `completeError` will be caught below + final result = await opCompleter.future; + if (result == null) return {'error': 'cancelled'}; + return result.cast<String, dynamic>(); + } on PlatformException catch (e, stack) { + if (e.code != 'edit-resolve') { + await reportService.recordError(e, stack); + } + return {'error': e.code}; + } + } + + @override + Future<bool> open(String uri, String mimeType, {required bool forceChooser}) async { + try { + final result = await _platform.invokeMethod('open', <String, dynamic>{ + 'uri': uri, + 'mimeType': mimeType, + 'forceChooser': forceChooser, + }); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + @override + Future<bool> openMap(LatLng latLng) async { + try { + final result = await _platform.invokeMethod('openMap', <String, dynamic>{ + 'geoUri': toGeoUri(latLng), + }); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + @override + Future<bool> setAs(String uri, String mimeType) async { + try { + final result = await _platform.invokeMethod('setAs', <String, dynamic>{ + 'uri': uri, + 'mimeType': mimeType, + }); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + @override + Future<bool> shareEntries(Iterable<AvesEntry> entries) { + return _share(groupBy<AvesEntry, String>( + entries, + // loosen MIME type to a generic one, so we can share with badly defined apps + // e.g. Google Lens declares receiving "image/jpeg" only, but it can actually handle more formats + (e) => e.mimeTypeAnySubtype, + ).map((k, v) => MapEntry(k, v.map((e) => e.uri).toList()))); + } + + @override + Future<bool> shareSingle(String uri, String mimeType) { + return _share({ + mimeType: [uri] + }); + } + + Future<bool> _share(Map<String, List<String>> urisByMimeType) async { + try { + final result = await _platform.invokeMethod('share', <String, dynamic>{ + 'urisByMimeType': urisByMimeType, + }); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + if (e.code == 'share-large') { + throw TooManyItemsException(); + } else { + await reportService.recordError(e, stack); + } + } + return false; + } + + // app shortcuts + + @override + Future<void> pinToHomeScreen( + String label, + AvesEntry? coverEntry, { + required String route, + Set<CollectionFilter>? filters, + String? path, + String? viewUri, + String? geoUri, + }) async { + Uint8List? iconBytes; + if (coverEntry != null) { + final size = coverEntry.isVideo ? 0.0 : 256.0; + try { + final codec = await mediaFetchService.getThumbnail( + decoded: false, + request: ThumbnailProviderKey( + uri: coverEntry.uri, + mimeType: coverEntry.mimeType, + pageId: coverEntry.pageId, + rotationDegrees: coverEntry.rotationDegrees, + isFlipped: coverEntry.isFlipped, + dateModifiedMillis: coverEntry.dateModifiedMillis ?? -1, + extent: size, + ), + decode: PaintingBinding.instance.instantiateImageCodecWithSize + ); + final frameInfo = await codec.getNextFrame(); + final byteData = await frameInfo.image.toByteData(format: ImageByteFormat.png); + iconBytes = byteData?.buffer.asUint8List(); + } catch (error) { + debugPrint('failed to get home pin thumbnail for entry=$coverEntry, error=$error'); + } + } + try { + await _platform.invokeMethod('pinShortcut', <String, dynamic>{ + 'label': label, + 'iconBytes': iconBytes, + 'route': route, + 'filters': filters?.map((filter) => filter.toJson()).toList(), + 'path': path, + 'viewUri': viewUri, + 'geoUri': geoUri, + }); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } +} + +class TooManyItemsException implements Exception {} diff --git a/lib/services/common/channel.dart b/lib/services/common/channel.dart new file mode 100644 index 0000000..79985b0 --- /dev/null +++ b/lib/services/common/channel.dart @@ -0,0 +1,29 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:streams_channel/streams_channel.dart'; + +const bool debugAvesPlatformChannels = kDebugMode; + +class AvesMethodChannel extends MethodChannel { + const AvesMethodChannel(super.name); + + @override + Future<T?> invokeMethod<T>(String method, [arguments]) { + if (debugAvesPlatformChannels) { + debugPrint('$runtimeType invokeMethod name=$name method=$method arguments=$arguments'); + } + return super.invokeMethod(method, arguments); + } +} + +class AvesStreamsChannel extends StreamsChannel { + AvesStreamsChannel(super.name); + + @override + Stream receiveBroadcastStream([arguments]) { + if (debugAvesPlatformChannels) { + debugPrint('$runtimeType invokeMethod name=$name arguments=$arguments'); + } + return super.receiveBroadcastStream(arguments); + } +}
\ No newline at end of file diff --git a/lib/services/common/decoding.dart b/lib/services/common/decoding.dart new file mode 100644 index 0000000..67ee61e --- /dev/null +++ b/lib/services/common/decoding.dart @@ -0,0 +1,55 @@ +import 'dart:async'; +import 'dart:ui' as ui; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/painting.dart'; +import 'package:flutter/services.dart'; + +class InteropDecoding { + // bytes are expected to be in a basic format decodable by Flutter + static Future<ui.Codec?> encodedBytesToCodec(Uint8List? bytes, ImageDecoderCallback? decode) async { + if (bytes == null || decode == null) return null; + + const trailerLength = 1; // decoded/encoded format byte + final byteCount = bytes.lengthInBytes; + if (byteCount < trailerLength) return null; + + final trailerOffset = byteCount - trailerLength; + + // trim custom trailer + // a view does not reallocate memory and uses the underlying buffer + final imageBytes = Uint8List.sublistView(bytes, 0, trailerOffset); + + final buffer = await ui.ImmutableBuffer.fromUint8List(imageBytes); + return await decode(buffer); + } + + // bytes are expected to be in ARGB_8888 + // with a custom trailer from the platform side + static Future<ui.ImageDescriptor?> rawBytesToDescriptor(Uint8List? bytes) async { + if (bytes == null) return null; + + const trailerLength = 4 * 2 + 1; // 2 integers + decoded/encoded format byte + final byteCount = bytes.lengthInBytes; + if (byteCount < trailerLength) return null; + + final trailerOffset = byteCount - trailerLength; + + // fetch trailer + final trailer = ByteData.sublistView(bytes, trailerOffset); + final bitmapWidth = trailer.getUint32(0); + final bitmapHeight = trailer.getUint32(4); + + // trim custom trailer + // a view does not reallocate memory and uses the underlying buffer + final imageBytes = Uint8List.sublistView(bytes, 0, trailerOffset); + + final buffer = await ui.ImmutableBuffer.fromUint8List(imageBytes); + return ui.ImageDescriptor.raw( + buffer, + width: bitmapWidth, + height: bitmapHeight, + pixelFormat: ui.PixelFormat.rgba8888, + ); + } +} diff --git a/lib/services/common/image_op_events.dart b/lib/services/common/image_op_events.dart new file mode 100644 index 0000000..60f055a --- /dev/null +++ b/lib/services/common/image_op_events.dart @@ -0,0 +1,86 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; + +@immutable +class ImageOpEvent extends Equatable { + final bool success, skipped; + final String uri; + + @override + List<Object?> get props => [success, skipped, uri]; + + const ImageOpEvent({ + required this.success, + required this.skipped, + required this.uri, + }); + + factory ImageOpEvent.fromMap(Map map) { + final skipped = map['skipped'] ?? false; + return ImageOpEvent( + success: (map['success'] ?? false) || skipped, + skipped: skipped, + uri: map['uri'], + ); + } +} + +@immutable +class MoveOpEvent extends ImageOpEvent { + final Map newFields; + final bool deleted; + + @override + List<Object?> get props => [success, skipped, uri, newFields, deleted]; + + const MoveOpEvent({ + required super.success, + required super.skipped, + required super.uri, + required this.newFields, + required this.deleted, + }); + + factory MoveOpEvent.fromMap(Map map) { + final newFields = map['newFields'] ?? {}; + final skipped = (map['skipped'] ?? false) || (newFields['skipped'] ?? false); + final deleted = (map['deleted'] ?? false) || (newFields['deleted'] ?? false); + return MoveOpEvent( + success: (map['success'] ?? false) || skipped, + skipped: skipped, + uri: map['uri'], + newFields: newFields, + deleted: deleted, + ); + } +} + +@immutable +class ExportOpEvent extends MoveOpEvent { + final int? pageId; + + @override + List<Object?> get props => [success, skipped, uri, pageId, newFields]; + + const ExportOpEvent({ + required super.success, + required super.skipped, + required super.uri, + this.pageId, + required super.newFields, + }) : super( + deleted: false, + ); + + factory ExportOpEvent.fromMap(Map map) { + final newFields = map['newFields'] ?? {}; + final skipped = (map['skipped'] ?? false) || (newFields['skipped'] ?? false); + return ExportOpEvent( + success: (map['success'] ?? false) || skipped, + skipped: skipped, + uri: map['uri'], + pageId: map['pageId'], + newFields: newFields, + ); + } +} diff --git a/lib/services/common/output_buffer.dart b/lib/services/common/output_buffer.dart new file mode 100644 index 0000000..e64f046 --- /dev/null +++ b/lib/services/common/output_buffer.dart @@ -0,0 +1,36 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +// adapted from Flutter `_OutputBuffer` in `/foundation/consolidate_response.dart` +class OutputBuffer extends ByteConversionSinkBase { + List<List<int>>? _chunks = <List<int>>[]; + int _contentLength = 0; + Uint8List? _bytes; + + @override + void add(List<int> chunk) { + assert(_bytes == null); + _chunks!.add(chunk); + _contentLength += chunk.length; + } + + @override + void close() { + if (_bytes != null) { + // We've already been closed; this is a no-op + return; + } + _bytes = Uint8List(_contentLength); + int offset = 0; + for (final List<int> chunk in _chunks!) { + _bytes!.setRange(offset, offset + chunk.length, chunk); + offset += chunk.length; + } + _chunks = null; + } + + Uint8List get bytes { + assert(_bytes != null); + return _bytes!; + } +} diff --git a/lib/services/common/service_policy.dart b/lib/services/common/service_policy.dart new file mode 100644 index 0000000..1b53ccc --- /dev/null +++ b/lib/services/common/service_policy.dart @@ -0,0 +1,135 @@ +import 'dart:async'; +import 'dart:collection'; + +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; + +final ServicePolicy servicePolicy = ServicePolicy._private(); + +class ServicePolicy { + final StreamController<QueueState> _queueStreamController = StreamController.broadcast(); + final Map<Object, (int, _Task)> _paused = {}; + final SplayTreeMap<int, LinkedHashMap<Object, _Task>> _queues = SplayTreeMap(); + final LinkedHashMap<Object, _Task> _runningQueue = LinkedHashMap(); + + // magic number + static const concurrentTaskMax = 4; + + Stream<QueueState> get queueStream => _queueStreamController.stream; + + ServicePolicy._private(); + + Future<T> call<T>( + Future<T> Function() platformCall, { + int priority = ServiceCallPriority.normal, + Object? key, + }) { + Completer<T> taskCompleter; + _Task<T> task; + key ??= platformCall.hashCode; + final toResume = _paused.remove(key); + if (toResume != null) { + priority = toResume.$1; + task = toResume.$2 as _Task<T>; + taskCompleter = task.completer; + } else { + taskCompleter = Completer<T>(); + task = _Task<T>( + () async { + try { + taskCompleter.complete(await platformCall()); + } catch (error, stack) { + taskCompleter.completeError(error, stack); + } + _runningQueue.remove(key); + _pickNext(); + }, + taskCompleter, + ); + } + _getQueue(priority)[key] = task; + _pickNext(); + return taskCompleter.future; + } + + Future<T>? resume<T>(Object key) { + final toResume = _paused.remove(key); + if (toResume != null) { + final priority = toResume.$1; + final task = toResume.$2 as _Task<T>; + _getQueue(priority)[key] = task; + _pickNext(); + return task.completer.future; + } else { + return null; + } + } + + LinkedHashMap<Object, _Task> _getQueue(int priority) => _queues.putIfAbsent(priority, LinkedHashMap.new); + + void _pickNext() { + _notifyQueueState(); + if (_runningQueue.length >= concurrentTaskMax) return; + final queue = _queues.entries.firstWhereOrNull((kv) => kv.value.isNotEmpty)?.value; + if (queue != null && queue.isNotEmpty) { + final key = queue.keys.first; + final task = queue.remove(key)!; + _runningQueue[key] = task; + task.callback(); + } + } + + bool _takeOut(Object key, Iterable<int> priorities, void Function(int priority, _Task task) action) { + var out = false; + priorities.forEach((priority) { + final task = _getQueue(priority).remove(key); + if (task != null) { + out = true; + action(priority, task); + } + }); + return out; + } + + bool cancel(Object key, Iterable<int> priorities) { + return _takeOut(key, priorities, (priority, task) => task.completer.completeError(CancelledException())); + } + + bool pause(Object key, Iterable<int> priorities) { + return _takeOut(key, priorities, (priority, task) => _paused.putIfAbsent(key, () => (priority, task))); + } + + bool isPaused(Object key) => _paused.containsKey(key); + + void _notifyQueueState() { + if (!_queueStreamController.hasListener) return; + + final queueByPriority = Map.fromEntries(_queues.entries.map((kv) => MapEntry(kv.key, kv.value.length))); + _queueStreamController.add(QueueState(queueByPriority, _runningQueue.length, _paused.length)); + } +} + +class _Task<T> { + final VoidCallback callback; + final Completer<T> completer; + + const _Task(this.callback, this.completer); +} + +class CancelledException {} + +class ServiceCallPriority { + static const int getFastThumbnail = 100; + static const int getRegion = 150; + static const int getSizedThumbnail = 200; + static const int normal = 500; + static const int getMetadata = 1000; + static const int getLocation = 1000; +} + +class QueueState { + final Map<int, int> queueByPriority; + final int runningCount, pausedCount; + + const QueueState(this.queueByPriority, this.runningCount, this.pausedCount); +} diff --git a/lib/services/common/services.dart b/lib/services/common/services.dart new file mode 100644 index 0000000..eae00cb --- /dev/null +++ b/lib/services/common/services.dart @@ -0,0 +1,77 @@ +import 'package:aves/model/availability.dart'; +import 'package:aves/model/db/db.dart'; +import 'package:aves/model/db/db_sqflite.dart'; +import 'package:aves/model/settings/store_shared_pref.dart'; +import 'package:aves/services/app_profile_service.dart'; +import 'package:aves/services/app_service.dart'; +import 'package:aves/services/device_service.dart'; +import 'package:aves/services/media/embedded_data_service.dart'; +import 'package:aves/services/media/media_edit_service.dart'; +import 'package:aves/services/media/media_fetch_service.dart'; +import 'package:aves/services/media/media_session_service.dart'; +import 'package:aves/services/media/media_store_service.dart'; +import 'package:aves/services/metadata/metadata_edit_service.dart'; +import 'package:aves/services/metadata/metadata_fetch_service.dart'; +import 'package:aves/services/security_service.dart'; +import 'package:aves/services/storage_service.dart'; +import 'package:aves/services/window_service.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:aves_report/aves_report.dart'; +import 'package:aves_report_platform/aves_report_platform.dart'; +import 'package:aves_services/aves_services.dart'; +import 'package:aves_services_platform/aves_services_platform.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:aves_video_mpv/aves_video_mpv.dart'; +import 'package:get_it/get_it.dart'; +import 'package:path/path.dart' as p; + +final getIt = GetIt.instance; + +// fixed implementation is easier for test driver setup +final SettingsStore settingsStore = SharedPrefSettingsStore(); + +final p.Context pContext = getIt<p.Context>(); +final AvesAvailability availability = getIt<AvesAvailability>(); +final LocalMediaDb localMediaDb = getIt<LocalMediaDb>(); +final AvesVideoControllerFactory videoControllerFactory = getIt<AvesVideoControllerFactory>(); +final AvesVideoMetadataFetcher videoMetadataFetcher = getIt<AvesVideoMetadataFetcher>(); + +final AppService appService = getIt<AppService>(); +final AppProfileService appProfileService = getIt<AppProfileService>(); +final DeviceService deviceService = getIt<DeviceService>(); +final EmbeddedDataService embeddedDataService = getIt<EmbeddedDataService>(); +final MediaEditService mediaEditService = getIt<MediaEditService>(); +final MediaFetchService mediaFetchService = getIt<MediaFetchService>(); +final MediaSessionService mediaSessionService = getIt<MediaSessionService>(); +final MediaStoreService mediaStoreService = getIt<MediaStoreService>(); +final MetadataEditService metadataEditService = getIt<MetadataEditService>(); +final MetadataFetchService metadataFetchService = getIt<MetadataFetchService>(); +final MobileServices mobileServices = getIt<MobileServices>(); +final ReportService reportService = getIt<ReportService>(); +final SecurityService securityService = getIt<SecurityService>(); +final StorageService storageService = getIt<StorageService>(); +final WindowService windowService = getIt<WindowService>(); + +void initPlatformServices() { + getIt.registerLazySingleton<p.Context>(p.Context.new); + getIt.registerLazySingleton<AvesAvailability>(LiveAvesAvailability.new); + getIt.registerLazySingleton<LocalMediaDb>(SqfliteLocalMediaDb.new); + getIt.registerLazySingleton<AvesVideoControllerFactory>(MpvVideoControllerFactory.new); + getIt.registerLazySingleton<AvesVideoMetadataFetcher>(MpvVideoMetadataFetcher.new); + + getIt.registerLazySingleton<AppService>(PlatformAppService.new); + getIt.registerLazySingleton<AppProfileService>(PlatformAppProfileService.new); + getIt.registerLazySingleton<DeviceService>(PlatformDeviceService.new); + getIt.registerLazySingleton<EmbeddedDataService>(PlatformEmbeddedDataService.new); + getIt.registerLazySingleton<MediaEditService>(PlatformMediaEditService.new); + getIt.registerLazySingleton<MediaFetchService>(PlatformMediaFetchService.new); + getIt.registerLazySingleton<MediaSessionService>(PlatformMediaSessionService.new); + getIt.registerLazySingleton<MediaStoreService>(PlatformMediaStoreService.new); + getIt.registerLazySingleton<MetadataEditService>(PlatformMetadataEditService.new); + getIt.registerLazySingleton<MetadataFetchService>(PlatformMetadataFetchService.new); + getIt.registerLazySingleton<MobileServices>(PlatformMobileServices.new); + getIt.registerLazySingleton<ReportService>(PlatformReportService.new); + getIt.registerLazySingleton<SecurityService>(PlatformSecurityService.new); + getIt.registerLazySingleton<StorageService>(PlatformStorageService.new); + getIt.registerLazySingleton<WindowService>(PlatformWindowService.new); +} diff --git a/lib/services/device_service.dart b/lib/services/device_service.dart new file mode 100644 index 0000000..418c1c1 --- /dev/null +++ b/lib/services/device_service.dart @@ -0,0 +1,179 @@ +import 'dart:ui'; + +import 'package:aves/services/common/services.dart'; +import 'package:flutter/services.dart'; +import 'package:aves/services/common/channel.dart'; + +abstract class DeviceService { + Future<bool> canManageMedia(); + + Future<Map<String, dynamic>> getCapabilities(); + + Future<List<Locale>> getLocales(); + + Future<void> setLocaleConfig(List<Locale> locales); + + // 0 is Sunday + Future<int?> getFirstDayOfWeekIndex(); + + Future<int> getPerformanceClass(); + + Future<double?> getWidgetCornerRadiusPx(); + + Future<bool> isLocked(); + + Future<bool> isSystemFilePickerEnabled(); + + Future<void> requestMediaManagePermission(); + + Future<int> getAvailableHeapSize(); + + Future<void> requestGarbageCollection(); +} + +class PlatformDeviceService implements DeviceService { + static const _platform = AvesMethodChannel('deckers.thibault/aves/device'); + + @override + Future<bool> canManageMedia() async { + try { + final result = await _platform.invokeMethod('canManageMedia'); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + @override + Future<Map<String, dynamic>> getCapabilities() async { + try { + final result = await _platform.invokeMethod('getCapabilities'); + if (result != null) return (result as Map).cast<String, dynamic>(); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + @override + Future<List<Locale>> getLocales() async { + try { + final result = await _platform.invokeMethod('getLocales'); + if (result != null) { + return (result as List).cast<Map>().map((tags) { + final language = tags['language'] as String?; + final country = tags['country'] as String?; + return Locale( + language ?? 'und', + (country != null && country.isEmpty) ? null : country, + ); + }).toList(); + } + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return []; + } + + @override + Future<void> setLocaleConfig(List<Locale> locales) async { + try { + await _platform.invokeMethod('setLocaleConfig', <String, dynamic>{ + 'locales': locales.map((v) => v.toLanguageTag()).toList(), + }); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } + + @override + Future<int?> getFirstDayOfWeekIndex() async { + try { + final result = await _platform.invokeMethod('getFirstDayOfWeek'); + if (result != null) { + final day = result as String; + final index = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].indexOf(day); + if (index >= 0) { + return index; + } + } + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return null; + } + + @override + Future<int> getPerformanceClass() async { + try { + final result = await _platform.invokeMethod('getPerformanceClass'); + if (result != null) return result as int; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return 0; + } + + @override + Future<double?> getWidgetCornerRadiusPx() async { + try { + final result = await _platform.invokeMethod('getWidgetCornerRadiusPx'); + if (result != null) return result as double; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return null; + } + + @override + Future<bool> isLocked() async { + try { + final result = await _platform.invokeMethod('isLocked'); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + @override + Future<bool> isSystemFilePickerEnabled() async { + try { + final result = await _platform.invokeMethod('isSystemFilePickerEnabled'); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + @override + Future<void> requestMediaManagePermission() async { + try { + await _platform.invokeMethod('requestMediaManagePermission'); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } + + @override + Future<int> getAvailableHeapSize() async { + try { + final result = await _platform.invokeMethod('getAvailableHeapSize'); + if (result != null) return result as int; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return 0; + } + + @override + Future<void> requestGarbageCollection() async { + try { + await _platform.invokeMethod('requestGarbageCollection'); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } +} diff --git a/lib/services/geocoding_service.dart b/lib/services/geocoding_service.dart new file mode 100644 index 0000000..c5b1133 --- /dev/null +++ b/lib/services/geocoding_service.dart @@ -0,0 +1,66 @@ +import 'dart:async'; +import 'dart:ui'; + +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:aves/services/common/channel.dart'; + +class GeocodingService { + static const _platform = AvesMethodChannel('deckers.thibault/aves/geocoding'); + + // geocoding requires Google Play Services + static Future<List<Address>> getAddress(LatLng coordinates, Locale locale) async { + try { + final result = await _platform.invokeMethod('getAddress', <String, dynamic>{ + 'latitude': coordinates.latitude, + 'longitude': coordinates.longitude, + 'localeLanguageTag': locale.toLanguageTag(), + // we only really need one address, but sometimes the native geocoder + // returns nothing with `maxResults` of 1, but succeeds with `maxResults` of 2+ + 'maxResults': 2, + }); + return (result as List).cast<Map>().map(Address.fromMap).toList(); + } on PlatformException catch (_) { + // do not report + } + return []; + } +} + +@immutable +class Address extends Equatable { + final String? addressLine, adminArea, countryCode, countryName, featureName, locality, postalCode, subAdminArea, subLocality, subThoroughfare, thoroughfare; + + @override + List<Object?> get props => [addressLine, adminArea, countryCode, countryName, featureName, locality, postalCode, subAdminArea, subLocality, subThoroughfare, thoroughfare]; + + const Address({ + this.addressLine, + this.adminArea, + this.countryCode, + this.countryName, + this.featureName, + this.locality, + this.postalCode, + this.subAdminArea, + this.subLocality, + this.subThoroughfare, + this.thoroughfare, + }); + + factory Address.fromMap(Map map) => Address( + addressLine: map['addressLine'], + adminArea: map['adminArea'], + countryCode: map['countryCode'], + countryName: map['countryName'], + featureName: map['featureName'], + locality: map['locality'], + postalCode: map['postalCode'], + subAdminArea: map['subAdminArea'], + subLocality: map['subLocality'], + subThoroughfare: map['subThoroughfare'], + thoroughfare: map['thoroughfare'], + ); +} diff --git a/lib/services/global_search.dart b/lib/services/global_search.dart new file mode 100644 index 0000000..0ef7c1e --- /dev/null +++ b/lib/services/global_search.dart @@ -0,0 +1,77 @@ +import 'dart:ui'; + +import 'package:aves/model/entry/sort.dart'; +import 'package:aves/services/common/channel.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/format.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:intl/date_symbol_data_local.dart'; + +class GlobalSearch { + static const _platform = AvesMethodChannel('deckers.thibault/aves/global_search'); + + static Future<void> registerCallback() async { + try { + await _platform.invokeMethod('registerCallback', <String, dynamic>{ + // callback needs to be annotated with `@pragma('vm:entry-point')` to work in release mode + 'callbackHandle': PluginUtilities.getCallbackHandle(_init)?.toRawHandle(), + }); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } +} + +@pragma('vm:entry-point') +Future<void> _init() async { + WidgetsFlutterBinding.ensureInitialized(); + + // service initialization for path context, database + initPlatformServices(); + await localMediaDb.init(); + + // `intl` initialization for date formatting + await initializeDateFormatting(); + + const _channel = AvesMethodChannel('deckers.thibault/aves/global_search_background'); + _channel.setMethodCallHandler((call) async { + switch (call.method) { + case 'getSuggestions': + return await _getSuggestions(call.arguments); + default: + throw PlatformException(code: 'not-implemented', message: 'failed to handle method=${call.method}'); + } + }); + await _channel.invokeMethod('initialized'); +} + +Future<List<Map<String, String?>>> _getSuggestions(dynamic args) async { + final suggestions = <Map<String, String?>>[]; + if (args is Map) { + final query = args['query']; + final locale = args['locale']; + final use24hour = args['use24hour']; + debugPrint('getSuggestions query=$query, locale=$locale use24hour=$use24hour'); + + if (query is String && locale is String) { + final entries = (await localMediaDb.searchLiveEntries(query, limit: 9)).toList(); + final catalogMetadata = await localMediaDb.loadCatalogMetadataById(entries.map((entry) => entry.id).toSet()); + catalogMetadata.forEach((metadata) => entries.firstWhereOrNull((entry) => entry.id == metadata.id)?.catalogMetadata = metadata); + entries.sort(AvesEntrySort.compareByDate); + + suggestions.addAll(entries.map((entry) { + final date = entry.bestDate; + return { + 'data': entry.uri, + 'mimeType': entry.mimeType, + 'title': entry.bestTitle, + 'subtitle': date != null ? formatDateTime(date, locale, use24hour) : null, + 'iconUri': entry.uri, + }; + })); + } + } + return suggestions; +} diff --git a/lib/services/intent_service.dart b/lib/services/intent_service.dart new file mode 100644 index 0000000..2c03fe6 --- /dev/null +++ b/lib/services/intent_service.dart @@ -0,0 +1,72 @@ +import 'dart:async'; + +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/services/app_service.dart'; +import 'package:aves/services/common/channel.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:flutter/services.dart'; + +class IntentService { + static const _platform = AvesMethodChannel('deckers.thibault/aves/intent'); + static final _stream = AvesStreamsChannel('deckers.thibault/aves/activity_result_stream'); + + static Future<Map<String, dynamic>> getIntentData() async { + try { + // returns nullable map with 'action' and possibly 'uri' 'mimeType' + final result = await _platform.invokeMethod('getIntentData'); + if (result != null) return (result as Map).cast<String, dynamic>(); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + static Future<void> submitPickedItems(List<String> uris) async { + try { + await _platform.invokeMethod('submitPickedItems', <String, dynamic>{ + 'uris': uris, + }); + } on PlatformException catch (e, stack) { + if (e.code == 'submitPickedItems-large') { + throw TooManyItemsException(); + } else { + await reportService.recordError(e, stack); + } + } + } + + static Future<void> submitPickedCollectionFilters(Set<CollectionFilter>? filters) async { + try { + await _platform.invokeMethod('submitPickedCollectionFilters', <String, dynamic>{ + 'filters': filters?.map((filter) => filter.toJson()).toList(), + }); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } + + static Future<Set<CollectionFilter>?> pickCollectionFilters(Set<CollectionFilter>? initialFilters) async { + try { + final opCompleter = Completer<Set<CollectionFilter>?>(); + _stream.receiveBroadcastStream(<String, dynamic>{ + 'op': 'pickCollectionFilters', + 'initialFilters': initialFilters?.map((filter) => filter.toJson()).toList(), + }).listen( + (data) { + final result = (data as List?)?.cast<String>().map(CollectionFilter.fromJson).nonNulls.toSet(); + opCompleter.complete(result); + }, + onError: opCompleter.completeError, + onDone: () { + if (!opCompleter.isCompleted) opCompleter.complete(null); + }, + cancelOnError: true, + ); + // `await` here, so that `completeError` will be caught below + return await opCompleter.future; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return null; + } +} diff --git a/lib/services/media/embedded_data_service.dart b/lib/services/media/embedded_data_service.dart new file mode 100644 index 0000000..b9d3633 --- /dev/null +++ b/lib/services/media/embedded_data_service.dart @@ -0,0 +1,147 @@ +import 'dart:ui' as ui; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/services/common/decoding.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/text.dart'; +import 'package:flutter/services.dart'; +import 'package:aves/services/common/channel.dart'; + +abstract class EmbeddedDataService { + Future<List<ui.ImageDescriptor?>> getExifThumbnails(AvesEntry entry); + + Future<Map> extractGoogleDeviceItem(AvesEntry entry, String dataUri); + + Future<Map> extractMotionPhotoImage(AvesEntry entry); + + Future<Map> extractMotionPhotoVideo(AvesEntry entry); + + Future<Map> extractJpegMpfItem(AvesEntry entry, int index); + + Future<Map> extractVideoEmbeddedPicture(AvesEntry entry); + + Future<Map> extractXmpDataProp(AvesEntry entry, List<dynamic>? props, String? propMimeType); +} + +class PlatformEmbeddedDataService implements EmbeddedDataService { + static const _platform = AvesMethodChannel('deckers.thibault/aves/embedded'); + + @override + Future<List<ui.ImageDescriptor?>> getExifThumbnails(AvesEntry entry) async { + try { + final result = await _platform.invokeMethod('getExifThumbnails', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + }); + if (result != null) { + final descriptors = <ui.ImageDescriptor?>[]; + await Future.forEach((result as List).cast<Uint8List>(), (bytes) async { + descriptors.add(await InteropDecoding.rawBytesToDescriptor(bytes)); + }); + return descriptors; + } + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return []; + } + + @override + Future<Map> extractGoogleDeviceItem(AvesEntry entry, String dataUri) async { + try { + final result = await _platform.invokeMethod('extractGoogleDeviceItem', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + 'displayName': ['${entry.bestTitle}', dataUri].join(AText.separator), + 'dataUri': dataUri, + }); + if (result != null) return result as Map; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + @override + Future<Map> extractMotionPhotoImage(AvesEntry entry) async { + try { + final result = await _platform.invokeMethod('extractMotionPhotoImage', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + 'displayName': ['${entry.bestTitle}', 'Image'].join(AText.separator), + }); + if (result != null) return result as Map; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + @override + Future<Map> extractMotionPhotoVideo(AvesEntry entry) async { + try { + final result = await _platform.invokeMethod('extractMotionPhotoVideo', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + 'displayName': ['${entry.bestTitle}', 'Video'].join(AText.separator), + }); + if (result != null) return result as Map; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + @override + Future<Map> extractJpegMpfItem(AvesEntry entry, int id) async { + try { + final result = await _platform.invokeMethod('extractJpegMpfItem', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + 'displayName': ['${entry.bestTitle}', 'MPF #$id'].join(AText.separator), + 'id': id, + }); + if (result != null) return result as Map; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + @override + Future<Map> extractVideoEmbeddedPicture(AvesEntry entry) async { + try { + final result = await _platform.invokeMethod('extractVideoEmbeddedPicture', <String, dynamic>{ + 'uri': entry.uri, + 'displayName': ['${entry.bestTitle}', 'Cover'].join(AText.separator), + }); + if (result != null) return result as Map; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + @override + Future<Map> extractXmpDataProp(AvesEntry entry, List<dynamic>? props, String? propMimeType) async { + try { + final result = await _platform.invokeMethod('extractXmpDataProp', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + 'displayName': ['${entry.bestTitle}', '$props'].join(AText.separator), + 'propPath': props, + 'propMimeType': propMimeType, + }); + if (result != null) return result as Map; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } +} diff --git a/lib/services/media/enums.dart b/lib/services/media/enums.dart new file mode 100644 index 0000000..4f47d6d --- /dev/null +++ b/lib/services/media/enums.dart @@ -0,0 +1,18 @@ +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/widgets.dart'; + +// names should match possible values on platform +enum NameConflictStrategy { rename, replace, skip } + +extension ExtraNameConflictStrategy on NameConflictStrategy { + String toPlatform() => name; + + String getName(BuildContext context) { + final l10n = context.l10n; + return switch (this) { + NameConflictStrategy.rename => l10n.nameConflictStrategyRename, + NameConflictStrategy.replace => l10n.nameConflictStrategyReplace, + NameConflictStrategy.skip => l10n.nameConflictStrategySkip, + }; + } +} diff --git a/lib/services/media/media_edit_service.dart b/lib/services/media/media_edit_service.dart new file mode 100644 index 0000000..a7dd0f4 --- /dev/null +++ b/lib/services/media/media_edit_service.dart @@ -0,0 +1,209 @@ +import 'dart:async'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/services/common/channel.dart'; +import 'package:aves/services/common/image_op_events.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/media/enums.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +abstract class MediaEditService { + String get newOpId; + + Future<void> cancelFileOp(String opId); + + Stream<ImageOpEvent> delete({ + String? opId, + required Iterable<AvesEntry> entries, + }); + + Stream<MoveOpEvent> move({ + String? opId, + required Map<String, Iterable<AvesEntry>> entriesByDestination, + required bool copy, + required NameConflictStrategy nameConflictStrategy, + }); + + Stream<ExportOpEvent> export( + Iterable<AvesEntry> entries, { + required EntryConvertOptions options, + required String destinationAlbum, + required NameConflictStrategy nameConflictStrategy, + }); + + Stream<MoveOpEvent> rename({ + String? opId, + required Map<AvesEntry, String> entriesToNewName, + }); + + Future<Map<String, dynamic>> captureFrame( + AvesEntry entry, { + required String desiredName, + required Map<String, dynamic> exif, + required Uint8List bytes, + required String destinationAlbum, + required NameConflictStrategy nameConflictStrategy, + }); +} + +class PlatformMediaEditService implements MediaEditService { + static const _platform = AvesMethodChannel('deckers.thibault/aves/media_edit'); + static final _opStream = AvesStreamsChannel('deckers.thibault/aves/media_op_stream'); + + @override + String get newOpId => DateTime.now().millisecondsSinceEpoch.toString(); + + @override + Future<void> cancelFileOp(String opId) async { + try { + await _platform.invokeMethod('cancelFileOp', <String, dynamic>{ + 'opId': opId, + }); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } + + @override + Stream<ImageOpEvent> delete({ + String? opId, + required Iterable<AvesEntry> entries, + }) { + try { + return _opStream + .receiveBroadcastStream(<String, dynamic>{ + 'op': 'delete', + 'id': opId, + 'entries': entries.map((entry) => entry.toPlatformEntryMap()).toList(), + }) + .where((event) => event is Map) + .map((event) => ImageOpEvent.fromMap(event as Map)); + } on PlatformException catch (e, stack) { + reportService.recordError(e, stack); + return Stream.error(e); + } + } + + @override + Stream<MoveOpEvent> move({ + String? opId, + required Map<String, Iterable<AvesEntry>> entriesByDestination, + required bool copy, + required NameConflictStrategy nameConflictStrategy, + }) { + try { + return _opStream + .receiveBroadcastStream(<String, dynamic>{ + 'op': 'move', + 'id': opId, + 'entriesByDestination': entriesByDestination.map((destination, entries) => MapEntry(destination, entries.map((entry) => entry.toPlatformEntryMap()).toList())), + 'copy': copy, + 'nameConflictStrategy': nameConflictStrategy.toPlatform(), + }) + .where((event) => event is Map) + .map((event) => MoveOpEvent.fromMap(event as Map)); + } on PlatformException catch (e, stack) { + reportService.recordError(e, stack); + return Stream.error(e); + } + } + + @override + Stream<ExportOpEvent> export( + Iterable<AvesEntry> entries, { + required EntryConvertOptions options, + required String destinationAlbum, + required NameConflictStrategy nameConflictStrategy, + }) { + try { + return _opStream + .receiveBroadcastStream(<String, dynamic>{ + 'op': 'convert', + 'entries': entries.map((entry) => entry.toPlatformEntryMap()).toList(), + 'mimeType': options.mimeType, + 'quality': options.quality, + 'lengthUnit': options.lengthUnit.name, + 'width': options.width, + 'height': options.height, + 'writeMetadata': options.writeMetadata, + 'destinationPath': destinationAlbum, + 'nameConflictStrategy': nameConflictStrategy.toPlatform(), + }) + .where((event) => event is Map) + .map((event) => ExportOpEvent.fromMap(event as Map)); + } on PlatformException catch (e, stack) { + reportService.recordError(e, stack); + return Stream.error(e); + } + } + + @override + Stream<MoveOpEvent> rename({ + String? opId, + required Map<AvesEntry, String> entriesToNewName, + }) { + try { + return _opStream + .receiveBroadcastStream(<String, dynamic>{ + 'op': 'rename', + 'id': opId, + 'entriesToNewName': entriesToNewName.map((entry, name) => MapEntry(entry.toPlatformEntryMap(), name)), + }) + .where((event) => event is Map) + .map((event) => MoveOpEvent.fromMap(event as Map)); + } on PlatformException catch (e, stack) { + reportService.recordError(e, stack); + return Stream.error(e); + } + } + + @override + Future<Map<String, dynamic>> captureFrame( + AvesEntry entry, { + required String desiredName, + required Map<String, dynamic> exif, + required Uint8List bytes, + required String destinationAlbum, + required NameConflictStrategy nameConflictStrategy, + }) async { + try { + final result = await _platform.invokeMethod('captureFrame', <String, dynamic>{ + 'uri': entry.uri, + 'desiredName': desiredName, + 'exif': exif, + 'bytes': bytes, + 'destinationPath': destinationAlbum, + 'nameConflictStrategy': nameConflictStrategy.toPlatform(), + }); + if (result != null) return (result as Map).cast<String, dynamic>(); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } +} + +@immutable +class EntryConvertOptions extends Equatable { + final EntryConvertAction action; + final String mimeType; + final bool writeMetadata; + final LengthUnit lengthUnit; + final int width, height, quality; + + @override + List<Object?> get props => [action, mimeType, writeMetadata, lengthUnit, width, height, quality]; + + const EntryConvertOptions({ + required this.action, + required this.mimeType, + required this.writeMetadata, + required this.lengthUnit, + required this.width, + required this.height, + required this.quality, + }); +} diff --git a/lib/services/media/media_fetch_service.dart b/lib/services/media/media_fetch_service.dart new file mode 100644 index 0000000..72fcdbf --- /dev/null +++ b/lib/services/media/media_fetch_service.dart @@ -0,0 +1,383 @@ +import 'dart:async'; +import 'dart:ui' as ui; + +import 'package:aves/image_providers/region_provider.dart'; +import 'package:aves/image_providers/thumbnail_provider.dart'; +import 'package:aves/model/app/support.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/channel.dart'; +import 'package:aves/services/common/decoding.dart'; +import 'package:aves/services/common/output_buffer.dart'; +import 'package:aves/services/common/service_policy.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves_report/aves_report.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/painting.dart'; +import 'package:flutter/services.dart'; + +abstract class MediaFetchService { + Future<AvesEntry?> getEntry(String uri, String? mimeType, {bool allowUnsized = false}); + + Future<Uint8List> getOriginalBytes(AvesEntry entry); + + Future<ui.Codec> getFullImage({ + required bool decoded, + required ImageRequest request, + required ImageDecoderCallback decode, + }); + + // `rect`: region to decode, with coordinates in reference to `imageSize` + Future<ui.Codec> getRegion({ + required bool decoded, + required RegionProviderKey request, + required ImageDecoderCallback decode, + Object? taskKey, + int? priority, + }); + + Future<ui.Codec> getThumbnail({ + required bool decoded, + required ThumbnailProviderKey request, + ImageDecoderCallback? decode, + Object? taskKey, + int? priority, + }); + + Future<void> clearImageDiskCache(); + + Future<void> clearImageMemoryCache(); + + bool cancelRegion(Object taskKey); + + bool cancelThumbnail(Object taskKey); + + Future<T>? resumeLoading<T>(Object taskKey); +} + +class PlatformMediaFetchService implements MediaFetchService { + static const _platformObject = AvesMethodChannel('deckers.thibault/aves/media_fetch_object'); + static final _byteStream = AvesStreamsChannel('deckers.thibault/aves/media_byte_stream'); + static const double _thumbnailDefaultSize = 64.0; + + static const int formatTrailerLength = 1; // single format byte + static const int formatByteEncoded = 0xCA; + static const int formatByteDecoded = 0xFE; + + @override + Future<AvesEntry?> getEntry(String uri, String? mimeType, {bool allowUnsized = false}) async { + try { + final result = await _platformObject.invokeMethod('getEntry', <String, dynamic>{ + 'uri': uri, + 'mimeType': mimeType, + 'allowUnsized': allowUnsized, + }) as Map; + AvesEntry.normalizeMimeTypeFields(result); + return AvesEntry.fromMap(result); + } on PlatformException catch (e, stack) { + // do not report issues with media content as it is likely an obsolete Media Store entry + if (!uri.startsWith('content://media/') && !_isUnknownVisual(mimeType)) { + await reportService.recordError(e, stack); + } + } + return null; + } + + Map<String, dynamic> _requestToArgs(ImageRequest request, {required bool decoded}) { + return <String, dynamic>{ + 'op': 'getFullImage', + 'decoded': decoded, + 'uri': request.uri, + 'pageId': request.pageId, + 'mimeType': request.mimeType, + 'sizeBytes': request.sizeBytes, + 'rotationDegrees': request.rotationDegrees ?? 0, + 'isFlipped': request.isFlipped, + }; + } + + Future<Uint8List> _getBytes({ + required String mimeType, + required Map<String, dynamic> arguments, + BytesReceivedCallback? onBytesReceived, + int? sizeBytes, + }) async { + var bytesReceived = 0; + final opCompleter = Completer<Uint8List>(); + final sink = OutputBuffer(); + try { + _byteStream.receiveBroadcastStream(arguments).listen( + (data) { + final chunk = data as Uint8List; + sink.add(chunk); + if (onBytesReceived != null) { + bytesReceived += chunk.length; + try { + onBytesReceived(bytesReceived, sizeBytes); + } catch (error, stack) { + opCompleter.completeError(error, stack); + return; + } + } + }, + onError: opCompleter.completeError, + onDone: () { + sink.close(); + opCompleter.complete(sink.bytes); + }, + cancelOnError: true, + ); + // `await` here, so that `completeError` will be caught below + return await opCompleter.future; + } on PlatformException catch (e, stack) { + debugPrint('$runtimeType _getBytes failed with error=$e'); + if (_isUnknownVisual(mimeType)) { + await reportService.recordError(e, stack); + } + } + return Uint8List(0); + } + + Future<ui.Codec> _bytesToCodec(Map<String, dynamic> args, Uint8List bytes, ImageDecoderCallback? decode) async { + final byteCount = bytes.lengthInBytes; + if (byteCount < formatTrailerLength) { + throw UnreportedStateError('failed to get image bytes for args=$args'); + } + + final trailerOffset = byteCount - formatTrailerLength; + final format = bytes[trailerOffset]; + switch (format) { + case formatByteEncoded: + if (decode == null) { + throw Exception('failed to decode encoded image bytes because decoder callback is missing for args=$args'); + } + // bytes are expected to be in a basic format decodable by Flutter + final codec = await InteropDecoding.encodedBytesToCodec(bytes, decode); + if (codec == null) { + throw UnreportedStateError('failed to get codec from encoded image bytes for args=$args'); + } + return codec; + case formatByteDecoded: + // bytes are expected to be in ARGB_8888, necessary for wide gamut or HDR + final descriptor = await InteropDecoding.rawBytesToDescriptor(bytes); + if (descriptor == null) { + throw UnreportedStateError('failed to get descriptor from decoded image bytes for args=$args'); + } + return descriptor.instantiateCodec(); + default: + throw UnreportedStateError('unsupported image format byte=$format for args=$args'); + } + } + + @override + Future<Uint8List> getOriginalBytes(AvesEntry entry) async { + final request = ImageRequest( + entry.uri, + entry.mimeType, + rotationDegrees: entry.rotationDegrees, + isFlipped: entry.isFlipped, + isAnimated: entry.isAnimated, + pageId: entry.pageId, + sizeBytes: entry.sizeBytes, + ); + final bytes = await _getBytes( + mimeType: request.mimeType, + arguments: _requestToArgs(request, decoded: false), + onBytesReceived: request.onBytesReceived, + sizeBytes: request.sizeBytes, + ); + + final byteCount = bytes.lengthInBytes; + if (byteCount <= formatTrailerLength) { + throw UnreportedStateError('failed to get image bytes for request=$request'); + } + + // trim custom trailer + // a view does not reallocate memory and uses the underlying buffer + return Uint8List.sublistView(bytes, 0, byteCount - formatTrailerLength); + } + + @override + Future<ui.Codec> getFullImage({ + required bool decoded, + required ImageRequest request, + required ImageDecoderCallback decode, + }) async { + final args = _requestToArgs(request, decoded: decoded); + final bytes = await _getBytes( + mimeType: request.mimeType, + arguments: args, + onBytesReceived: request.onBytesReceived, + sizeBytes: request.sizeBytes, + ); + return await _bytesToCodec(args, bytes, decode); + } + + @override + Future<ui.Codec> getRegion({ + required bool decoded, + required RegionProviderKey request, + required ImageDecoderCallback decode, + Object? taskKey, + int? priority, + }) { + final args = <String, dynamic>{ + 'op': 'getRegion', + 'decoded': decoded, + 'uri': request.uri, + 'pageId': request.pageId, + 'mimeType': request.mimeType, + 'sizeBytes': request.sizeBytes, + 'sampleSize': request.sampleSize, + 'regionX': request.regionRect.left, + 'regionY': request.regionRect.top, + 'regionWidth': request.regionRect.width, + 'regionHeight': request.regionRect.height, + 'imageWidth': request.imageSize.width.toInt(), + 'imageHeight': request.imageSize.height.toInt(), + }; + return servicePolicy.call( + () async { + final bytes = await _getBytes( + mimeType: request.mimeType, + arguments: args, + ); + return await _bytesToCodec(args, bytes, decode); + }, + priority: priority ?? ServiceCallPriority.getRegion, + key: taskKey, + ); + } + + @override + Future<ui.Codec> getThumbnail({ + required bool decoded, + required ThumbnailProviderKey request, + ImageDecoderCallback? decode, + Object? taskKey, + int? priority, + }) { + final args = <String, dynamic>{ + 'op': 'getThumbnail', + 'decoded': decoded, + 'uri': request.uri, + 'pageId': request.pageId, + 'mimeType': request.mimeType, + 'dateModifiedMillis': request.dateModifiedMillis, + 'rotationDegrees': request.rotationDegrees, + 'isFlipped': request.isFlipped, + 'widthDip': request.extent, + 'heightDip': request.extent, + 'defaultSizeDip': _thumbnailDefaultSize, + 'quality': 100, + }; + return servicePolicy.call( + () async { + final bytes = await _getBytes( + mimeType: request.mimeType, + arguments: args, + ); + return await _bytesToCodec(args, bytes, decode); + }, + priority: priority ?? (request.extent == 0 ? ServiceCallPriority.getFastThumbnail : ServiceCallPriority.getSizedThumbnail), + key: taskKey, + ); + } + + @override + Future<void> clearImageDiskCache() async { + try { + return _platformObject.invokeMethod('clearImageDiskCache'); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } + + @override + Future<void> clearImageMemoryCache() async { + try { + return _platformObject.invokeMethod('clearImageMemoryCache'); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } + + @override + bool cancelRegion(Object taskKey) => servicePolicy.pause(taskKey, [ServiceCallPriority.getRegion]); + + @override + bool cancelThumbnail(Object taskKey) => servicePolicy.pause(taskKey, [ServiceCallPriority.getFastThumbnail, ServiceCallPriority.getSizedThumbnail]); + + @override + Future<T>? resumeLoading<T>(Object taskKey) => servicePolicy.resume<T>(taskKey); + + // convenience methods + + bool _isUnknownVisual(String? mimeType) => mimeType != null && !_knownMediaTypes.contains(mimeType) && MimeTypes.isVisual(mimeType); + + static const Set<String> _knownOpaqueImages = { + MimeTypes.jpeg, + }; + + static const Set<String> _knownVideos = { + MimeTypes.v3gpp, + MimeTypes.asf, + MimeTypes.avi, + MimeTypes.aviMSVideo, + MimeTypes.aviVnd, + MimeTypes.aviXMSVideo, + MimeTypes.dvd, + MimeTypes.flv, + MimeTypes.flvX, + MimeTypes.mkv, + MimeTypes.mkvX, + MimeTypes.mov, + MimeTypes.movX, + MimeTypes.mp2p, + MimeTypes.mp2t, + MimeTypes.mp2ts, + MimeTypes.mp4, + MimeTypes.mpeg, + MimeTypes.ogv, + MimeTypes.realVideo, + MimeTypes.webm, + MimeTypes.wmv, + }; + + static final Set<String> _knownMediaTypes = { + MimeTypes.anyImage, + ..._knownOpaqueImages, + ...MimeTypes.alphaImages, + ...MimeTypes.rawImages, + ...AppSupport.undecodableImages, + MimeTypes.anyVideo, + ..._knownVideos, + }; +} + +@immutable +class ImageRequest extends Equatable { + final String uri; + final String mimeType; + final int? rotationDegrees; + final bool isFlipped; + final bool isAnimated; + final int? pageId; + final int? sizeBytes; + final BytesReceivedCallback? onBytesReceived; + + @override + List<Object?> get props => [uri, mimeType, rotationDegrees, isFlipped, isAnimated, pageId, sizeBytes, onBytesReceived]; + + const ImageRequest( + this.uri, + this.mimeType, { + required this.rotationDegrees, + required this.isFlipped, + required this.isAnimated, + required this.pageId, + required this.sizeBytes, + this.onBytesReceived, + }); +} diff --git a/lib/services/media/media_session_service.dart b/lib/services/media/media_session_service.dart new file mode 100644 index 0000000..ace1122 --- /dev/null +++ b/lib/services/media/media_session_service.dart @@ -0,0 +1,140 @@ +import 'dart:async'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/services/common/channel.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:get_it/get_it.dart'; + +abstract class MediaSessionService { + Stream<MediaCommandEvent> get mediaCommands; + + Future<void> update({ + required AvesEntry entry, + required AvesVideoController controller, + required bool canSkipToNext, + required bool canSkipToPrevious, + }); + + Future<void> release(); +} + +class PlatformMediaSessionService implements MediaSessionService, Disposable { + static const _platformObject = AvesMethodChannel('deckers.thibault/aves/media_session'); + + final Set<StreamSubscription> _subscriptions = {}; + final EventChannel _mediaCommandChannel = const OptionalEventChannel('deckers.thibault/aves/media_command'); + final StreamController _streamController = StreamController.broadcast(); + + PlatformMediaSessionService() { + _subscriptions.add(_mediaCommandChannel.receiveBroadcastStream().listen((event) => _onMediaCommand(event as Map?))); + } + + @override + FutureOr onDispose() { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + @override + Stream<MediaCommandEvent> get mediaCommands => _streamController.stream.where((event) => event is MediaCommandEvent).cast<MediaCommandEvent>(); + + @override + Future<void> update({ + required AvesEntry entry, + required AvesVideoController controller, + required bool canSkipToNext, + required bool canSkipToPrevious, + }) async { + try { + await _platformObject.invokeMethod('update', <String, dynamic>{ + 'uri': entry.uri, + 'title': entry.bestTitle, + 'durationMillis': controller.duration, + 'state': _toPlatformState(controller.status), + 'positionMillis': controller.currentPosition, + 'playbackSpeed': controller.speed, + 'canSkipToNext': canSkipToNext, + 'canSkipToPrevious': canSkipToPrevious, + }); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } + + @override + Future<void> release() async { + try { + await _platformObject.invokeMethod('release'); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } + + String _toPlatformState(VideoStatus status) { + switch (status) { + case VideoStatus.paused: + return 'paused'; + case VideoStatus.playing: + return 'playing'; + case VideoStatus.idle: + case VideoStatus.initialized: + case VideoStatus.completed: + case VideoStatus.error: + return 'stopped'; + } + } + + void _onMediaCommand(Map? fields) { + if (fields == null) return; + final command = fields['command'] as String?; + MediaCommandEvent? event; + switch (command) { + case 'play': + event = const MediaCommandEvent(MediaCommand.play); + case 'pause': + event = const MediaCommandEvent(MediaCommand.pause); + case 'skip_to_next': + event = const MediaCommandEvent(MediaCommand.skipToNext); + case 'skip_to_previous': + event = const MediaCommandEvent(MediaCommand.skipToPrevious); + case 'stop': + event = const MediaCommandEvent(MediaCommand.stop); + case 'seek': + final position = fields['position'] as int?; + if (position != null) { + event = MediaSeekCommandEvent(MediaCommand.stop, position: position); + } + } + if (event != null) { + _streamController.add(event); + } + } +} + +enum MediaCommand { play, pause, skipToNext, skipToPrevious, stop, seek } + +@immutable +class MediaCommandEvent extends Equatable { + final MediaCommand command; + + @override + List<Object?> get props => [command]; + + const MediaCommandEvent(this.command); +} + +@immutable +class MediaSeekCommandEvent extends MediaCommandEvent { + final int position; + + @override + List<Object?> get props => [...super.props, position]; + + const MediaSeekCommandEvent(super.command, {required this.position}); +} diff --git a/lib/services/media/media_store_service.dart b/lib/services/media/media_store_service.dart new file mode 100644 index 0000000..c33e248 --- /dev/null +++ b/lib/services/media/media_store_service.dart @@ -0,0 +1,113 @@ +import 'dart:async'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/services/common/channel.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:flutter/services.dart'; + +abstract class MediaStoreService { + Future<List<int>> checkObsoleteContentIds(List<int?> knownContentIds); + + Future<List<int>> checkObsoletePaths(Map<int?, String?> knownPathById); + + Future<List<String>> getChangedUris(int sinceGeneration); + + Future<int?> getGeneration(); + + // knownEntries: map of contentId -> dateModifiedMillis + Stream<AvesEntry> getEntries(Map<int?, int?> knownEntries, {String? directory}); + + // returns media URI + Future<Uri?> scanFile(String path, String mimeType); +} + +class PlatformMediaStoreService implements MediaStoreService { + static const _platform = AvesMethodChannel('deckers.thibault/aves/media_store'); + static final _stream = AvesStreamsChannel('deckers.thibault/aves/media_store_stream'); + + @override + Future<List<int>> checkObsoleteContentIds(List<int?> knownContentIds) async { + try { + final result = await _platform.invokeMethod('checkObsoleteContentIds', <String, dynamic>{ + 'knownContentIds': knownContentIds, + }); + return (result as List).cast<int>(); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return []; + } + + @override + Future<List<int>> checkObsoletePaths(Map<int?, String?> knownPathById) async { + try { + final result = await _platform.invokeMethod('checkObsoletePaths', <String, dynamic>{ + 'knownPathById': knownPathById, + }); + return (result as List).cast<int>(); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return []; + } + + @override + Future<List<String>> getChangedUris(int sinceGeneration) async { + try { + final result = await _platform.invokeMethod('getChangedUris', <String, dynamic>{ + 'sinceGeneration': sinceGeneration, + }); + return (result as List).cast<String>(); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return []; + } + + @override + Future<int?> getGeneration() async { + try { + return await _platform.invokeMethod('getGeneration'); + } on PlatformException catch (e, stack) { + if (e.code != 'getGeneration-primary') { + await reportService.recordError(e, stack); + } + } + return null; + } + + @override + Stream<AvesEntry> getEntries(Map<int?, int?> knownEntries, {String? directory}) { + try { + return _stream + .receiveBroadcastStream(<String, dynamic>{ + 'knownEntries': knownEntries, + 'directory': directory, + }) + .where((event) => event is Map) + .map((event) { + final fields = event as Map; + AvesEntry.normalizeMimeTypeFields(fields); + return AvesEntry.fromMap(fields); + }); + } on PlatformException catch (e, stack) { + reportService.recordError(e, stack); + return Stream.error(e); + } + } + + // returns media URI + @override + Future<Uri?> scanFile(String path, String mimeType) async { + try { + final result = await _platform.invokeMethod('scanFile', <String, dynamic>{ + 'path': path, + 'mimeType': mimeType, + }); + if (result != null) return Uri.tryParse(result); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return null; + } +} diff --git a/lib/services/metadata/metadata_edit_service.dart b/lib/services/metadata/metadata_edit_service.dart new file mode 100644 index 0000000..92f63f8 --- /dev/null +++ b/lib/services/metadata/metadata_edit_service.dart @@ -0,0 +1,180 @@ +import 'dart:async'; + +import 'package:aves/convert/convert.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/metadata/date_modifier.dart'; +import 'package:aves/services/common/channel.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +abstract class MetadataEditService { + Future<Map<String, dynamic>> rotate(AvesEntry entry, {required bool clockwise}); + + Future<Map<String, dynamic>> flip(AvesEntry entry); + + Future<Map<String, dynamic>> editExifDate(AvesEntry entry, DateModifier modifier); + + Future<Map<String, dynamic>> editMetadata(AvesEntry entry, Map<MetadataType, dynamic> modifier, {bool autoCorrectTrailerOffset = true}); + + Future<Map<String, dynamic>> removeTrailerVideo(AvesEntry entry); + + Future<Map<String, dynamic>> removeTypes(AvesEntry entry, Set<MetadataType> types); +} + +class PlatformMetadataEditService implements MetadataEditService { + static const _platform = AvesMethodChannel('deckers.thibault/aves/metadata_edit'); + + @override + Future<Map<String, dynamic>> rotate(AvesEntry entry, {required bool clockwise}) async { + try { + // returns map with: 'rotationDegrees' 'isFlipped' + final result = await _platform.invokeMethod('rotate', <String, dynamic>{ + 'entry': entry.toPlatformEntryMap(), + 'clockwise': clockwise, + }); + if (result != null) return (result as Map).cast<String, dynamic>(); + } on PlatformException catch (e, stack) { + await _processPlatformException(entry, e, stack); + } + return {}; + } + + @override + Future<Map<String, dynamic>> flip(AvesEntry entry) async { + try { + // returns map with: 'rotationDegrees' 'isFlipped' + final result = await _platform.invokeMethod('flip', <String, dynamic>{ + 'entry': entry.toPlatformEntryMap(), + }); + if (result != null) return (result as Map).cast<String, dynamic>(); + } on PlatformException catch (e, stack) { + await _processPlatformException(entry, e, stack); + } + return {}; + } + + @override + Future<Map<String, dynamic>> editExifDate(AvesEntry entry, DateModifier modifier) async { + try { + final result = await _platform.invokeMethod('editDate', <String, dynamic>{ + 'entry': entry.toPlatformEntryMap(), + 'dateMillis': modifier.setDateTime?.millisecondsSinceEpoch, + 'shiftSeconds': modifier.shiftSeconds, + 'fields': modifier.fields.where((v) => v.type == MetadataType.exif).map((v) => v.toPlatform).nonNulls.toList(), + }); + if (result != null) return (result as Map).cast<String, dynamic>(); + } on PlatformException catch (e, stack) { + await _processPlatformException(entry, e, stack); + } + return {}; + } + + @override + Future<Map<String, dynamic>> editMetadata( + AvesEntry entry, + Map<MetadataType, dynamic> metadata, { + bool autoCorrectTrailerOffset = true, + }) async { + try { + final result = await _platform.invokeMethod('editMetadata', <String, dynamic>{ + 'entry': entry.toPlatformEntryMap(), + 'metadata': metadata.map((type, value) => MapEntry(type.toPlatform, value)), + 'autoCorrectTrailerOffset': autoCorrectTrailerOffset, + }); + if (result != null) return (result as Map).cast<String, dynamic>(); + } on PlatformException catch (e, stack) { + await _processPlatformException(entry, e, stack); + } + return {}; + } + + @override + Future<Map<String, dynamic>> removeTrailerVideo(AvesEntry entry) async { + try { + final result = await _platform.invokeMethod('removeTrailerVideo', <String, dynamic>{ + 'entry': entry.toPlatformEntryMap(), + }); + if (result != null) return (result as Map).cast<String, dynamic>(); + } on PlatformException catch (e, stack) { + await _processPlatformException(entry, e, stack); + } + return {}; + } + + @override + Future<Map<String, dynamic>> removeTypes(AvesEntry entry, Set<MetadataType> types) async { + try { + final result = await _platform.invokeMethod('removeTypes', <String, dynamic>{ + 'entry': entry.toPlatformEntryMap(), + 'types': types.map((v) => v.toPlatform).toList(), + }); + if (result != null) return (result as Map).cast<String, dynamic>(); + } on PlatformException catch (e, stack) { + await _processPlatformException(entry, e, stack); + } + return {}; + } + + Future<void> _processPlatformException(AvesEntry entry, PlatformException e, StackTrace stack) async { + if (entry.isValid) { + final code = e.code; + final customException = CustomPlatformException.fromStandard(e); + if (code.endsWith('mp4largemoov')) { + await mp4LargeMoov(customException); + } else if (code.endsWith('mp4largeother')) { + await mp4LargeOther(customException); + } else if (code.endsWith('filenotfound')) { + await fileNotFound(customException); + } else { + await reportService.recordError(e, stack); + } + } + } + + // distinct exceptions to convince Crashlytics to split reports into distinct issues + // The distinct debug statement is there to make the body unique, so that the methods are not merged at compile time. + + Future<void> mp4LargeMoov(CustomPlatformException e) { + debugPrint('mp4LargeMoov $e'); + return reportService.recordError(e); + } + + Future<void> mp4LargeOther(CustomPlatformException e) { + debugPrint('mp4LargeOther $e'); + return reportService.recordError(e); + } + + Future<void> fileNotFound(CustomPlatformException e) { + debugPrint('fileNotFound $e'); + return reportService.recordError(e); + } +} + +class CustomPlatformException { + final String code; + final String? message; + final dynamic details; + final String? stacktrace; + + CustomPlatformException({ + required this.code, + this.message, + this.details, + this.stacktrace, + }); + + factory CustomPlatformException.fromStandard(PlatformException e) { + return CustomPlatformException( + code: e.code, + message: e.message, + details: e.details, + stacktrace: e.stacktrace, + ); + } + + @override + String toString() => '$runtimeType($code, $message, $details, $stacktrace)'; +} diff --git a/lib/services/metadata/metadata_fetch_service.dart b/lib/services/metadata/metadata_fetch_service.dart new file mode 100644 index 0000000..6fc95b9 --- /dev/null +++ b/lib/services/metadata/metadata_fetch_service.dart @@ -0,0 +1,306 @@ +import 'package:aves/convert/convert.dart'; +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/geotiff.dart'; +import 'package:aves/model/media/panorama.dart'; +import 'package:aves/model/metadata/catalog.dart'; +import 'package:aves/model/metadata/overlay.dart'; +import 'package:aves/model/multipage.dart'; +import 'package:aves/services/common/service_policy.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_model/aves_model.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:aves/services/common/channel.dart'; + +abstract class MetadataFetchService { + // returns Map<Map<Key, Value>> (map of directories, each directory being a map of metadata label and value description) + Future<Map> getAllMetadata(AvesEntry entry); + + Future<CatalogMetadata?> getCatalogMetadata(AvesEntry entry, {bool background = false}); + + Future<OverlayMetadata> getOverlayMetadata(AvesEntry entry, Set<MetadataSyntheticField> fields); + + Future<GeoTiffInfo?> getGeoTiffInfo(AvesEntry entry); + + Future<MultiPageInfo?> getMultiPageInfo(AvesEntry entry); + + Future<PanoramaInfo?> getPanoramaInfo(AvesEntry entry); + + Future<List<Map<String, dynamic>>?> getIptc(AvesEntry entry); + + Future<AvesXmp?> getXmp(AvesEntry entry); + + Future<bool> hasContentResolverProp(String prop); + + Future<String?> getContentResolverProp(AvesEntry entry, String prop); + + Future<DateTime?> getDate(AvesEntry entry, MetadataField field); + + Future<Map<String, dynamic>> getFields(AvesEntry entry, Set<MetadataField> fields); +} + +class PlatformMetadataFetchService implements MetadataFetchService { + static const _platform = AvesMethodChannel('deckers.thibault/aves/metadata_fetch'); + + @override + Future<Map> getAllMetadata(AvesEntry entry) async { + if (entry.isSvg) return {}; + + try { + final result = await _platform.invokeMethod('getAllMetadata', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + }); + if (result != null) return result as Map; + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + return {}; + } + + @override + Future<CatalogMetadata?> getCatalogMetadata(AvesEntry entry, {bool background = false}) async { + if (entry.isSvg) return null; + + Future<CatalogMetadata?> call() async { + try { + // returns map with: + // 'mimeType': MIME type as reported by metadata extractors, not Media Store (string) + // 'dateMillis': date taken in milliseconds since Epoch (long) + // 'isAnimated': animated gif/webp (bool) + // 'isFlipped': flipped according to EXIF orientation (bool) + // 'rating': rating in [-1,5] (int) + // 'rotationDegrees': rotation degrees according to EXIF orientation or other metadata (int) + // 'latitude': latitude (double) + // 'longitude': longitude (double) + // 'xmpSubjects': ';' separated XMP subjects (string) + // 'xmpTitle': XMP title (string) + final result = await _platform.invokeMethod('getCatalogMetadata', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'path': entry.path, + 'sizeBytes': entry.sizeBytes, + }) as Map; + result['id'] = entry.id; + AvesEntry.normalizeMimeTypeFields(result); + return CatalogMetadata.fromMap(result); + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + return null; + } + + return background + ? servicePolicy.call( + call, + priority: ServiceCallPriority.getMetadata, + ) + : call(); + } + + @override + Future<OverlayMetadata> getOverlayMetadata(AvesEntry entry, Set<MetadataSyntheticField> fields) async { + if (fields.isNotEmpty && !entry.isSvg) { + try { + // returns fields on demand, with various value types: + // 'aperture' (double), + // 'description' (string) + // 'exposureTime' (string), + // 'focalLength' (double), + // 'iso' (int), + final result = await _platform.invokeMethod('getOverlayMetadata', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + 'fields': fields.map((v) => v.toPlatform).toList(), + }) as Map; + return OverlayMetadata.fromMap(result); + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + } + return const OverlayMetadata(); + } + + @override + Future<GeoTiffInfo?> getGeoTiffInfo(AvesEntry entry) async { + try { + final result = await _platform.invokeMethod('getGeoTiffInfo', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + }) as Map; + return GeoTiffInfo.fromMap(result); + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + return null; + } + + @override + Future<MultiPageInfo?> getMultiPageInfo(AvesEntry entry) async { + try { + final result = await _platform.invokeMethod('getMultiPageInfo', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + 'isMotionPhoto': entry.isMotionPhoto, + }); + final pageMaps = ((result as List?) ?? []).cast<Map>(); + if (entry.isMotionPhoto && pageMaps.isNotEmpty) { + final imagePage = pageMaps[0]; + imagePage['width'] = entry.width; + imagePage['height'] = entry.height; + imagePage['rotationDegrees'] = entry.rotationDegrees; + } + pageMaps.forEach(AvesEntry.normalizeMimeTypeFields); + return MultiPageInfo.fromPageMaps(entry, pageMaps); + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + return null; + } + + @override + Future<PanoramaInfo?> getPanoramaInfo(AvesEntry entry) async { + try { + // returns map with values for: + // 'croppedAreaLeft' (int), 'croppedAreaTop' (int), 'croppedAreaWidth' (int), 'croppedAreaHeight' (int), + // 'fullPanoWidth' (int), 'fullPanoHeight' (int) + final result = await _platform.invokeMethod('getPanoramaInfo', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + }) as Map; + return PanoramaInfo.fromMap(result); + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + return null; + } + + @override + Future<List<Map<String, dynamic>>?> getIptc(AvesEntry entry) async { + try { + final result = await _platform.invokeMethod('getIptc', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + }); + if (result != null) return (result as List).cast<Map>().map((fields) => fields.cast<String, dynamic>()).toList(); + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + return null; + } + + @override + Future<AvesXmp?> getXmp(AvesEntry entry) async { + try { + final result = await _platform.invokeMethod('getXmp', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + }); + if (result != null) return AvesXmp.fromList((result as List).cast<String>()); + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + return null; + } + + final Map<String, bool> _contentResolverProps = {}; + + @override + Future<bool> hasContentResolverProp(String prop) async { + var exists = _contentResolverProps[prop]; + if (exists != null) return SynchronousFuture(exists); + + try { + exists = await _platform.invokeMethod('hasContentResolverProp', <String, dynamic>{ + 'prop': prop, + }); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + exists ??= false; + _contentResolverProps[prop] = exists; + return exists; + } + + @override + Future<String?> getContentResolverProp(AvesEntry entry, String prop) async { + try { + return await _platform.invokeMethod('getContentResolverProp', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'prop': prop, + }); + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + return null; + } + + @override + Future<DateTime?> getDate(AvesEntry entry, MetadataField field) async { + try { + final result = await _platform.invokeMethod('getDate', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + 'field': field.toPlatform, + }); + if (result is int) { + return dateTimeFromMillis(result, isUtc: false); + } + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + return null; + } + + @override + Future<Map<String, dynamic>> getFields(AvesEntry entry, Set<MetadataField> fields) async { + if (fields.isNotEmpty && !entry.isSvg) { + try { + final result = await _platform.invokeMethod('getFields', <String, dynamic>{ + 'mimeType': entry.mimeType, + 'uri': entry.uri, + 'sizeBytes': entry.sizeBytes, + 'fields': fields.map((v) => v.toPlatform).toList(), + }); + if (result != null) return (result as Map).cast<String, dynamic>(); + } on PlatformException catch (e, stack) { + if (entry.isValid) { + await reportService.recordError(e, stack); + } + } + } + return {}; + } +} diff --git a/lib/services/metadata/svg_metadata_service.dart b/lib/services/metadata/svg_metadata_service.dart new file mode 100644 index 0000000..4160f1b --- /dev/null +++ b/lib/services/metadata/svg_metadata_service.dart @@ -0,0 +1,92 @@ +import 'dart:convert'; +import 'dart:ui'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/utils/string_utils.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:xml/xml.dart'; + +class SvgMetadataService { + static const docDirectory = 'Document'; + static const metadataDirectory = 'Metadata'; + + static const _attributes = ['x', 'y', 'width', 'height', 'preserveAspectRatio', 'viewBox']; + static const _textElements = ['title', 'desc']; + static const _metadataElement = 'metadata'; + + static Future<Size?> getSize(AvesEntry entry) async { + try { + final data = await mediaFetchService.getOriginalBytes(entry); + final document = XmlDocument.parse(utf8.decode(data)); + final root = document.rootElement; + + String? getAttribute(String attributeName) => root.attributes.firstWhereOrNull((a) => a.name.qualified == attributeName)?.value; + double? tryParseWithoutUnit(String? s) => s == null ? null : double.tryParse(s.replaceAll(RegExp(r'[a-z%]'), '')); + + // prefer the viewbox over the viewport to determine size + + // viewbox + final viewBox = getAttribute('viewBox'); + if (viewBox != null) { + final parts = viewBox.split(RegExp(r'[\s,]+')); + if (parts.length == 4) { + final vbWidth = tryParseWithoutUnit(parts[2]); + final vbHeight = tryParseWithoutUnit(parts[3]); + if (vbWidth != null && vbWidth > 0 && vbHeight != null && vbHeight > 0) { + return Size(vbWidth, vbHeight); + } + } + } + + // viewport + final width = tryParseWithoutUnit(getAttribute('width')); + final height = tryParseWithoutUnit(getAttribute('height')); + if (width != null && height != null) { + return Size(width, height); + } + } catch (error, stack) { + debugPrint('failed to parse XML from SVG with error=$error\n$stack'); + } + return null; + } + + static Future<Map<String, Map<String, String>>> getAllMetadata(AvesEntry entry) async { + String formatKey(String key) { + switch (key) { + case 'desc': + return 'Description'; + default: + return key.toSentenceCase(); + } + } + + try { + final data = await mediaFetchService.getOriginalBytes(entry); + final document = XmlDocument.parse(utf8.decode(data)); + final root = document.rootElement; + + final docDir = Map.fromEntries([ + ...root.attributes.where((a) => _attributes.contains(a.name.qualified)).map((a) => MapEntry(formatKey(a.name.qualified), a.value)), + ..._textElements.map((name) { + final value = root.getElement(name)?.innerText; + return value != null ? MapEntry(formatKey(name), value) : null; + }).nonNulls, + ]); + + final metadata = root.getElement(_metadataElement); + final metadataDir = Map.fromEntries([ + if (metadata != null) MapEntry('Metadata', metadata.toXmlString(pretty: true)), + ]); + + return { + if (docDir.isNotEmpty) docDirectory: docDir, + if (metadataDir.isNotEmpty) metadataDirectory: metadataDir, + }; + } catch (error, stack) { + debugPrint('failed to parse XML from SVG with error=$error\n$stack'); + } + return {}; + } +} diff --git a/lib/services/metadata/xmp.dart b/lib/services/metadata/xmp.dart new file mode 100644 index 0000000..e56adec --- /dev/null +++ b/lib/services/metadata/xmp.dart @@ -0,0 +1,40 @@ +import 'package:collection/collection.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; + +@immutable +class AvesXmp extends Equatable { + final String? xmpString; + final String? extendedXmpString; + + @override + List<Object?> get props => [xmpString, extendedXmpString]; + + const AvesXmp({ + required this.xmpString, + this.extendedXmpString, + }); + + static AvesXmp fromList(List<String> xmpStrings) { + switch (xmpStrings.length) { + case 0: + return const AvesXmp(xmpString: null); + case 1: + return AvesXmp(xmpString: xmpStrings.single); + default: + final byExtending = groupBy<String, bool>(xmpStrings, (v) => v.contains(':HasExtendedXMP=')); + final extending = byExtending[true] ?? []; + final extension = byExtending[false] ?? []; + if (extending.length == 1 && extension.length == 1) { + return AvesXmp( + xmpString: extending.single, + extendedXmpString: extension.single, + ); + } + + // take the first XMP and ignore the rest when the file is weirdly constructed + debugPrint('warning: entry has ${xmpStrings.length} XMP directories, xmpStrings=$xmpStrings'); + return AvesXmp(xmpString: xmpStrings.firstOrNull); + } + } +} diff --git a/lib/services/security_service.dart b/lib/services/security_service.dart new file mode 100644 index 0000000..5cc1d65 --- /dev/null +++ b/lib/services/security_service.dart @@ -0,0 +1,40 @@ +import 'package:aves/services/common/services.dart'; +import 'package:flutter/services.dart'; +import 'package:aves/services/common/channel.dart'; + +abstract class SecurityService { + Future<bool> writeValue<T>(String key, T? value); + + Future<T?> readValue<T>(String key); +} + +class PlatformSecurityService implements SecurityService { + static const _platform = AvesMethodChannel('deckers.thibault/aves/security'); + + @override + Future<bool> writeValue<T>(String key, T? value) async { + try { + await _platform.invokeMethod('writeValue', <String, dynamic>{ + 'key': key, + 'value': value, + }); + return true; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + @override + Future<T?> readValue<T>(String key) async { + try { + final result = await _platform.invokeMethod('readValue', <String, dynamic>{ + 'key': key, + }); + if (result != null) return result as T; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return null; + } +} diff --git a/lib/services/storage_service.dart b/lib/services/storage_service.dart new file mode 100644 index 0000000..80bc211 --- /dev/null +++ b/lib/services/storage_service.dart @@ -0,0 +1,400 @@ +import 'dart:async'; + +import 'package:aves/model/covers.dart'; +import 'package:aves/services/common/channel.dart'; +import 'package:aves/services/common/output_buffer.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/services.dart'; + +abstract class StorageService { + Future<Map<String, int>> getDataUsage(); + + Future<Set<StorageVolume>> getStorageVolumes(); + + Future<String> getExternalCacheDirectory(); + + Future<Set<String>> getUntrackedTrashPaths(Iterable<String> knownPaths); + + Future<Set<String>> getUntrackedVaultPaths(String vaultName, Iterable<String> knownPaths); + + Future<String> getVaultRoot(); + + Future<int?> getFreeSpace(StorageVolume volume); + + Future<List<String>> getGrantedDirectories(); + + Future<Set<VolumeRelativeDirectory>> getInaccessibleDirectories(Iterable<String> dirPaths); + + // returns directories with restricted access, + // with the relative part in lowercase, for case-insensitive comparison + Future<Set<VolumeRelativeDirectory>> getRestrictedDirectoriesLowerCase(); + + Future<void> revokeDirectoryAccess(String path); + + // returns number of deleted directories + Future<int> deleteEmptyRegularDirectories(Set<String> dirPaths); + + Future<bool> deleteTempDirectory(); + + Future<bool> deleteExternalCache(); + + // returns whether user granted access to a directory of his choosing + Future<bool> requestDirectoryAccess(String path); + + Future<bool> canRequestMediaFileBulkAccess(); + + Future<bool> canInsertMedia(Set<VolumeRelativeDirectory> directories); + + // returns whether user granted access to URIs + Future<bool> requestMediaFileAccess(List<String> uris, List<String> mimeTypes); + + // returns whether operation succeeded (`null` if user cancelled) + Future<bool?> createFile(String name, String mimeType, Uint8List bytes); + + Future<Uint8List> openFile([String? mimeType]); + + // returns whether operation succeeded (`null` if user cancelled) + Future<bool?> copyFile(String name, String mimeType, String sourceUri); +} + +class PlatformStorageService implements StorageService { + static const _platform = AvesMethodChannel('deckers.thibault/aves/storage'); + static final _stream = AvesStreamsChannel('deckers.thibault/aves/activity_result_stream'); + + @override + Future<Map<String, int>> getDataUsage() async { + try { + final result = await _platform.invokeMethod('getDataUsage'); + if (result != null) return (result as Map).cast<String, int>(); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + @override + Future<Set<StorageVolume>> getStorageVolumes() async { + try { + final result = await _platform.invokeMethod('getStorageVolumes'); + return (result as List).cast<Map>().map(StorageVolume.fromMap).toSet(); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + @override + Future<String> getExternalCacheDirectory() async { + try { + final result = await _platform.invokeMethod('getCacheDirectory', <String, dynamic>{ + 'external': true, + }); + return result as String; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return ''; + } + + @override + Future<Set<String>> getUntrackedTrashPaths(Iterable<String> knownPaths) async { + try { + final result = await _platform.invokeMethod('getUntrackedTrashPaths', <String, dynamic>{ + 'knownPaths': knownPaths.toList(), + }); + return (result as List).cast<String>().toSet(); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + @override + Future<Set<String>> getUntrackedVaultPaths(String vaultName, Iterable<String> knownPaths) async { + try { + final result = await _platform.invokeMethod('getUntrackedVaultPaths', <String, dynamic>{ + 'vault': vaultName, + 'knownPaths': knownPaths.toList(), + }); + return (result as List).cast<String>().toSet(); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + @override + Future<String> getVaultRoot() async { + try { + final result = await _platform.invokeMethod('getVaultRoot'); + return result as String; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return ''; + } + + @override + Future<int?> getFreeSpace(StorageVolume volume) async { + try { + final result = await _platform.invokeMethod('getFreeSpace', <String, dynamic>{ + 'path': volume.path, + }); + return result as int?; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return null; + } + + @override + Future<List<String>> getGrantedDirectories() async { + try { + final result = await _platform.invokeMethod('getGrantedDirectories'); + return (result as List).cast<String>(); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return []; + } + + @override + Future<Set<VolumeRelativeDirectory>> getInaccessibleDirectories(Iterable<String> dirPaths) async { + try { + final result = await _platform.invokeMethod('getInaccessibleDirectories', <String, dynamic>{ + 'dirPaths': dirPaths.toList(), + }); + if (result != null) { + return (result as List).cast<Map>().map(VolumeRelativeDirectory.fromMap).toSet(); + } + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + @override + Future<Set<VolumeRelativeDirectory>> getRestrictedDirectoriesLowerCase() async { + try { + final result = await _platform.invokeMethod('getRestrictedDirectories'); + if (result != null) { + return (result as List) + .cast<Map>() + .map(VolumeRelativeDirectory.fromMap) + .map((dir) => dir.copyWith( + relativeDir: dir.relativeDir.toLowerCase(), + )) + .toSet(); + } + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return {}; + } + + @override + Future<void> revokeDirectoryAccess(String path) async { + try { + await _platform.invokeMethod('revokeDirectoryAccess', <String, dynamic>{ + 'path': path, + }); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } + + // returns number of deleted directories + @override + Future<int> deleteEmptyRegularDirectories(Set<String> dirPaths) async { + try { + final result = await _platform.invokeMethod('deleteEmptyDirectories', <String, dynamic>{ + 'dirPaths': dirPaths.where((v) => covers.effectiveAlbumType(v) == AlbumType.regular).toList(), + }); + if (result != null) return result as int; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return 0; + } + + @override + Future<bool> deleteTempDirectory() async { + try { + final result = await _platform.invokeMethod('deleteTempDirectory'); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + @override + Future<bool> deleteExternalCache() async { + try { + final result = await _platform.invokeMethod('deleteExternalCache'); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + @override + Future<bool> canRequestMediaFileBulkAccess() async { + try { + final result = await _platform.invokeMethod('canRequestMediaFileBulkAccess'); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + @override + Future<bool> canInsertMedia(Set<VolumeRelativeDirectory> directories) async { + try { + final result = await _platform.invokeMethod('canInsertMedia', <String, dynamic>{ + 'directories': directories.map((v) => v.toMap()).toList(), + }); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + // returns whether user granted access to a directory of his choosing + @override + Future<bool> requestDirectoryAccess(String path) async { + try { + final opCompleter = Completer<bool>(); + _stream.receiveBroadcastStream(<String, dynamic>{ + 'op': 'requestDirectoryAccess', + 'path': path, + }).listen( + (data) => opCompleter.complete(data as bool), + onError: opCompleter.completeError, + onDone: () { + if (!opCompleter.isCompleted) opCompleter.complete(false); + }, + cancelOnError: true, + ); + // `await` here, so that `completeError` will be caught below + return await opCompleter.future; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + // returns whether user granted access to URIs + @override + Future<bool> requestMediaFileAccess(List<String> uris, List<String> mimeTypes) async { + try { + final opCompleter = Completer<bool>(); + _stream.receiveBroadcastStream(<String, dynamic>{ + 'op': 'requestMediaFileAccess', + 'uris': uris, + 'mimeTypes': mimeTypes, + }).listen( + (data) => opCompleter.complete(data as bool), + onError: opCompleter.completeError, + onDone: () { + if (!opCompleter.isCompleted) opCompleter.complete(false); + }, + cancelOnError: true, + ); + // `await` here, so that `completeError` will be caught below + return await opCompleter.future; + } on PlatformException catch (e, stack) { + final message = e.message; + // mute issue in the specific case when an item: + // 1) is a Media Store `file` content, + // 2) has no `images` or `video` entry, + // 3) is in a restricted directory + if (message == null || !message.contains('/external/file/')) { + await reportService.recordError(e, stack); + } + } + return false; + } + + @override + Future<bool?> createFile(String name, String mimeType, Uint8List bytes) async { + try { + final opCompleter = Completer<bool?>(); + _stream.receiveBroadcastStream(<String, dynamic>{ + 'op': 'createFile', + 'name': name, + 'mimeType': mimeType, + 'bytes': bytes, + }).listen( + (data) => opCompleter.complete(data as bool?), + onError: opCompleter.completeError, + onDone: () { + if (!opCompleter.isCompleted) opCompleter.complete(false); + }, + cancelOnError: true, + ); + // `await` here, so that `completeError` will be caught below + return await opCompleter.future; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + @override + Future<Uint8List> openFile([String? mimeType]) async { + try { + final opCompleter = Completer<Uint8List>(); + final sink = OutputBuffer(); + _stream.receiveBroadcastStream(<String, dynamic>{ + 'op': 'openFile', + 'mimeType': mimeType, + }).listen( + (data) { + final chunk = data as Uint8List; + sink.add(chunk); + }, + onError: opCompleter.completeError, + onDone: () { + sink.close(); + opCompleter.complete(sink.bytes); + }, + cancelOnError: true, + ); + // `await` here, so that `completeError` will be caught below + return await opCompleter.future; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return Uint8List(0); + } + + @override + Future<bool?> copyFile(String name, String mimeType, String sourceUri) async { + try { + final opCompleter = Completer<bool?>(); + _stream.receiveBroadcastStream(<String, dynamic>{ + 'op': 'copyFile', + 'name': name, + 'mimeType': mimeType, + 'sourceUri': sourceUri, + }).listen( + (data) => opCompleter.complete(data as bool?), + onError: opCompleter.completeError, + onDone: () { + if (!opCompleter.isCompleted) opCompleter.complete(false); + }, + cancelOnError: true, + ); + // `await` here, so that `completeError` will be caught below + return await opCompleter.future; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } +} diff --git a/lib/services/wallpaper_service.dart b/lib/services/wallpaper_service.dart new file mode 100644 index 0000000..b753640 --- /dev/null +++ b/lib/services/wallpaper_service.dart @@ -0,0 +1,22 @@ +import 'package:aves/services/common/services.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/services.dart'; +import 'package:aves/services/common/channel.dart'; + +class WallpaperService { + static const _platform = AvesMethodChannel('deckers.thibault/aves/wallpaper'); + + static Future<bool> set(Uint8List bytes, WallpaperTarget target) async { + try { + await _platform.invokeMethod('setWallpaper', <String, dynamic>{ + 'bytes': bytes, + 'home': {WallpaperTarget.home, WallpaperTarget.homeLock}.contains(target), + 'lock': {WallpaperTarget.lock, WallpaperTarget.homeLock}.contains(target), + }); + return true; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } +} diff --git a/lib/services/widget_service.dart b/lib/services/widget_service.dart new file mode 100644 index 0000000..21d1181 --- /dev/null +++ b/lib/services/widget_service.dart @@ -0,0 +1,30 @@ +import 'package:aves/services/common/channel.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:flutter/services.dart'; + +class WidgetService { + static const _configureChannel = AvesMethodChannel('deckers.thibault/aves/widget_configure'); + static const _updateChannel = AvesMethodChannel('deckers.thibault/aves/widget_update'); + + static Future<bool> configure() async { + try { + await _configureChannel.invokeMethod('configure'); + return true; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + static Future<bool> update(int widgetId) async { + try { + await _updateChannel.invokeMethod('update', <String, dynamic>{ + 'widgetId': widgetId, + }); + return true; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } +} diff --git a/lib/services/window_service.dart b/lib/services/window_service.dart new file mode 100644 index 0000000..5559fc7 --- /dev/null +++ b/lib/services/window_service.dart @@ -0,0 +1,246 @@ +import 'package:aves/services/common/services.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:aves/services/common/channel.dart'; + +abstract class WindowService { + Future<bool> isActivity(); + + Future<void> keepScreenOn(bool on); + + Future<void> secureScreen(bool on); + + Future<bool> isInMultiWindowMode(); + + Future<bool> isInPictureInPictureMode(); + + Future<bool> isRotationLocked(); + + Future<int> getOrientation(); + + Future<void> requestOrientation([Orientation? orientation]); + + Future<bool> isCutoutAware(); + + Future<EdgeInsets> getCutoutInsets(); + + Future<bool> supportsWideGamut(); + + Future<bool> supportsHdr(); + + Future<void> setColorMode({required bool wideColorGamut, required bool hdr}); + + Future<bool> startGlobalDrag(String uri, String? label, Size shadowSize, Uint8List shadowBytes); +} + +class PlatformWindowService implements WindowService { + static const _platform = AvesMethodChannel('deckers.thibault/aves/window'); + + bool? _isCutoutAware, _supportsHdr, _supportsWideGamut; + + @override + Future<bool> isActivity() async { + try { + final result = await _platform.invokeMethod('isActivity'); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + @override + Future<void> keepScreenOn(bool on) async { + try { + await _platform.invokeMethod('keepScreenOn', <String, dynamic>{ + 'on': on, + }); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } + + @override + Future<void> secureScreen(bool on) async { + try { + await _platform.invokeMethod('secureScreen', <String, dynamic>{ + 'on': on, + }); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } + + @override + Future<bool> isInMultiWindowMode() async { + try { + final result = await _platform.invokeMethod('isInMultiWindowMode'); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + @override + Future<bool> isInPictureInPictureMode() async { + try { + final result = await _platform.invokeMethod('isInPictureInPictureMode'); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + @override + Future<bool> isRotationLocked() async { + try { + final result = await _platform.invokeMethod('isRotationLocked'); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } + + @override + Future<int> getOrientation() async { + try { + final result = await _platform.invokeMethod('getOrientation'); + if (result != null) return result as int; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return 0; + } + + // cf https://developer.android.com/reference/android/R.attr#screenOrientation + // cf Android `ActivityInfo.ScreenOrientation` + static const screenOrientationUnspecified = -1; // SCREEN_ORIENTATION_UNSPECIFIED + static const screenOrientationLandscape = 0; // SCREEN_ORIENTATION_LANDSCAPE + static const screenOrientationPortrait = 1; // SCREEN_ORIENTATION_PORTRAIT + static const screenOrientationSensorLandscape = 6; // SCREEN_ORIENTATION_SENSOR_LANDSCAPE + static const screenOrientationSensorPortrait = 7; // SCREEN_ORIENTATION_SENSOR_PORTRAIT + static const screenOrientationReverseLandscape = 8; // SCREEN_ORIENTATION_REVERSE_LANDSCAPE + static const screenOrientationReversePortrait = 9; // SCREEN_ORIENTATION_REVERSE_PORTRAIT + static const screenOrientationUserLandscape = 11; // SCREEN_ORIENTATION_USER_LANDSCAPE + static const screenOrientationUserPortrait = 12; // SCREEN_ORIENTATION_USER_PORTRAIT + + @override + Future<void> requestOrientation([Orientation? orientation]) async { + Future<void> apply(int orientationCode) async { + try { + await _platform.invokeMethod('requestOrientation', <String, dynamic>{ + 'orientation': orientationCode, + }); + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } + + switch (orientation) { + case Orientation.landscape: + // first use the `sensor` variant to flip according to the sensor, + // then switch to a specific landscape orientation + // so that it no longer listens to the sensor + await apply(screenOrientationSensorLandscape); + switch (await getOrientation()) { + case 270: + await apply(screenOrientationReverseLandscape); + case 90: + default: + await apply(screenOrientationLandscape); + } + case Orientation.portrait: + await apply(screenOrientationUserPortrait); + default: + await apply(screenOrientationUnspecified); + } + } + + @override + Future<bool> isCutoutAware() async { + if (_isCutoutAware != null) return SynchronousFuture(_isCutoutAware!); + try { + final result = await _platform.invokeMethod('isCutoutAware'); + _isCutoutAware = result as bool?; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return _isCutoutAware ?? false; + } + + @override + Future<EdgeInsets> getCutoutInsets() async { + try { + final result = await _platform.invokeMethod('getCutoutInsets'); + if (result != null) { + return EdgeInsets.only( + left: result['left']?.toDouble() ?? 0, + top: result['top']?.toDouble() ?? 0, + right: result['right']?.toDouble() ?? 0, + bottom: result['bottom']?.toDouble() ?? 0, + ); + } + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return EdgeInsets.zero; + } + + @override + Future<bool> supportsWideGamut() async { + if (_supportsWideGamut != null) return SynchronousFuture(_supportsWideGamut!); + try { + final result = await _platform.invokeMethod('supportsWideGamut'); + _supportsWideGamut = result as bool?; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return _supportsWideGamut ?? false; + } + + @override + Future<bool> supportsHdr() async { + if (_supportsHdr != null) return SynchronousFuture(_supportsHdr!); + try { + final result = await _platform.invokeMethod('supportsHdr'); + _supportsHdr = result as bool?; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return _supportsHdr ?? false; + } + + @override + Future<void> setColorMode({required bool wideColorGamut, required bool hdr}) async { + // TODO TLAD [hdr] enable when ready + // try { + // await _platform.invokeMethod('setColorMode', <String, dynamic>{ + // 'wideColorGamut': wideColorGamut, + // 'hdr': hdr, + // }); + // } on PlatformException catch (e, stack) { + // await reportService.recordError(e, stack); + // } + } + + @override + Future<bool> startGlobalDrag(String uri, String? label, Size shadowSize, Uint8List shadowBytes) async { + try { + final result = await _platform.invokeMethod('startGlobalDrag', <String, dynamic>{ + 'uri': uri, + 'label': label, + 'shadowWidthDip': shadowSize.width, + 'shadowHeightDip': shadowSize.height, + 'shadowBytes': shadowBytes, + }); + if (result != null) return result as bool; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + return false; + } +} |
