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/aves_magnifier | |
| download | aves-src-master.tar.gz aves-src-master.zip | |
Diffstat (limited to 'plugins/aves_magnifier')
18 files changed, 1648 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: |
