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 /plugins | |
| download | aves-src-master.tar.gz aves-src-master.zip | |
Diffstat (limited to 'plugins')
151 files changed, 7228 insertions, 0 deletions
diff --git a/plugins/aves_magnifier/.gitignore b/plugins/aves_magnifier/.gitignore new file mode 100644 index 0000000..79c113f --- /dev/null +++ b/plugins/aves_magnifier/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/plugins/aves_magnifier/.metadata b/plugins/aves_magnifier/.metadata new file mode 100644 index 0000000..b13014b --- /dev/null +++ b/plugins/aves_magnifier/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: 098aac7ffeef2a1846eb3a7f14788520c8400a14 + channel: master + +project_type: package diff --git a/plugins/aves_magnifier/analysis_options.yaml b/plugins/aves_magnifier/analysis_options.yaml new file mode 100644 index 0000000..f04c6cf --- /dev/null +++ b/plugins/aves_magnifier/analysis_options.yaml @@ -0,0 +1 @@ +include: ../../analysis_options.yaml diff --git a/plugins/aves_magnifier/lib/aves_magnifier.dart b/plugins/aves_magnifier/lib/aves_magnifier.dart new file mode 100644 index 0000000..80a5d71 --- /dev/null +++ b/plugins/aves_magnifier/lib/aves_magnifier.dart @@ -0,0 +1,9 @@ +export 'src/controller/controller.dart'; +export 'src/controller/state.dart'; +export 'src/core/core.dart'; +export 'src/core/scale_gesture_recognizer.dart'; +export 'src/pan/gesture_detector_scope.dart'; +export 'src/pan/scroll_physics.dart'; +export 'src/scale/scale_boundaries.dart'; +export 'src/scale/scale_level.dart'; +export 'src/scale/state.dart'; diff --git a/plugins/aves_magnifier/lib/src/controller/controller.dart b/plugins/aves_magnifier/lib/src/controller/controller.dart new file mode 100644 index 0000000..d2d3695 --- /dev/null +++ b/plugins/aves_magnifier/lib/src/controller/controller.dart @@ -0,0 +1,144 @@ +import 'dart:async'; + +import 'package:aves_magnifier/src/controller/state.dart'; +import 'package:aves_magnifier/src/scale/scale_boundaries.dart'; +import 'package:aves_magnifier/src/scale/scale_level.dart'; +import 'package:aves_magnifier/src/scale/state.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:leak_tracker/leak_tracker.dart'; + +class AvesMagnifierController { + final StreamController<MagnifierState> _stateStreamController = StreamController.broadcast(); + final StreamController<ScaleBoundaries> _scaleBoundariesStreamController = StreamController.broadcast(); + final StreamController<ScaleStateChange> _scaleStateChangeStreamController = StreamController.broadcast(); + + bool _disposed = false; + late MagnifierState _currentState, initial, previousState; + ScaleBoundaries? _scaleBoundaries; + late ScaleStateChange _currentScaleState, previousScaleState; + + AvesMagnifierController({ + MagnifierState? initialState, + }) : super() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$AvesMagnifierController', + object: this, + ); + } + const source = ChangeSource.internal; + initial = initialState ?? const MagnifierState(position: Offset.zero, scale: null, source: source); + previousState = initial; + _currentState = initial; + reset(); + + const _initialScaleState = ScaleStateChange(state: ScaleState.initial, source: source); + previousScaleState = _initialScaleState; + _currentScaleState = _initialScaleState; + _setScaleState(_initialScaleState); + } + + void dispose() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + _disposed = true; + _stateStreamController.close(); + _scaleBoundariesStreamController.close(); + _scaleStateChangeStreamController.close(); + } + + Stream<MagnifierState> get stateStream => _stateStreamController.stream; + + Stream<ScaleBoundaries> get scaleBoundariesStream => _scaleBoundariesStreamController.stream; + + Stream<ScaleStateChange> get scaleStateChangeStream => _scaleStateChangeStreamController.stream; + + MagnifierState get currentState => _currentState; + + Offset get position => currentState.position; + + double? get scale => currentState.scale; + + ScaleBoundaries? get scaleBoundaries => _scaleBoundaries; + + ScaleStateChange get scaleState => _currentScaleState; + + bool get hasScaleSateChanged => previousScaleState != scaleState; + + bool get isZooming => scaleState.state == ScaleState.zoomedIn || scaleState.state == ScaleState.zoomedOut; + + void reset() => _setState(initial); + + void update({ + Offset? position, + double? scale, + required ChangeSource source, + }) { + position = position ?? this.position; + scale = scale ?? this.scale; + if (this.position == position && this.scale == scale) return; + assert((scale ?? 0) >= 0); + + previousState = currentState; + _setState(MagnifierState( + position: position, + scale: scale, + source: source, + )); + } + + void setScaleState(ScaleState newValue, ChangeSource source, {Offset? childFocalPoint}) { + if (_disposed || _currentScaleState.state == newValue) return; + + previousScaleState = _currentScaleState; + _currentScaleState = ScaleStateChange(state: newValue, source: source, childFocalPoint: childFocalPoint); + _scaleStateChangeStreamController.add(scaleState); + } + + void _setState(MagnifierState state) { + if (_disposed || _currentState == state) return; + + _currentState = state; + _stateStreamController.add(state); + } + + void setScaleBoundaries(ScaleBoundaries scaleBoundaries) { + if (_disposed || _scaleBoundaries == scaleBoundaries) return; + + _scaleBoundaries = scaleBoundaries; + _scaleBoundariesStreamController.add(scaleBoundaries); + + if (!isZooming) { + update( + scale: getScaleForScaleState(_currentScaleState.state), + source: ChangeSource.internal, + ); + } + } + + void _setScaleState(ScaleStateChange scaleState) { + if (_disposed || _currentScaleState == scaleState) return; + + _currentScaleState = scaleState; + _scaleStateChangeStreamController.add(_currentScaleState); + } + + double? getScaleForScaleState(ScaleState scaleState) { + final boundaries = scaleBoundaries; + if (boundaries == null) return null; + + switch (scaleState) { + case ScaleState.initial: + case ScaleState.zoomedIn: + case ScaleState.zoomedOut: + return boundaries.clampScale(boundaries.initialScale); + case ScaleState.covering: + return boundaries.clampScale(ScaleLevel.scaleForCovering(boundaries.viewportSize, boundaries.contentSize)); + case ScaleState.originalSize: + return boundaries.clampScale(boundaries.originalScale); + } + } +} diff --git a/plugins/aves_magnifier/lib/src/controller/controller_delegate.dart b/plugins/aves_magnifier/lib/src/controller/controller_delegate.dart new file mode 100644 index 0000000..57e1b98 --- /dev/null +++ b/plugins/aves_magnifier/lib/src/controller/controller_delegate.dart @@ -0,0 +1,130 @@ +import 'dart:async'; + +import 'package:aves_magnifier/src/controller/controller.dart'; +import 'package:aves_magnifier/src/controller/state.dart'; +import 'package:aves_magnifier/src/core/core.dart'; +import 'package:aves_magnifier/src/scale/scale_boundaries.dart'; +import 'package:aves_magnifier/src/scale/state.dart'; +import 'package:flutter/widgets.dart'; + +/// A class to hold internal layout logic to sync both controller states +/// +/// It reacts to layout changes (eg: enter landscape or widget resize) and syncs the two controllers. +mixin AvesMagnifierControllerDelegate on State<AvesMagnifier> { + AvesMagnifierController get controller => widget.controller; + + ScaleBoundaries? get scaleBoundaries => controller.scaleBoundaries; + + ScaleStateCycle get scaleStateCycle => widget.scaleStateCycle; + + Alignment get basePosition => ScaleBoundaries.basePosition; + + Function(double? prevScale, double? nextScale, Offset nextPosition)? _animateScale; + + final List<StreamSubscription> _subscriptions = []; + + void registerDelegate(AvesMagnifier widget) { + _subscriptions.add(widget.controller.stateStream.listen(_onMagnifierStateChanged)); + _subscriptions.add(widget.controller.scaleStateChangeStream.listen(_onScaleStateChanged)); + // _subscriptions.add(widget.controller.scaleBoundariesStream.listen(_onScaleBoundariesChanged)); + } + + void unregisterDelegate(AvesMagnifier oldWidget) { + _animateScale = null; + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + // TODO TLAD should not reset scale when boundaries change because of transform + // void _onScaleBoundariesChanged(ScaleBoundaries boundaries) { + // initScale(); + // } + + void _onScaleStateChanged(ScaleStateChange scaleStateChange) { + if (scaleStateChange.source == ChangeSource.internal) return; + if (!controller.hasScaleSateChanged) return; + + if (_animateScale == null || controller.isZooming) { + controller.update(scale: controller.scale, source: scaleStateChange.source); + return; + } + + final nextScaleState = scaleStateChange.state; + final nextScale = controller.getScaleForScaleState(nextScaleState); + var nextPosition = Offset.zero; + if (nextScaleState == ScaleState.covering || nextScaleState == ScaleState.originalSize) { + final childFocalPoint = scaleStateChange.childFocalPoint; + final boundaries = scaleBoundaries; + if (childFocalPoint != null && boundaries != null) { + nextPosition = boundaries.contentToStatePosition(nextScale!, childFocalPoint); + } + } + + final prevScale = controller.scale ?? controller.getScaleForScaleState(controller.previousScaleState.state); + _animateScale!(prevScale, nextScale, nextPosition); + } + + void setScaleStateUpdateAnimation(void Function(double? prevScale, double? nextScale, Offset nextPosition) animateScale) { + _animateScale = animateScale; + } + + void _onMagnifierStateChanged(MagnifierState state) { + final boundaries = scaleBoundaries; + final currentScale = controller.scale; + if (boundaries == null || currentScale == null) return; + + controller.update(position: boundaries.clampPosition(position: position, scale: currentScale), source: state.source); + final newScale = controller.scale; + if (newScale == null || newScale == currentScale) return; + + if (state.source == ChangeSource.internal || state.source == ChangeSource.animation) return; + final newScaleState = (newScale > boundaries.initialScale) ? ScaleState.zoomedIn : ScaleState.zoomedOut; + controller.setScaleState(newScaleState, state.source); + } + + Offset get position => controller.position; + + void initScale() { + final scaleState = controller.scaleState.state; + final newScale = controller.getScaleForScaleState(scaleState); + setScale(newScale, ChangeSource.internal); + } + + void setScale(double? scale, ChangeSource source) => controller.update(scale: scale, source: source); + + void updateScaleStateFromNewScale(double newScale, ChangeSource source) { + final boundaries = scaleBoundaries; + if (boundaries == null) return; + + var newScaleState = ScaleState.initial; + if (controller.scale != boundaries.initialScale) { + newScaleState = (newScale > boundaries.initialScale) ? ScaleState.zoomedIn : ScaleState.zoomedOut; + } + controller.setScaleState(newScaleState, source); + } + + void nextScaleState(ChangeSource source, {Offset? childFocalPoint}) { + final scaleState = controller.scaleState.state; + if (scaleState == ScaleState.zoomedIn || scaleState == ScaleState.zoomedOut) { + controller.setScaleState(scaleStateCycle(scaleState), source, childFocalPoint: childFocalPoint); + return; + } + final originalScale = controller.getScaleForScaleState(scaleState); + + var prevScale = originalScale; + var prevScaleState = scaleState; + var nextScale = originalScale; + var nextScaleState = scaleState; + + do { + prevScale = nextScale; + prevScaleState = nextScaleState; + nextScaleState = scaleStateCycle(prevScaleState); + nextScale = controller.getScaleForScaleState(nextScaleState); + } while (prevScale == nextScale && scaleState != nextScaleState); + + if (originalScale == nextScale) return; + controller.setScaleState(nextScaleState, source, childFocalPoint: childFocalPoint); + } +} diff --git a/plugins/aves_magnifier/lib/src/controller/range.dart b/plugins/aves_magnifier/lib/src/controller/range.dart new file mode 100644 index 0000000..116ceef --- /dev/null +++ b/plugins/aves_magnifier/lib/src/controller/range.dart @@ -0,0 +1,15 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; + +@immutable +class EdgeRange extends Equatable { + final double min; + final double max; + + @override + List<Object?> get props => [min, max]; + + const EdgeRange(this.min, this.max); + + static const EdgeRange zero = EdgeRange(0, 0); +} diff --git a/plugins/aves_magnifier/lib/src/controller/state.dart b/plugins/aves_magnifier/lib/src/controller/state.dart new file mode 100644 index 0000000..ee8313d --- /dev/null +++ b/plugins/aves_magnifier/lib/src/controller/state.dart @@ -0,0 +1,22 @@ +import 'dart:ui'; + +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; + +@immutable +class MagnifierState extends Equatable { + final Offset position; + final double? scale; + final ChangeSource source; + + @override + List<Object?> get props => [position, scale, source]; + + const MagnifierState({ + required this.position, + required this.scale, + required this.source, + }); +} + +enum ChangeSource { internal, gesture, animation } diff --git a/plugins/aves_magnifier/lib/src/core/core.dart b/plugins/aves_magnifier/lib/src/core/core.dart new file mode 100644 index 0000000..009ad1b --- /dev/null +++ b/plugins/aves_magnifier/lib/src/core/core.dart @@ -0,0 +1,557 @@ +import 'dart:math'; + +import 'package:aves_magnifier/src/controller/controller.dart'; +import 'package:aves_magnifier/src/controller/controller_delegate.dart'; +import 'package:aves_magnifier/src/controller/state.dart'; +import 'package:aves_magnifier/src/core/gesture_detector.dart'; +import 'package:aves_magnifier/src/pan/edge_hit_detector.dart'; +import 'package:aves_magnifier/src/scale/scale_boundaries.dart'; +import 'package:aves_magnifier/src/scale/scale_level.dart'; +import 'package:aves_magnifier/src/scale/state.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/widgets.dart'; + +/* + adapted from package `photo_view` v0.9.2: + - removed image related aspects to focus on a general purpose pan/scale viewer (Ã la `InteractiveViewer`) + - removed rotation and many customization parameters + - removed ignorable/ignoring partial notifiers + - formatted, renamed and reorganized + - fixed gesture recognizers when used inside a scrollable widget like `PageView` + - fixed corner hit detection when in containers scrollable in both axes + - fixed corner hit detection issues due to imprecise double comparisons + - added single & double tap position feedback + - fixed focus when scaling by double-tap/pinch + */ +class AvesMagnifier extends StatefulWidget { + static const double defaultPanInertia = .2; + + final AvesMagnifierController controller; + final EdgeInsets viewportPadding; + + // The size of the custom [child]. This value is used to compute the relation between the child and the container's size to calculate the scale value. + final Size contentSize; + + final bool allowOriginalScaleBeyondRange; + final bool allowGestureScaleBeyondRange; + final MagnifierDoubleTapCallback? allowDoubleTap; + final double panInertia; + + // Defines the minimum size in which the image will be allowed to assume, it is proportional to the original image size. + final ScaleLevel minScale; + + // Defines the maximum size in which the image will be allowed to assume, it is proportional to the original image size. + final ScaleLevel maxScale; + + // Defines the size the image will assume when the component is initialized, it is proportional to the original image size. + final ScaleLevel initialScale; + + final ScaleStateCycle scaleStateCycle; + final bool applyScale; + final MagnifierGestureScaleStartCallback? onScaleStart; + final MagnifierGestureScaleUpdateCallback? onScaleUpdate; + final MagnifierGestureScaleEndCallback? onScaleEnd; + final MagnifierGestureFlingCallback? onFling; + final MagnifierTapCallback? onTap; + final GestureLongPressCallback? onLongPress; + final MagnifierDoubleTapCallback? onDoubleTap; + final Widget child; + + const AvesMagnifier({ + super.key, + required this.controller, + required this.contentSize, + this.viewportPadding = EdgeInsets.zero, + this.allowOriginalScaleBeyondRange = true, + this.allowGestureScaleBeyondRange = true, + this.allowDoubleTap, + this.minScale = const ScaleLevel(factor: .0), + this.maxScale = const ScaleLevel(factor: double.infinity), + this.initialScale = const ScaleLevel(ref: ScaleReference.contained), + this.scaleStateCycle = defaultScaleStateCycle, + this.applyScale = true, + this.panInertia = defaultPanInertia, + this.onScaleStart, + this.onScaleUpdate, + this.onScaleEnd, + this.onFling, + this.onTap, + this.onLongPress, + this.onDoubleTap, + required this.child, + }); + + @override + State<StatefulWidget> createState() => _AvesMagnifierState(); +} + +class _AvesMagnifierState extends State<AvesMagnifier> with TickerProviderStateMixin, AvesMagnifierControllerDelegate, EdgeHitDetector { + Offset? _startFocalPoint, _lastViewportFocalPosition; + double? _startScale, _quickScaleLastY, _quickScaleLastDistance; + late bool _dropped, _doubleTap, _quickScaleMoved; + DateTime _lastScaleGestureDate = DateTime.now(); + + late AnimationController _scaleAnimationController; + late Animation<double> _scaleAnimation; + + late AnimationController _positionAnimationController; + late Animation<Offset> _positionAnimation; + + static const _flingPointerKind = PointerDeviceKind.unknown; + + @override + void initState() { + super.initState(); + _scaleAnimationController = AnimationController(vsync: this) + ..addListener(handleScaleAnimation) + ..addStatusListener(onAnimationStatus); + _positionAnimationController = AnimationController(vsync: this)..addListener(handlePositionAnimate); + _registerWidget(widget); + // force delegate scale computing on initialization + // so that it does not happen lazily at the beginning of a scale animation + initScale(); + } + + @override + void didUpdateWidget(covariant AvesMagnifier oldWidget) { + super.didUpdateWidget(oldWidget); + + if (oldWidget.controller != widget.controller) { + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + if (oldWidget.allowOriginalScaleBeyondRange != widget.allowOriginalScaleBeyondRange || oldWidget.minScale != widget.minScale || oldWidget.maxScale != widget.maxScale || oldWidget.initialScale != widget.initialScale || oldWidget.contentSize != widget.contentSize) { + controller.setScaleBoundaries((controller.scaleBoundaries ?? ScaleBoundaries.zero).copyWith( + allowOriginalScaleBeyondRange: widget.allowOriginalScaleBeyondRange, + minScale: widget.minScale, + maxScale: widget.maxScale, + initialScale: widget.initialScale, + contentSize: widget.contentSize.isEmpty == false ? widget.contentSize : null, + )); + } + } + + @override + void dispose() { + _unregisterWidget(widget); + _scaleAnimationController.dispose(); + _positionAnimationController.dispose(); + super.dispose(); + } + + void _registerWidget(AvesMagnifier widget) { + registerDelegate(widget); + setScaleStateUpdateAnimation(animateOnScaleStateUpdate); + } + + void _unregisterWidget(AvesMagnifier oldWidget) { + unregisterDelegate(oldWidget); + } + + void handleScaleAnimation() { + setScale(_scaleAnimation.value, ChangeSource.animation); + } + + void handlePositionAnimate() { + controller.update(position: _positionAnimation.value, source: ChangeSource.animation); + } + + Stopwatch? _scaleStopwatch; + VelocityTracker? _velocityTracker; + var _mayFlingLTRB = const (false, false, false, false); + + void onScaleStart(ScaleStartDetails details, bool doubleTap) { + final boundaries = scaleBoundaries; + if (boundaries == null) return; + + widget.onScaleStart?.call(details, doubleTap, boundaries); + + _scaleStopwatch = Stopwatch()..start(); + _velocityTracker = VelocityTracker.withKind(_flingPointerKind); + _mayFlingLTRB = const (true, true, true, true); + _updateMayFling(); + + _startScale = controller.scale; + _startFocalPoint = details.localFocalPoint; + _lastViewportFocalPosition = _startFocalPoint; + _dropped = false; + _doubleTap = doubleTap; + _quickScaleLastDistance = null; + _quickScaleLastY = _startFocalPoint!.dy; + _quickScaleMoved = false; + + _scaleAnimationController.stop(); + _positionAnimationController.stop(); + } + + void onScaleUpdate(ScaleUpdateDetails details) { + final boundaries = scaleBoundaries; + if (boundaries == null) return; + + _dropped |= widget.onScaleUpdate?.call(details) ?? false; + if (_dropped) return; + + final elapsed = _scaleStopwatch?.elapsed; + if (elapsed != null) { + _velocityTracker?.addPosition(elapsed, details.focalPoint); + } + _updateMayFling(); + + double newScale; + if (_doubleTap) { + // quick scale, aka one finger zoom + // magic numbers from `davemorrissey/subsampling-scale-image-view` + final focalPointY = details.localFocalPoint.dy; + final distance = (focalPointY - _startFocalPoint!.dy).abs() * 2 + 20; + _quickScaleLastDistance ??= distance; + final spanDiff = (1 - (distance / _quickScaleLastDistance!)).abs() * .5; + _quickScaleMoved |= spanDiff > .03; + final factor = _quickScaleMoved ? (focalPointY > _quickScaleLastY! ? (1 + spanDiff) : (1 - spanDiff)) : 1; + _quickScaleLastDistance = distance; + _quickScaleLastY = focalPointY; + newScale = controller.scale! * factor; + } else { + newScale = _startScale! * details.scale; + } + if (!widget.allowGestureScaleBeyondRange) { + newScale = boundaries.clampScale(newScale); + } + newScale = max(0, newScale); + // focal point is in viewport coordinates + final scaleFocalPoint = _doubleTap ? _startFocalPoint! : details.localFocalPoint; + + final viewportCenter = boundaries.viewportCenter; + final centerContentPosition = boundaries.viewportToContentPosition(controller, viewportCenter); + final scalePositionDelta = (scaleFocalPoint - viewportCenter) * (controller.scale! / newScale - 1); + final panPositionDelta = scaleFocalPoint - _lastViewportFocalPosition!; + + final newPosition = boundaries.clampPosition( + position: boundaries.contentToStatePosition(newScale, centerContentPosition) + scalePositionDelta + panPositionDelta, + scale: newScale, + ); + + updateScaleStateFromNewScale(newScale, ChangeSource.gesture); + controller.update(position: newPosition, scale: newScale, source: ChangeSource.gesture); + + _lastViewportFocalPosition = scaleFocalPoint; + } + + void onScaleEnd(ScaleEndDetails details) { + final boundaries = scaleBoundaries; + if (boundaries == null) return; + + widget.onScaleEnd?.call(details); + + _updateMayFling(); + final estimate = _velocityTracker?.getVelocityEstimate(); + final onFling = widget.onFling; + if (estimate != null && onFling != null) { + final (left, up, right, down) = _mayFlingLTRB; + if (_isFlingGesture(estimate, _flingPointerKind, Axis.horizontal)) { + if (left ^ right) { + if (left) { + onFling(AxisDirection.left); + } else if (right) { + onFling(AxisDirection.right); + } + } + } else if (_isFlingGesture(estimate, _flingPointerKind, Axis.vertical)) { + if (up ^ down) { + if (up) { + onFling(AxisDirection.up); + } else if (down) { + onFling(AxisDirection.down); + } + } + } + } + + final currentPosition = controller.position; + final currentScale = controller.scale!; + + // animate back to min/max scale if gesture yielded a scale exceeding them + final newScale = boundaries.clampScale(currentScale); + if (currentScale != newScale) { + final newPosition = boundaries.clampPosition( + position: currentPosition * newScale / currentScale, + scale: newScale, + ); + animateScale(currentScale, newScale); + animatePosition(currentPosition, newPosition); + return; + } + + // The gesture recognizer triggers a new `onScaleStart` every time a pointer/finger is added or removed. + // Following a pinch-to-zoom gesture, a new panning gesture may start if the user does not lift both fingers at the same time, + // so we dismiss such panning gestures when it looks like it followed a scaling gesture. + final isPanning = currentScale == _startScale && (DateTime.now().difference(_lastScaleGestureDate)).inMilliseconds > 100; + + // animate position only when panning without scaling + if (isPanning) { + var pps = details.velocity.pixelsPerSecond; + if (pps != Offset.zero) { + final externalTransform = boundaries.externalTransform; + if (externalTransform != null) { + pps = Matrix4.inverted(externalTransform).transformOffset(pps); + } + final newPosition = boundaries.clampPosition( + position: currentPosition + pps * widget.panInertia, + scale: currentScale, + ); + if (currentPosition != newPosition) { + final tween = Tween<Offset>(begin: currentPosition, end: newPosition); + const curve = Curves.easeOutCubic; + _positionAnimation = tween.animate(CurvedAnimation(parent: _positionAnimationController, curve: curve)); + _positionAnimationController + ..duration = _getAnimationDurationForVelocity(curve: curve, tween: tween, targetPixelPerSecond: pps) + ..forward(from: 0.0); + } + } + } + + if (currentScale != _startScale) { + _lastScaleGestureDate = DateTime.now(); + } + } + + void _updateMayFling() { + final xHit = getXEdgeHit(); + final yHit = getYEdgeHit(); + final (left, up, right, down) = _mayFlingLTRB; + _mayFlingLTRB = ( + xHit.hasHitMin && left, + yHit.hasHitMin && up, + xHit.hasHitMax && right, + yHit.hasHitMax && down, + ); + } + + bool _isFlingGesture(VelocityEstimate estimate, PointerDeviceKind kind, Axis axis) { + final gestureSettings = MediaQuery.gestureSettingsOf(context); + const minVelocity = kMinFlingVelocity; + final minDistance = computeHitSlop(kind, gestureSettings); + + final pps = estimate.pixelsPerSecond; + final offset = estimate.offset; + if (axis == Axis.horizontal) { + return pps.dx.abs() > minVelocity && offset.dx.abs() > minDistance; + } else { + return pps.dy.abs() > minVelocity && offset.dy.abs() > minDistance; + } + } + + Duration _getAnimationDurationForVelocity({ + required Cubic curve, + required Tween<Offset> tween, + required Offset targetPixelPerSecond, + }) { + assert(targetPixelPerSecond != Offset.zero); + // find initial animation velocity over the first 20% of the specified curve + const t = 0.2; + final animationVelocity = (tween.end! - tween.begin!).distance * curve.transform(t) / t; + final gestureVelocity = targetPixelPerSecond.distance; + return Duration(milliseconds: gestureVelocity != 0 ? (animationVelocity / gestureVelocity * 1000).round() : 0); + } + + Alignment? _getTapAlignment(Offset viewportTapPosition) { + final boundaries = scaleBoundaries; + if (boundaries == null) return null; + + final viewportSize = boundaries.viewportSize; + return Alignment(viewportTapPosition.dx / viewportSize.width, viewportTapPosition.dy / viewportSize.height); + } + + Offset? _getChildTapPosition(Offset viewportTapPosition) { + final boundaries = scaleBoundaries; + if (boundaries == null) return null; + + return boundaries.viewportToContentPosition(controller, viewportTapPosition); + } + + void _onTapUp(TapUpDetails details) { + final onTap = widget.onTap; + if (onTap == null) return; + + final viewportTapPosition = details.localPosition; + final alignment = _getTapAlignment(viewportTapPosition); + final childTapPosition = _getChildTapPosition(viewportTapPosition); + if (alignment != null && childTapPosition != null) { + onTap(context, controller.currentState, alignment, childTapPosition); + } + } + + bool _allowDoubleTap(Offset localPosition) { + final allowDoubleTap = widget.allowDoubleTap; + if (allowDoubleTap != null) { + final alignment = _getTapAlignment(localPosition); + if (alignment != null) { + return allowDoubleTap(alignment); + } + } + return true; + } + + void _onDoubleTap(TapDownDetails details) { + final onDoubleTap = widget.onDoubleTap; + if (onDoubleTap != null) { + final alignment = _getTapAlignment(details.localPosition); + if (alignment != null && onDoubleTap(alignment)) return; + } + + final childTapPosition = _getChildTapPosition(details.localPosition); + if (childTapPosition != null) { + nextScaleState(ChangeSource.gesture, childFocalPoint: childTapPosition); + } + } + + void animateScale(double? from, double? to) { + _scaleAnimation = Tween<double>( + begin: from, + end: to, + ).animate(_scaleAnimationController); + _scaleAnimationController + ..value = 0.0 + ..fling(velocity: 0.4); + } + + void animatePosition(Offset from, Offset to) { + _positionAnimation = Tween<Offset>(begin: from, end: to).animate(_positionAnimationController); + _positionAnimationController + ..value = 0.0 + ..fling(velocity: 0.4); + } + + void onAnimationStatus(AnimationStatus status) { + if (status.isCompleted) { + onAnimationStatusCompleted(); + } + } + + /// Check if scale is equal to initial after scale animation update + void onAnimationStatusCompleted() { + if (controller.scaleState.state != ScaleState.initial && controller.scale == scaleBoundaries?.initialScale) { + controller.setScaleState(ScaleState.initial, ChangeSource.animation); + } + } + + void animateOnScaleStateUpdate(double? prevScale, double? nextScale, Offset nextPosition) { + animateScale(prevScale, nextScale); + animatePosition(controller.position, nextPosition); + } + + @override + Widget build(BuildContext context) { + return StreamBuilder<MagnifierState>( + stream: controller.stateStream, + initialData: controller.previousState, + builder: (context, snapshot) { + if (!snapshot.hasData) return const SizedBox(); + + final magnifierState = snapshot.data!; + final position = magnifierState.position; + final applyScale = widget.applyScale; + + Widget child = CustomSingleChildLayout( + delegate: _CenterWithOriginalSizeDelegate( + widget.contentSize, + basePosition, + applyScale, + ), + child: widget.child, + ); + + return MagnifierGestureDetector( + hitDetector: this, + onScaleStart: onScaleStart, + onScaleUpdate: onScaleUpdate, + onScaleEnd: onScaleEnd, + onTapUp: widget.onTap == null ? null : _onTapUp, + onLongPress: widget.onLongPress, + onDoubleTap: _onDoubleTap, + allowDoubleTap: _allowDoubleTap, + child: Padding( + padding: widget.viewportPadding, + child: LayoutBuilder( + builder: (context, constraints) { + final boundaries = (controller.scaleBoundaries ?? ScaleBoundaries.zero).copyWith( + allowOriginalScaleBeyondRange: widget.allowOriginalScaleBeyondRange, + minScale: widget.minScale, + maxScale: widget.maxScale, + initialScale: widget.initialScale, + viewportSize: constraints.biggest, + contentSize: widget.contentSize.isEmpty == false ? widget.contentSize : constraints.biggest, + ); + controller.setScaleBoundaries(boundaries); + + // `Matrix4.scale` uses dynamic typing and can throw `UnimplementedError` on wrong types + final double effectiveScale = (applyScale ? controller.scale : null) ?? 1.0; + return Transform( + transform: Matrix4.identity() + ..translate(position.dx, position.dy) + ..scale(effectiveScale), + alignment: basePosition, + child: child, + ); + }, + ), + ), + ); + }, + ); + } +} + +@immutable +class _CenterWithOriginalSizeDelegate extends SingleChildLayoutDelegate with EquatableMixin { + final Size subjectSize; + final Alignment basePosition; + final bool applyScale; + + @override + List<Object?> get props => [subjectSize, basePosition, applyScale]; + + const _CenterWithOriginalSizeDelegate( + this.subjectSize, + this.basePosition, + this.applyScale, + ); + + @override + Offset getPositionForChild(Size size, Size childSize) { + final childWidth = applyScale ? subjectSize.width : childSize.width; + final childHeight = applyScale ? subjectSize.height : childSize.height; + + final halfWidth = (size.width - childWidth) / 2; + final halfHeight = (size.height - childHeight) / 2; + + final offsetX = halfWidth * (basePosition.x + 1); + final offsetY = halfHeight * (basePosition.y + 1); + return Offset(offsetX, offsetY); + } + + @override + BoxConstraints getConstraintsForChild(BoxConstraints constraints) { + return applyScale ? BoxConstraints.tight(subjectSize) : const BoxConstraints(); + } + + @override + bool shouldRelayout(_CenterWithOriginalSizeDelegate oldDelegate) { + return oldDelegate != this; + } +} + +typedef MagnifierTapCallback = Function( + BuildContext context, + MagnifierState state, + Alignment alignment, + Offset childTapPosition, +); +typedef MagnifierDoubleTapPredicate = bool Function(Offset localPosition); +typedef MagnifierDoubleTapCallback = bool Function(Alignment alignment); +typedef MagnifierGestureScaleStartCallback = void Function(ScaleStartDetails details, bool doubleTap, ScaleBoundaries boundaries); +typedef MagnifierGestureScaleUpdateCallback = bool Function(ScaleUpdateDetails details); +typedef MagnifierGestureScaleEndCallback = void Function(ScaleEndDetails details); +typedef MagnifierGestureFlingCallback = void Function(AxisDirection direction); diff --git a/plugins/aves_magnifier/lib/src/core/gesture_detector.dart b/plugins/aves_magnifier/lib/src/core/gesture_detector.dart new file mode 100644 index 0000000..f4cf1cb --- /dev/null +++ b/plugins/aves_magnifier/lib/src/core/gesture_detector.dart @@ -0,0 +1,149 @@ +import 'package:aves_magnifier/aves_magnifier.dart'; +import 'package:aves_magnifier/src/pan/edge_hit_detector.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/widgets.dart'; + +class MagnifierGestureDetector extends StatefulWidget { + final EdgeHitDetector hitDetector; + + final void Function(ScaleStartDetails details, bool doubleTap)? onScaleStart; + final GestureScaleUpdateCallback? onScaleUpdate; + final GestureScaleEndCallback? onScaleEnd; + + final GestureTapDownCallback? onTapDown; + final GestureTapUpCallback? onTapUp; + final GestureLongPressCallback? onLongPress; + final GestureTapDownCallback? onDoubleTap; + + final MagnifierDoubleTapPredicate? allowDoubleTap; + final HitTestBehavior? behavior; + final Widget? child; + + const MagnifierGestureDetector({ + super.key, + required this.hitDetector, + this.onScaleStart, + this.onScaleUpdate, + this.onScaleEnd, + this.onTapDown, + this.onTapUp, + this.onLongPress, + this.onDoubleTap, + this.allowDoubleTap, + this.behavior, + this.child, + }); + + @override + State<MagnifierGestureDetector> createState() => _MagnifierGestureDetectorState(); +} + +class _MagnifierGestureDetectorState extends State<MagnifierGestureDetector> { + final ValueNotifier<TapDownDetails?> doubleTapDetails = ValueNotifier(null); + + @override + void dispose() { + doubleTapDetails.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final gestureSettings = MediaQuery.gestureSettingsOf(context); + final gestures = <Type, GestureRecognizerFactory>{}; + + if (widget.onTapDown != null || widget.onTapUp != null) { + gestures[TapGestureRecognizer] = GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>( + () => TapGestureRecognizer(debugOwner: this), + (instance) { + instance + ..onTapDown = widget.onTapDown + ..onTapUp = widget.onTapUp; + }, + ); + } + + if (widget.onLongPress != null) { + gestures[LongPressGestureRecognizer] = GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>( + () => LongPressGestureRecognizer(debugOwner: this), + (instance) { + instance.onLongPress = widget.onLongPress; + }, + ); + } + + final scope = MagnifierGestureDetectorScope.maybeOf(context); + if (scope != null) { + gestures[MagnifierGestureRecognizer] = GestureRecognizerFactoryWithHandlers<MagnifierGestureRecognizer>( + () => MagnifierGestureRecognizer( + debugOwner: this, + scope: scope, + doubleTapDetails: doubleTapDetails, + ), + (instance) { + instance + ..hitDetector = widget.hitDetector + ..onStart = widget.onScaleStart != null ? (details) => widget.onScaleStart!(details, doubleTapDetails.value != null) : null + ..onUpdate = widget.onScaleUpdate + ..onEnd = widget.onScaleEnd + ..gestureSettings = gestureSettings; + }, + ); + } + + gestures[MagnifierDoubleTapGestureRecognizer] = GestureRecognizerFactoryWithHandlers<MagnifierDoubleTapGestureRecognizer>( + () => MagnifierDoubleTapGestureRecognizer( + debugOwner: this, + allowDoubleTap: widget.allowDoubleTap ?? (_) => true, + ), + (instance) { + final onDoubleTap = widget.onDoubleTap; + instance + ..onDoubleTapCancel = _onDoubleTapCancel + ..onDoubleTapDown = _onDoubleTapDown + ..onDoubleTap = onDoubleTap != null + ? () { + final details = doubleTapDetails.value; + if (details != null) { + onDoubleTap(details); + doubleTapDetails.value = null; + } + } + : null; + }, + ); + + return RawGestureDetector( + gestures: gestures, + behavior: widget.behavior ?? HitTestBehavior.translucent, + child: widget.child, + ); + } + + void _onDoubleTapCancel() => doubleTapDetails.value = null; + + void _onDoubleTapDown(TapDownDetails details) { + if (widget.allowDoubleTap?.call(details.localPosition) ?? true) { + doubleTapDetails.value = details; + } + } +} + +class MagnifierDoubleTapGestureRecognizer extends DoubleTapGestureRecognizer { + final MagnifierDoubleTapPredicate allowDoubleTap; + + MagnifierDoubleTapGestureRecognizer({ + super.debugOwner, + super.supportedDevices, + super.allowedButtonsFilter, + required this.allowDoubleTap, + }); + + @override + bool isPointerAllowed(PointerDownEvent event) { + if (!allowDoubleTap(event.localPosition)) { + return false; + } + return super.isPointerAllowed(event); + } +} diff --git a/plugins/aves_magnifier/lib/src/core/scale_gesture_recognizer.dart b/plugins/aves_magnifier/lib/src/core/scale_gesture_recognizer.dart new file mode 100644 index 0000000..8fc3186 --- /dev/null +++ b/plugins/aves_magnifier/lib/src/core/scale_gesture_recognizer.dart @@ -0,0 +1,165 @@ +import 'dart:math'; + +import 'package:aves_magnifier/aves_magnifier.dart'; +import 'package:aves_magnifier/src/pan/edge_hit_detector.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/widgets.dart'; + +class MagnifierGestureRecognizer extends ScaleGestureRecognizer { + final MagnifierGestureDetectorScope scope; + final ValueNotifier<TapDownDetails?> doubleTapDetails; + + EdgeHitDetector? hitDetector; + + MagnifierGestureRecognizer({ + super.debugOwner, + required this.scope, + required this.doubleTapDetails, + }); + + Map<int, Offset> _pointerLocations = <int, Offset>{}; + + Offset? _initialFocalPoint; + Offset? _currentFocalPoint; + double? _initialSpan; + double? _currentSpan; + + bool ready = true; + + @override + void addAllowedPointer(PointerDownEvent event) { + if (ready) { + ready = false; + _initialSpan = 0.0; + _currentSpan = 0.0; + _pointerLocations = <int, Offset>{}; + } + super.addAllowedPointer(event); + } + + @override + void didStopTrackingLastPointer(int pointer) { + ready = true; + super.didStopTrackingLastPointer(pointer); + } + + @override + void handleEvent(PointerEvent event) { + if (scope.axis.isNotEmpty) { + var didChangeConfiguration = false; + final pointer = event.pointer; + if (event is PointerMoveEvent) { + if (!event.synthesized) { + _pointerLocations[pointer] = event.position; + } + } else if (event is PointerDownEvent) { + _pointerLocations[pointer] = event.position; + didChangeConfiguration = true; + } else if (event is PointerUpEvent || event is PointerCancelEvent) { + _pointerLocations.remove(pointer); + didChangeConfiguration = true; + } + + _updateDistances(); + + if (didChangeConfiguration) { + // cf super._reconfigure + _initialFocalPoint = _currentFocalPoint; + _initialSpan = _currentSpan; + } + + if (event is PointerMoveEvent) { + if (_areMultiPointers()) { + acceptGesture(pointer); + } else if (_isPriorityGesture() && _isOverSlop(event.kind)) { + acceptGesture(pointer); + } else { + final axis = scope.axis; + final isPriorityMove = (axis.contains(Axis.horizontal) && _canPanX()) || (axis.contains(Axis.vertical) && _canPanY()); + if (isPriorityMove && _isOverSlop(event.kind)) { + acceptGesture(pointer); + } + } + } + } + super.handleEvent(event); + } + + @override + void resolve(GestureDisposition disposition) { + switch (disposition) { + case GestureDisposition.accepted: + // do not let super `ScaleGestureRecognizer` accept gestures + // when it should yield to other recognizers + final canAccept = _areMultiPointers() || _isPriorityGesture() || _canPanX() || _canPanY(); + super.resolve(canAccept ? GestureDisposition.accepted : GestureDisposition.rejected); + case GestureDisposition.rejected: + super.resolve(disposition); + } + } + + void _updateDistances() { + // cf super._update + final count = _pointerLocations.keys.length; + + // Compute the focal point + var focalPoint = Offset.zero; + for (final pointer in _pointerLocations.keys) { + focalPoint += _pointerLocations[pointer]!; + } + _currentFocalPoint = count > 0 ? focalPoint / count.toDouble() : Offset.zero; + + // Span is the average deviation from focal point. Horizontal and vertical + // spans are the average deviations from the focal point's horizontal and + // vertical coordinates, respectively. + var totalDeviation = 0.0; + for (final pointer in _pointerLocations.keys) { + totalDeviation += (_currentFocalPoint! - _pointerLocations[pointer]!).distance; + } + _currentSpan = count > 0 ? totalDeviation / count : 0.0; + } + + Offset get move => _initialFocalPoint! - _currentFocalPoint!; + + // when there are multiple pointers, we always accept the gesture to scale + // as this is not competing with single taps or other drag gestures + bool _areMultiPointers() => _pointerLocations.keys.length >= 2; + + bool _isPriorityGesture() { + // e.g. vertical drag to adjust brightness instead of panning + if (scope.acceptPointerEvent?.call(move) ?? false) return true; + + // e.g. double tap & drag for one finger zoom + if (doubleTapDetails.value != null) return true; + + return false; + } + + bool _canPanX() => hitDetector != null && hitDetector!.shouldMoveX(move, scope.escapeByFling) && isXPan(move); + + bool _canPanY() => hitDetector != null && hitDetector!.shouldMoveY(move, scope.escapeByFling) && isYPan(move); + + bool _isOverSlop(PointerDeviceKind kind) { + final spanDelta = (_currentSpan! - _initialSpan!).abs(); + final focalPointDelta = move.distance; + // warning: do not compare `focalPointDelta` to `kPanSlop` + // `ScaleGestureRecognizer` uses `kPanSlop` (or platform settings, cf gestures/events.dart `computePanSlop`), + // but `HorizontalDragGestureRecognizer` uses `kTouchSlop` (or platform settings, cf gestures/events.dart `computeHitSlop`) + // and the magnifier recognizer may compete with the `HorizontalDragGestureRecognizer` from a containing `PageView` + // setting `touchSlopFactor` to 2 restores default `ScaleGestureRecognizer` behaviour as `kPanSlop = kTouchSlop * 2.0` + // setting `touchSlopFactor` in [0, 1] will allow this recognizer to accept the gesture before the one from `PageView` + return spanDelta > computeScaleSlop(kind) || focalPointDelta > computeHitSlop(kind, gestureSettings) * scope.touchSlopFactor; + } + + static bool isXPan(Offset move) { + // the gesture direction angle is in ]-pi, pi], cf `Offset` doc for details + final d = move.direction; + return (-pi / 4 < d && d < pi / 4) || (3 / 4 * pi < d && d <= pi) || (-pi < d && d < -3 / 4 * pi); + } + + static bool isYPan(Offset move) { + // the gesture direction angle is in ]-pi, pi], cf `Offset` doc for details + final d = move.direction; + return (pi / 4 < d && d < 3 / 4 * pi) || (-3 / 4 * pi < d && d < -pi / 4); + } +} diff --git a/plugins/aves_magnifier/lib/src/pan/edge_hit_detector.dart b/plugins/aves_magnifier/lib/src/pan/edge_hit_detector.dart new file mode 100644 index 0000000..04277a7 --- /dev/null +++ b/plugins/aves_magnifier/lib/src/pan/edge_hit_detector.dart @@ -0,0 +1,65 @@ +import 'package:aves_magnifier/src/controller/controller_delegate.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +mixin EdgeHitDetector on AvesMagnifierControllerDelegate { + // the content width/height is not accurate for some image size & scale combos + // e.g. 3580.0 * 0.1005586592178771 yields 360.0 + // but 4764.0 * 0.07556675062972293 yields 360.00000000000006 + // so be sure to compare with `precisionErrorTolerance` + + EdgeHit getXEdgeHit() { + final _boundaries = scaleBoundaries; + final _scale = controller.scale; + if (_boundaries == null || _scale == null) return const EdgeHit(false, false); + + final x = -position.dx; + final range = _boundaries.getXEdges(scale: _scale); + return EdgeHit(x <= range.min + precisionErrorTolerance, x >= range.max - precisionErrorTolerance); + } + + EdgeHit getYEdgeHit() { + final _boundaries = scaleBoundaries; + final _scale = controller.scale; + if (_boundaries == null || _scale == null) return const EdgeHit(false, false); + + final y = -position.dy; + final range = _boundaries.getYEdges(scale: _scale); + return EdgeHit(y <= range.min + precisionErrorTolerance, y >= range.max - precisionErrorTolerance); + } + + bool shouldMoveX(Offset move, bool canFling) { + final hit = getXEdgeHit(); + return _shouldMove(hit, move.dx) || (canFling && !hit.hasHitBoth); + } + + bool shouldMoveY(Offset move, bool canFling) { + final hit = getYEdgeHit(); + return _shouldMove(hit, move.dy) || (canFling && !hit.hasHitBoth); + } + + bool _shouldMove(EdgeHit hit, double move) { + if (hit.hasHitAny && move != 0) { + if (hit.hasHitBoth) return false; + if (hit.hasHitMax) return move < 0; + return move > 0; + } + return true; + } +} + +@immutable +class EdgeHit extends Equatable { + final bool hasHitMin; + final bool hasHitMax; + + @override + List<Object?> get props => [hasHitMin, hasHitMax]; + + const EdgeHit(this.hasHitMin, this.hasHitMax); + + bool get hasHitAny => hasHitMin || hasHitMax; + + bool get hasHitBoth => hasHitMin && hasHitMax; +} diff --git a/plugins/aves_magnifier/lib/src/pan/gesture_detector_scope.dart b/plugins/aves_magnifier/lib/src/pan/gesture_detector_scope.dart new file mode 100644 index 0000000..d464121 --- /dev/null +++ b/plugins/aves_magnifier/lib/src/pan/gesture_detector_scope.dart @@ -0,0 +1,55 @@ +import 'package:flutter/widgets.dart'; + +/// When a `Magnifier` is wrapped in this inherited widget, +/// it will check whether the zoomed content has hit edges, +/// and if so, will let parent gesture detectors win the gesture arena +/// +/// Useful when placing Magnifier inside a gesture sensitive context, +/// such as [PageView], [Dismissible], [BottomSheet]. +class MagnifierGestureDetectorScope extends InheritedWidget { + final List<Axis> axis; + + // in [0, 1[ + // 0: most reactive but will not let tap recognizers accept gestures + // <1: less reactive but gives the most leeway to other recognizers + // 1: will not be able to compete with a `HorizontalDragGestureRecognizer` up the widget tree + final double touchSlopFactor; + + // when zoomed in and hitting an edge, allow using a fling gesture to go to the previous/next page, + // instead of yielding to the outer scrollable right away + final bool escapeByFling; + + final bool? Function(Offset move)? acceptPointerEvent; + + const MagnifierGestureDetectorScope({ + super.key, + required this.axis, + this.touchSlopFactor = .8, + this.escapeByFling = true, + this.acceptPointerEvent, + required super.child, + }); + + static MagnifierGestureDetectorScope? maybeOf(BuildContext context) { + return context.dependOnInheritedWidgetOfExactType<MagnifierGestureDetectorScope>(); + } + + MagnifierGestureDetectorScope copyWith({ + List<Axis>? axis, + double? touchSlopFactor, + bool? Function(Offset move)? acceptPointerEvent, + required Widget child, + }) { + return MagnifierGestureDetectorScope( + axis: axis ?? this.axis, + touchSlopFactor: touchSlopFactor ?? this.touchSlopFactor, + acceptPointerEvent: acceptPointerEvent ?? this.acceptPointerEvent, + child: child, + ); + } + + @override + bool updateShouldNotify(MagnifierGestureDetectorScope oldWidget) { + return axis != oldWidget.axis || touchSlopFactor != oldWidget.touchSlopFactor || acceptPointerEvent != oldWidget.acceptPointerEvent; + } +} diff --git a/plugins/aves_magnifier/lib/src/pan/scroll_physics.dart b/plugins/aves_magnifier/lib/src/pan/scroll_physics.dart new file mode 100644 index 0000000..30b2ce7 --- /dev/null +++ b/plugins/aves_magnifier/lib/src/pan/scroll_physics.dart @@ -0,0 +1,34 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/widgets.dart'; + +// `PageView` contains a `Scrollable` which sets up a `HorizontalDragGestureRecognizer`. +// This recognizer will win in the gesture arena when the drag distance reaches +// `kTouchSlop` (or platform settings, cf gestures/events.dart `computeHitSlop`). +// We cannot change that, but we can prevent the scrollable from panning until this threshold is reached +// and let other recognizers accept the gesture instead. +class MagnifierScrollerPhysics extends ScrollPhysics { + final DeviceGestureSettings? gestureSettings; + + // in [0, 1] + // 0: most reactive but will not let Magnifier recognizers accept gestures + // 1: less reactive but gives the most leeway to Magnifier recognizers + final double touchSlopFactor; + + const MagnifierScrollerPhysics({ + required this.gestureSettings, + this.touchSlopFactor = 1, + super.parent, + }); + + @override + MagnifierScrollerPhysics applyTo(ScrollPhysics? ancestor) { + return MagnifierScrollerPhysics( + gestureSettings: gestureSettings, + touchSlopFactor: touchSlopFactor, + parent: buildParent(ancestor), + ); + } + + @override + double get dragStartDistanceMotionThreshold => (gestureSettings?.touchSlop ?? kTouchSlop) * touchSlopFactor; +} diff --git a/plugins/aves_magnifier/lib/src/scale/scale_boundaries.dart b/plugins/aves_magnifier/lib/src/scale/scale_boundaries.dart new file mode 100644 index 0000000..d738edb --- /dev/null +++ b/plugins/aves_magnifier/lib/src/scale/scale_boundaries.dart @@ -0,0 +1,159 @@ +import 'dart:math'; + +import 'package:aves_magnifier/src/controller/controller.dart'; +import 'package:aves_magnifier/src/controller/range.dart'; +import 'package:aves_magnifier/src/scale/scale_level.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/widgets.dart'; + +/// Internal class to wrap custom scale boundaries (min, max and initial) +/// Also, stores values regarding the two sizes: the container and the content. +@immutable +class ScaleBoundaries extends Equatable { + final bool _allowOriginalScaleBeyondRange; + final ScaleLevel _minScale; + final ScaleLevel _maxScale; + final ScaleLevel _initialScale; + final Size viewportSize; + final Size contentSize; + final EdgeInsets Function(double scale)? padding; + final Matrix4? externalTransform; + + static const Alignment basePosition = Alignment.center; + + @override + List<Object?> get props => [_allowOriginalScaleBeyondRange, _minScale, _maxScale, _initialScale, viewportSize, contentSize, padding, externalTransform]; + + const ScaleBoundaries({ + required bool allowOriginalScaleBeyondRange, + required ScaleLevel minScale, + required ScaleLevel maxScale, + required ScaleLevel initialScale, + required this.viewportSize, + required this.contentSize, + this.padding, + this.externalTransform, + }) : _allowOriginalScaleBeyondRange = allowOriginalScaleBeyondRange, + _minScale = minScale, + _maxScale = maxScale, + _initialScale = initialScale; + + static const ScaleBoundaries zero = ScaleBoundaries( + allowOriginalScaleBeyondRange: true, + minScale: ScaleLevel(factor: .0), + maxScale: ScaleLevel(factor: double.infinity), + initialScale: ScaleLevel(ref: ScaleReference.contained), + viewportSize: Size.zero, + contentSize: Size.zero, + padding: null, + ); + + ScaleBoundaries copyWith({ + bool? allowOriginalScaleBeyondRange, + ScaleLevel? minScale, + ScaleLevel? maxScale, + ScaleLevel? initialScale, + Size? viewportSize, + Size? contentSize, + EdgeInsets Function(double scale)? padding, + Matrix4? externalTransform, + }) { + return ScaleBoundaries( + allowOriginalScaleBeyondRange: allowOriginalScaleBeyondRange ?? _allowOriginalScaleBeyondRange, + minScale: minScale ?? _minScale, + maxScale: maxScale ?? _maxScale, + initialScale: initialScale ?? _initialScale, + viewportSize: viewportSize ?? this.viewportSize, + contentSize: contentSize ?? this.contentSize, + padding: padding ?? this.padding, + externalTransform: externalTransform ?? this.externalTransform, + ); + } + + Size get _transformedViewportSize { + final matrix = externalTransform; + return matrix != null ? MatrixUtils.transformRect(Matrix4.inverted(matrix), Offset.zero & viewportSize).size : viewportSize; + } + + double scaleForLevel(ScaleLevel level) { + final factor = level.factor; + switch (level.ref) { + case ScaleReference.contained: + return factor * ScaleLevel.scaleForContained(viewportSize, contentSize); + case ScaleReference.covered: + return factor * ScaleLevel.scaleForCovering(viewportSize, contentSize); + case ScaleReference.absolute: + return factor; + } + } + + double get originalScale { + final view = WidgetsBinding.instance.platformDispatcher.views.firstOrNull; + return 1.0 / (view?.devicePixelRatio ?? 1.0); + } + + double get initialScale => scaleForLevel(_initialScale); + + Offset get viewportCenter => viewportSize.center(Offset.zero); + + Offset get _contentCenter => contentSize.center(Offset.zero); + + Offset viewportToContentPosition(AvesMagnifierController controller, Offset viewportPosition) { + return (viewportPosition - viewportCenter - controller.position) / controller.scale! + _contentCenter; + } + + Offset contentToStatePosition(double scale, Offset contentPosition) { + return (_contentCenter - contentPosition) * scale; + } + + EdgeRange getXEdges({required double scale}) { + final computedWidth = contentSize.width * scale; + final viewportWidth = _transformedViewportSize.width; + + final positionX = basePosition.x; + final widthDiff = max(0, computedWidth - viewportWidth); + + final minX = ((positionX - 1).abs() / 2) * widthDiff * -1; + final maxX = ((positionX + 1).abs() / 2) * widthDiff; + final _padding = padding?.call(scale) ?? EdgeInsets.zero; + return EdgeRange(minX - _padding.left, maxX + _padding.right); + } + + EdgeRange getYEdges({required double scale}) { + final computedHeight = contentSize.height * scale; + final viewportHeight = _transformedViewportSize.height; + + final positionY = basePosition.y; + final heightDiff = max(0, computedHeight - viewportHeight); + + final minY = ((positionY - 1).abs() / 2) * heightDiff * -1; + final maxY = ((positionY + 1).abs() / 2) * heightDiff; + final _padding = padding?.call(scale) ?? EdgeInsets.zero; + return EdgeRange(minY - _padding.top, maxY + _padding.bottom); + } + + double clampScale(double scale) { + final minScale = { + scaleForLevel(_minScale), + _allowOriginalScaleBeyondRange ? originalScale : double.infinity, + initialScale, + }.fold(double.infinity, min); + + final maxScale = { + scaleForLevel(_maxScale), + _allowOriginalScaleBeyondRange ? originalScale : double.negativeInfinity, + initialScale, + }.fold(.0, max); + + return scale.clamp(minScale, maxScale); + } + + Offset clampPosition({required Offset position, required double scale}) { + final rangeX = getXEdges(scale: scale); + final rangeY = getYEdges(scale: scale); + return Offset( + position.dx.clamp(rangeX.min, rangeX.max), + position.dy.clamp(rangeY.min, rangeY.max), + ); + } +} diff --git a/plugins/aves_magnifier/lib/src/scale/scale_level.dart b/plugins/aves_magnifier/lib/src/scale/scale_level.dart new file mode 100644 index 0000000..b186684 --- /dev/null +++ b/plugins/aves_magnifier/lib/src/scale/scale_level.dart @@ -0,0 +1,25 @@ +import 'dart:math'; + +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/rendering.dart'; + +@immutable +class ScaleLevel extends Equatable { + final ScaleReference ref; + final double factor; + + @override + List<Object?> get props => [ref, factor]; + + const ScaleLevel({ + this.ref = ScaleReference.absolute, + this.factor = 1.0, + }); + + static double scaleForContained(Size viewportSize, Size contentSize) => min(viewportSize.width / contentSize.width, viewportSize.height / contentSize.height); + + static double scaleForCovering(Size viewportSize, Size contentSize) => max(viewportSize.width / contentSize.width, viewportSize.height / contentSize.height); +} + +enum ScaleReference { absolute, contained, covered } diff --git a/plugins/aves_magnifier/lib/src/scale/state.dart b/plugins/aves_magnifier/lib/src/scale/state.dart new file mode 100644 index 0000000..6cf44a3 --- /dev/null +++ b/plugins/aves_magnifier/lib/src/scale/state.dart @@ -0,0 +1,42 @@ +import 'package:aves_magnifier/src/controller/state.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/widgets.dart'; + +@immutable +class ScaleStateChange extends Equatable { + final ScaleState state; + final ChangeSource source; + final Offset? childFocalPoint; + + @override + List<Object?> get props => [state, source, childFocalPoint]; + + const ScaleStateChange({ + required this.state, + required this.source, + this.childFocalPoint, + }); +} + +enum ScaleState { + initial, + covering, + originalSize, + zoomedIn, + zoomedOut, +} + +ScaleState defaultScaleStateCycle(ScaleState actual) { + switch (actual) { + case ScaleState.initial: + return ScaleState.covering; + case ScaleState.covering: + return ScaleState.originalSize; + case ScaleState.originalSize: + case ScaleState.zoomedIn: + case ScaleState.zoomedOut: + return ScaleState.initial; + } +} + +typedef ScaleStateCycle = ScaleState Function(ScaleState actual); diff --git a/plugins/aves_magnifier/pubspec.yaml b/plugins/aves_magnifier/pubspec.yaml new file mode 100644 index 0000000..5a22afa --- /dev/null +++ b/plugins/aves_magnifier/pubspec.yaml @@ -0,0 +1,21 @@ +name: aves_magnifier +version: 0.0.1 +publish_to: none + +environment: + sdk: ">=3.6.0 <4.0.0" # incoherent dartfmt from 3.7.0 +resolution: workspace + +dependencies: + flutter: + sdk: flutter + aves_utils: + path: ../aves_utils + equatable: + leak_tracker: + provider: + +dev_dependencies: + flutter_lints: + +flutter: diff --git a/plugins/aves_map/.gitignore b/plugins/aves_map/.gitignore new file mode 100644 index 0000000..79c113f --- /dev/null +++ b/plugins/aves_map/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/plugins/aves_map/.metadata b/plugins/aves_map/.metadata new file mode 100644 index 0000000..c24d00d --- /dev/null +++ b/plugins/aves_map/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: 5464c5bac742001448fe4fc0597be939379f88ea + channel: stable + +project_type: package diff --git a/plugins/aves_map/analysis_options.yaml b/plugins/aves_map/analysis_options.yaml new file mode 100644 index 0000000..f04c6cf --- /dev/null +++ b/plugins/aves_map/analysis_options.yaml @@ -0,0 +1 @@ +include: ../../analysis_options.yaml diff --git a/plugins/aves_map/lib/aves_map.dart b/plugins/aves_map/lib/aves_map.dart new file mode 100644 index 0000000..2098916 --- /dev/null +++ b/plugins/aves_map/lib/aves_map.dart @@ -0,0 +1,13 @@ +export 'src/controller.dart'; +export 'src/geo_entry.dart'; +export 'src/geo_utils.dart'; +export 'src/interface.dart'; +export 'src/marker/dot.dart'; +export 'src/marker/generator.dart'; +export 'src/marker/image.dart'; +export 'src/marker/key.dart'; +export 'src/overlay/overlay.dart'; +export 'src/overlay/tile.dart'; +export 'src/style.dart'; +export 'src/theme.dart'; +export 'src/zoomed_bounds.dart'; diff --git a/plugins/aves_map/lib/src/controller.dart b/plugins/aves_map/lib/src/controller.dart new file mode 100644 index 0000000..8997993 --- /dev/null +++ b/plugins/aves_map/lib/src/controller.dart @@ -0,0 +1,77 @@ +import 'dart:async'; + +import 'package:aves_map/src/zoomed_bounds.dart'; +import 'package:flutter/foundation.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:leak_tracker/leak_tracker.dart'; + +class AvesMapController { + final StreamController _streamController = StreamController.broadcast(); + ZoomedBounds? _idleBounds; + + ZoomedBounds? get idleBounds => _idleBounds; + + Stream<dynamic> get _events => _streamController.stream; + + Stream<MapControllerMoveEvent> get moveCommands => _events.where((event) => event is MapControllerMoveEvent).cast<MapControllerMoveEvent>(); + + Stream<MapControllerZoomEvent> get zoomCommands => _events.where((event) => event is MapControllerZoomEvent).cast<MapControllerZoomEvent>(); + + Stream<MapControllerRotationResetEvent> get rotationResetCommands => _events.where((event) => event is MapControllerRotationResetEvent).cast<MapControllerRotationResetEvent>(); + + Stream<MapIdleUpdate> get idleUpdates => _events.where((event) => event is MapIdleUpdate).cast<MapIdleUpdate>(); + + Stream<MapMarkerLocationChangeEvent> get markerLocationChanges => _events.where((event) => event is MapMarkerLocationChangeEvent).cast<MapMarkerLocationChangeEvent>(); + + AvesMapController() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$AvesMapController', + object: this, + ); + } + } + + void dispose() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + _streamController.close(); + } + + void moveTo(LatLng latLng) => _streamController.add(MapControllerMoveEvent(latLng)); + + void zoomBy(double delta) => _streamController.add(MapControllerZoomEvent(delta)); + + void resetRotation() => _streamController.add(MapControllerRotationResetEvent()); + + void notifyIdle(ZoomedBounds bounds) { + _idleBounds = bounds; + _streamController.add(MapIdleUpdate(bounds)); + } + + void notifyMarkerLocationChange() => _streamController.add(MapMarkerLocationChangeEvent()); +} + +class MapControllerMoveEvent { + final LatLng latLng; + + MapControllerMoveEvent(this.latLng); +} + +class MapControllerZoomEvent { + final double delta; + + MapControllerZoomEvent(this.delta); +} + +class MapControllerRotationResetEvent {} + +class MapIdleUpdate { + final ZoomedBounds bounds; + + MapIdleUpdate(this.bounds); +} + +class MapMarkerLocationChangeEvent {} diff --git a/plugins/aves_map/lib/src/geo_entry.dart b/plugins/aves_map/lib/src/geo_entry.dart new file mode 100644 index 0000000..4699e38 --- /dev/null +++ b/plugins/aves_map/lib/src/geo_entry.dart @@ -0,0 +1,32 @@ +import 'package:fluster/fluster.dart'; +import 'package:flutter/foundation.dart'; + +class GeoEntry<T> extends Clusterable { + T? entry; + + GeoEntry({ + this.entry, + super.latitude, + super.longitude, + super.isCluster = false, + super.clusterId, + super.pointsSize, + super.markerId, + super.childMarkerId, + }); + + factory GeoEntry.createCluster(BaseCluster cluster, double longitude, double latitude) { + return GeoEntry( + latitude: latitude, + longitude: longitude, + isCluster: cluster.isCluster, + clusterId: cluster.id, + pointsSize: cluster.pointsSize, + markerId: cluster.id.toString(), + childMarkerId: cluster.childMarkerId, + ); + } + + @override + String toString() => '$runtimeType#${shortHash(this)}{isCluster=$isCluster, lat=$latitude, lng=$longitude, clusterId=$clusterId, pointsSize=$pointsSize, markerId=$markerId, childMarkerId=$childMarkerId}'; +} diff --git a/plugins/aves_map/lib/src/geo_utils.dart b/plugins/aves_map/lib/src/geo_utils.dart new file mode 100644 index 0000000..5272482 --- /dev/null +++ b/plugins/aves_map/lib/src/geo_utils.dart @@ -0,0 +1,134 @@ +import 'dart:math'; + +import 'package:latlong2/latlong.dart'; + +class GeoUtils { + static LatLng getLatLngCenter(List<LatLng> points) { + double x = 0; + double y = 0; + double z = 0; + + points.forEach((point) { + final lat = point.latitudeInRad; + final lng = point.longitudeInRad; + x += cos(lat) * cos(lng); + y += cos(lat) * sin(lng); + z += sin(lat); + }); + + final pointCount = points.length; + x /= pointCount; + y /= pointCount; + z /= pointCount; + + final lng = atan2(y, x); + final hyp = sqrt(x * x + y * y); + final lat = atan2(z, hyp); + return LatLng(radianToDeg(lat), radianToDeg(lng)); + } + + static bool contains(LatLng sw, LatLng ne, LatLng? point) { + if (point == null) return false; + final lat = point.latitude; + final lng = point.longitude; + final south = sw.latitude; + final north = ne.latitude; + final west = sw.longitude; + final east = ne.longitude; + return (south <= lat && lat <= north) && (west <= east ? (west <= lng && lng <= east) : (west <= lng || lng <= east)); + } + + // cf https://epsg.io/EPSGCODE.proj4 + // cf https://github.com/stevage/epsg + // cf https://github.com/maRci002/proj4dart/blob/master/test/data/all_proj4_defs.dart + static String? epsgToProj4(int? epsg) { + // `32767` refers to user defined values + if (epsg == null || epsg == 32767) return null; + + if (3038 <= epsg && epsg <= 3051) { + // ETRS89 / UTM (N-E) + final zone = epsg - 3012; + return '+proj=utm +zone=$zone +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs'; + } else if (26700 <= epsg && epsg <= 26799) { + // US State Plane (NAD27): 267xx/320xx + if (26703 <= epsg && epsg <= 26722) { + final zone = epsg - 26700; + return '+proj=utm +zone=$zone +datum=NAD27 +units=m +no_defs'; + } + // NAD27 datum requires loading `nadgrids` for accurate transformation: + // cf https://github.com/proj4js/proj4js/pull/363 + // cf https://github.com/maRci002/proj4dart/issues/8 + if (epsg == 26746) { + // NAD27 / California zone VI + return '+proj=lcc +lat_1=33.88333333333333 +lat_2=32.78333333333333 +lat_0=32.16666666666666 +lon_0=-116.25 +x_0=609601.2192024384 +y_0=0 +datum=NAD27 +units=us-ft +no_defs'; + } else if (epsg == 26771) { + // NAD27 / Illinois East + return '+proj=tmerc +lat_0=36.66666666666666 +lon_0=-88.33333333333333 +k=0.9999749999999999 +x_0=152400.3048006096 +y_0=0 +datum=NAD27 +units=us-ft +no_defs'; + } + } else if ((26900 <= epsg && epsg <= 26999) || (32100 <= epsg && epsg <= 32199)) { + // US State Plane (NAD83): 269xx/321xx + if (epsg == 26966) { + // NAD83 Georgia East + return '+proj=tmerc +lat_0=30 +lon_0=-82.16666666666667 +k=0.9999 +x_0=200000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs'; + } + } else if (32200 <= epsg && epsg <= 32299) { + // WGS72 / UTM northern hemisphere: 322zz where zz is UTM zone number + final zone = epsg - 32200; + return '+proj=utm +zone=$zone +ellps=WGS72 +towgs84=0,0,4.5,0,0,0.554,0.2263 +units=m +no_defs'; + } else if (32300 <= epsg && epsg <= 32399) { + // WGS72 / UTM southern hemisphere: 323zz where zz is UTM zone number + final zone = epsg - 32300; + return '+proj=utm +zone=$zone +south +ellps=WGS72 +towgs84=0,0,4.5,0,0,0.554,0.2263 +units=m +no_defs'; + } else if (32400 <= epsg && epsg <= 32460) { + // WGS72BE / UTM northern hemisphere: 324zz where zz is UTM zone number + final zone = epsg - 32400; + return '+proj=utm +zone=$zone +ellps=WGS72 +towgs84=0,0,1.9,0,0,0.814,-0.38 +units=m +no_defs'; + } else if (32500 <= epsg && epsg <= 32599) { + // WGS72BE / UTM southern hemisphere: 325zz where zz is UTM zone number + final zone = epsg - 32500; + return '+proj=utm +zone=$zone +south +ellps=WGS72 +towgs84=0,0,1.9,0,0,0.814,-0.38 +units=m +no_defs'; + } else if (32600 <= epsg && epsg <= 32699) { + // WGS84 / UTM northern hemisphere: 326zz where zz is UTM zone number + final zone = epsg - 32600; + return '+proj=utm +zone=$zone +datum=WGS84 +units=m +no_defs'; + } else if (32700 <= epsg && epsg <= 32799) { + // WGS84 / UTM southern hemisphere: 327zz where zz is UTM zone number + final zone = epsg - 32700; + return '+proj=utm +zone=$zone +south +datum=WGS84 +units=m +no_defs'; + } + + return null; + } +} + +// cf https://www.maptiler.com/google-maps-coordinates-tile-bounds-projection/ +class MapServiceHelper { + final int tileSize; + late final double initialResolution, originShift; + + MapServiceHelper(this.tileSize) { + initialResolution = 2 * pi * 6378137 / tileSize; + originShift = 2 * pi * 6378137 / 2.0; + } + + int matrixSize(int zoomLevel) { + return 1 << zoomLevel; + } + + Point<double> pixelsToMeters(double px, double py, int zoomLevel) { + double res = resolution(zoomLevel); + double mx = px * res - originShift; + double my = -py * res + originShift; + return Point(mx, my); + } + + double resolution(int zoomLevel) { + return initialResolution / matrixSize(zoomLevel); + } + + Point<double> tileTopLeft(int tx, int ty, int zoomLevel) { + final px = tx * tileSize; + final py = ty * tileSize; + return pixelsToMeters(px.toDouble(), py.toDouble(), zoomLevel); + } +} diff --git a/plugins/aves_map/lib/src/interface.dart b/plugins/aves_map/lib/src/interface.dart new file mode 100644 index 0000000..3f2cc17 --- /dev/null +++ b/plugins/aves_map/lib/src/interface.dart @@ -0,0 +1,12 @@ +import 'package:aves_map/src/geo_entry.dart'; +import 'package:aves_map/src/marker/key.dart'; +import 'package:flutter/material.dart'; +import 'package:latlong2/latlong.dart'; + +typedef MarkerClusterBuilder<T> = Map<MarkerKey<T>, GeoEntry<T>> Function(); +typedef MarkerWidgetBuilder<T> = Widget Function(MarkerKey<T> key); +typedef MarkerImageReadyChecker<T> = bool Function(MarkerKey<T> key); +typedef UserZoomChangeCallback = void Function(double zoom); +typedef MapTapCallback = void Function(LatLng location); +typedef MarkerTapCallback<T> = void Function(GeoEntry<T> geoEntry); +typedef MarkerLongPressCallback<T> = void Function(GeoEntry<T> geoEntry, LatLng tapLocation); diff --git a/plugins/aves_map/lib/src/marker/arrow_painter.dart b/plugins/aves_map/lib/src/marker/arrow_painter.dart new file mode 100644 index 0000000..c38367f --- /dev/null +++ b/plugins/aves_map/lib/src/marker/arrow_painter.dart @@ -0,0 +1,44 @@ +import 'package:flutter/material.dart'; + +class MarkerArrowPainter extends CustomPainter { + final Color color, outlineColor; + final double outlineWidth; + final Size size; + + const MarkerArrowPainter({ + required this.color, + required this.outlineColor, + required this.outlineWidth, + required this.size, + }); + + @override + void paint(Canvas canvas, Size size) { + final triangleWidth = this.size.width; + final triangleHeight = this.size.height; + + final bottomCenter = Offset(size.width / 2, size.height); + final topLeft = bottomCenter + Offset(-triangleWidth / 2, -triangleHeight); + final topRight = bottomCenter + Offset(triangleWidth / 2, -triangleHeight); + + canvas.drawPath( + Path() + ..moveTo(bottomCenter.dx, bottomCenter.dy) + ..lineTo(topRight.dx, topRight.dy) + ..lineTo(topLeft.dx, topLeft.dy) + ..close(), + Paint()..color = outlineColor); + + canvas.translate(0, -outlineWidth.ceilToDouble()); + canvas.drawPath( + Path() + ..moveTo(bottomCenter.dx, bottomCenter.dy) + ..lineTo(topRight.dx, topRight.dy) + ..lineTo(topLeft.dx, topLeft.dy) + ..close(), + Paint()..color = color); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +} diff --git a/plugins/aves_map/lib/src/marker/dot.dart b/plugins/aves_map/lib/src/marker/dot.dart new file mode 100644 index 0000000..b43b81b --- /dev/null +++ b/plugins/aves_map/lib/src/marker/dot.dart @@ -0,0 +1,18 @@ +import 'package:aves_map/src/theme.dart'; +import 'package:aves_ui/aves_ui.dart'; +import 'package:flutter/material.dart'; + +class DotMarker extends StatelessWidget { + const DotMarker({super.key}); + + @override + Widget build(BuildContext context) { + return const AvesDot( + diameter: MapThemeData.markerDotDiameter, + outerBorderWidth: MapThemeData.markerOuterBorderWidth, + innerBorderWidth: MapThemeData.markerInnerBorderWidth, + getOuterBorderColor: MapThemeData.markerThemedOuterBorderColor, + getInnerBorderColor: MapThemeData.markerThemedInnerBorderColor, + ); + } +} diff --git a/plugins/aves_map/lib/src/marker/generator.dart b/plugins/aves_map/lib/src/marker/generator.dart new file mode 100644 index 0000000..ca536b3 --- /dev/null +++ b/plugins/aves_map/lib/src/marker/generator.dart @@ -0,0 +1,138 @@ +import 'dart:ui' as ui; + +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +// generate bitmap from widget, for Google map +class MarkerGeneratorWidget<T extends Key> extends StatefulWidget { + final List<Widget> markers; + final bool Function(T markerKey) isReadyToRender; + final void Function(T markerKey, Uint8List bitmap) onRendered; + + const MarkerGeneratorWidget({ + super.key, + required this.markers, + required this.isReadyToRender, + required this.onRendered, + }); + + @override + State<MarkerGeneratorWidget<T>> createState() => _MarkerGeneratorWidgetState<T>(); +} + +class _MarkerGeneratorWidgetState<T extends Key> extends State<MarkerGeneratorWidget<T>> { + final Set<_MarkerGeneratorItem<T>> _items = {}; + + @override + void initState() { + super.initState(); + _checkNextFrame(); + } + + @override + void didUpdateWidget(covariant MarkerGeneratorWidget<T> oldWidget) { + super.didUpdateWidget(oldWidget); + final devicePixelRatio = View.of(context).devicePixelRatio; + widget.markers.forEach((markerWidget) { + final item = _getOrCreate( + markerKey: markerWidget.key as T, + devicePixelRatio: devicePixelRatio, + ); + item.globalKey = GlobalKey(); + }); + _checkNextFrame(); + } + + void _checkNextFrame() { + WidgetsBinding.instance.addPostFrameCallback((_) async { + if (!mounted) return; + final waitingItems = _items.where((v) => v.isWaiting).toSet(); + final readyItems = waitingItems.where((v) => widget.isReadyToRender(v.markerKey)).toSet(); + readyItems.forEach((v) async { + final bitmap = await v.render(); + if (bitmap != null) { + widget.onRendered(v.markerKey, bitmap); + } + }); + if (readyItems.length < waitingItems.length) { + _checkNextFrame(); + setState(() {}); + } + }); + } + + @override + Widget build(BuildContext context) { + return Transform.translate( + offset: Offset(MediaQuery.sizeOf(context).width, 0), + child: Material( + type: MaterialType.transparency, + child: Stack( + children: _items.map((item) { + return RepaintBoundary( + key: item.globalKey, + child: widget.markers.firstWhereOrNull((v) => v.key == item.markerKey) ?? const SizedBox(), + ); + }).toList(), + ), + ), + ); + } + + _MarkerGeneratorItem _getOrCreate({ + required T markerKey, + required double devicePixelRatio, + }) { + final existingItem = _items.firstWhereOrNull((v) => v.markerKey == markerKey); + if (existingItem != null) return existingItem; + + final newItem = _MarkerGeneratorItem( + markerKey: markerKey, + devicePixelRatio: devicePixelRatio, + ); + _items.add(newItem); + return newItem; + } +} + +enum MarkerGeneratorItemState { waiting, rendering, done } + +class _MarkerGeneratorItem<T extends Key> { + final T markerKey; + final double devicePixelRatio; + GlobalKey? globalKey; + MarkerGeneratorItemState state = MarkerGeneratorItemState.waiting; + + _MarkerGeneratorItem({ + required this.markerKey, + required this.devicePixelRatio, + }); + + bool get isWaiting => state == MarkerGeneratorItemState.waiting; + + Future<Uint8List?> render() async { + Uint8List? bytes; + final _globalKey = globalKey; + if (_globalKey != null) { + state = MarkerGeneratorItemState.rendering; + final boundary = _globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary; + if (boundary.hasSize && boundary.size != Size.zero) { + try { + final image = await boundary.toImage(pixelRatio: devicePixelRatio); + final byteData = await image.toByteData(format: ui.ImageByteFormat.png); + bytes = byteData?.buffer.asUint8List(); + } catch (error) { + // happens when widget is offscreen + debugPrint('failed to render image for key=$_globalKey with error=$error'); + } + } + state = bytes != null ? MarkerGeneratorItemState.done : MarkerGeneratorItemState.waiting; + } + return bytes; + } + + @override + String toString() => '$runtimeType#${shortHash(this)}{markerKey=$markerKey, globalKey=$globalKey, state=$state}'; +} diff --git a/plugins/aves_map/lib/src/marker/image.dart b/plugins/aves_map/lib/src/marker/image.dart new file mode 100644 index 0000000..58f0377 --- /dev/null +++ b/plugins/aves_map/lib/src/marker/image.dart @@ -0,0 +1,166 @@ +import 'package:aves_map/aves_map.dart'; +import 'package:aves_map/src/marker/arrow_painter.dart'; +import 'package:collection/collection.dart'; +import 'package:custom_rounded_rectangle_border/custom_rounded_rectangle_border.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:intl/intl.dart' as intl; +import 'package:latlong2/latlong.dart'; + +class ImageMarker extends StatelessWidget { + final int? count; + final intl.NumberFormat countFormatter; + final bool drawArrow; + final Widget Function(double extent) buildThumbnailImage; + + static const double outerBorderRadiusDim = 8; + static const outerBorderWidth = MapThemeData.markerOuterBorderWidth; + static const innerBorderWidth = MapThemeData.markerInnerBorderWidth; + static const extent = MapThemeData.markerImageExtent; + static const arrowSize = MapThemeData.markerArrowSize; + static const outerBorderRadius = BorderRadius.all(Radius.circular(outerBorderRadiusDim)); + static const innerRadius = Radius.circular(outerBorderRadiusDim - outerBorderWidth); + static const innerBorderRadius = BorderRadius.all(innerRadius); + + ImageMarker({ + super.key, + required this.count, + required String? locale, + this.drawArrow = true, + required this.buildThumbnailImage, + }) : countFormatter = intl.NumberFormat.decimalPattern(locale); + + @override + Widget build(BuildContext context) { + Widget child = buildThumbnailImage(extent); + + // need to be sized for the Google map marker generator + child = SizedBox( + width: extent, + height: extent, + child: child, + ); + + final theme = Theme.of(context); + final isDark = theme.brightness == Brightness.dark; + final outerBorderColor = MapThemeData.markerThemedOuterBorderColor(isDark); + final innerBorderColor = MapThemeData.markerThemedInnerBorderColor(isDark); + + final outerDecoration = BoxDecoration( + border: Border.fromBorderSide(BorderSide( + color: outerBorderColor, + width: outerBorderWidth, + )), + borderRadius: outerBorderRadius, + ); + + final innerDecoration = BoxDecoration( + border: Border.fromBorderSide(BorderSide( + color: innerBorderColor, + width: innerBorderWidth, + )), + borderRadius: innerBorderRadius, + ); + + child = DecoratedBox( + decoration: innerDecoration, + position: DecorationPosition.foreground, + child: ClipRRect( + borderRadius: innerBorderRadius, + child: child, + ), + ); + + if (count != null) { + final borderSide = BorderSide( + color: innerBorderColor, + width: innerBorderWidth, + ); + child = Stack( + children: [ + child, + Container( + padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 2), + decoration: ShapeDecoration( + color: theme.colorScheme.primary, + shape: _buildCornerDetailShape(context, borderSide), + ), + child: Text( + countFormatter.format(count), + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.onPrimary, + ), + ), + ), + ], + ); + } + + child = Container( + decoration: outerDecoration, + child: child, + ); + + if (drawArrow) { + child = CustomPaint( + foregroundPainter: MarkerArrowPainter( + color: innerBorderColor, + outlineColor: outerBorderColor, + outlineWidth: outerBorderWidth, + size: arrowSize, + ), + child: Padding( + padding: EdgeInsets.only(bottom: arrowSize.height), + child: child, + ), + ); + } + + return child; + } + + ShapeBorder _buildCornerDetailShape(BuildContext context, BorderSide side) { + final isRtl = Directionality.of(context) == TextDirection.rtl; + return CustomRoundedRectangleBorder( + leftSide: side, + rightSide: side, + topSide: side, + bottomSide: side, + topLeftCornerSide: isRtl ? null : side, + topRightCornerSide: isRtl ? side : null, + bottomLeftCornerSide: isRtl ? side : null, + bottomRightCornerSide: isRtl ? null : side, + borderRadius: BorderRadius.only( + topLeft: isRtl ? Radius.zero : innerRadius, + topRight: isRtl ? innerRadius : Radius.zero, + bottomLeft: isRtl ? innerRadius : Radius.zero, + bottomRight: isRtl ? Radius.zero : innerRadius, + ), + ); + } + + static const _crs = Epsg3857(); + + static GeoEntry<T>? markerMatch<T>(LatLng position, double zoom, Set<GeoEntry<T>> markers) { + final pressOffset = _crs.latLngToOffset(position, zoom); + + const double markerWidth = extent; + const double markerHeight = extent; + + return markers.firstWhereOrNull((marker) { + final latitude = marker.latitude; + final longitude = marker.longitude; + if (latitude == null || longitude == null) return false; + + final markerAnchorPoint = _crs.latLngToOffset(LatLng(latitude, longitude), zoom); + final bottom = markerAnchorPoint.dy; + final top = bottom - markerHeight; + final left = markerAnchorPoint.dx - markerWidth / 2; + final right = left + markerWidth; + final markerRect = Rect.fromLTRB(left, top, right, bottom); + + return markerRect.contains(pressOffset); + }); + } +} diff --git a/plugins/aves_map/lib/src/marker/key.dart b/plugins/aves_map/lib/src/marker/key.dart new file mode 100644 index 0000000..188ec01 --- /dev/null +++ b/plugins/aves_map/lib/src/marker/key.dart @@ -0,0 +1,13 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter/material.dart'; + +@immutable +class MarkerKey<T> extends LocalKey with EquatableMixin { + final T entry; + final int? count; + + @override + List<Object?> get props => [entry, count]; + + const MarkerKey(this.entry, this.count); +} diff --git a/plugins/aves_map/lib/src/overlay/overlay.dart b/plugins/aves_map/lib/src/overlay/overlay.dart new file mode 100644 index 0000000..6fafa66 --- /dev/null +++ b/plugins/aves_map/lib/src/overlay/overlay.dart @@ -0,0 +1,17 @@ +import 'package:aves_map/src/overlay/tile.dart'; +import 'package:flutter/painting.dart'; +import 'package:latlong2/latlong.dart'; + +mixin MapOverlay { + String get id; + + bool get canOverlay; + + LatLng? get topLeft; + + LatLng? get bottomRight; + + ImageProvider get imageProvider; + + Future<MapTile?> getTile(int tx, int ty, int? zoomLevel); +} diff --git a/plugins/aves_map/lib/src/overlay/tile.dart b/plugins/aves_map/lib/src/overlay/tile.dart new file mode 100644 index 0000000..cc5e5a0 --- /dev/null +++ b/plugins/aves_map/lib/src/overlay/tile.dart @@ -0,0 +1,13 @@ +import 'package:flutter/foundation.dart'; + +@immutable +class MapTile { + final int width, height; + final Uint8List data; + + const MapTile({ + required this.width, + required this.height, + required this.data, + }); +} diff --git a/plugins/aves_map/lib/src/style.dart b/plugins/aves_map/lib/src/style.dart new file mode 100644 index 0000000..b0d0066 --- /dev/null +++ b/plugins/aves_map/lib/src/style.dart @@ -0,0 +1,134 @@ +import 'dart:convert'; + +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; + +// OSM raster tile providers: https://wiki.openstreetmap.org/wiki/Raster_tile_providers +// OSM vector tile providers: https://wiki.openstreetmap.org/wiki/Vector_tiles#Providers +// Leaflet providers preview: https://leaflet-extras.github.io/leaflet-providers/preview/ +// OpenMapTiles styles: https://openmaptiles.org/styles/ +// Examples: https://github.com/deckerst/aves/wiki/Custom-maps +class EntryMapStyle extends Equatable { + final String key; + final String? name; + final bool isRaster; + final String? url; // not strictly a `Uri` as it may contain templates like `{x}` + final List<String> subdomains; + final String? userAgent; + final bool needMobileService; + final bool isHeavy; + + @override + List<Object?> get props => [key, name, isRaster, url]; + + const EntryMapStyle({ + required this.key, + this.name, + this.isRaster = true, + this.url, + List<String>? subdomains, + this.userAgent, + this.needMobileService = false, + this.isHeavy = false, + }) : subdomains = subdomains ?? const ['a', 'b', 'c']; + + static EntryMapStyle? fromJson(String? jsonString) { + if (jsonString == null || jsonString.isEmpty) return null; + + try { + final jsonMap = jsonDecode(jsonString); + if (jsonMap is Map<String, dynamic>) { + return _fromMap(jsonMap); + } + debugPrint('failed to parse style from json=$jsonString'); + } catch (error) { + // no need for stack + debugPrint('failed to parse style from json=$jsonString error=$error'); + } + return null; + } + + String toJson() => jsonEncode(_toMap()); + + static EntryMapStyle _fromMap(Map<String, dynamic> jsonMap) { + return EntryMapStyle( + key: jsonMap['key'], + name: jsonMap['name'], + isRaster: jsonMap['isRaster'], + url: jsonMap['url'], + subdomains: (jsonMap['subdomains'] as List<dynamic>?)?.cast<String>(), + userAgent: jsonMap['userAgent'], + needMobileService: jsonMap['needMobileService'], + isHeavy: jsonMap['isHeavy'], + ); + } + + Map<String, dynamic> _toMap() { + return { + 'key': key, + 'name': name, + 'isRaster': isRaster, + 'url': url, + 'subdomains': subdomains, + 'userAgent': userAgent, + 'needMobileService': needMobileService, + 'isHeavy': isHeavy, + }; + } +} + +class EntryMapStyles { + // Google + + static const googleNormal = EntryMapStyle( + key: 'googleNormal', + needMobileService: true, + isHeavy: true, + ); + + static const googleHybrid = EntryMapStyle( + key: 'googleHybrid', + needMobileService: true, + isHeavy: true, + ); + + static const googleTerrain = EntryMapStyle( + key: 'googleTerrain', + needMobileService: true, + isHeavy: true, + ); + + // Vector (OpenMapTiles) + + static const osmLiberty = EntryMapStyle( + key: 'osmLiberty', + isRaster: false, + ); + + // Raster (Leaflet) + + static const openTopoMap = EntryMapStyle( + key: 'openTopoMap', + url: 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', + ); + + static const osmHot = EntryMapStyle( + key: 'osmHot', + url: 'https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', + ); + + static const stamenWatercolor = EntryMapStyle( + key: 'stamenWatercolor', + url: 'https://watercolormaps.collection.cooperhewitt.org/tile/watercolor/{z}/{x}/{y}.jpg', + ); + + // default styles that do not need mobile services + static List<EntryMapStyle> baseStyles = [ + // Vector (OpenMapTiles) + osmLiberty, + // Raster (Leaflet) + openTopoMap, + osmHot, + stamenWatercolor, + ]; +} diff --git a/plugins/aves_map/lib/src/theme.dart b/plugins/aves_map/lib/src/theme.dart new file mode 100644 index 0000000..521d94d --- /dev/null +++ b/plugins/aves_map/lib/src/theme.dart @@ -0,0 +1,33 @@ +import 'package:flutter/material.dart'; + +enum MapNavigationButton { back, close, map, none } + +class MapThemeData { + final bool interactive, showCoordinateFilter; + final MapNavigationButton navigationButton; + final Animation<double> scale; + final VisualDensity visualDensity; + final double? mapHeight; + final EdgeInsets attributionPadding; + + const MapThemeData({ + required this.interactive, + required this.showCoordinateFilter, + required this.navigationButton, + required this.scale, + required this.visualDensity, + required this.mapHeight, + required this.attributionPadding, + }); + + static const double markerOuterBorderWidth = 1.5; + static const double markerInnerBorderWidth = 2; + static const double markerImageExtent = 48.0; + static const Size markerArrowSize = Size(8, 6); + static const double markerDotDiameter = 16; + static const int trackWidth = 5; + + static Color markerThemedOuterBorderColor(bool isDark) => isDark ? Colors.white30 : Colors.black26; + + static Color markerThemedInnerBorderColor(bool isDark) => isDark ? const Color(0xFF212121) : Colors.white; +} diff --git a/plugins/aves_map/lib/src/zoomed_bounds.dart b/plugins/aves_map/lib/src/zoomed_bounds.dart new file mode 100644 index 0000000..3c709bd --- /dev/null +++ b/plugins/aves_map/lib/src/zoomed_bounds.dart @@ -0,0 +1,105 @@ +import 'dart:math'; +import 'dart:ui'; + +import 'package:aves_map/src/geo_utils.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:latlong2/latlong.dart'; + +@immutable +class ZoomedBounds extends Equatable { + final LatLng sw, ne; + final double zoom, rotation; + + // returns [southwestLng, southwestLat, northeastLng, northeastLat], as expected by Fluster + List<double> get boundingBox => [sw.longitude, sw.latitude, ne.longitude, ne.latitude]; + + // Map services (Google Maps, OpenStreetMap) use the spherical Mercator projection (EPSG 3857). + static const _crs = Epsg3857(); + + // The projected center appears visually in the middle of the bounds. + LatLng get projectedCenter { + final swPoint = _crs.latLngToOffset(sw, zoom); + final nePoint = _crs.latLngToOffset(ne, zoom); + // assume no padding around bounds + return _crs.offsetToLatLng((swPoint + nePoint) / 2, zoom); + } + + @override + List<Object?> get props => [sw, ne, zoom, rotation]; + + const ZoomedBounds({ + required this.sw, + required this.ne, + required this.zoom, + required this.rotation, + }); + + static const _collocationMaxDeltaThreshold = 360 / (2 << 19); + + factory ZoomedBounds.fromPoints({ + required Set<LatLng> points, + double collocationZoom = 20, + }) { + var west = .0, south = .0, east = .0, north = .0; + var zoom = collocationZoom; + + if (points.isNotEmpty) { + final first = points.first; + west = first.longitude; + south = first.latitude; + east = first.longitude; + north = first.latitude; + + for (var point in points) { + final lng = point.longitude; + final lat = point.latitude; + if (lng < west) west = lng; + if (lat < south) south = lat; + if (lng > east) east = lng; + if (lat > north) north = lat; + } + + final boundsDelta = max(north - south, east - west); + if (boundsDelta > _collocationMaxDeltaThreshold) { + zoom = max(1, log(360) / ln2 - log(boundsDelta) / ln2); + } + } + return ZoomedBounds( + sw: LatLng(south, west), + ne: LatLng(north, east), + zoom: zoom, + rotation: 0, + ); + } + + ZoomedBounds copyWith({ + LatLng? sw, + LatLng? ne, + double? zoom, + double? rotation, + }) { + return ZoomedBounds( + sw: sw ?? this.sw, + ne: ne ?? this.ne, + zoom: zoom ?? this.zoom, + rotation: rotation ?? this.rotation, + ); + } + + bool contains(LatLng location) => GeoUtils.contains(sw, ne, location); + + Size toDisplaySize() { + final swPoint = _crs.latLngToOffset(sw, zoom); + final nePoint = _crs.latLngToOffset(ne, zoom); + return Size((swPoint.dx - nePoint.dx).abs(), (swPoint.dy - nePoint.dy).abs()); + } + + Offset offset(LatLng location) { + final swPoint = _crs.latLngToOffset(sw, zoom); + final nePoint = _crs.latLngToOffset(ne, zoom); + final point = _crs.latLngToOffset(location, zoom); + return Offset(point.dx - swPoint.dx, point.dy - nePoint.dy); + } +} diff --git a/plugins/aves_map/pubspec.yaml b/plugins/aves_map/pubspec.yaml new file mode 100644 index 0000000..e8a54ad --- /dev/null +++ b/plugins/aves_map/pubspec.yaml @@ -0,0 +1,27 @@ +name: aves_map +version: 0.0.1 +publish_to: none + +environment: + sdk: ">=3.6.0 <4.0.0" # incoherent dartfmt from 3.7.0 +resolution: workspace + +dependencies: + flutter: + sdk: flutter + aves_ui: + path: ../aves_ui + collection: + custom_rounded_rectangle_border: + equatable: + fluster: + flutter_map: + intl: + latlong2: + leak_tracker: + provider: + +dev_dependencies: + flutter_lints: + +flutter: diff --git a/plugins/aves_model/.gitignore b/plugins/aves_model/.gitignore new file mode 100644 index 0000000..79c113f --- /dev/null +++ b/plugins/aves_model/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/plugins/aves_model/.metadata b/plugins/aves_model/.metadata new file mode 100644 index 0000000..ad910f5 --- /dev/null +++ b/plugins/aves_model/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: 2ad6cd72c040113b47ee9055e722606a490ef0da + channel: stable + +project_type: package diff --git a/plugins/aves_model/analysis_options.yaml b/plugins/aves_model/analysis_options.yaml new file mode 100644 index 0000000..f04c6cf --- /dev/null +++ b/plugins/aves_model/analysis_options.yaml @@ -0,0 +1 @@ +include: ../../analysis_options.yaml diff --git a/plugins/aves_model/lib/aves_model.dart b/plugins/aves_model/lib/aves_model.dart new file mode 100644 index 0000000..5ed3e68 --- /dev/null +++ b/plugins/aves_model/lib/aves_model.dart @@ -0,0 +1,29 @@ +export 'src/actions/chip.dart'; +export 'src/actions/chip_set.dart'; +export 'src/actions/entry.dart'; +export 'src/actions/entry_set.dart'; +export 'src/actions/explorer.dart'; +export 'src/actions/map.dart'; +export 'src/actions/map_cluster.dart'; +export 'src/actions/move_type.dart'; +export 'src/actions/settings.dart'; +export 'src/actions/share.dart'; +export 'src/actions/slideshow.dart'; +export 'src/editor/enums.dart'; +export 'src/entry/base.dart'; +export 'src/events/actions.dart'; +export 'src/metadata/enums.dart'; +export 'src/metadata/fields.dart'; +export 'src/settings/access.dart'; +export 'src/settings/enums.dart'; +export 'src/settings/event.dart'; +export 'src/settings/keys.dart'; +export 'src/settings/store.dart'; +export 'src/source/album.dart'; +export 'src/source/enums.dart'; +export 'src/source/vault.dart'; +export 'src/storage/relative_dir.dart'; +export 'src/storage/volume.dart'; +export 'src/video/keys.dart'; +export 'src/video/stream_types.dart'; +export 'src/wallpaper_target.dart'; diff --git a/plugins/aves_model/lib/src/actions/chip.dart b/plugins/aves_model/lib/src/actions/chip.dart new file mode 100644 index 0000000..b2b119c --- /dev/null +++ b/plugins/aves_model/lib/src/actions/chip.dart @@ -0,0 +1,13 @@ +enum ChipAction { + goToAlbumPage, + goToCountryPage, + goToPlacePage, + goToTagPage, + goToExplorerPage, + ratingOrGreater, + ratingOrLower, + decompose, + reverse, + hide, + lockVault, +} diff --git a/plugins/aves_model/lib/src/actions/chip_set.dart b/plugins/aves_model/lib/src/actions/chip_set.dart new file mode 100644 index 0000000..13db2f8 --- /dev/null +++ b/plugins/aves_model/lib/src/actions/chip_set.dart @@ -0,0 +1,74 @@ +enum ChipSetAction { + // general + configureView, + select, + selectAll, + selectNone, + // browsing + search, + toggleTitleSearch, + createGroup, + createAlbum, + createVault, + // browsing or selecting + map, + slideshow, + stats, + // selecting (single/multiple filters) + delete, + remove, + hide, + pin, + unpin, + group, + lockVault, + showCountryStates, + showCollection, + // selecting (single filter) + rename, + setCover, + configureVault, +} + +class ChipSetActions { + static const general = [ + ChipSetAction.configureView, + ChipSetAction.select, + ChipSetAction.selectAll, + ChipSetAction.selectNone, + ]; + + // `null` items are converted to dividers + static const browsing = [ + ChipSetAction.search, + ChipSetAction.toggleTitleSearch, + null, + ChipSetAction.map, + ChipSetAction.slideshow, + ChipSetAction.stats, + null, + ChipSetAction.createAlbum, + ChipSetAction.createVault, + ]; + + // `null` items are converted to dividers + static const selection = [ + ChipSetAction.setCover, + ChipSetAction.pin, + ChipSetAction.unpin, + ChipSetAction.delete, + ChipSetAction.remove, + ChipSetAction.rename, + ChipSetAction.showCountryStates, + ChipSetAction.hide, + ChipSetAction.group, + null, + ChipSetAction.showCollection, + ChipSetAction.map, + ChipSetAction.slideshow, + ChipSetAction.stats, + null, + ChipSetAction.configureVault, + ChipSetAction.lockVault, + ]; +} diff --git a/plugins/aves_model/lib/src/actions/entry.dart b/plugins/aves_model/lib/src/actions/entry.dart new file mode 100644 index 0000000..02becf1 --- /dev/null +++ b/plugins/aves_model/lib/src/actions/entry.dart @@ -0,0 +1,148 @@ +enum EntryAction { + info, + addShortcut, + copyToClipboard, + delete, + restore, + convert, + print, + rename, + copy, + move, + share, + toggleFavourite, + // raster + rotateCCW, + rotateCW, + flip, + // vector + viewSource, + // video + lockViewer, + videoCaptureFrame, + videoSelectStreams, + videoSetSpeed, + videoABRepeat, + videoToggleMute, + videoSettings, + videoTogglePlay, + videoReplay10, + videoSkip10, + videoShowPreviousFrame, + videoShowNextFrame, + // external + edit, + open, + openVideoPlayer, + openMap, + setAs, + cast, + // platform + rotateScreen, + // metadata + editDate, + editLocation, + editTitleDescription, + editRating, + editTags, + removeMetadata, + exportMetadata, + // metadata / GeoTIFF + showGeoTiffOnMap, + // metadata / motion photo + convertMotionPhotoToStillImage, + viewMotionPhotoVideo, + // debug + debug, +} + +class EntryActions { + static const topLevel = [ + EntryAction.info, + EntryAction.share, + EntryAction.edit, + EntryAction.rename, + EntryAction.delete, + EntryAction.copy, + EntryAction.move, + EntryAction.toggleFavourite, + EntryAction.rotateScreen, + EntryAction.viewSource, + ]; + + static const export = [ + ...exportInternal, + ...exportExternal, + ]; + + static const exportInternal = [ + EntryAction.convert, + EntryAction.addShortcut, + EntryAction.copyToClipboard, + EntryAction.print, + ]; + + static const exportExternal = [ + EntryAction.open, + EntryAction.openMap, + EntryAction.setAs, + EntryAction.cast, + ]; + + static const pageActions = { + EntryAction.videoCaptureFrame, + EntryAction.videoToggleMute, + EntryAction.videoSetSpeed, + EntryAction.videoABRepeat, + EntryAction.videoSelectStreams, + EntryAction.videoSettings, + ...videoPlayback, + ...orientationActions, + }; + + static const orientationActions = [ + EntryAction.rotateCCW, + EntryAction.rotateCW, + EntryAction.flip, + ]; + + static const trashed = [ + EntryAction.delete, + EntryAction.restore, + EntryAction.debug, + ]; + + static const video = [ + EntryAction.videoCaptureFrame, + EntryAction.videoToggleMute, + EntryAction.videoSetSpeed, + EntryAction.videoABRepeat, + EntryAction.videoSelectStreams, + EntryAction.videoSettings, + EntryAction.lockViewer, + ]; + + static const videoPlayback = [ + EntryAction.videoReplay10, + EntryAction.videoShowPreviousFrame, + EntryAction.videoTogglePlay, + EntryAction.videoShowNextFrame, + EntryAction.videoSkip10, + ]; + + static const commonMetadataActions = [ + EntryAction.editDate, + EntryAction.editLocation, + EntryAction.editTitleDescription, + EntryAction.editRating, + EntryAction.editTags, + EntryAction.removeMetadata, + EntryAction.exportMetadata, + ]; + + static const formatSpecificMetadataActions = [ + EntryAction.showGeoTiffOnMap, + EntryAction.convertMotionPhotoToStillImage, + EntryAction.viewMotionPhotoVideo, + ]; +} diff --git a/plugins/aves_model/lib/src/actions/entry_set.dart b/plugins/aves_model/lib/src/actions/entry_set.dart new file mode 100644 index 0000000..90bc1df --- /dev/null +++ b/plugins/aves_model/lib/src/actions/entry_set.dart @@ -0,0 +1,129 @@ +enum EntrySetAction { + // general + configureView, + select, + selectAll, + selectNone, + // browsing + searchCollection, + toggleTitleSearch, + addDynamicAlbum, + addShortcut, + setHome, + emptyBin, + // browsing or selecting + map, + slideshow, + stats, + rescan, + // selecting + share, + delete, + restore, + copy, + move, + rename, + convert, + toggleFavourite, + rotateCCW, + rotateCW, + flip, + editDate, + editLocation, + editTitleDescription, + editRating, + editTags, + removeMetadata, +} + +class EntrySetActions { + static const general = [ + EntrySetAction.configureView, + EntrySetAction.select, + EntrySetAction.selectAll, + EntrySetAction.selectNone, + ]; + + // `null` items are converted to dividers + static const pageBrowsing = [ + EntrySetAction.searchCollection, + EntrySetAction.toggleTitleSearch, + EntrySetAction.addDynamicAlbum, + EntrySetAction.addShortcut, + EntrySetAction.setHome, + null, + EntrySetAction.map, + EntrySetAction.slideshow, + EntrySetAction.stats, + null, + EntrySetAction.rescan, + EntrySetAction.emptyBin, + ]; + + // exclude bin related actions + static const collectionEditorBrowsing = [ + EntrySetAction.searchCollection, + EntrySetAction.toggleTitleSearch, + EntrySetAction.map, + EntrySetAction.slideshow, + EntrySetAction.stats, + // only available as a quick action + EntrySetAction.selectAll, + ]; + + // `null` items are converted to dividers + static const pageSelection = [ + EntrySetAction.share, + EntrySetAction.delete, + EntrySetAction.restore, + EntrySetAction.copy, + EntrySetAction.move, + EntrySetAction.rename, + EntrySetAction.convert, + EntrySetAction.toggleFavourite, + null, + EntrySetAction.map, + EntrySetAction.slideshow, + EntrySetAction.stats, + null, + EntrySetAction.rescan, + // editing actions are in their subsection + ]; + + // exclude bin related actions + static const collectionEditorSelectionRegular = [ + EntrySetAction.share, + EntrySetAction.delete, + EntrySetAction.copy, + EntrySetAction.move, + EntrySetAction.rename, + EntrySetAction.convert, + EntrySetAction.toggleFavourite, + EntrySetAction.map, + EntrySetAction.slideshow, + EntrySetAction.stats, + EntrySetAction.selectAll, + // editing actions are in their subsection + ]; + + static const collectionEditorSelectionEdit = [ + EntrySetAction.rotateCCW, + EntrySetAction.rotateCW, + EntrySetAction.flip, + EntrySetAction.editDate, + EntrySetAction.editLocation, + EntrySetAction.editTitleDescription, + EntrySetAction.editRating, + EntrySetAction.editTags, + EntrySetAction.removeMetadata, + ]; + + static const edit = [ + EntrySetAction.editDate, + EntrySetAction.editLocation, + EntrySetAction.editTitleDescription, + EntrySetAction.editRating, + EntrySetAction.editTags, + EntrySetAction.removeMetadata, + ]; +} diff --git a/plugins/aves_model/lib/src/actions/explorer.dart b/plugins/aves_model/lib/src/actions/explorer.dart new file mode 100644 index 0000000..58d595b --- /dev/null +++ b/plugins/aves_model/lib/src/actions/explorer.dart @@ -0,0 +1,6 @@ +enum ExplorerAction { + addShortcut, + setHome, + hide, + stats, +} diff --git a/plugins/aves_model/lib/src/actions/map.dart b/plugins/aves_model/lib/src/actions/map.dart new file mode 100644 index 0000000..1c71363 --- /dev/null +++ b/plugins/aves_model/lib/src/actions/map.dart @@ -0,0 +1,9 @@ +enum MapAction { + // any map panel + selectStyle, + openMapApp, + zoomIn, + zoomOut, + // full page only + addShortcut, +} diff --git a/plugins/aves_model/lib/src/actions/map_cluster.dart b/plugins/aves_model/lib/src/actions/map_cluster.dart new file mode 100644 index 0000000..d022934 --- /dev/null +++ b/plugins/aves_model/lib/src/actions/map_cluster.dart @@ -0,0 +1,4 @@ +enum MapClusterAction { + editLocation, + removeLocation, +} diff --git a/plugins/aves_model/lib/src/actions/move_type.dart b/plugins/aves_model/lib/src/actions/move_type.dart new file mode 100644 index 0000000..7c362b0 --- /dev/null +++ b/plugins/aves_model/lib/src/actions/move_type.dart @@ -0,0 +1,7 @@ +enum MoveType { + copy, + move, + export, + toBin, + fromBin, +} diff --git a/plugins/aves_model/lib/src/actions/settings.dart b/plugins/aves_model/lib/src/actions/settings.dart new file mode 100644 index 0000000..77e5a55 --- /dev/null +++ b/plugins/aves_model/lib/src/actions/settings.dart @@ -0,0 +1,4 @@ +enum SettingsAction { + export, + import, +} diff --git a/plugins/aves_model/lib/src/actions/share.dart b/plugins/aves_model/lib/src/actions/share.dart new file mode 100644 index 0000000..3be6fb6 --- /dev/null +++ b/plugins/aves_model/lib/src/actions/share.dart @@ -0,0 +1,4 @@ +enum ShareAction { + imageOnly, + videoOnly, +} diff --git a/plugins/aves_model/lib/src/actions/slideshow.dart b/plugins/aves_model/lib/src/actions/slideshow.dart new file mode 100644 index 0000000..a4f7825 --- /dev/null +++ b/plugins/aves_model/lib/src/actions/slideshow.dart @@ -0,0 +1,6 @@ +enum SlideshowAction { + resume, + showInCollection, + cast, + settings, +} diff --git a/plugins/aves_model/lib/src/editor/enums.dart b/plugins/aves_model/lib/src/editor/enums.dart new file mode 100644 index 0000000..7d03820 --- /dev/null +++ b/plugins/aves_model/lib/src/editor/enums.dart @@ -0,0 +1,66 @@ +enum EditorAction { transform } + +enum CropAspectRatio { free, original, square, ar_16_9, ar_4_3 } + +enum TransformActivity { none, pan, resize, straighten } + +enum TransformOrientation { normal, rotate90, rotate180, rotate270, transverse, flipVertical, transpose, flipHorizontal } + +extension ExtraTransformOrientation on TransformOrientation { + TransformOrientation flipHorizontally() { + switch (this) { + case TransformOrientation.normal: + return TransformOrientation.flipHorizontal; + case TransformOrientation.rotate90: + return TransformOrientation.transverse; + case TransformOrientation.rotate180: + return TransformOrientation.flipVertical; + case TransformOrientation.rotate270: + return TransformOrientation.transpose; + case TransformOrientation.transverse: + return TransformOrientation.rotate90; + case TransformOrientation.flipVertical: + return TransformOrientation.rotate180; + case TransformOrientation.transpose: + return TransformOrientation.rotate270; + case TransformOrientation.flipHorizontal: + return TransformOrientation.normal; + } + } + + bool get isFlipped { + switch (this) { + case TransformOrientation.normal: + case TransformOrientation.rotate90: + case TransformOrientation.rotate180: + case TransformOrientation.rotate270: + return false; + case TransformOrientation.transverse: + case TransformOrientation.flipVertical: + case TransformOrientation.transpose: + case TransformOrientation.flipHorizontal: + return true; + } + } + + TransformOrientation rotateClockwise() { + switch (this) { + case TransformOrientation.normal: + return TransformOrientation.rotate90; + case TransformOrientation.rotate90: + return TransformOrientation.rotate180; + case TransformOrientation.rotate180: + return TransformOrientation.rotate270; + case TransformOrientation.rotate270: + return TransformOrientation.normal; + case TransformOrientation.transverse: + return TransformOrientation.flipHorizontal; + case TransformOrientation.flipVertical: + return TransformOrientation.transverse; + case TransformOrientation.transpose: + return TransformOrientation.flipVertical; + case TransformOrientation.flipHorizontal: + return TransformOrientation.transpose; + } + } +} diff --git a/plugins/aves_model/lib/src/entry/base.dart b/plugins/aves_model/lib/src/entry/base.dart new file mode 100644 index 0000000..6d97bcf --- /dev/null +++ b/plugins/aves_model/lib/src/entry/base.dart @@ -0,0 +1,31 @@ +import 'dart:ui'; + +import 'package:flutter/foundation.dart'; + +mixin AvesEntryBase { + int get id; + + String get uri; + + int? get pageId; + + String get mimeType; + + String? get path; + + String? get bestTitle; + + int? get sizeBytes; + + int? get durationMillis; + + bool get isAnimated; + + int get rotationDegrees; + + Size get displaySize; + + double get displayAspectRatio; + + Listenable get visualChangeNotifier; +} diff --git a/plugins/aves_model/lib/src/events/actions.dart b/plugins/aves_model/lib/src/events/actions.dart new file mode 100644 index 0000000..8a82b1e --- /dev/null +++ b/plugins/aves_model/lib/src/events/actions.dart @@ -0,0 +1,22 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; + +@immutable +class ActionEvent<T> extends Equatable { + final T action; + + @override + List<Object?> get props => [action]; + + const ActionEvent(this.action); +} + +@immutable +class ActionStartedEvent<T> extends ActionEvent<T> { + const ActionStartedEvent(super.action); +} + +@immutable +class ActionEndedEvent<T> extends ActionEvent<T> { + const ActionEndedEvent(super.action); +} diff --git a/plugins/aves_model/lib/src/metadata/enums.dart b/plugins/aves_model/lib/src/metadata/enums.dart new file mode 100644 index 0000000..2137d44 --- /dev/null +++ b/plugins/aves_model/lib/src/metadata/enums.dart @@ -0,0 +1,75 @@ +enum DateEditAction { + setCustom, + copyField, + copyItem, + extractFromTitle, + shift, + remove, +} + +enum DateFieldSource { + fileModifiedDate, + exifDate, + exifDateOriginal, + exifDateDigitized, + exifGpsDate, +} + +enum EntryConvertAction { convert, convertMotionPhotoToStillImage } + +enum LengthUnit { px, percent } + +enum LocationEditAction { + chooseOnMap, + copyItem, + setCustom, + importGpx, + remove, +} + +enum MetadataType { + // JPEG COM marker or GIF comment + comment, + // Exif: https://en.wikipedia.org/wiki/Exif + exif, + // ICC profile: https://en.wikipedia.org/wiki/ICC_profile + iccProfile, + // IPTC: https://en.wikipedia.org/wiki/IPTC_Information_Interchange_Model + iptc, + // JPEG APP0 / JFIF: https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format + jfif, + // JPEG APP14 / Adobe: https://www.exiftool.org/TagNames/JPEG.html#Adobe + jpegAdobe, + // JPEG APP12 / Ducky: https://www.exiftool.org/TagNames/APP12.html#Ducky + jpegDucky, + // ISO User Data box content, etc. + mp4, + // Photoshop IRB: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ + photoshopIrb, + // XMP: https://en.wikipedia.org/wiki/Extensible_Metadata_Platform + xmp, + // others (hash, etc.) + file, +} + +class MetadataTypes { + static const main = { + MetadataType.exif, + MetadataType.xmp, + }; + + static const common = { + MetadataType.exif, + MetadataType.xmp, + MetadataType.comment, + MetadataType.iccProfile, + MetadataType.iptc, + MetadataType.photoshopIrb, + }; + + static const jpeg = { + MetadataType.jfif, + MetadataType.jpegAdobe, + MetadataType.jpegDucky, + }; +} diff --git a/plugins/aves_model/lib/src/metadata/fields.dart b/plugins/aves_model/lib/src/metadata/fields.dart new file mode 100644 index 0000000..0f5c0f5 --- /dev/null +++ b/plugins/aves_model/lib/src/metadata/fields.dart @@ -0,0 +1,97 @@ +enum MetadataSyntheticField { + aperture, + description, + exposureTime, + focalLength, + iso, +} + +enum MetadataField { + // exif + exifDate, + exifDateOriginal, + exifDateDigitized, + exifGpsAltitude, + exifGpsAltitudeRef, + exifGpsAreaInformation, + exifGpsDatestamp, + exifGpsDestBearing, + exifGpsDestBearingRef, + exifGpsDestDistance, + exifGpsDestDistanceRef, + exifGpsDestLatitude, + exifGpsDestLatitudeRef, + exifGpsDestLongitude, + exifGpsDestLongitudeRef, + exifGpsDifferential, + exifGpsDOP, + exifGpsHPositioningError, + exifGpsImgDirection, + exifGpsImgDirectionRef, + exifGpsLatitude, + exifGpsLatitudeRef, + exifGpsLongitude, + exifGpsLongitudeRef, + exifGpsMapDatum, + exifGpsMeasureMode, + exifGpsProcessingMethod, + exifGpsSatellites, + exifGpsSpeed, + exifGpsSpeedRef, + exifGpsStatus, + exifGpsTimestamp, + exifGpsTrack, + exifGpsTrackRef, + exifGpsVersionId, + exifImageDescription, + exifMake, + exifModel, + exifUserComment, + // mp4 + mp4GpsCoordinates, + mp4RotationDegrees, + mp4Xmp, + // xmp + xmpXmpCreateDate, + // file + hashMd5, + hashSha1, + hashSha256, +} + +class MetadataFields { + static const Set<MetadataField> exifGpsFields = { + MetadataField.exifGpsAltitude, + MetadataField.exifGpsAltitudeRef, + MetadataField.exifGpsAreaInformation, + MetadataField.exifGpsDatestamp, + MetadataField.exifGpsDestBearing, + MetadataField.exifGpsDestBearingRef, + MetadataField.exifGpsDestDistance, + MetadataField.exifGpsDestDistanceRef, + MetadataField.exifGpsDestLatitude, + MetadataField.exifGpsDestLatitudeRef, + MetadataField.exifGpsDestLongitude, + MetadataField.exifGpsDestLongitudeRef, + MetadataField.exifGpsDifferential, + MetadataField.exifGpsDOP, + MetadataField.exifGpsHPositioningError, + MetadataField.exifGpsImgDirection, + MetadataField.exifGpsImgDirectionRef, + MetadataField.exifGpsLatitude, + MetadataField.exifGpsLatitudeRef, + MetadataField.exifGpsLongitude, + MetadataField.exifGpsLongitudeRef, + MetadataField.exifGpsMapDatum, + MetadataField.exifGpsMeasureMode, + MetadataField.exifGpsProcessingMethod, + MetadataField.exifGpsSatellites, + MetadataField.exifGpsSpeed, + MetadataField.exifGpsSpeedRef, + MetadataField.exifGpsStatus, + MetadataField.exifGpsTimestamp, + MetadataField.exifGpsTrack, + MetadataField.exifGpsTrackRef, + MetadataField.exifGpsVersionId, + }; +} diff --git a/plugins/aves_model/lib/src/settings/access.dart b/plugins/aves_model/lib/src/settings/access.dart new file mode 100644 index 0000000..c87fe22 --- /dev/null +++ b/plugins/aves_model/lib/src/settings/access.dart @@ -0,0 +1,105 @@ +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; + +mixin SettingsAccess { + bool get initialized; + + SettingsStore get store; + + Stream<SettingsChangedEvent> get updateStream; + + void notifyKeyChange(String key, dynamic oldValue, dynamic newValue); + + void notifyListeners(); + + void set(String key, dynamic newValue) { + var oldValue = store.get(key); + if (newValue == null) { + store.remove(key); + } else if (newValue is String) { + oldValue = getString(key); + store.setString(key, newValue); + } else if (newValue is List<String>) { + oldValue = getStringList(key); + store.setStringList(key, newValue); + } else if (newValue is int) { + oldValue = getInt(key); + store.setInt(key, newValue); + } else if (newValue is double) { + oldValue = getDouble(key); + store.setDouble(key, newValue); + } else if (newValue is bool) { + oldValue = getBool(key); + store.setBool(key, newValue); + } + if (oldValue != newValue) { + notifyKeyChange(key, oldValue, newValue); + notifyListeners(); + } + } + + // getters + + bool? getBool(String key) { + try { + return store.getBool(key); + } catch (error) { + // ignore, could be obsolete value of different type + return null; + } + } + + int? getInt(String key) { + try { + return store.getInt(key); + } catch (error) { + // ignore, could be obsolete value of different type + return null; + } + } + + double? getDouble(String key) { + try { + return store.getDouble(key); + } catch (error) { + // ignore, could be obsolete value of different type + return null; + } + } + + String? getString(String key) { + try { + return store.getString(key); + } catch (error) { + // ignore, could be obsolete value of different type + return null; + } + } + + List<String>? getStringList(String key) { + try { + return store.getStringList(key); + } catch (error) { + // ignore, could be obsolete value of different type + return null; + } + } + + T getEnumOrDefault<T>(String key, T defaultValue, Iterable<T> values) { + try { + final valueString = store.getString(key); + for (final v in values) { + if (v.toString() == valueString) { + return v; + } + } + } catch (error) { + // ignore, could be obsolete value of different type + } + return defaultValue; + } + + List<T> getEnumListOrDefault<T extends Object>(String key, List<T> defaultValue, Iterable<T> values) { + return store.getStringList(key)?.map((s) => values.firstWhereOrNull((v) => v.toString() == s)).nonNulls.toList() ?? defaultValue; + } +} diff --git a/plugins/aves_model/lib/src/settings/enums.dart b/plugins/aves_model/lib/src/settings/enums.dart new file mode 100644 index 0000000..fa6945d --- /dev/null +++ b/plugins/aves_model/lib/src/settings/enums.dart @@ -0,0 +1,71 @@ +enum AccessibilityAnimations { system, disabled, enabled } + +enum AccessibilityTimeout { system, s1, s3, s5, s10, s30 } + +enum AvesThemeBrightness { system, light, dark, black } + +enum AvesThemeColorMode { monochrome, polychrome } + +enum ConfirmationDialog { createVault, deleteForever, moveToBin, moveUndatedItems } + +enum CoordinateFormat { dms, ddm, decimal } + +enum DisplayRefreshRateMode { auto, highest, lowest } + +enum EntryBackground { black, white, checkered } + +enum HomePageSetting { collection, albums, tags, explorer } + +enum KeepScreenOn { never, videoPlayback, viewerOnly, always } + +enum MaxBrightness { never, viewerOnly, always } + +enum OverlayHistogramStyle { none, rgb, luminance } + +enum SlideshowVideoPlayback { skip, playMuted, playWithSound } + +enum SubtitlePosition { top, bottom } + +enum ThumbnailOverlayLocationIcon { located, unlocated, none } + +enum ThumbnailOverlayTagIcon { tagged, untagged, none } + +enum UnitSystem { metric, imperial } + +enum VideoAutoPlayMode { disabled, playMuted, playWithSound } + +enum VideoBackgroundMode { disabled, pip } + +enum VideoLoopMode { never, shortOnly, always } + +enum VideoResumptionMode { never, ask, always } + +enum ViewerTransition { slide, parallax, fade, zoomIn, none, random } + +enum WidgetDisplayedItem { random, mostRecent } + +enum WidgetOpenPage { home, collection, viewer, updateWidget } + +enum WidgetOutline { + none, + black, + white, + // system brightness dependent (low contrast): + // - white on light theme + // - black on dark theme + systemBlackAndWhite, + // system brightness dependent (high contrast): + // - black on light theme + // - white on dark theme + systemBlackAndWhiteHighContrast, + // system brightness dependent (low contrast): + // light dynamic colour on light theme + // dark dynamic colour on dark theme. + systemDynamicLowContrast, + // system brightness dependent (high contrast): + // dark dynamic colour on light theme + // light dynamic colour on dark theme. + systemDynamic, +} + +enum WidgetShape { rrect, circle, heart, concaveSquare, wavyCircle16, tearRectLeft, tearRectRight, bumpyRows, bumpyColumns } diff --git a/plugins/aves_model/lib/src/settings/event.dart b/plugins/aves_model/lib/src/settings/event.dart new file mode 100644 index 0000000..22b3bfa --- /dev/null +++ b/plugins/aves_model/lib/src/settings/event.dart @@ -0,0 +1,11 @@ +import 'package:meta/meta.dart'; + +@immutable +class SettingsChangedEvent { + final String key; + final dynamic oldValue; + final dynamic newValue; + + // old and new values as stored, e.g. `List<String>` for collections + const SettingsChangedEvent(this.key, this.oldValue, this.newValue); +} diff --git a/plugins/aves_model/lib/src/settings/keys.dart b/plugins/aves_model/lib/src/settings/keys.dart new file mode 100644 index 0000000..f85d21d --- /dev/null +++ b/plugins/aves_model/lib/src/settings/keys.dart @@ -0,0 +1,199 @@ +class SettingKeys { + static bool isInternalKey(String key) => _internalKeys.contains(key) || key.startsWith(_widgetKeyPrefix); + + static const Set<String> _internalKeys = { + hasAcceptedTermsKey, + catalogTimeZoneOffsetMillisKey, + searchHistoryKey, + platformAccelerometerRotationKey, + platformTransitionAnimationScaleKey, + topEntryIdsKey, + recentDestinationAlbumsKey, + recentTagsKey, + debugShowViewerTilesKey, + }; + + static const _widgetKeyPrefix = 'widget_'; + + // app + static const hasAcceptedTermsKey = 'has_accepted_terms'; + static const canUseAnalysisServiceKey = 'can_use_analysis_service'; + static const isInstalledAppAccessAllowedKey = 'is_installed_app_access_allowed'; + static const isErrorReportingAllowedKey = 'is_crashlytics_enabled'; + static const localeKey = 'locale'; + static const forceWesternArabicNumeralsKey = 'force_western_arabic_numerals'; + static const catalogTimeZoneOffsetMillisKey = 'catalog_time_zone_raw_offset_millis'; + static const tileExtentPrefixKey = 'tile_extent_'; + static const tileLayoutPrefixKey = 'tile_layout_'; + static const entryRenamingPatternKey = 'entry_renaming_pattern'; + static const topEntryIdsKey = 'top_entry_ids'; + static const recentDestinationAlbumsKey = 'recent_destination_albums'; + static const recentTagsKey = 'recent_tags'; + + // debug + static const debugShowViewerTilesKey = 'debug_show_viewer_tiles'; + + // display + static const displayRefreshRateModeKey = 'display_refresh_rate_mode'; + static const themeBrightnessKey = 'theme_brightness'; + static const themeColorModeKey = 'theme_color_mode'; + static const enableDynamicColorKey = 'dynamic_color'; + static const enableBlurEffectKey = 'enable_overlay_blur_effect'; + static const maxBrightnessKey = 'max_brightness'; + static const forceTvLayoutKey = 'force_tv_layout'; + + // navigation + static const mustBackTwiceToExitKey = 'must_back_twice_to_exit'; + static const keepScreenOnKey = 'keep_screen_on'; + static const homePageKey = 'home_page'; + static const homeCustomCollectionKey = 'home_custom_collection'; + static const homeCustomExplorerPathKey = 'home_custom_explorer_path'; + static const confirmCreateVaultKey = 'confirm_create_vault'; + static const confirmDeleteForeverKey = 'confirm_delete_forever'; + static const confirmMoveToBinKey = 'confirm_move_to_bin'; + static const confirmMoveUndatedItemsKey = 'confirm_move_undated_items'; + static const confirmAfterMoveToBinKey = 'confirm_after_move_to_bin'; + static const setMetadataDateBeforeFileOpKey = 'set_metadata_date_before_file_op'; + static const drawerTypeBookmarksKey = 'drawer_type_bookmarks'; + static const drawerAlbumBookmarksKey = 'drawer_album_bookmarks'; + static const drawerPageBookmarksKey = 'drawer_page_bookmarks'; + static const bottomNavigationActionsKey = 'bottom_navigation_actions'; + + // collection + static const collectionBurstPatternsKey = 'collection_burst_patterns'; + static const collectionGroupFactorKey = 'collection_group_factor'; + static const collectionSortFactorKey = 'collection_sort_factor'; + static const collectionSortReverseKey = 'collection_sort_reverse'; + static const collectionBrowsingQuickActionsKey = 'collection_browsing_quick_actions'; + static const collectionSelectionQuickActionsKey = 'collection_selection_quick_actions'; + static const showThumbnailFavouriteKey = 'show_thumbnail_favourite'; + static const showThumbnailHdrKey = 'show_thumbnail_hdr'; + static const thumbnailLocationIconKey = 'thumbnail_location_icon'; + static const thumbnailTagIconKey = 'thumbnail_tag_icon'; + static const showThumbnailMotionPhotoKey = 'show_thumbnail_motion_photo'; + static const showThumbnailRatingKey = 'show_thumbnail_rating'; + static const showThumbnailRawKey = 'show_thumbnail_raw'; + static const showThumbnailVideoDurationKey = 'show_thumbnail_video_duration'; + + // filter grids + static const albumSectionFactorKey = 'album_section_factor'; + static const albumSortFactorKey = 'album_sort_factor'; + static const countrySortFactorKey = 'country_sort_factor'; + static const stateSortFactorKey = 'state_sort_factor'; + static const placeSortFactorKey = 'place_sort_factor'; + static const tagSortFactorKey = 'tag_sort_factor'; + static const albumSortReverseKey = 'album_sort_reverse'; + static const countrySortReverseKey = 'country_sort_reverse'; + static const stateSortReverseKey = 'state_sort_reverse'; + static const placeSortReverseKey = 'place_sort_reverse'; + static const tagSortReverseKey = 'tag_sort_reverse'; + static const albumGroupsKey = 'album_groups'; + static const tagGroupsKey = 'tag_groups'; + static const pinnedFiltersKey = 'pinned_filters'; + static const hiddenFiltersKey = 'hidden_filters'; + static const deactivatedHiddenFiltersKey = 'deactivated_hidden_filters'; + static const showTitleQueryPrefixKey = 'show_title_query_'; + + // viewer + static const viewerQuickActionsKey = 'viewer_quick_actions'; + static const showOverlayOnOpeningKey = 'show_overlay_on_opening'; + static const showOverlayMinimapKey = 'show_overlay_minimap'; + static const showOverlayZoomLevelKey = 'show_overlay_zoom_level'; + static const overlayHistogramStyleKey = 'show_overlay_histogram'; + static const showOverlayInfoKey = 'show_overlay_info'; + static const showOverlayDescriptionKey = 'show_overlay_description'; + static const showOverlayRatingTagsKey = 'show_overlay_rating_tags'; + static const showOverlayShootingDetailsKey = 'show_overlay_shooting_details'; + static const showOverlayThumbnailPreviewKey = 'show_overlay_thumbnail_preview'; + static const viewerGestureSideTapNextKey = 'viewer_gesture_side_tap_next'; + static const viewerUseCutoutKey = 'viewer_use_cutout'; + static const enableMotionPhotoAutoPlayKey = 'motion_photo_auto_play'; + static const imageBackgroundKey = 'image_background'; + + // video + static const enableVideoHardwareAccelerationKey = 'video_hwaccel_mediacodec'; + static const videoBackgroundModeKey = 'video_background_mode'; + static const videoAutoPlayModeKey = 'video_auto_play_mode'; + static const videoLoopModeKey = 'video_loop'; + static const videoResumptionModeKey = 'video_resumption_mode'; + static const videoControlActionsKey = 'video_control_actions'; + static const videoGestureDoubleTapTogglePlayKey = 'video_gesture_double_tap_toggle_play'; + static const videoGestureSideDoubleTapSeekKey = 'video_gesture_side_double_tap_skip'; + static const videoGestureVerticalDragBrightnessVolumeKey = 'video_gesture_vertical_drag_brightness_volume'; + + // subtitles + static const subtitleFontSizeKey = 'subtitle_font_size'; + static const subtitleTextAlignmentKey = 'subtitle_text_alignment'; + static const subtitleTextPositionKey = 'subtitle_text_position'; + static const subtitleShowOutlineKey = 'subtitle_show_outline'; + static const subtitleTextColorKey = 'subtitle_text_color_string'; + static const subtitleBackgroundColorKey = 'subtitle_background_color_string'; + + // info + static const infoMapZoomKey = 'info_map_zoom'; + static const coordinateFormatKey = 'coordinates_format'; + static const unitSystemKey = 'unit_system'; + + // tag editor + + static const tagEditorCurrentFilterSectionExpandedKey = 'tag_editor_current_filter_section_expanded'; + static const tagEditorExpandedSectionKey = 'tag_editor_expanded_section'; + + // converter + + static const convertMimeTypeKey = 'convert_mime_type'; + static const convertQualityKey = 'convert_quality'; + static const convertWriteMetadataKey = 'convert_write_metadata'; + + // map + static const mapStyleKey = 'info_map_style'; + static const mapDefaultCenterKey = 'map_default_center'; + static const customMapStylesKey = 'custom_map_styles'; + + // search + static const saveSearchHistoryKey = 'save_search_history'; + static const searchHistoryKey = 'search_history'; + + // bin + static const enableBinKey = 'enable_bin'; + + // accessibility + static const showPinchGestureAlternativesKey = 'show_pinch_gesture_alternatives'; + static const accessibilityAnimationsKey = 'accessibility_animations'; + static const timeToTakeActionKey = 'time_to_take_action'; + + // screen saver + static const screenSaverFillScreenKey = 'screen_saver_fill_screen'; + static const screenSaverAnimatedZoomEffectKey = 'screen_saver_animated_zoom_effect'; + static const screenSaverTransitionKey = 'screen_saver_transition'; + static const screenSaverVideoPlaybackKey = 'screen_saver_video_playback'; + static const screenSaverIntervalKey = 'screen_saver_interval'; + static const screenSaverCollectionFiltersKey = 'screen_saver_collection_filters'; + + // slideshow + static const slideshowRepeatKey = 'slideshow_loop'; + static const slideshowShuffleKey = 'slideshow_shuffle'; + static const slideshowFillScreenKey = 'slideshow_fill_screen'; + static const slideshowAnimatedZoomEffectKey = 'slideshow_animated_zoom_effect'; + static const slideshowTransitionKey = 'slideshow_transition'; + static const slideshowVideoPlaybackKey = 'slideshow_video_playback'; + static const slideshowIntervalKey = 'slideshow_interval'; + + // widget + static const widgetOutlinePrefixKey = '${_widgetKeyPrefix}outline_'; + static const widgetShapePrefixKey = '${_widgetKeyPrefix}shape_'; + static const widgetCollectionFiltersPrefixKey = '${_widgetKeyPrefix}collection_filters_'; + static const widgetOpenPagePrefixKey = '${_widgetKeyPrefix}open_page_'; + static const widgetDisplayedItemPrefixKey = '${_widgetKeyPrefix}displayed_item_'; + static const widgetUriPrefixKey = '${_widgetKeyPrefix}uri_'; + + // platform settings + // cf Android `Settings.System.ACCELEROMETER_ROTATION` + static const platformAccelerometerRotationKey = 'accelerometer_rotation'; + + // cf Android `Settings.Global.TRANSITION_ANIMATION_SCALE` + static const platformTransitionAnimationScaleKey = 'transition_animation_scale'; + + // cf Android `Settings.Secure.LONG_PRESS_TIMEOUT` + static const platformLongPressTimeoutMillisKey = 'long_press_timeout'; +} diff --git a/plugins/aves_model/lib/src/settings/store.dart b/plugins/aves_model/lib/src/settings/store.dart new file mode 100644 index 0000000..84a7feb --- /dev/null +++ b/plugins/aves_model/lib/src/settings/store.dart @@ -0,0 +1,39 @@ +abstract class SettingsStore { + bool get initialized; + + Future<void> init(); + + Future<void> reload(); + + Future<bool> clear(); + + Future<bool> remove(String key); + + // get + + Set<String> getKeys(); + + Object? get(String key); + + bool? getBool(String key); + + int? getInt(String key); + + double? getDouble(String key); + + String? getString(String key); + + List<String>? getStringList(String key); + + // set + + Future<bool> setBool(String key, bool value); + + Future<bool> setInt(String key, int value); + + Future<bool> setDouble(String key, double value); + + Future<bool> setString(String key, String value); + + Future<bool> setStringList(String key, List<String> value); +} diff --git a/plugins/aves_model/lib/src/source/album.dart b/plugins/aves_model/lib/src/source/album.dart new file mode 100644 index 0000000..1520e8b --- /dev/null +++ b/plugins/aves_model/lib/src/source/album.dart @@ -0,0 +1,10 @@ +enum AlbumType { + regular, + vault, + app, + camera, + download, + screenRecordings, + screenshots, + videoCaptures, +} diff --git a/plugins/aves_model/lib/src/source/enums.dart b/plugins/aves_model/lib/src/source/enums.dart new file mode 100644 index 0000000..e029534 --- /dev/null +++ b/plugins/aves_model/lib/src/source/enums.dart @@ -0,0 +1,11 @@ +enum SourceState { loading, cataloguing, locatingCountries, locatingPlaces, ready } + +enum ChipSortFactor { date, name, count, size, path } + +enum AlbumChipSectionFactor { none, importance, mimeType, volume } + +enum EntrySortFactor { date, name, rating, size, duration, path } + +enum EntrySectionFactor { none, album, month, day } + +enum TileLayout { mosaic, grid, list } diff --git a/plugins/aves_model/lib/src/source/vault.dart b/plugins/aves_model/lib/src/source/vault.dart new file mode 100644 index 0000000..b560948 --- /dev/null +++ b/plugins/aves_model/lib/src/source/vault.dart @@ -0,0 +1 @@ +enum VaultLockType { system, pattern, pin, password } diff --git a/plugins/aves_model/lib/src/storage/relative_dir.dart b/plugins/aves_model/lib/src/storage/relative_dir.dart new file mode 100644 index 0000000..377318f --- /dev/null +++ b/plugins/aves_model/lib/src/storage/relative_dir.dart @@ -0,0 +1,44 @@ +import 'package:aves_model/aves_model.dart'; +import 'package:equatable/equatable.dart'; +import 'package:meta/meta.dart'; + +@immutable +class VolumeRelativeDirectory extends Equatable { + final String volumePath, relativeDir; + + @override + List<Object?> get props => [volumePath, relativeDir]; + + String get dirPath => '$volumePath$relativeDir'; + + const VolumeRelativeDirectory({ + required this.volumePath, + required this.relativeDir, + }); + + factory VolumeRelativeDirectory.volume(StorageVolume volume) { + return VolumeRelativeDirectory(volumePath: volume.path, relativeDir: ''); + } + + static VolumeRelativeDirectory fromMap(Map map) { + return VolumeRelativeDirectory( + volumePath: map['volumePath'] ?? '', + relativeDir: map['relativeDir'] ?? '', + ); + } + + Map<String, dynamic> toMap() => { + 'volumePath': volumePath, + 'relativeDir': relativeDir, + }; + + VolumeRelativeDirectory copyWith({ + String? volumePath, + String? relativeDir, + }) { + return VolumeRelativeDirectory( + volumePath: volumePath ?? this.volumePath, + relativeDir: relativeDir ?? this.relativeDir, + ); + } +} diff --git a/plugins/aves_model/lib/src/storage/volume.dart b/plugins/aves_model/lib/src/storage/volume.dart new file mode 100644 index 0000000..ff6df3d --- /dev/null +++ b/plugins/aves_model/lib/src/storage/volume.dart @@ -0,0 +1,31 @@ +import 'package:equatable/equatable.dart'; +import 'package:meta/meta.dart'; + +@immutable +class StorageVolume extends Equatable { + final String? description; + final String path, state; + final bool isPrimary, isRemovable; + + @override + List<Object?> get props => [description, path, state, isPrimary, isRemovable]; + + const StorageVolume({ + required this.description, + required this.isPrimary, + required this.isRemovable, + required this.path, + required this.state, + }); + + factory StorageVolume.fromMap(Map map) { + final isPrimary = map['isPrimary'] ?? false; + return StorageVolume( + description: map['description'], + isPrimary: isPrimary, + isRemovable: map['isRemovable'] ?? false, + path: map['path'] ?? '', + state: map['state'] ?? '', + ); + } +} diff --git a/plugins/aves_model/lib/src/video/keys.dart b/plugins/aves_model/lib/src/video/keys.dart new file mode 100644 index 0000000..c27f9b2 --- /dev/null +++ b/plugins/aves_model/lib/src/video/keys.dart @@ -0,0 +1,109 @@ +// keys returned by fijkplayer when getting media and streams info +// they originate from FFmpeg, fijkplayer, and other software +// that write additional metadata to media files +class Keys { + static const alpha = 'alpha'; + static const androidCaptureFramerate = 'com.android.capture.fps'; + static const androidManufacturer = 'com.android.manufacturer'; + static const androidModel = 'com.android.model'; + static const androidVersion = 'com.android.version'; + static const audioChannels = 'audio-channels'; + static const avgFrameRate = 'avg_frame_rate'; + static const bps = 'bps'; + static const bitrate = 'bitrate'; + static const bitsPerSample = 'bits_per_sample'; + static const byteCount = 'number_of_bytes'; + static const channelLayout = 'channel_layout'; + static const chapters = 'chapters'; + static const chromaLocation = 'chroma_location'; + static const closedCaptions = 'closed_captions'; + static const codecLevel = 'codec_level'; + static const codecLongName = 'codec_long_name'; + static const codecName = 'codec_name'; + static const codecPixelFormat = 'codec_pixel_format'; + static const codecProfileId = 'codec_profile_id'; + static const codecTag = 'codec_tag'; + static const codecTagString = 'codec_tag_string'; + static const codedHeight = 'coded_height'; + static const codedWidth = 'coded_width'; + static const colorLevels = 'color_levels'; + static const colorMatrix = 'color_matrix'; + static const colorPrimaries = 'color_primaries'; + static const colorRange = 'color_range'; + static const colorSpace = 'color_space'; + static const colorTransfer = 'color_transfer'; + static const compatibleBrands = 'compatible_brands'; + static const creationTime = 'creation_time'; + static const dar = 'display_aspect_ratio'; + static const date = 'date'; + static const decoderHeight = 'dh'; + static const decoderWidth = 'dw'; + static const disposition = 'disposition'; + static const duration = 'duration'; + static const durationMicros = 'duration_us'; + static const durationTs = 'duration_ts'; + static const encoder = 'encoder'; + static const extraDataSize = 'extradata_size'; + static const filename = 'filename'; + static const filmGrain = 'film_grain'; + static const fpsDen = 'fps_den'; + static const fpsNum = 'fps_num'; + static const fps = 'fps'; + static const frameCount = 'number_of_frames'; + static const gamma = 'gamma'; + static const hasBFrames = 'has_b_frames'; + static const hearingImpaired = 'hearing_impaired'; + static const hwPixelFormat = 'hw_pixel_format'; + static const index = 'index'; + static const isAvc = 'is_avc'; + static const language = 'language'; + static const light = 'light'; + static const location = 'location'; + static const majorBrand = 'major_brand'; + static const mediaFormat = 'format'; + static const minorVersion = 'minor_version'; + static const nalLengthSize = 'nal_length_size'; + static const par = 'pixel_aspect_ratio'; + static const probeScore = 'probe_score'; + static const programCount = 'nb_programs'; + static const quicktimeCreationDate = 'com.apple.quicktime.creationdate'; + static const quicktimeLocationAccuracyHorizontal = 'com.apple.quicktime.location.accuracy.horizontal'; + static const quicktimeLocationIso6709 = 'com.apple.quicktime.location.iso6709'; + static const quicktimeMake = 'com.apple.quicktime.make'; + static const quicktimeModel = 'com.apple.quicktime.model'; + static const quicktimeSoftware = 'com.apple.quicktime.software'; + static const refs = 'refs'; + static const rFrameRate = 'r_frame_rate'; + static const rotate = 'rotate'; + static const sampleFormat = 'sample_fmt'; + static const sampleRate = 'sample_rate'; + static const sar = 'sample_aspect_ratio'; + static const sarDen = 'sar_den'; + static const sarNum = 'sar_num'; + static const selectedAudioStream = 'audio'; + static const selectedTextStream = 'timedtext'; + static const selectedVideoStream = 'video'; + static const sourceOshash = 'source_oshash'; + static const startMicros = 'start_us'; + static const startPts = 'start_pts'; + static const startTime = 'start_time'; + static const statisticsTags = '_statistics_tags'; + static const statisticsWritingApp = '_statistics_writing_app'; + static const statisticsWritingDateUtc = '_statistics_writing_date_utc'; + static const stereo3dMode = 'stereo_3d_mode'; + static const streamCount = 'nb_streams'; + static const streams = 'streams'; + static const tbrDen = 'tbr_den'; + static const tbrNum = 'tbr_num'; + static const time = 'time'; + static const segmentCount = 'segment_count'; + static const streamType = 'type'; + static const title = 'title'; + static const timeBase = 'time_base'; + static const track = 'track'; + static const vendorId = 'vendor_id'; + static const videoHeight = 'height'; + static const videoWidth = 'width'; + static const visualImpaired = 'visual_impaired'; + static const xiaomiSlowMoment = 'com.xiaomi.slow_moment'; +} diff --git a/plugins/aves_model/lib/src/video/stream_types.dart b/plugins/aves_model/lib/src/video/stream_types.dart new file mode 100644 index 0000000..d2be820 --- /dev/null +++ b/plugins/aves_model/lib/src/video/stream_types.dart @@ -0,0 +1,9 @@ +class MediaStreamTypes { + static const attachment = 'attachment'; + static const audio = 'audio'; + static const metadata = 'metadata'; + static const subtitle = 'subtitle'; + static const timedText = 'timedtext'; + static const unknown = 'unknown'; + static const video = 'video'; +} diff --git a/plugins/aves_model/lib/src/wallpaper_target.dart b/plugins/aves_model/lib/src/wallpaper_target.dart new file mode 100644 index 0000000..210a363 --- /dev/null +++ b/plugins/aves_model/lib/src/wallpaper_target.dart @@ -0,0 +1 @@ +enum WallpaperTarget { home, lock, homeLock } diff --git a/plugins/aves_model/pubspec.yaml b/plugins/aves_model/pubspec.yaml new file mode 100644 index 0000000..7487d16 --- /dev/null +++ b/plugins/aves_model/pubspec.yaml @@ -0,0 +1,19 @@ +name: aves_model +version: 0.0.1 +publish_to: none + +environment: + sdk: ">=3.6.0 <4.0.0" # incoherent dartfmt from 3.7.0 +resolution: workspace + +dependencies: + flutter: + sdk: flutter + collection: + equatable: + meta: + +dev_dependencies: + flutter_lints: + +flutter: diff --git a/plugins/aves_report/.gitignore b/plugins/aves_report/.gitignore new file mode 100644 index 0000000..79c113f --- /dev/null +++ b/plugins/aves_report/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/plugins/aves_report/.metadata b/plugins/aves_report/.metadata new file mode 100644 index 0000000..5bed526 --- /dev/null +++ b/plugins/aves_report/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: 18116933e77adc82f80866c928266a5b4f1ed645 + channel: stable + +project_type: plugin diff --git a/plugins/aves_report/analysis_options.yaml b/plugins/aves_report/analysis_options.yaml new file mode 100644 index 0000000..f04c6cf --- /dev/null +++ b/plugins/aves_report/analysis_options.yaml @@ -0,0 +1 @@ +include: ../../analysis_options.yaml diff --git a/plugins/aves_report/lib/aves_report.dart b/plugins/aves_report/lib/aves_report.dart new file mode 100644 index 0000000..6092522 --- /dev/null +++ b/plugins/aves_report/lib/aves_report.dart @@ -0,0 +1,39 @@ +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:stack_trace/stack_trace.dart'; + +abstract class ReportService { + Future<void> init(); + + Map<String, String> get state; + + Future<void> setCollectionEnabled(bool enabled); + + Future<void> log(String message); + + Future<void> setCustomKey(String key, Object value); + + Future<void> setCustomKeys(Map<String, Object> map); + + Future<void> recordError(dynamic exception, [StackTrace? stack]); + + Future<void> recordFlutterError(FlutterErrorDetails flutterErrorDetails); + + static StackTrace? buildReportStack(StackTrace stack, {int level = 0}) { + // simply creating a trace with `Trace.current(1)` or creating a `Trace` from modified frames + // does not yield a stack trace that Crashlytics can segment, + // so we reconstruct a string stack trace instead + return StackTrace.fromString(Trace.from(stack) + .frames + .skip(level) + .toList() + .mapIndexed( + (i, f) => '#${(i++).toString().padRight(8)}${f.member} (${f.uri}:${f.line}:${f.column})', + ) + .join('\n')); + } +} + +class UnreportedStateError extends StateError { + UnreportedStateError(super.message); +}
\ No newline at end of file diff --git a/plugins/aves_report/pubspec.yaml b/plugins/aves_report/pubspec.yaml new file mode 100644 index 0000000..4eaa74d --- /dev/null +++ b/plugins/aves_report/pubspec.yaml @@ -0,0 +1,18 @@ +name: aves_report +version: 0.0.1 +publish_to: none + +environment: + sdk: ">=3.6.0 <4.0.0" # incoherent dartfmt from 3.7.0 +resolution: workspace + +dependencies: + flutter: + sdk: flutter + collection: + stack_trace: + +dev_dependencies: + flutter_lints: + +flutter: diff --git a/plugins/aves_report_console/.gitignore b/plugins/aves_report_console/.gitignore new file mode 100644 index 0000000..79c113f --- /dev/null +++ b/plugins/aves_report_console/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/plugins/aves_report_console/.metadata b/plugins/aves_report_console/.metadata new file mode 100644 index 0000000..db56104 --- /dev/null +++ b/plugins/aves_report_console/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: 18116933e77adc82f80866c928266a5b4f1ed645 + channel: stable + +project_type: package diff --git a/plugins/aves_report_console/analysis_options.yaml b/plugins/aves_report_console/analysis_options.yaml new file mode 100644 index 0000000..f04c6cf --- /dev/null +++ b/plugins/aves_report_console/analysis_options.yaml @@ -0,0 +1 @@ +include: ../../analysis_options.yaml diff --git a/plugins/aves_report_console/lib/aves_report_platform.dart b/plugins/aves_report_console/lib/aves_report_platform.dart new file mode 100644 index 0000000..dd1d461 --- /dev/null +++ b/plugins/aves_report_console/lib/aves_report_platform.dart @@ -0,0 +1,28 @@ +import 'package:aves_report/aves_report.dart'; +import 'package:flutter/foundation.dart'; + +class PlatformReportService extends ReportService { + @override + Future<void> init() => SynchronousFuture(null); + + @override + Future<void> log(String message) async => debugPrint('Report log with message=$message'); + + @override + Future<void> recordError(dynamic exception, [StackTrace? stack]) async => debugPrint('Report error with exception=$exception, stack=$stack'); + + @override + Future<void> recordFlutterError(FlutterErrorDetails flutterErrorDetails) async => debugPrint('Report Flutter error with details=$flutterErrorDetails'); + + @override + Future<void> setCollectionEnabled(bool enabled) => SynchronousFuture(null); + + @override + Future<void> setCustomKey(String key, Object value) async => debugPrint('Report set key $key=$value'); + + @override + Future<void> setCustomKeys(Map<String, Object> map) async => debugPrint('Report set keys ${map.entries.map((kv) => '${kv.key}=${kv.value}').join(', ')}'); + + @override + Map<String, String> get state => {'Reporter': 'Console'}; +} diff --git a/plugins/aves_report_console/pubspec.yaml b/plugins/aves_report_console/pubspec.yaml new file mode 100644 index 0000000..abf3801 --- /dev/null +++ b/plugins/aves_report_console/pubspec.yaml @@ -0,0 +1,18 @@ +name: aves_report_platform +version: 0.0.1 +publish_to: none + +environment: + sdk: ">=3.6.0 <4.0.0" # incoherent dartfmt from 3.7.0 +resolution: workspace + +dependencies: + flutter: + sdk: flutter + aves_report: + path: ../aves_report + +dev_dependencies: + flutter_lints: + +flutter: diff --git a/plugins/aves_report_crashlytics/.gitignore b/plugins/aves_report_crashlytics/.gitignore new file mode 100644 index 0000000..79c113f --- /dev/null +++ b/plugins/aves_report_crashlytics/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/plugins/aves_report_crashlytics/.metadata b/plugins/aves_report_crashlytics/.metadata new file mode 100644 index 0000000..db56104 --- /dev/null +++ b/plugins/aves_report_crashlytics/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: 18116933e77adc82f80866c928266a5b4f1ed645 + channel: stable + +project_type: package diff --git a/plugins/aves_report_crashlytics/analysis_options.yaml b/plugins/aves_report_crashlytics/analysis_options.yaml new file mode 100644 index 0000000..f04c6cf --- /dev/null +++ b/plugins/aves_report_crashlytics/analysis_options.yaml @@ -0,0 +1 @@ +include: ../../analysis_options.yaml diff --git a/plugins/aves_report_crashlytics/lib/aves_report_platform.dart b/plugins/aves_report_crashlytics/lib/aves_report_platform.dart new file mode 100644 index 0000000..05a7efb --- /dev/null +++ b/plugins/aves_report_crashlytics/lib/aves_report_platform.dart @@ -0,0 +1,85 @@ +import 'dart:async'; + +import 'package:aves_report/aves_report.dart'; +import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_crashlytics/firebase_crashlytics.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:stack_trace/stack_trace.dart'; + +class PlatformReportService extends ReportService { + FirebaseCrashlytics? get _instance { + try { + return FirebaseCrashlytics.instance; + } catch (error, stack) { + // as of firebase_core v1.21.0 / firebase_crashlytics v2.8.8, `Firebase.app` sometimes fail with: + // `No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()` + debugPrint('failed to get Firebase Crashlytics instance with error=$error\n$stack'); + } + return null; + } + + @override + Future<void> init() => Firebase.initializeApp(); + + @override + Map<String, String> get state { + try { + return { + 'Reporter': 'Crashlytics', + 'Firebase data collection enabled': '${Firebase.app().isAutomaticDataCollectionEnabled}', + 'Crashlytics collection enabled': '${_instance?.isCrashlyticsCollectionEnabled}', + }; + } catch (error, stack) { + // as of firebase_core v1.21.0 / firebase_crashlytics v2.8.8, `Firebase.app` sometimes fail with: + // `No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()` + debugPrint('failed to access Firebase properties with error=$error\n$stack'); + } + return {}; + } + + @override + Future<void> setCollectionEnabled(bool enabled) async { + debugPrint('${enabled ? 'enable' : 'disable'} Firebase & Crashlytics collection'); + try { + await Firebase.app().setAutomaticDataCollectionEnabled(enabled); + await _instance?.setCrashlyticsCollectionEnabled(enabled); + } catch (error, stack) { + // as of firebase_core v1.21.0 / firebase_crashlytics v2.8.8, `Firebase.app` sometimes fail with: + // `No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()` + debugPrint('failed to access Firebase properties with error=$error\n$stack'); + } + } + + @override + Future<void> log(String message) async { + debugPrint('Report log=$message'); + await _instance?.log(message); + } + + @override + Future<void> setCustomKey(String key, Object value) async => _instance?.setCustomKey(key, value); + + @override + Future<void> setCustomKeys(Map<String, Object> map) { + return Future.forEach<MapEntry<String, Object>>(map.entries, (kv) => setCustomKey(kv.key, kv.value)); + } + + @override + Future<void> recordError(dynamic exception, [StackTrace? stack]) async { + if (exception is PlatformException && stack != null) { + stack = ReportService.buildReportStack(stack, level: 2); + } + if (exception is! UnreportedStateError) { + stack ??= ReportService.buildReportStack(Trace.current(), level: 1); + return _instance?.recordError(exception, stack); + } + } + + @override + Future<void> recordFlutterError(FlutterErrorDetails flutterErrorDetails) async { + if (!flutterErrorDetails.silent) { + return _instance?.recordFlutterError(flutterErrorDetails); + } + } +} diff --git a/plugins/aves_report_crashlytics/pubspec.yaml b/plugins/aves_report_crashlytics/pubspec.yaml new file mode 100644 index 0000000..277b8d9 --- /dev/null +++ b/plugins/aves_report_crashlytics/pubspec.yaml @@ -0,0 +1,23 @@ +name: aves_report_platform +version: 0.0.1 +publish_to: none + +environment: + sdk: ">=3.6.0 <4.0.0" # incoherent dartfmt from 3.7.0 +resolution: workspace + +dependencies: + flutter: + sdk: flutter + aves_report: + path: ../aves_report + # `firebase_core` v4.0.0 requires minSdkVersion 23 + firebase_core: + # `firebase_crashlytics` v5.0.0 requires minSdkVersion 23 + firebase_crashlytics: ^4.3.10 + stack_trace: + +dev_dependencies: + flutter_lints: + +flutter: diff --git a/plugins/aves_screen_state/.gitignore b/plugins/aves_screen_state/.gitignore new file mode 100644 index 0000000..79c113f --- /dev/null +++ b/plugins/aves_screen_state/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/plugins/aves_screen_state/.metadata b/plugins/aves_screen_state/.metadata new file mode 100644 index 0000000..20225b1 --- /dev/null +++ b/plugins/aves_screen_state/.metadata @@ -0,0 +1,30 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled. + +version: + revision: f72efea43c3013323d1b95cff571f3c1caa37583 + channel: stable + +project_type: plugin + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: f72efea43c3013323d1b95cff571f3c1caa37583 + base_revision: f72efea43c3013323d1b95cff571f3c1caa37583 + - platform: android + create_revision: f72efea43c3013323d1b95cff571f3c1caa37583 + base_revision: f72efea43c3013323d1b95cff571f3c1caa37583 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/plugins/aves_screen_state/analysis_options.yaml b/plugins/aves_screen_state/analysis_options.yaml new file mode 100644 index 0000000..f04c6cf --- /dev/null +++ b/plugins/aves_screen_state/analysis_options.yaml @@ -0,0 +1 @@ +include: ../../analysis_options.yaml diff --git a/plugins/aves_screen_state/android/.gitignore b/plugins/aves_screen_state/android/.gitignore new file mode 100644 index 0000000..5343532 --- /dev/null +++ b/plugins/aves_screen_state/android/.gitignore @@ -0,0 +1,16 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ +.kotlin/ +/build/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/plugins/aves_screen_state/android/build.gradle b/plugins/aves_screen_state/android/build.gradle new file mode 100644 index 0000000..9f55061 --- /dev/null +++ b/plugins/aves_screen_state/android/build.gradle @@ -0,0 +1,52 @@ +group = 'deckers.thibault.aves.aves_screen_state' +version = '1.0-SNAPSHOT' + +buildscript { + ext { + kotlin_version = '2.2.0' + agp_version = '8.13.1' + } + + repositories { + google() + mavenCentral() + } + + dependencies { + classpath "com.android.tools.build:gradle:$agp_version" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' + +kotlin { + jvmToolchain 17 +} + +android { + namespace = 'deckers.thibault.aves.aves_screen_state' + compileSdk = 36 + + lintOptions { + checkAllWarnings = true + warningsAsErrors = true + disable 'InvalidPackage' + } + + sourceSets { + main.java.srcDirs += 'src/main/kotlin' + } + + defaultConfig { + minSdk = 21 + } +} diff --git a/plugins/aves_screen_state/android/gradle/wrapper/gradle-wrapper.properties b/plugins/aves_screen_state/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ccc6808 --- /dev/null +++ b/plugins/aves_screen_state/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
\ No newline at end of file diff --git a/plugins/aves_screen_state/android/settings.gradle b/plugins/aves_screen_state/android/settings.gradle new file mode 100644 index 0000000..f3d6d44 --- /dev/null +++ b/plugins/aves_screen_state/android/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'aves_screen_state' diff --git a/plugins/aves_screen_state/android/src/main/AndroidManifest.xml b/plugins/aves_screen_state/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000..cc947c5 --- /dev/null +++ b/plugins/aves_screen_state/android/src/main/AndroidManifest.xml @@ -0,0 +1 @@ +<manifest /> diff --git a/plugins/aves_screen_state/android/src/main/kotlin/deckers/thibault/aves/aves_screen_state/AvesScreenStatePlugin.kt b/plugins/aves_screen_state/android/src/main/kotlin/deckers/thibault/aves/aves_screen_state/AvesScreenStatePlugin.kt new file mode 100644 index 0000000..8beb09d --- /dev/null +++ b/plugins/aves_screen_state/android/src/main/kotlin/deckers/thibault/aves/aves_screen_state/AvesScreenStatePlugin.kt @@ -0,0 +1,40 @@ +package deckers.thibault.aves.aves_screen_state + +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import androidx.annotation.NonNull +import io.flutter.embedding.engine.plugins.FlutterPlugin +import io.flutter.plugin.common.EventChannel +import io.flutter.plugin.common.EventChannel.EventSink + +class AvesScreenStatePlugin : FlutterPlugin, EventChannel.StreamHandler { + private lateinit var eventChannel: EventChannel + private var context: Context? = null + private var screenReceiver: ScreenReceiver? = null + + override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { + eventChannel = EventChannel(flutterPluginBinding.binaryMessenger, "deckers.thibault/aves_screen_state/events") + context = flutterPluginBinding.applicationContext + eventChannel.setStreamHandler(this) + } + + override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { + eventChannel.setStreamHandler(null) + } + + override fun onListen(arguments: Any?, events: EventSink) { + screenReceiver = ScreenReceiver(events) + + val filter = IntentFilter().apply { + addAction(Intent.ACTION_SCREEN_ON) // Turn on + addAction(Intent.ACTION_SCREEN_OFF) // Turn off + addAction(Intent.ACTION_USER_PRESENT) // Unlock + } + context!!.registerReceiver(screenReceiver, filter) + } + + override fun onCancel(arguments: Any?) { + context!!.unregisterReceiver(screenReceiver) + } +}
\ No newline at end of file diff --git a/plugins/aves_screen_state/android/src/main/kotlin/deckers/thibault/aves/aves_screen_state/ScreenReceiver.kt b/plugins/aves_screen_state/android/src/main/kotlin/deckers/thibault/aves/aves_screen_state/ScreenReceiver.kt new file mode 100644 index 0000000..a03fd75 --- /dev/null +++ b/plugins/aves_screen_state/android/src/main/kotlin/deckers/thibault/aves/aves_screen_state/ScreenReceiver.kt @@ -0,0 +1,12 @@ +package deckers.thibault.aves.aves_screen_state + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import io.flutter.plugin.common.EventChannel.EventSink + +class ScreenReceiver(private val eventSink: EventSink) : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + eventSink.success(intent.action) + } +}
\ No newline at end of file diff --git a/plugins/aves_screen_state/lib/aves_screen_state.dart b/plugins/aves_screen_state/lib/aves_screen_state.dart new file mode 100644 index 0000000..0e0b608 --- /dev/null +++ b/plugins/aves_screen_state/lib/aves_screen_state.dart @@ -0,0 +1,40 @@ +import 'dart:io'; + +import 'package:flutter/services.dart'; + +class AvesScreenState { + final EventChannel _eventChannel = const EventChannel('deckers.thibault/aves_screen_state/events'); + Stream<ScreenStateEvent>? _screenStateStream; + + Stream<ScreenStateEvent>? get screenStateStream { + if (Platform.isAndroid) { + _screenStateStream ??= _eventChannel.receiveBroadcastStream().map((event) => _parse(event as String)); + return _screenStateStream; + } + throw ScreenStateException('Screen State API is only available on Android.'); + } + + ScreenStateEvent _parse(String event) { + switch (event) { + case 'android.intent.action.SCREEN_OFF': + return ScreenStateEvent.off; + case 'android.intent.action.SCREEN_ON': + return ScreenStateEvent.on; + case 'android.intent.action.USER_PRESENT': + return ScreenStateEvent.unlocked; + default: + throw ArgumentError('$event was not recognized.'); + } + } +} + +enum ScreenStateEvent { unlocked, on, off } + +class ScreenStateException implements Exception { + final String _cause; + + ScreenStateException(this._cause); + + @override + String toString() => _cause; +} diff --git a/plugins/aves_screen_state/pubspec.yaml b/plugins/aves_screen_state/pubspec.yaml new file mode 100644 index 0000000..b3436e7 --- /dev/null +++ b/plugins/aves_screen_state/pubspec.yaml @@ -0,0 +1,22 @@ +name: aves_screen_state +version: 0.0.1 +publish_to: none + +environment: + sdk: ">=3.6.0 <4.0.0" # incoherent dartfmt from 3.7.0 +resolution: workspace + +dependencies: + flutter: + sdk: flutter + plugin_platform_interface: + +dev_dependencies: + flutter_lints: + +flutter: + plugin: + platforms: + android: + package: deckers.thibault.aves.aves_screen_state + pluginClass: AvesScreenStatePlugin diff --git a/plugins/aves_services/.gitignore b/plugins/aves_services/.gitignore new file mode 100644 index 0000000..79c113f --- /dev/null +++ b/plugins/aves_services/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/plugins/aves_services/.metadata b/plugins/aves_services/.metadata new file mode 100644 index 0000000..c24d00d --- /dev/null +++ b/plugins/aves_services/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: 5464c5bac742001448fe4fc0597be939379f88ea + channel: stable + +project_type: package diff --git a/plugins/aves_services/analysis_options.yaml b/plugins/aves_services/analysis_options.yaml new file mode 100644 index 0000000..f04c6cf --- /dev/null +++ b/plugins/aves_services/analysis_options.yaml @@ -0,0 +1 @@ +include: ../../analysis_options.yaml diff --git a/plugins/aves_services/lib/aves_services.dart b/plugins/aves_services/lib/aves_services.dart new file mode 100644 index 0000000..99240a4 --- /dev/null +++ b/plugins/aves_services/lib/aves_services.dart @@ -0,0 +1,33 @@ +import 'package:aves_map/aves_map.dart'; +import 'package:flutter/widgets.dart'; +import 'package:latlong2/latlong.dart'; + +abstract class MobileServices { + Future<void> init(); + + bool get isServiceAvailable; + + EntryMapStyle? get defaultMapStyle; + + List<EntryMapStyle> get mapStyles; + + Widget buildMap<T>({ + required AvesMapController controller, + required Listenable clusterListenable, + required ValueNotifier<ZoomedBounds> boundsNotifier, + required EntryMapStyle style, + required TransitionBuilder decoratorBuilder, + required WidgetBuilder buttonPanelBuilder, + required MarkerClusterBuilder<T> markerClusterBuilder, + required MarkerWidgetBuilder<T> markerWidgetBuilder, + required MarkerImageReadyChecker<T> markerImageReadyChecker, + required ValueNotifier<LatLng?>? dotLocationNotifier, + required ValueNotifier<double>? overlayOpacityNotifier, + required MapOverlay? overlayEntry, + required Set<List<LatLng>>? tracks, + required UserZoomChangeCallback? onUserZoomChange, + required MapTapCallback? onMapTap, + required MarkerTapCallback<T>? onMarkerTap, + required MarkerLongPressCallback<T>? onMarkerLongPress, + }); +} diff --git a/plugins/aves_services/pubspec.yaml b/plugins/aves_services/pubspec.yaml new file mode 100644 index 0000000..aee063f --- /dev/null +++ b/plugins/aves_services/pubspec.yaml @@ -0,0 +1,19 @@ +name: aves_services +version: 0.0.1 +publish_to: none + +environment: + sdk: ">=3.6.0 <4.0.0" # incoherent dartfmt from 3.7.0 +resolution: workspace + +dependencies: + flutter: + sdk: flutter + aves_map: + path: ../aves_map + latlong2: + +dev_dependencies: + flutter_lints: + +flutter: diff --git a/plugins/aves_services_google/.gitignore b/plugins/aves_services_google/.gitignore new file mode 100644 index 0000000..79c113f --- /dev/null +++ b/plugins/aves_services_google/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/plugins/aves_services_google/.metadata b/plugins/aves_services_google/.metadata new file mode 100644 index 0000000..c24d00d --- /dev/null +++ b/plugins/aves_services_google/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: 5464c5bac742001448fe4fc0597be939379f88ea + channel: stable + +project_type: package diff --git a/plugins/aves_services_google/analysis_options.yaml b/plugins/aves_services_google/analysis_options.yaml new file mode 100644 index 0000000..f04c6cf --- /dev/null +++ b/plugins/aves_services_google/analysis_options.yaml @@ -0,0 +1 @@ +include: ../../analysis_options.yaml diff --git a/plugins/aves_services_google/lib/aves_services_platform.dart b/plugins/aves_services_google/lib/aves_services_platform.dart new file mode 100644 index 0000000..842f4d1 --- /dev/null +++ b/plugins/aves_services_google/lib/aves_services_platform.dart @@ -0,0 +1,89 @@ +import 'package:aves_map/aves_map.dart'; +import 'package:aves_services/aves_services.dart'; +import 'package:aves_services_platform/src/map.dart'; +import 'package:device_info_plus/device_info_plus.dart'; +import 'package:flutter/widgets.dart'; +import 'package:google_api_availability/google_api_availability.dart'; +import 'package:google_maps_flutter_android/google_maps_flutter_android.dart'; +import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; +import 'package:latlong2/latlong.dart' as ll; + +class PlatformMobileServices extends MobileServices { + bool _isAvailable = false; + + @override + Future<void> init() async { + final result = await GoogleApiAvailability.instance.checkGooglePlayServicesAvailability(); + _isAvailable = result == GooglePlayServicesAvailability.success; + debugPrint('Device has Google Play Services=$_isAvailable'); + + final androidInfo = await DeviceInfoPlugin().androidInfo; + final mapsImplementation = GoogleMapsFlutterPlatform.instance; + if (mapsImplementation is GoogleMapsFlutterAndroid) { + // As of Flutter v3.22.2 / google_maps_flutter_android 2.12.0, + // using Texture Layer Hybrid Composition (`useAndroidViewSurface = false`) + // is the default and the best. But it fails to render on API < 23, yielding: + // "UnsupportedOperationException: Platform views cannot be displayed below API level 23" + // so we fall back to Hybrid Composition (`useAndroidViewSurface = true`) + mapsImplementation.useAndroidViewSurface = androidInfo.version.sdkInt < 23; + } + } + + @override + bool get isServiceAvailable => _isAvailable; + + @override + EntryMapStyle? get defaultMapStyle => EntryMapStyles.googleNormal; + + @override + List<EntryMapStyle> get mapStyles => isServiceAvailable + ? [ + EntryMapStyles.googleNormal, + EntryMapStyles.googleHybrid, + EntryMapStyles.googleTerrain, + ] + : []; + + @override + Widget buildMap<T>({ + required AvesMapController controller, + required Listenable clusterListenable, + required ValueNotifier<ZoomedBounds> boundsNotifier, + required EntryMapStyle style, + required TransitionBuilder decoratorBuilder, + required WidgetBuilder buttonPanelBuilder, + required MarkerClusterBuilder<T> markerClusterBuilder, + required MarkerWidgetBuilder<T> markerWidgetBuilder, + required MarkerImageReadyChecker<T> markerImageReadyChecker, + required ValueNotifier<ll.LatLng?>? dotLocationNotifier, + required ValueNotifier<double>? overlayOpacityNotifier, + required MapOverlay? overlayEntry, + required Set<List<ll.LatLng>>? tracks, + required UserZoomChangeCallback? onUserZoomChange, + required MapTapCallback? onMapTap, + required MarkerTapCallback<T>? onMarkerTap, + required MarkerLongPressCallback<T>? onMarkerLongPress, + }) { + return EntryGoogleMap<T>( + controller: controller, + clusterListenable: clusterListenable, + boundsNotifier: boundsNotifier, + minZoom: 0, + maxZoom: 20, + style: style, + decoratorBuilder: decoratorBuilder, + buttonPanelBuilder: buttonPanelBuilder, + markerClusterBuilder: markerClusterBuilder, + markerWidgetBuilder: markerWidgetBuilder, + markerImageReadyChecker: markerImageReadyChecker, + dotLocationNotifier: dotLocationNotifier, + overlayOpacityNotifier: overlayOpacityNotifier, + overlayEntry: overlayEntry, + tracks: tracks, + onUserZoomChange: onUserZoomChange, + onMapTap: onMapTap, + onMarkerTap: onMarkerTap, + onMarkerLongPress: onMarkerLongPress, + ); + } +} diff --git a/plugins/aves_services_google/lib/src/map.dart b/plugins/aves_services_google/lib/src/map.dart new file mode 100644 index 0000000..bbbbbf4 --- /dev/null +++ b/plugins/aves_services_google/lib/src/map.dart @@ -0,0 +1,434 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:aves_map/aves_map.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:flutter/material.dart'; +import 'package:google_maps_flutter/google_maps_flutter.dart'; +import 'package:latlong2/latlong.dart' as ll; +import 'package:provider/provider.dart'; + +class EntryGoogleMap<T> extends StatefulWidget { + final AvesMapController controller; + final Listenable clusterListenable; + final ValueNotifier<ZoomedBounds> boundsNotifier; + final double? minZoom, maxZoom; + final EntryMapStyle style; + final TransitionBuilder decoratorBuilder; + final WidgetBuilder buttonPanelBuilder; + final MarkerClusterBuilder<T> markerClusterBuilder; + final MarkerWidgetBuilder<T> markerWidgetBuilder; + final MarkerImageReadyChecker<T> markerImageReadyChecker; + final ValueNotifier<ll.LatLng?>? dotLocationNotifier; + final ValueNotifier<double>? overlayOpacityNotifier; + final MapOverlay? overlayEntry; + final Set<List<ll.LatLng>>? tracks; + final UserZoomChangeCallback? onUserZoomChange; + final MapTapCallback? onMapTap; + final MarkerTapCallback<T>? onMarkerTap; + final MarkerLongPressCallback<T>? onMarkerLongPress; + + const EntryGoogleMap({ + super.key, + required this.controller, + required this.clusterListenable, + required this.boundsNotifier, + this.minZoom, + this.maxZoom, + required this.style, + required this.decoratorBuilder, + required this.buttonPanelBuilder, + required this.markerClusterBuilder, + required this.markerWidgetBuilder, + required this.markerImageReadyChecker, + required this.dotLocationNotifier, + this.overlayOpacityNotifier, + this.overlayEntry, + this.tracks, + this.onUserZoomChange, + this.onMapTap, + this.onMarkerTap, + this.onMarkerLongPress, + }); + + @override + State<StatefulWidget> createState() => _EntryGoogleMapState<T>(); +} + +class _EntryGoogleMapState<T> extends State<EntryGoogleMap<T>> { + GoogleMapController? _serviceMapController; + final List<StreamSubscription> _subscriptions = []; + Map<MarkerKey<T>, GeoEntry<T>> _geoEntryByMarkerKey = {}; + final Map<MarkerKey<T>, Uint8List> _markerBitmaps = {}; + final StreamController<MarkerKey<T>> _markerBitmapReadyStreamController = StreamController.broadcast(); + Uint8List? _dotMarkerBitmap; + final ValueNotifier<Size> _sizeNotifier = ValueNotifier(Size.zero); + + ValueNotifier<ZoomedBounds> get boundsNotifier => widget.boundsNotifier; + + ZoomedBounds get bounds => boundsNotifier.value; + + static const uninitializedLatLng = LatLng(0, 0); + static const boundInitDelay = Duration(milliseconds: 100); + + @override + void initState() { + super.initState(); + _sizeNotifier.addListener(_onSizeChanged); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant EntryGoogleMap<T> oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + _serviceMapController?.dispose(); + _sizeNotifier.dispose(); + super.dispose(); + } + + void _registerWidget(EntryGoogleMap<T> widget) { + final avesMapController = widget.controller; + _subscriptions.add(avesMapController.moveCommands.listen((event) => _moveTo(_toServiceLatLng(event.latLng)))); + _subscriptions.add(avesMapController.zoomCommands.listen((event) => _zoomBy(event.delta))); + _subscriptions.add(avesMapController.rotationResetCommands.listen((_) => _resetRotation())); + widget.clusterListenable.addListener(_updateMarkers); + } + + void _unregisterWidget(EntryGoogleMap<T> widget) { + widget.clusterListenable.removeListener(_updateMarkers); + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + @override + Widget build(BuildContext context) { + return Stack( + children: [ + MarkerGeneratorWidget<Key>( + markers: const [DotMarker(key: Key('dot'))], + isReadyToRender: (key) => true, + onRendered: (key, bitmap) => _dotMarkerBitmap = bitmap, + ), + MarkerGeneratorWidget<MarkerKey<T>>( + markers: _geoEntryByMarkerKey.keys.map(widget.markerWidgetBuilder).toList(), + isReadyToRender: widget.markerImageReadyChecker, + onRendered: (key, bitmap) { + _markerBitmaps[key] = bitmap; + _markerBitmapReadyStreamController.add(key); + }, + ), + widget.decoratorBuilder(context, _buildMap()), + widget.buttonPanelBuilder(context), + ], + ); + } + + Widget _buildMap() { + return StreamBuilder( + stream: _markerBitmapReadyStreamController.stream, + builder: (context, _) { + final mediaMarkers = <Marker>{}; + _geoEntryByMarkerKey.forEach((markerKey, geoEntry) { + final bytes = _markerBitmaps[markerKey]; + if (bytes != null) { + final point = LatLng(geoEntry.latitude!, geoEntry.longitude!); + mediaMarkers.add(Marker( + markerId: MarkerId(geoEntry.markerId!), + consumeTapEvents: true, + icon: BytesMapBitmap( + bytes, + bitmapScaling: MapBitmapScaling.none, + ), + position: point, + onTap: () => widget.onMarkerTap?.call(geoEntry), + // TODO TLAD [map] GoogleMap.onLongPress is not appropriate for mediaMarkers, so the call should be here when this is fixed: https://github.com/flutter/flutter/issues/107148 + // onLongPress: widget.onMarkerLongPress != null + // ? (v) { + // final pressLocation = _fromServiceLatLng(v); + // final mediaMarkers = _geoEntryByMarkerKey.values.toSet(); + // final geoEntry = ImageMarker.markerMatch(pressLocation, bounds.zoom, mediaMarkers); + // if (geoEntry != null) { + // widget.onMarkerLongPress?.call(geoEntry, pressLocation); + // } + // } + // : null, + )); + } + }); + + final interactive = context.select<MapThemeData, bool>((v) => v.interactive); + final overlayEntry = widget.overlayEntry; + final tracks = widget.tracks; + final trackColor = Theme.of(context).colorScheme.primary; + return NullableValueListenableBuilder<ll.LatLng?>( + valueListenable: widget.dotLocationNotifier, + builder: (context, dotLocation, child) { + return NullableValueListenableBuilder<double>( + valueListenable: widget.overlayOpacityNotifier, + builder: (context, value, child) { + final double overlayOpacity = value ?? 1.0; + return LayoutBuilder( + builder: (context, constraints) { + _sizeNotifier.value = constraints.biggest; + return _GoogleMap( + dotLocationNotifier: widget.dotLocationNotifier ?? ValueNotifier(null), + initialCameraPosition: CameraPosition( + bearing: -bounds.rotation, + target: _toServiceLatLng(bounds.projectedCenter), + zoom: bounds.zoom, + ), + onMapCreated: (controller) async { + _serviceMapController = controller; + final zoom = await controller.getZoomLevel(); + // the visible region is sometimes incorrect when queried right after creation, + await Future.delayed(boundInitDelay); + await _updateVisibleRegion(zoom: zoom, rotation: bounds.rotation); + // `onCameraIdle` is not always automatically triggered following map creation + _onIdle(); + }, + mapType: _toMapType(widget.style), + minMaxZoomPreference: MinMaxZoomPreference(widget.minZoom, widget.maxZoom), + interactive: interactive, + markers: { + ...mediaMarkers, + if (dotLocation != null && _dotMarkerBitmap != null) + Marker( + markerId: const MarkerId('dot'), + anchor: const Offset(.5, .5), + consumeTapEvents: true, + icon: BytesMapBitmap( + _dotMarkerBitmap!, + bitmapScaling: MapBitmapScaling.none, + ), + position: _toServiceLatLng(dotLocation), + zIndexInt: 1, + ) + }, + polylines: { + if (tracks != null) + for (final track in tracks) + Polyline( + polylineId: PolylineId(track.hashCode.toString()), + points: track.map(_toServiceLatLng).toList(), + width: MapThemeData.trackWidth, + color: trackColor, + ), + }, + // TODO TLAD [geotiff] may use ground overlay instead when this is fixed: https://github.com/flutter/flutter/issues/26479 + tileOverlays: { + if (overlayEntry != null && overlayEntry.canOverlay) + TileOverlay( + tileOverlayId: TileOverlayId(overlayEntry.id), + tileProvider: GmsGeoTiffTileProvider(overlayEntry), + transparency: 1 - overlayOpacity, + ), + }, + onCameraMove: (position) => _updateVisibleRegion(zoom: position.zoom, rotation: -position.bearing), + onCameraIdle: _onIdle, + onTap: (v) => widget.onMapTap?.call(_fromServiceLatLng(v)), + ); + }, + ); + }, + ); + }, + ); + }, + ); + } + + // sometimes the map does not properly update after changing the widget size, + // so we monitor the size and force refreshing after an arbitrary small delay + Future<void> _onSizeChanged() async { + await Future.delayed(boundInitDelay); + _onIdle(); + } + + void _onIdle() { + if (!mounted) return; + widget.controller.notifyIdle(bounds); + _updateMarkers(); + } + + void _updateMarkers() { + setState(() => _geoEntryByMarkerKey = widget.markerClusterBuilder()); + } + + Future<void> _updateVisibleRegion({required double zoom, required double rotation}) async { + if (!mounted) return; + + final bounds = await _serviceMapController?.getVisibleRegion(); + if (bounds != null && (bounds.northeast != uninitializedLatLng || bounds.southwest != uninitializedLatLng)) { + final sw = bounds.southwest; + final ne = bounds.northeast; + boundsNotifier.value = ZoomedBounds( + sw: _fromServiceLatLng(sw), + ne: _fromServiceLatLng(ne), + zoom: zoom, + rotation: rotation, + ); + } + } + + Future<void> _resetRotation() async { + final controller = _serviceMapController; + if (controller == null) return; + + await controller.animateCamera(CameraUpdate.newCameraPosition(CameraPosition( + target: _toServiceLatLng(bounds.projectedCenter), + zoom: bounds.zoom, + ))); + } + + Future<void> _zoomBy(double amount) async { + final controller = _serviceMapController; + if (controller == null) return; + + widget.onUserZoomChange?.call(await controller.getZoomLevel() + amount); + await controller.animateCamera(CameraUpdate.zoomBy(amount)); + } + + Future<void> _moveTo(LatLng point) async { + final controller = _serviceMapController; + if (controller == null) return; + + await controller.animateCamera(CameraUpdate.newLatLng(point)); + } + + // `LatLng` used by `google_maps_flutter` is not the one from `latlong2` package + LatLng _toServiceLatLng(ll.LatLng location) => LatLng(location.latitude, location.longitude); + + ll.LatLng _fromServiceLatLng(LatLng location) => ll.LatLng(location.latitude, location.longitude); + + MapType _toMapType(EntryMapStyle style) { + if (style == EntryMapStyles.googleNormal) return MapType.normal; + if (style == EntryMapStyles.googleHybrid) return MapType.hybrid; + if (style == EntryMapStyles.googleTerrain) return MapType.terrain; + return MapType.none; + } +} + +class GmsGeoTiffTileProvider extends TileProvider { + MapOverlay overlayEntry; + + GmsGeoTiffTileProvider(this.overlayEntry); + + @override + Future<Tile> getTile(int x, int y, int? zoom) async { + final tile = await overlayEntry.getTile(x, y, zoom); + if (tile != null) { + return Tile(tile.width, tile.height, tile.data); + } + return TileProvider.noTile; + } +} + +class _GoogleMap extends StatefulWidget { + final ValueNotifier<ll.LatLng?>? dotLocationNotifier; + final CameraPosition initialCameraPosition; + final MapCreatedCallback? onMapCreated; + final MapType mapType; + final MinMaxZoomPreference minMaxZoomPreference; + final bool interactive; + final Set<Marker> markers; + final Set<Polyline> polylines; + final Set<TileOverlay> tileOverlays; + final CameraPositionCallback? onCameraMove; + final VoidCallback? onCameraIdle; + final ArgumentCallback<LatLng>? onTap; + + const _GoogleMap({ + required this.dotLocationNotifier, + required this.initialCameraPosition, + required this.onMapCreated, + required this.mapType, + required this.minMaxZoomPreference, + required this.interactive, + required this.markers, + required this.polylines, + required this.tileOverlays, + required this.onCameraMove, + required this.onCameraIdle, + required this.onTap, + }); + + @override + State<_GoogleMap> createState() => _GoogleMapState(); +} + +class _GoogleMapState extends State<_GoogleMap> { + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant _GoogleMap oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(_GoogleMap widget) { + widget.dotLocationNotifier?.addListener(_onDotLocationChanged); + } + + void _unregisterWidget(_GoogleMap widget) { + widget.dotLocationNotifier?.removeListener(_onDotLocationChanged); + } + + // TODO TLAD [map] remove when this is fixed: https://github.com/flutter/flutter/issues/103686 + Future<void> _onDotLocationChanged() async { + // workaround for dot location marker not always reflecting the current location, + // despite `ValueListenableBuilder` on `widget.dotLocationNotifier` + await Future.delayed(const Duration(milliseconds: 100)); + if (mounted) { + setState(() {}); + } + } + + @override + Widget build(BuildContext context) { + return GoogleMap( + initialCameraPosition: widget.initialCameraPosition, + onMapCreated: widget.onMapCreated, + // compass disabled to use provider agnostic controls + compassEnabled: false, + mapToolbarEnabled: false, + mapType: widget.mapType, + minMaxZoomPreference: widget.minMaxZoomPreference, + rotateGesturesEnabled: true, + scrollGesturesEnabled: widget.interactive, + // zoom controls disabled to use provider agnostic controls + zoomControlsEnabled: false, + zoomGesturesEnabled: widget.interactive, + // lite mode disabled because it lacks camera animation + liteModeEnabled: false, + // tilt disabled to match leaflet + tiltGesturesEnabled: false, + myLocationEnabled: false, + myLocationButtonEnabled: false, + markers: widget.markers, + polylines: widget.polylines, + tileOverlays: widget.tileOverlays, + onCameraMove: widget.onCameraMove, + onCameraIdle: widget.onCameraIdle, + onTap: widget.onTap, + ); + } +} diff --git a/plugins/aves_services_google/pubspec.yaml b/plugins/aves_services_google/pubspec.yaml new file mode 100644 index 0000000..2324f38 --- /dev/null +++ b/plugins/aves_services_google/pubspec.yaml @@ -0,0 +1,29 @@ +name: aves_services_platform +version: 0.0.1 +publish_to: none + +environment: + sdk: ">=3.6.0 <4.0.0" # incoherent dartfmt from 3.7.0 +resolution: workspace + +dependencies: + flutter: + sdk: flutter + aves_map: + path: ../aves_map + aves_services: + path: ../aves_services + aves_utils: + path: ../aves_utils + device_info_plus: + google_api_availability: + google_maps_flutter: + google_maps_flutter_android: + google_maps_flutter_platform_interface: + latlong2: + provider: + +dev_dependencies: + flutter_lints: + +flutter: diff --git a/plugins/aves_services_none/.gitignore b/plugins/aves_services_none/.gitignore new file mode 100644 index 0000000..79c113f --- /dev/null +++ b/plugins/aves_services_none/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/plugins/aves_services_none/.metadata b/plugins/aves_services_none/.metadata new file mode 100644 index 0000000..a831254 --- /dev/null +++ b/plugins/aves_services_none/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: 52b3dc25f6471c27b2144594abb11c741cb88f57 + channel: stable + +project_type: package diff --git a/plugins/aves_services_none/analysis_options.yaml b/plugins/aves_services_none/analysis_options.yaml new file mode 100644 index 0000000..f04c6cf --- /dev/null +++ b/plugins/aves_services_none/analysis_options.yaml @@ -0,0 +1 @@ +include: ../../analysis_options.yaml diff --git a/plugins/aves_services_none/lib/aves_services_platform.dart b/plugins/aves_services_none/lib/aves_services_platform.dart new file mode 100644 index 0000000..c15ad78 --- /dev/null +++ b/plugins/aves_services_none/lib/aves_services_platform.dart @@ -0,0 +1,41 @@ +import 'package:aves_map/aves_map.dart'; +import 'package:aves_services/aves_services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:latlong2/latlong.dart'; + +class PlatformMobileServices extends MobileServices { + @override + Future<void> init() async {} + + @override + bool get isServiceAvailable => false; + + @override + EntryMapStyle? get defaultMapStyle => null; + + @override + List<EntryMapStyle> get mapStyles => []; + + @override + Widget buildMap<T>({ + required AvesMapController controller, + required Listenable clusterListenable, + required ValueNotifier<ZoomedBounds> boundsNotifier, + required EntryMapStyle style, + required TransitionBuilder decoratorBuilder, + required WidgetBuilder buttonPanelBuilder, + required MarkerClusterBuilder<T> markerClusterBuilder, + required MarkerWidgetBuilder<T> markerWidgetBuilder, + required MarkerImageReadyChecker<T> markerImageReadyChecker, + required ValueNotifier<LatLng?>? dotLocationNotifier, + required ValueNotifier<double>? overlayOpacityNotifier, + required MapOverlay? overlayEntry, + required Set<List<LatLng>>? tracks, + required UserZoomChangeCallback? onUserZoomChange, + required MapTapCallback? onMapTap, + required MarkerTapCallback<T>? onMarkerTap, + required MarkerLongPressCallback<T>? onMarkerLongPress, + }) { + return const SizedBox(); + } +} diff --git a/plugins/aves_services_none/pubspec.yaml b/plugins/aves_services_none/pubspec.yaml new file mode 100644 index 0000000..6c15e04 --- /dev/null +++ b/plugins/aves_services_none/pubspec.yaml @@ -0,0 +1,21 @@ +name: aves_services_platform +version: 0.0.1 +publish_to: none + +environment: + sdk: ">=3.6.0 <4.0.0" # incoherent dartfmt from 3.7.0 +resolution: workspace + +dependencies: + flutter: + sdk: flutter + aves_map: + path: ../aves_map + aves_services: + path: ../aves_services + latlong2: + +dev_dependencies: + flutter_lints: + +flutter: diff --git a/plugins/aves_ui/.gitignore b/plugins/aves_ui/.gitignore new file mode 100644 index 0000000..79c113f --- /dev/null +++ b/plugins/aves_ui/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/plugins/aves_ui/.metadata b/plugins/aves_ui/.metadata new file mode 100644 index 0000000..c24d00d --- /dev/null +++ b/plugins/aves_ui/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: 5464c5bac742001448fe4fc0597be939379f88ea + channel: stable + +project_type: package diff --git a/plugins/aves_ui/analysis_options.yaml b/plugins/aves_ui/analysis_options.yaml new file mode 100644 index 0000000..f04c6cf --- /dev/null +++ b/plugins/aves_ui/analysis_options.yaml @@ -0,0 +1 @@ +include: ../../analysis_options.yaml diff --git a/plugins/aves_ui/lib/aves_ui.dart b/plugins/aves_ui/lib/aves_ui.dart new file mode 100644 index 0000000..148314a --- /dev/null +++ b/plugins/aves_ui/lib/aves_ui.dart @@ -0,0 +1 @@ +export 'src/dot.dart'; diff --git a/plugins/aves_ui/lib/src/dot.dart b/plugins/aves_ui/lib/src/dot.dart new file mode 100644 index 0000000..5ae99af --- /dev/null +++ b/plugins/aves_ui/lib/src/dot.dart @@ -0,0 +1,62 @@ +import 'package:flutter/material.dart'; + +class AvesDot extends StatelessWidget { + final double diameter, outerBorderWidth, innerBorderWidth; + final Color Function(bool isDark) getOuterBorderColor, getInnerBorderColor; + + const AvesDot({ + super.key, + this.diameter = 16, + this.outerBorderWidth = 1.5, + this.innerBorderWidth = 2, + this.getOuterBorderColor = themedOuterBorderColor, + this.getInnerBorderColor = themedInnerBorderColor, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final isDark = theme.brightness == Brightness.dark; + final outerBorderColor = getOuterBorderColor(isDark); + final innerBorderColor = getInnerBorderColor(isDark); + final outerBorderRadius = BorderRadius.all(Radius.circular(diameter)); + final innerRadius = Radius.circular(diameter - outerBorderWidth); + final innerBorderRadius = BorderRadius.all(innerRadius); + + final outerDecoration = BoxDecoration( + border: Border.fromBorderSide(BorderSide( + color: outerBorderColor, + width: outerBorderWidth, + )), + borderRadius: outerBorderRadius, + ); + + final innerDecoration = BoxDecoration( + border: Border.fromBorderSide(BorderSide( + color: innerBorderColor, + width: innerBorderWidth, + )), + borderRadius: innerBorderRadius, + ); + + return Container( + decoration: outerDecoration, + child: DecoratedBox( + decoration: innerDecoration, + position: DecorationPosition.foreground, + child: ClipRRect( + borderRadius: innerBorderRadius, + child: Container( + width: diameter, + height: diameter, + color: theme.colorScheme.primary, + ), + ), + ), + ); + } + + static Color themedOuterBorderColor(bool isDark) => isDark ? Colors.white30 : Colors.black26; + + static Color themedInnerBorderColor(bool isDark) => isDark ? const Color(0xFF212121) : Colors.white; +} diff --git a/plugins/aves_ui/pubspec.yaml b/plugins/aves_ui/pubspec.yaml new file mode 100644 index 0000000..0d730fd --- /dev/null +++ b/plugins/aves_ui/pubspec.yaml @@ -0,0 +1,16 @@ +name: aves_ui +version: 0.0.1 +publish_to: none + +environment: + sdk: ">=3.6.0 <4.0.0" # incoherent dartfmt from 3.7.0 +resolution: workspace + +dependencies: + flutter: + sdk: flutter + +dev_dependencies: + flutter_lints: + +flutter: diff --git a/plugins/aves_utils/.gitignore b/plugins/aves_utils/.gitignore new file mode 100644 index 0000000..79c113f --- /dev/null +++ b/plugins/aves_utils/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/plugins/aves_utils/.metadata b/plugins/aves_utils/.metadata new file mode 100644 index 0000000..ad910f5 --- /dev/null +++ b/plugins/aves_utils/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: 2ad6cd72c040113b47ee9055e722606a490ef0da + channel: stable + +project_type: package diff --git a/plugins/aves_utils/analysis_options.yaml b/plugins/aves_utils/analysis_options.yaml new file mode 100644 index 0000000..f04c6cf --- /dev/null +++ b/plugins/aves_utils/analysis_options.yaml @@ -0,0 +1 @@ +include: ../../analysis_options.yaml diff --git a/plugins/aves_utils/lib/aves_utils.dart b/plugins/aves_utils/lib/aves_utils.dart new file mode 100644 index 0000000..0058969 --- /dev/null +++ b/plugins/aves_utils/lib/aves_utils.dart @@ -0,0 +1,4 @@ +export 'src/colors.dart'; +export 'src/listenable.dart'; +export 'src/optional_event_channel.dart'; +export 'src/vector_utils.dart'; diff --git a/plugins/aves_utils/lib/src/colors.dart b/plugins/aves_utils/lib/src/colors.dart new file mode 100644 index 0000000..95c9d66 --- /dev/null +++ b/plugins/aves_utils/lib/src/colors.dart @@ -0,0 +1,72 @@ +import 'dart:convert'; +import 'dart:ui'; + +import 'package:flutter/foundation.dart'; + +class ColorUtils { + // `Color(0x00FFFFFF)` is different from `Color(0x00000000)` (or `Colors.transparent`) + // when used in gradients or lerping to it + static const transparentWhite = Color(0x00FFFFFF); + static const transparentBlack = Color(0x00000000); + + static Color textColorOn(Color background) { + final l = luma( + background.intRed, + background.intGreen, + background.intBlue, + ); + return Color(l >= .5 ? 0xFF000000 : 0xFFFFFFFF); + } + + // quick computation of luma (Y component of YUV or YIQ) from RGB + // cf https://en.wikipedia.org/wiki/Y%E2%80%B2UV + // cf https://en.wikipedia.org/wiki/YIQ + // `Color.computeLuminance()` is more accurate, but slower + // r, g, b in [0, 255], luma in [0, 1] + static double luma(int r, int g, int b) { + return (r * .299 + g * .587 + b * .114) / 255; + } +} + +extension ExtraColor on Color { + int get intRed => (r * 255).round(); // sRGB red component + int get intGreen => (g * 255).round(); // sRGB green component + int get intBlue => (b * 255).round(); // sRGB blue component + + // serialization + + String toJson() => jsonEncode(_toMap()); + + static Color? fromJson(String? jsonString) { + if (jsonString == null || jsonString.isEmpty) return null; + + try { + final jsonMap = jsonDecode(jsonString); + if (jsonMap is Map<String, dynamic>) { + return _fromMap(jsonMap); + } + debugPrint('failed to parse color from json=$jsonString'); + } catch (error, stack) { + debugPrint('failed to parse color from json=$jsonString error=$error\n$stack'); + } + return null; + } + + Map<String, dynamic> _toMap() => { + 'a': a, + 'r': r, + 'g': g, + 'b': b, + 'colorSpace': colorSpace.name, + }; + + static Color _fromMap(Map<String, dynamic> map) { + return Color.from( + alpha: map['a'] as double, + red: map['r'] as double, + green: map['g'] as double, + blue: map['b'] as double, + colorSpace: ColorSpace.values.byName(map['colorSpace'] as String), + ); + } +} diff --git a/plugins/aves_utils/lib/src/listenable.dart b/plugins/aves_utils/lib/src/listenable.dart new file mode 100644 index 0000000..75701cd --- /dev/null +++ b/plugins/aves_utils/lib/src/listenable.dart @@ -0,0 +1,55 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +// `ChangeNotifier` wrapper to call `notify` without constraint +class AChangeNotifier extends ChangeNotifier { + void notify() { + // why is this protected? + super.notifyListeners(); + } +} + +// contrary to standard `ValueListenableBuilder`, this widget allows providing a null listenable +class NullableValueListenableBuilder<T> extends StatefulWidget { + final ValueListenable<T?>? valueListenable; + final ValueWidgetBuilder<T?> builder; + final Widget? child; + + const NullableValueListenableBuilder({ + super.key, + required this.valueListenable, + required this.builder, + this.child, + }); + + @override + State<NullableValueListenableBuilder> createState() => _NullableValueListenableBuilderState<T>(); +} + +class _NullableValueListenableBuilderState<T> extends State<NullableValueListenableBuilder<T>> { + ValueNotifier<T?>? _internalValueListenable; + + ValueListenable<T?> get _valueListenable { + var listenable = widget.valueListenable; + if (listenable == null) { + _internalValueListenable ??= ValueNotifier(null); + listenable = _internalValueListenable; + } + return listenable!; + } + + @override + void dispose() { + _internalValueListenable?.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder<T?>( + valueListenable: _valueListenable, + builder: widget.builder, + child: widget.child, + ); + } +} diff --git a/plugins/aves_utils/lib/src/optional_event_channel.dart b/plugins/aves_utils/lib/src/optional_event_channel.dart new file mode 100644 index 0000000..4f8aff6 --- /dev/null +++ b/plugins/aves_utils/lib/src/optional_event_channel.dart @@ -0,0 +1,58 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +// adapted from Flutter `EventChannel` in `/services/platform_channel.dart` +// to use an `OptionalMethodChannel` when subscribing to events +class OptionalEventChannel extends EventChannel { + const OptionalEventChannel(super.name, [super.codec = const StandardMethodCodec(), super.binaryMessenger]); + + @override + Stream<dynamic> receiveBroadcastStream([dynamic arguments]) { + final MethodChannel methodChannel = OptionalMethodChannel(name, codec); + late StreamController<dynamic> controller; + controller = StreamController<dynamic>.broadcast(onListen: () async { + binaryMessenger.setMessageHandler(name, (reply) async { + if (reply == null) { + await controller.close(); + } else { + try { + controller.add(codec.decodeEnvelope(reply)); + } on PlatformException catch (e) { + controller.addError(e); + } + } + return null; + }); + try { + await methodChannel.invokeMethod<void>('listen', arguments); + } catch (error, stack) { + FlutterError.reportError(FlutterErrorDetails( + exception: error, + stack: stack, + library: 'services library', + context: ErrorDescription('while activating platform stream on channel $name'), + )); + } + }, onCancel: () async { + binaryMessenger.setMessageHandler(name, null); + try { + await methodChannel.invokeMethod<void>('cancel', arguments); + } catch (error, stack) { + if (error is PlatformException && error.message == 'No active stream to cancel') { + // ignore + return; + } + + FlutterError.reportError(FlutterErrorDetails( + exception: error, + stack: stack, + library: 'services library', + context: ErrorDescription('while de-activating platform stream on channel $name'), + )); + } + }); + return controller.stream; + } +} diff --git a/plugins/aves_utils/lib/src/vector_utils.dart b/plugins/aves_utils/lib/src/vector_utils.dart new file mode 100644 index 0000000..14f3207 --- /dev/null +++ b/plugins/aves_utils/lib/src/vector_utils.dart @@ -0,0 +1,15 @@ +import 'dart:ui'; + +import 'package:vector_math/vector_math_64.dart'; + +extension ExtraOffset on Offset { + Vector3 get toVector3 => Vector3(dx, dy, 0); +} + +extension ExtraVector3 on Vector3 { + Offset get toOffset => Offset(x, y); +} + +extension ExtraMatrix4 on Matrix4 { + Offset transformOffset(Offset v) => transform3(v.toVector3).toOffset; +} diff --git a/plugins/aves_utils/pubspec.yaml b/plugins/aves_utils/pubspec.yaml new file mode 100644 index 0000000..60f2b2d --- /dev/null +++ b/plugins/aves_utils/pubspec.yaml @@ -0,0 +1,17 @@ +name: aves_utils +version: 0.0.1 +publish_to: none + +environment: + sdk: ">=3.6.0 <4.0.0" # incoherent dartfmt from 3.7.0 +resolution: workspace + +dependencies: + flutter: + sdk: flutter + vector_math: + +dev_dependencies: + flutter_lints: + +flutter: diff --git a/plugins/aves_video/.gitignore b/plugins/aves_video/.gitignore new file mode 100644 index 0000000..79c113f --- /dev/null +++ b/plugins/aves_video/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/plugins/aves_video/.metadata b/plugins/aves_video/.metadata new file mode 100644 index 0000000..ad910f5 --- /dev/null +++ b/plugins/aves_video/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: 2ad6cd72c040113b47ee9055e722606a490ef0da + channel: stable + +project_type: package diff --git a/plugins/aves_video/analysis_options.yaml b/plugins/aves_video/analysis_options.yaml new file mode 100644 index 0000000..f04c6cf --- /dev/null +++ b/plugins/aves_video/analysis_options.yaml @@ -0,0 +1 @@ +include: ../../analysis_options.yaml diff --git a/plugins/aves_video/lib/aves_video.dart b/plugins/aves_video/lib/aves_video.dart new file mode 100644 index 0000000..8fca1cc --- /dev/null +++ b/plugins/aves_video/lib/aves_video.dart @@ -0,0 +1,7 @@ +export 'src/ab_repeat.dart'; +export 'src/controller.dart'; +export 'src/metadata.dart'; +export 'src/settings/subtitles.dart'; +export 'src/settings/video.dart'; +export 'src/stream.dart'; +export 'src/video_loop_mode.dart'; diff --git a/plugins/aves_video/lib/src/ab_repeat.dart b/plugins/aves_video/lib/src/ab_repeat.dart new file mode 100644 index 0000000..379b62b --- /dev/null +++ b/plugins/aves_video/lib/src/ab_repeat.dart @@ -0,0 +1,33 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +class ABRepeat { + final int? start, end; + + ABRepeat({this.start, this.end}); + + ABRepeat sanitize() { + if (start != null && end != null && start! > end!) { + return ABRepeat(start: end, end: start); + } + return ABRepeat(start: start, end: end); + } + + int clamp(int position) => (start != null && end != null) ? position.clamp(start!, end!) : position; +} + +mixin ABRepeatMixin { + int get currentPosition; + + ValueNotifier<ABRepeat?> abRepeatNotifier = ValueNotifier(null); + + void toggleABRepeat() => _setAbRepeat(abRepeatNotifier.value != null ? null : ABRepeat()); + + void resetABRepeat() => _setAbRepeat(ABRepeat()); + + void setABRepeatStart() => _setAbRepeat(ABRepeat(start: currentPosition, end: abRepeatNotifier.value?.end)); + + void setABRepeatEnd() => _setAbRepeat(ABRepeat(start: abRepeatNotifier.value?.start, end: currentPosition)); + + void _setAbRepeat(ABRepeat? v) => abRepeatNotifier.value = v?.sanitize(); +} diff --git a/plugins/aves_video/lib/src/controller.dart b/plugins/aves_video/lib/src/controller.dart new file mode 100644 index 0000000..c68f3a2 --- /dev/null +++ b/plugins/aves_video/lib/src/controller.dart @@ -0,0 +1,161 @@ +import 'dart:async'; + +import 'package:aves_model/aves_model.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:leak_tracker/leak_tracker.dart'; + +abstract class AvesVideoControllerFactory { + void init(); + + AvesVideoController buildController( + AvesEntryBase entry, { + required PlaybackStateHandler playbackStateHandler, + required VideoSettings settings, + }); +} + +abstract class AvesVideoController with ABRepeatMixin { + final AvesEntryBase _entry; + final PlaybackStateHandler playbackStateHandler; + final VideoSettings settings; + bool _disposed = false; + + AvesEntryBase get entry => _entry; + + static const resumeTimeSaveMinDuration = Duration(minutes: 2); + + AvesVideoController( + AvesEntryBase entry, { + required this.playbackStateHandler, + required this.settings, + }) : _entry = entry { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$AvesVideoController', + object: this, + ); + } + entry.visualChangeNotifier.addListener(onVisualChanged); + } + + @mustCallSuper + Future<void> dispose() async { + assert(!_disposed); + _disposed = true; + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + abRepeatNotifier.dispose(); + _entry.visualChangeNotifier.removeListener(onVisualChanged); + await _savePlaybackState(); + } + + Future<void> _savePlaybackState() async { + if (!isReady || duration < resumeTimeSaveMinDuration.inMilliseconds) return; + await playbackStateHandler.saveResumeTime(entryId: _entry.id, position: currentPosition, progress: progress); + } + + Future<int?> getResumeTime(BuildContext context) => playbackStateHandler.getResumeTime(entryId: _entry.id, context: context); + + void onVisualChanged(); + + Future<void> play(); + + Future<void> pause(); + + Future<void> seekTo(int targetMillis); + + Future<void> seekToProgress(double progress) => seekTo((duration * progress.clamp(0, 1)).toInt()); + + Future<void> skipFrames(int frameCount); + + Listenable get playCompletedListenable; + + VideoStatus get status; + + Stream<VideoStatus> get statusStream; + + Stream<double> get volumeStream; + + Stream<double> get speedStream; + + bool get isReady; + + Future<void> get untilReady { + if (isReady) return Future.value(); + + final completer = Completer(); + late StreamSubscription<VideoStatus> sub; + sub = statusStream.where((_) => isReady).listen((_) { + sub.cancel(); + completer.complete(); + }); + return completer.future; + } + + bool get isPlaying => status == VideoStatus.playing; + + int get duration; + + @override + int get currentPosition; + + double get progress { + final _duration = duration; + return _duration != 0 ? currentPosition.toDouble() / _duration : 0; + } + + Stream<int> get positionStream; + + Stream<String?> get timedTextStream; + + ValueNotifier<bool> get canCaptureFrameNotifier; + + ValueNotifier<bool> get canMuteNotifier; + + ValueNotifier<bool> get canSetSpeedNotifier; + + ValueNotifier<bool> get canSelectStreamNotifier; + + ValueNotifier<double?> get sarNotifier; + + bool get isMuted; + + double get speed; + + double get minSpeed; + + double get maxSpeed; + + set speed(double speed); + + Future<void> selectStream(MediaStreamType type, MediaStreamSummary? selected); + + Future<MediaStreamSummary?> getSelectedStream(MediaStreamType type); + + List<MediaStreamSummary> get streams; + + Future<Uint8List?> captureFrame(); + + Future<void> mute(bool muted); + + Widget buildPlayerWidget(BuildContext context); +} + +enum VideoStatus { + idle, + initialized, + paused, + playing, + completed, + error, +} + +abstract class PlaybackStateHandler { + Future<int?> getResumeTime({required int entryId, required BuildContext context}); + + Future<void> saveResumeTime({required int entryId, required int position, required double progress}); +} diff --git a/plugins/aves_video/lib/src/metadata.dart b/plugins/aves_video/lib/src/metadata.dart new file mode 100644 index 0000000..21f6990 --- /dev/null +++ b/plugins/aves_video/lib/src/metadata.dart @@ -0,0 +1,9 @@ +import 'dart:async'; + +import 'package:aves_model/aves_model.dart'; + +abstract class AvesVideoMetadataFetcher { + void init(); + + Future<Map> getMetadata(AvesEntryBase entry); +} diff --git a/plugins/aves_video/lib/src/settings/defaults.dart b/plugins/aves_video/lib/src/settings/defaults.dart new file mode 100644 index 0000000..dd457cc --- /dev/null +++ b/plugins/aves_video/lib/src/settings/defaults.dart @@ -0,0 +1,26 @@ +import 'dart:ui'; + +import 'package:aves_model/aves_model.dart'; +import 'package:aves_utils/aves_utils.dart'; + +class SettingsDefaults { + // video + static const enableVideoHardwareAcceleration = true; + static const videoAutoPlayMode = VideoAutoPlayMode.disabled; + static const videoBackgroundMode = VideoBackgroundMode.disabled; + static const videoLoopMode = VideoLoopMode.shortOnly; + static const videoResumptionMode = VideoResumptionMode.ask; + static const videoShowRawTimedText = false; + static const videoControlActions = [EntryAction.videoTogglePlay]; + static const videoGestureDoubleTapTogglePlay = false; + static const videoGestureSideDoubleTapSeek = true; + static const videoGestureVerticalDragBrightnessVolume = false; + + // subtitles + static const subtitleFontSize = 20.0; + static const subtitleTextAlignment = TextAlign.center; + static const subtitleTextPosition = SubtitlePosition.bottom; + static const subtitleShowOutline = true; + static const subtitleTextColor = Color(0xFFFFFFFF); + static const subtitleBackgroundColor = ColorUtils.transparentBlack; +} diff --git a/plugins/aves_video/lib/src/settings/subtitles.dart b/plugins/aves_video/lib/src/settings/subtitles.dart new file mode 100644 index 0000000..baa757a --- /dev/null +++ b/plugins/aves_video/lib/src/settings/subtitles.dart @@ -0,0 +1,31 @@ +import 'dart:ui'; + +import 'package:aves_model/aves_model.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:aves_video/src/settings/defaults.dart'; + +mixin SubtitlesSettings on SettingsAccess { + double get subtitleFontSize => getDouble(SettingKeys.subtitleFontSizeKey) ?? SettingsDefaults.subtitleFontSize; + + set subtitleFontSize(double newValue) => set(SettingKeys.subtitleFontSizeKey, newValue); + + TextAlign get subtitleTextAlignment => getEnumOrDefault(SettingKeys.subtitleTextAlignmentKey, SettingsDefaults.subtitleTextAlignment, TextAlign.values); + + set subtitleTextAlignment(TextAlign newValue) => set(SettingKeys.subtitleTextAlignmentKey, newValue.toString()); + + SubtitlePosition get subtitleTextPosition => getEnumOrDefault(SettingKeys.subtitleTextPositionKey, SettingsDefaults.subtitleTextPosition, SubtitlePosition.values); + + set subtitleTextPosition(SubtitlePosition newValue) => set(SettingKeys.subtitleTextPositionKey, newValue.toString()); + + bool get subtitleShowOutline => getBool(SettingKeys.subtitleShowOutlineKey) ?? SettingsDefaults.subtitleShowOutline; + + set subtitleShowOutline(bool newValue) => set(SettingKeys.subtitleShowOutlineKey, newValue); + + Color get subtitleTextColor => ExtraColor.fromJson(getString(SettingKeys.subtitleTextColorKey)) ?? SettingsDefaults.subtitleTextColor; + + set subtitleTextColor(Color newValue) => set(SettingKeys.subtitleTextColorKey, newValue.toJson()); + + Color get subtitleBackgroundColor => ExtraColor.fromJson(getString(SettingKeys.subtitleBackgroundColorKey)) ?? SettingsDefaults.subtitleBackgroundColor; + + set subtitleBackgroundColor(Color newValue) => set(SettingKeys.subtitleBackgroundColorKey, newValue.toJson()); +} diff --git a/plugins/aves_video/lib/src/settings/video.dart b/plugins/aves_video/lib/src/settings/video.dart new file mode 100644 index 0000000..80be235 --- /dev/null +++ b/plugins/aves_video/lib/src/settings/video.dart @@ -0,0 +1,40 @@ +import 'package:aves_model/aves_model.dart'; +import 'package:aves_video/src/settings/defaults.dart'; + +mixin VideoSettings on SettingsAccess { + bool get enableVideoHardwareAcceleration => getBool(SettingKeys.enableVideoHardwareAccelerationKey) ?? SettingsDefaults.enableVideoHardwareAcceleration; + + set enableVideoHardwareAcceleration(bool newValue) => set(SettingKeys.enableVideoHardwareAccelerationKey, newValue); + + VideoAutoPlayMode get videoAutoPlayMode => getEnumOrDefault(SettingKeys.videoAutoPlayModeKey, SettingsDefaults.videoAutoPlayMode, VideoAutoPlayMode.values); + + set videoAutoPlayMode(VideoAutoPlayMode newValue) => set(SettingKeys.videoAutoPlayModeKey, newValue.toString()); + + VideoBackgroundMode get videoBackgroundMode => getEnumOrDefault(SettingKeys.videoBackgroundModeKey, SettingsDefaults.videoBackgroundMode, VideoBackgroundMode.values); + + set videoBackgroundMode(VideoBackgroundMode newValue) => set(SettingKeys.videoBackgroundModeKey, newValue.toString()); + + VideoLoopMode get videoLoopMode => getEnumOrDefault(SettingKeys.videoLoopModeKey, SettingsDefaults.videoLoopMode, VideoLoopMode.values); + + set videoLoopMode(VideoLoopMode newValue) => set(SettingKeys.videoLoopModeKey, newValue.toString()); + + VideoResumptionMode get videoResumptionMode => getEnumOrDefault(SettingKeys.videoResumptionModeKey, SettingsDefaults.videoResumptionMode, VideoResumptionMode.values); + + set videoResumptionMode(VideoResumptionMode newValue) => set(SettingKeys.videoResumptionModeKey, newValue.toString()); + + List<EntryAction> get videoControlActions => getEnumListOrDefault(SettingKeys.videoControlActionsKey, SettingsDefaults.videoControlActions, EntryAction.values); + + set videoControlActions(List<EntryAction> newValue) => set(SettingKeys.videoControlActionsKey, newValue.map((v) => v.toString()).toList()); + + bool get videoGestureDoubleTapTogglePlay => getBool(SettingKeys.videoGestureDoubleTapTogglePlayKey) ?? SettingsDefaults.videoGestureDoubleTapTogglePlay; + + set videoGestureDoubleTapTogglePlay(bool newValue) => set(SettingKeys.videoGestureDoubleTapTogglePlayKey, newValue); + + bool get videoGestureSideDoubleTapSeek => getBool(SettingKeys.videoGestureSideDoubleTapSeekKey) ?? SettingsDefaults.videoGestureSideDoubleTapSeek; + + set videoGestureSideDoubleTapSeek(bool newValue) => set(SettingKeys.videoGestureSideDoubleTapSeekKey, newValue); + + bool get videoGestureVerticalDragBrightnessVolume => getBool(SettingKeys.videoGestureVerticalDragBrightnessVolumeKey) ?? SettingsDefaults.videoGestureVerticalDragBrightnessVolume; + + set videoGestureVerticalDragBrightnessVolume(bool newValue) => set(SettingKeys.videoGestureVerticalDragBrightnessVolumeKey, newValue); +} diff --git a/plugins/aves_video/lib/src/stream.dart b/plugins/aves_video/lib/src/stream.dart new file mode 100644 index 0000000..1d75488 --- /dev/null +++ b/plugins/aves_video/lib/src/stream.dart @@ -0,0 +1,22 @@ +import 'package:flutter/foundation.dart'; + +enum MediaStreamType { video, audio, text } + +class MediaStreamSummary { + final MediaStreamType type; + final int? index, width, height; + final String? codecName, language, title; + + const MediaStreamSummary({ + required this.type, + required this.index, + required this.codecName, + required this.language, + required this.title, + required this.width, + required this.height, + }); + + @override + String toString() => '$runtimeType#${shortHash(this)}{type: $type, index: $index, codecName: $codecName, language: $language, title: $title, width: $width, height: $height}'; +} diff --git a/plugins/aves_video/lib/src/video_loop_mode.dart b/plugins/aves_video/lib/src/video_loop_mode.dart new file mode 100644 index 0000000..196bd01 --- /dev/null +++ b/plugins/aves_video/lib/src/video_loop_mode.dart @@ -0,0 +1,19 @@ +import 'package:aves_model/aves_model.dart'; + +extension ExtraVideoLoopMode on VideoLoopMode { + static const shortVideoThreshold = Duration(seconds: 30); + + bool shouldLoop(AvesEntryBase entry) { + if (entry.isAnimated) return true; + + switch (this) { + case VideoLoopMode.never: + return false; + case VideoLoopMode.shortOnly: + final durationMillis = entry.durationMillis; + return durationMillis != null ? durationMillis < shortVideoThreshold.inMilliseconds : false; + case VideoLoopMode.always: + return true; + } + } +} diff --git a/plugins/aves_video/pubspec.yaml b/plugins/aves_video/pubspec.yaml new file mode 100644 index 0000000..903cca2 --- /dev/null +++ b/plugins/aves_video/pubspec.yaml @@ -0,0 +1,21 @@ +name: aves_video +version: 0.0.1 +publish_to: none + +environment: + sdk: ">=3.6.0 <4.0.0" # incoherent dartfmt from 3.7.0 +resolution: workspace + +dependencies: + flutter: + sdk: flutter + aves_model: + path: ../aves_model + aves_utils: + path: ../aves_utils + leak_tracker: + +dev_dependencies: + flutter_lints: + +flutter: diff --git a/plugins/aves_video_mpv/.gitignore b/plugins/aves_video_mpv/.gitignore new file mode 100644 index 0000000..79c113f --- /dev/null +++ b/plugins/aves_video_mpv/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/plugins/aves_video_mpv/.metadata b/plugins/aves_video_mpv/.metadata new file mode 100644 index 0000000..9596fae --- /dev/null +++ b/plugins/aves_video_mpv/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: 796c8ef79279f9c774545b3771238c3098dbefab + channel: stable + +project_type: package diff --git a/plugins/aves_video_mpv/analysis_options.yaml b/plugins/aves_video_mpv/analysis_options.yaml new file mode 100644 index 0000000..f04c6cf --- /dev/null +++ b/plugins/aves_video_mpv/analysis_options.yaml @@ -0,0 +1 @@ +include: ../../analysis_options.yaml diff --git a/plugins/aves_video_mpv/lib/aves_video_mpv.dart b/plugins/aves_video_mpv/lib/aves_video_mpv.dart new file mode 100644 index 0000000..0ec578d --- /dev/null +++ b/plugins/aves_video_mpv/lib/aves_video_mpv.dart @@ -0,0 +1,3 @@ +export 'src/controller.dart'; +export 'src/factory.dart'; +export 'src/metadata.dart'; diff --git a/plugins/aves_video_mpv/lib/src/controller.dart b/plugins/aves_video_mpv/lib/src/controller.dart new file mode 100644 index 0000000..b169208 --- /dev/null +++ b/plugins/aves_video_mpv/lib/src/controller.dart @@ -0,0 +1,436 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:aves_model/aves_model.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:aves_video_mpv/src/tracks.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:media_kit/media_kit.dart'; +import 'package:media_kit_video/media_kit_video.dart'; +import 'package:path/path.dart' as p; + +class MpvVideoController extends AvesVideoController { + late Player _instance; + late VideoStatus _status; + bool _firstFrameRendered = false, _abRepeatSeeking = false; + final ValueNotifier<VideoController?> _controllerNotifier = ValueNotifier(null); + final List<StreamSubscription> _subscriptions = []; + final StreamController<VideoStatus> _statusStreamController = StreamController.broadcast(); + final StreamController<String?> _timedTextStreamController = StreamController.broadcast(); + final AChangeNotifier _completedNotifier = AChangeNotifier(); + final List<SubtitleTrack> _externalSubtitleTracks = []; + + static final _pContext = p.Context(); + + @override + double get minSpeed => .25; + + @override + double get maxSpeed => 4; + + @override + final ValueNotifier<bool> canCaptureFrameNotifier = ValueNotifier(true); + + @override + final ValueNotifier<bool> canMuteNotifier = ValueNotifier(true); + + @override + final ValueNotifier<bool> canSetSpeedNotifier = ValueNotifier(true); + + @override + final ValueNotifier<bool> canSelectStreamNotifier = ValueNotifier(false); + + @override + final ValueNotifier<double?> sarNotifier = ValueNotifier(null); + + MpvVideoController( + super.entry, { + required super.playbackStateHandler, + required super.settings, + }) { + _status = VideoStatus.idle; + _statusStreamController.add(_status); + + _instance = Player( + configuration: PlayerConfiguration( + title: entry.bestTitle ?? entry.uri, + libass: false, + logLevel: MPVLogLevel.warn, + protocolWhitelist: [ + ...const PlayerConfiguration().protocolWhitelist, + // Android `content` URIs are considered unsafe by default, + // as they are transferred via a custom `fd` protocol + 'fd', + ], + ), + ); + _initController(); + _init(); + + _startListening(); + } + + @override + Future<void> dispose() async { + await super.dispose(); + + _stopListening(); + _stopStreamFetchTimer(); + await _statusStreamController.close(); + await _timedTextStreamController.close(); + await _instance.dispose(); + _controllerNotifier.dispose(); + + _completedNotifier.dispose(); + canCaptureFrameNotifier.dispose(); + canMuteNotifier.dispose(); + canSetSpeedNotifier.dispose(); + canSelectStreamNotifier.dispose(); + sarNotifier.dispose(); + } + + void _startListening() { + _subscriptions.add(statusStream.listen((v) => _status = v)); + + final playerStream = _instance.stream; + _subscriptions.add(playerStream.completed.listen((completed) { + if (completed) { + _statusStreamController.add(VideoStatus.completed); + _completedNotifier.notify(); + } + })); + _subscriptions.add(playerStream.playing.listen((playing) { + if (status == VideoStatus.idle) return; + _statusStreamController.add(playing ? VideoStatus.playing : VideoStatus.paused); + })); + _subscriptions.add(playerStream.position.listen((v) { + final abRepeat = abRepeatNotifier.value; + if (abRepeat != null && status == VideoStatus.playing) { + final start = abRepeat.start; + final end = abRepeat.end; + if (start != null && end != null) { + if (v.inMilliseconds < end) { + _abRepeatSeeking = false; + } else if (!_abRepeatSeeking) { + _abRepeatSeeking = true; + _instance.seek(Duration(milliseconds: start)); + } + } + } + })); + _subscriptions.add(playerStream.subtitle.listen((v) => _timedTextStreamController.add(v.isEmpty ? null : v[0]))); + _subscriptions.add(playerStream.videoParams.listen((v) => sarNotifier.value = v.par)); + _subscriptions.add(playerStream.log.listen((v) => debugPrint('libmpv log: $v'))); + _subscriptions.add(playerStream.error.listen((v) => debugPrint('libmpv error: $v'))); + + final settingsStream = settings.updateStream; + _subscriptions.add(settingsStream.where((event) => event.key == SettingKeys.enableVideoHardwareAccelerationKey).listen((_) => _initController())); + _subscriptions.add(settingsStream.where((event) => event.key == SettingKeys.videoLoopModeKey).listen((_) => _applyLoop())); + + final path = entry.path; + if (path != null) { + final videoBasename = _pContext.basenameWithoutExtension(path); + // list subtitle files in the same directory + // some files may be visible to the app (e.g. SRT) while others may not (e.g. SUB, VTT) + _subscriptions.add(File(path).parent.list().where((v) => v is File && _isSubtitle(v.path)).listen((v) { + final subtitleBasename = _pContext.basename(v.path); + if (subtitleBasename.startsWith(videoBasename)) { + _externalSubtitleTracks.add(SubtitleTrack.uri( + v.uri.toString(), + title: 'File ${subtitleBasename.substring(videoBasename.length)}', + )); + _externalSubtitleTracks.sort((a, b) => a.title!.compareTo(b.title!)); + } + })); + } + } + + void _stopListening() { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + Future<void> _applyLoop() async { + final loopEnabled = settings.videoLoopMode.shouldLoop(entry); + await _instance.setPlaylistMode(loopEnabled ? PlaylistMode.single : PlaylistMode.none); + } + + Future<void> _init({int startMillis = 0}) async { + final playing = _instance.state.playing; + + // Audio quality is better with `audiotrack` than `opensles` (the default). + // Calling `setAudioDevice` does not seem to work. + // As of 2025/01/13, directly setting audio output via property works for some files but not all, + // and switching from a supported file to an unsupported file crashes: + // cf https://github.com/media-kit/media-kit/issues/1061 + + await _applyLoop(); + await _instance.open(Media(entry.uri), play: playing); + await _instance.setSubtitleTrack(SubtitleTrack.no()); + if (startMillis > 0) { + await seekTo(startMillis); + } + + _fetchStreams(); + _statusStreamController.add(_instance.state.playing ? VideoStatus.playing : VideoStatus.paused); + } + + void _initController() { + _firstFrameRendered = false; + _controllerNotifier.value = VideoController( + _instance, + configuration: VideoControllerConfiguration( + enableHardwareAcceleration: settings.enableVideoHardwareAcceleration, + ), + )..waitUntilFirstFrameRendered.then((v) { + _firstFrameRendered = true; + _statusStreamController.add(_status); + }); + } + + @override + void onVisualChanged() => _init(startMillis: currentPosition); + + @override + Future<void> play() async { + await untilReady; + await _instance.play(); + } + + @override + Future<void> pause() => _instance.pause(); + + @override + Future<void> seekTo(int targetMillis) async { + if (!isReady) { + await untilReady; + // When the player gets ready, it can play from the beginning right away, + // but trying to seek then just plays from the start. + // There is no state or hook identifying readiness to seek on start, + // and `PlayerConfiguration.ready` hook is useless. + await Future.delayed(const Duration(milliseconds: 500)); + } + targetMillis = abRepeatNotifier.value?.clamp(targetMillis) ?? targetMillis; + await _instance.seek(Duration(milliseconds: targetMillis)); + } + + @override + Future<void> skipFrames(int frameCount) async { + final platform = _instance.platform; + if (platform is NativePlayer) { + if (frameCount > 0) { + await platform.command(['frame-step']); + } else if (frameCount < 0) { + await platform.command(['frame-back-step']); + } + } else { + throw Exception('Platform player ${platform.runtimeType} does not support frame stepping'); + } + } + + @override + Listenable get playCompletedListenable => _completedNotifier; + + @override + VideoStatus get status => _status; + + @override + Stream<VideoStatus> get statusStream => _statusStreamController.stream; + + @override + Stream<double> get volumeStream => _instance.stream.volume; + + @override + Stream<double> get speedStream => _instance.stream.rate; + + @override + bool get isReady { + switch (_status) { + case VideoStatus.error: + case VideoStatus.idle: + case VideoStatus.initialized: + return false; + case VideoStatus.paused: + case VideoStatus.playing: + case VideoStatus.completed: + return _firstFrameRendered; + } + } + + @override + int get duration => _instance.state.duration.inMilliseconds; + + @override + int get currentPosition => _instance.state.position.inMilliseconds; + + @override + Stream<int> get positionStream => _instance.stream.position.map((pos) => pos.inMilliseconds); + + @override + Stream<String?> get timedTextStream => _timedTextStreamController.stream; + + @override + bool get isMuted => _instance.state.volume == 0; + + @override + Future<void> mute(bool muted) => _instance.setVolume(muted ? 0 : 100); + + @override + double get speed => _instance.state.rate; + + @override + set speed(double speed) => _instance.setRate(speed); + + @override + Future<Uint8List?> captureFrame() => _instance.screenshot(); + + @override + Widget buildPlayerWidget(BuildContext context) { + return ValueListenableBuilder<double?>( + valueListenable: sarNotifier, + builder: (context, sar, child) { + if (sar == null) return const SizedBox(); + + // derive DAR (Display Aspect Ratio) from SAR (Storage Aspect Ratio), if any + // e.g. 960x536 (~16:9) with SAR 4:3 should be displayed as ~2.39:1 + final dar = entry.displayAspectRatio * sar; + return ValueListenableBuilder<VideoController?>( + valueListenable: _controllerNotifier, + builder: (context, controller, child) { + if (controller == null) return const SizedBox(); + return Video( + controller: controller, + fill: Colors.transparent, + aspectRatio: dar, + controls: NoVideoControls, + wakelock: false, + subtitleViewConfiguration: const SubtitleViewConfiguration( + visible: false, + ), + ); + }); + }, + ); + } + + // streams (aka tracks) + + // `auto` and `no` are the first 2 tracks in the player state track lists + static const int fakeTrackCount = 2; + + Tracks get _tracks => _instance.state.tracks; + + List<VideoTrack> get _videoTracks => _tracks.video.skip(fakeTrackCount).toList(); + + List<AudioTrack> get _audioTracks => _tracks.audio.skip(fakeTrackCount).toList(); + + List<SubtitleTrack> get _subtitleTracks { + final externalTitles = _externalSubtitleTracks.map((v) => v.title).toSet(); + return [ + ..._tracks.subtitle.skip(fakeTrackCount).where((v) => !externalTitles.contains(v.title)), + ..._externalSubtitleTracks, + ]; + } + + @override + List<MediaStreamSummary> get streams { + return { + ..._videoTracks.mapIndexed((i, v) => v.toAves(i)), + ..._audioTracks.mapIndexed((i, v) => v.toAves(i)), + ..._subtitleTracks.mapIndexed((i, v) => v.toAves(i)), + }.toList(); + } + + Timer? _streamFetchTimer; + + void _stopStreamFetchTimer() { + _streamFetchTimer?.cancel(); + _streamFetchTimer = null; + } + + void _fetchStreams() { + _stopStreamFetchTimer(); + _streamFetchTimer = Timer.periodic(const Duration(milliseconds: 100), (_) { + if (status != VideoStatus.error) { + if (_videoTracks.isEmpty && _audioTracks.isEmpty) return; + + final videoStreamCount = _videoTracks.length; + final audioStreamCount = _audioTracks.length; + final textStreamCount = _subtitleTracks.length; + canSelectStreamNotifier.value = videoStreamCount > 1 || audioStreamCount > 1 || textStreamCount > 0; + } + _stopStreamFetchTimer(); + }); + } + + @override + Future<MediaStreamSummary?> getSelectedStream(MediaStreamType type) async { + final track = _instance.state.track; + switch (type) { + case MediaStreamType.video: + final video = track.video; + if (video != VideoTrack.no()) { + final index = video == VideoTrack.auto() ? 0 : _videoTracks.indexOf(video); + return video.toAves(index); + } + case MediaStreamType.audio: + final audio = track.audio; + if (audio != AudioTrack.no()) { + final index = audio == AudioTrack.auto() ? 0 : _audioTracks.indexOf(audio); + return audio.toAves(index); + } + case MediaStreamType.text: + final subtitle = track.subtitle; + if (subtitle != SubtitleTrack.no()) { + final index = subtitle == SubtitleTrack.auto() ? 0 : _subtitleTracks.indexOf(subtitle); + return subtitle.toAves(index); + } + } + return null; + } + + @override + Future<void> selectStream(MediaStreamType type, MediaStreamSummary? selected) async { + final current = await getSelectedStream(type); + if (current == selected) return; + + if (selected != null) { + final newIndex = selected.index; + if (newIndex != null) { + // select track + switch (type) { + case MediaStreamType.video: + await _instance.setVideoTrack(_videoTracks[selected.index ?? 0]); + break; + case MediaStreamType.audio: + await _instance.setAudioTrack(_audioTracks[selected.index ?? 0]); + break; + case MediaStreamType.text: + await _instance.setSubtitleTrack(_subtitleTracks[selected.index ?? 0]); + break; + } + } + } else if (current != null) { + // deselect track + switch (type) { + case MediaStreamType.video: + await _instance.setVideoTrack(VideoTrack.no()); + break; + case MediaStreamType.audio: + await _instance.setAudioTrack(AudioTrack.no()); + break; + case MediaStreamType.text: + await _instance.setSubtitleTrack(SubtitleTrack.no()); + break; + } + } + } + + static const Set<String> _subtitleExtensions = {'.srt', '.sub', '.vtt'}; + + static bool _isSubtitle(String path) => _subtitleExtensions.contains(_pContext.extension(path)); +} diff --git a/plugins/aves_video_mpv/lib/src/factory.dart b/plugins/aves_video_mpv/lib/src/factory.dart new file mode 100644 index 0000000..2fdbd74 --- /dev/null +++ b/plugins/aves_video_mpv/lib/src/factory.dart @@ -0,0 +1,21 @@ +import 'package:aves_model/aves_model.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:aves_video_mpv/aves_video_mpv.dart'; +import 'package:media_kit/media_kit.dart'; + +class MpvVideoControllerFactory extends AvesVideoControllerFactory { + @override + void init() => MediaKit.ensureInitialized(); + + @override + AvesVideoController buildController( + AvesEntryBase entry, { + required PlaybackStateHandler playbackStateHandler, + required VideoSettings settings, + }) => + MpvVideoController( + entry, + playbackStateHandler: playbackStateHandler, + settings: settings, + ); +} diff --git a/plugins/aves_video_mpv/lib/src/metadata.dart b/plugins/aves_video_mpv/lib/src/metadata.dart new file mode 100644 index 0000000..f488c08 --- /dev/null +++ b/plugins/aves_video_mpv/lib/src/metadata.dart @@ -0,0 +1,199 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:aves_model/aves_model.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:flutter/widgets.dart'; +import 'package:media_kit/media_kit.dart'; + +class MpvVideoMetadataFetcher extends AvesVideoMetadataFetcher { + static const mpvTypeAudio = 'audio'; + static const mpvTypeVideo = 'video'; + static const mpvTypeSub = 'sub'; + + static const probeTimeoutImage = 500; + static const probeTimeoutVideo = 5000; + + @override + void init() => MediaKit.ensureInitialized(); + + @override + Future<Map> getMetadata(AvesEntryBase entry) async { + final player = Player( + configuration: PlayerConfiguration( + logLevel: MPVLogLevel.warn, + protocolWhitelist: [ + ...const PlayerConfiguration().protocolWhitelist, + // Android `content` URIs are considered unsafe by default, + // as they are transferred via a custom `fd` protocol + 'fd', + ], + ), + ); + final platform = player.platform; + if (platform is! NativePlayer) { + throw Exception('Platform player ${platform.runtimeType} does not support property retrieval'); + } + + // We need to enable video decoding to retrieve video params, + // but it is disabled by default unless a `VideoController` is attached. + // Attaching a `VideoController` is problematic, because `player.open()` may not return + // unless a new frame is rendered, and triggering fails from a background service. + // It is simpler to enable the video track via properties. + await platform.setProperty('vid', 'auto'); + + // deselect audio track to prevent triggering Android audio sessions + await platform.setProperty('aid', 'no'); + + final videoDecodedCompleter = Completer(); + StreamSubscription? subscription; + subscription = player.stream.videoParams.listen((v) { + if (v.par != null) { + subscription?.cancel(); + videoDecodedCompleter.complete(); + } + }); + + await player.open(Media(entry.uri), play: false); + + final timeoutMillis = entry.mimeType.startsWith('image') ? probeTimeoutImage : probeTimeoutVideo; + await Future.any([videoDecodedCompleter.future, Future.delayed(Duration(milliseconds: timeoutMillis))]); + + final fields = <String, dynamic>{}; + + final videoParams = player.state.videoParams; + if (videoParams.par == null) { + debugPrint('failed to probe video metadata within $timeoutMillis ms for entry=$entry'); + } else { + // mpv properties: https://mpv.io/manual/stable/#property-list + + // mpv doc: "duration with milliseconds" + final durationMs = await platform.getProperty('duration/full'); + if (durationMs.isNotEmpty) { + fields[Keys.duration] = durationMs; + } + + // mpv doc: "metadata key/value pairs" + // note: seems to match FFprobe "format" > "tags" fields + final metadata = await platform.getProperty('metadata'); + if (metadata.isNotEmpty) { + try { + jsonDecode(metadata).forEach((key, value) { + fields[key] = value; + }); + } catch (error) { + debugPrint('failed to parse metadata=$metadata with error=$error'); + } + } + + final tracks = await platform.getProperty('track-list'); + if (tracks.isNotEmpty) { + try { + final tracksJson = jsonDecode(tracks); + if (tracksJson is List && tracksJson.isNotEmpty) { + fields[Keys.streams] = tracksJson.whereType<Map>().map((stream) { + return _normalizeStream(stream.cast<String, dynamic>(), videoParams); + }).toList(); + } + } catch (error) { + debugPrint('failed to parse tracks=$tracks with error=$error'); + } + } + + final chapters = await platform.getProperty('chapter-list'); + if (chapters.isNotEmpty) { + try { + final chaptersJson = jsonDecode(chapters); + if (chaptersJson is List && chaptersJson.isNotEmpty) { + final chapterMaps = chaptersJson.whereType<Map>().toList(); + if (chapterMaps.isNotEmpty) { + fields[Keys.chapters] = chapterMaps; + } + } + } catch (error) { + debugPrint('failed to parse chapters=$chapters with error=$error'); + } + } + } + + await player.dispose(); + return fields; + } + + Map<String, dynamic> _normalizeStream(Map<String, dynamic> stream, VideoParams videoParams) { + void replaceKey(String k1, String k2) { + final v = stream.remove(k1); + if (v != null) { + stream[k2] = v; + } + } + + void removeIfFalse(String k) { + if (stream[k] == false) { + stream.remove(k); + } + } + + stream.remove('id'); + stream.remove('decoder-desc'); + stream.remove('main-selection'); + stream.remove('selected'); + stream.remove('src-id'); + replaceKey('ff-index', Keys.index); + replaceKey('codec', Keys.codecName); + replaceKey('lang', Keys.language); + replaceKey('demux-bitrate', Keys.bitrate); + replaceKey('demux-channel-count', Keys.audioChannels); + replaceKey('demux-fps', Keys.fps); + replaceKey('demux-samplerate', Keys.sampleRate); + replaceKey('hearing-impaired', Keys.hearingImpaired); + replaceKey('visual-impaired', Keys.visualImpaired); + + stream.removeWhere((k, v) => k.startsWith('demux-')); + removeIfFalse('albumart'); + removeIfFalse('default'); + removeIfFalse('dependent'); + removeIfFalse('external'); + removeIfFalse('forced'); + removeIfFalse(Keys.hearingImpaired); + removeIfFalse(Keys.visualImpaired); + + final isImage = stream.remove('image'); + switch (stream.remove('type')) { + case mpvTypeAudio: + stream[Keys.streamType] = MediaStreamTypes.audio; + case mpvTypeVideo: + stream[Keys.streamType] = MediaStreamTypes.video; + if (isImage) { + stream.remove(Keys.fps); + } + + // Some video properties are not in the video track props but accessible via `video-params` (or `video-out-params`). + // These parameters are already stored in the player state, as `videoParams`. + // Parameters `sigPeak` and `averageBpp` are ignored. + final videoParamsTags = <String, dynamic>{ + Keys.alpha: videoParams.alpha, + Keys.chromaLocation: videoParams.chromaLocation, + Keys.codecPixelFormat: videoParams.pixelformat, + Keys.colorLevels: videoParams.colorlevels, + Keys.colorMatrix: videoParams.colormatrix, + Keys.colorPrimaries: videoParams.primaries, + Keys.dar: videoParams.aspect, + Keys.decoderHeight: videoParams.dh, + Keys.decoderWidth: videoParams.dw, + Keys.gamma: videoParams.gamma, + Keys.hwPixelFormat: videoParams.hwPixelformat, + Keys.light: videoParams.light, + Keys.par: videoParams.par, + Keys.rotate: videoParams.rotate, + Keys.stereo3dMode: videoParams.stereoIn, + Keys.videoHeight: videoParams.h, + Keys.videoWidth: videoParams.w, + }..removeWhere((k, v) => v == null); + stream.addAll(videoParamsTags); + case mpvTypeSub: + stream[Keys.streamType] = MediaStreamTypes.subtitle; + } + return stream; + } +} diff --git a/plugins/aves_video_mpv/lib/src/tracks.dart b/plugins/aves_video_mpv/lib/src/tracks.dart new file mode 100644 index 0000000..7deba54 --- /dev/null +++ b/plugins/aves_video_mpv/lib/src/tracks.dart @@ -0,0 +1,44 @@ +import 'package:aves_video/aves_video.dart'; +import 'package:media_kit/media_kit.dart'; + +extension ExtraVideoTrack on VideoTrack { + MediaStreamSummary toAves(int index) { + return MediaStreamSummary( + type: MediaStreamType.video, + index: index, + codecName: null, + language: language, + title: title, + width: null, + height: null, + ); + } +} + +extension ExtraAudioTrack on AudioTrack { + MediaStreamSummary toAves(int index) { + return MediaStreamSummary( + type: MediaStreamType.audio, + index: index, + codecName: null, + language: language, + title: title, + width: null, + height: null, + ); + } +} + +extension ExtraSubtitleTrack on SubtitleTrack { + MediaStreamSummary toAves(int index) { + return MediaStreamSummary( + type: MediaStreamType.text, + index: index, + codecName: null, + language: language, + title: title ?? '$index ($codec)', + width: null, + height: null, + ); + } +} diff --git a/plugins/aves_video_mpv/pubspec.yaml b/plugins/aves_video_mpv/pubspec.yaml new file mode 100644 index 0000000..ec2b5dc --- /dev/null +++ b/plugins/aves_video_mpv/pubspec.yaml @@ -0,0 +1,34 @@ +name: aves_video_mpv +version: 0.0.1 +publish_to: none + +environment: + sdk: ">=3.6.0 <4.0.0" # incoherent dartfmt from 3.7.0 +resolution: workspace + +dependencies: + flutter: + sdk: flutter + aves_model: + path: ../aves_model + aves_video: + path: ../aves_video + aves_utils: + path: ../aves_utils + collection: + media_kit: + media_kit_libs_android_video: + media_kit_video: + path: + +dependency_overrides: + media_kit_video: + git: + url: https://github.com/deckerst/media-kit.git + ref: flutter_v3.27 + path: media_kit_video + +dev_dependencies: + flutter_lints: + +flutter: |
