diff options
Diffstat (limited to 'lib/services/common')
| -rw-r--r-- | lib/services/common/channel.dart | 29 | ||||
| -rw-r--r-- | lib/services/common/decoding.dart | 55 | ||||
| -rw-r--r-- | lib/services/common/image_op_events.dart | 86 | ||||
| -rw-r--r-- | lib/services/common/output_buffer.dart | 36 | ||||
| -rw-r--r-- | lib/services/common/service_policy.dart | 135 | ||||
| -rw-r--r-- | lib/services/common/services.dart | 77 |
6 files changed, 418 insertions, 0 deletions
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); +} |
