scale.dart 20.8 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
import 'dart:math' as math;

7 8
import 'package:vector_math/vector_math_64.dart';

9 10
import 'arena.dart';
import 'constants.dart';
11
import 'events.dart';
12
import 'recognizer.dart';
13
import 'velocity_tracker.dart';
14

15
/// The possible states of a [ScaleGestureRecognizer].
16
enum _ScaleState {
17
  /// The recognizer is ready to start recognizing a gesture.
18
  ready,
19

20
  /// The sequence of pointer events seen thus far is consistent with a scale
21
  /// gesture but the gesture has not been accepted definitively.
22
  possible,
23

24
  /// The sequence of pointer events seen thus far has been accepted
25
  /// definitively as a scale gesture.
26
  accepted,
27

28
  /// The sequence of pointer events seen thus far has been accepted
29 30 31
  /// definitively as a scale gesture and the pointers established a focal point
  /// and initial scale.
  started,
32 33
}

34 35 36 37 38
/// Details for [GestureScaleStartCallback].
class ScaleStartDetails {
  /// Creates details for [GestureScaleStartCallback].
  ///
  /// The [focalPoint] argument must not be null.
39
  ScaleStartDetails({ this.focalPoint = Offset.zero, Offset? localFocalPoint, this.pointerCount = 0 })
40
    : assert(focalPoint != null), localFocalPoint = localFocalPoint ?? focalPoint;
41 42

  /// The initial focal point of the pointers in contact with the screen.
43
  ///
44
  /// Reported in global coordinates.
45 46 47 48 49
  ///
  /// See also:
  ///
  ///  * [localFocalPoint], which is the same value reported in local
  ///    coordinates.
50
  final Offset focalPoint;
51

52 53 54 55 56 57 58 59 60 61 62
  /// The initial focal point of the pointers in contact with the screen.
  ///
  /// Reported in local coordinates. Defaults to [focalPoint] if not set in the
  /// constructor.
  ///
  /// See also:
  ///
  ///  * [focalPoint], which is the same value reported in global
  ///    coordinates.
  final Offset localFocalPoint;

63 64 65 66 67
  /// The number of pointers being tracked by the gesture recognizer.
  ///
  /// Typically this is the number of fingers being used to pan the widget using the gesture
  /// recognizer.
  final int pointerCount;
68

69
  @override
70
  String toString() => 'ScaleStartDetails(focalPoint: $focalPoint, localFocalPoint: $localFocalPoint, pointersCount: $pointerCount)';
71 72 73 74 75 76
}

/// Details for [GestureScaleUpdateCallback].
class ScaleUpdateDetails {
  /// Creates details for [GestureScaleUpdateCallback].
  ///
77 78
  /// The [focalPoint], [scale], [horizontalScale], [verticalScale], [rotation]
  /// arguments must not be null. The [scale], [horizontalScale], and [verticalScale]
79
  /// argument must be greater than or equal to zero.
80
  ScaleUpdateDetails({
81
    this.focalPoint = Offset.zero,
82
    Offset? localFocalPoint,
83
    this.scale = 1.0,
84 85
    this.horizontalScale = 1.0,
    this.verticalScale = 1.0,
86
    this.rotation = 0.0,
87
    this.pointerCount = 0,
88
    this.delta = Offset.zero,
89
  }) : assert(focalPoint != null),
90
       assert(delta != null),
91
       assert(scale != null && scale >= 0.0),
92 93
       assert(horizontalScale != null && horizontalScale >= 0.0),
       assert(verticalScale != null && verticalScale >= 0.0),
94 95
       assert(rotation != null),
       localFocalPoint = localFocalPoint ?? focalPoint;
96

97 98 99 100 101 102
  /// The amount the pointer has moved in the coordinate space of the event
  /// receiver since the previous update.
  ///
  /// Defaults to zero if not specified in the constructor.
  final Offset delta;

103 104 105
  /// The focal point of the pointers in contact with the screen.
  ///
  /// Reported in global coordinates.
106 107 108 109 110
  ///
  /// See also:
  ///
  ///  * [localFocalPoint], which is the same value reported in local
  ///    coordinates.
111
  final Offset focalPoint;
112

113 114 115 116 117 118 119 120 121 122 123
  /// The focal point of the pointers in contact with the screen.
  ///
  /// Reported in local coordinates. Defaults to [focalPoint] if not set in the
  /// constructor.
  ///
  /// See also:
  ///
  ///  * [focalPoint], which is the same value reported in global
  ///    coordinates.
  final Offset localFocalPoint;

124 125 126 127 128 129 130 131 132
  /// The scale implied by the average distance between the pointers in contact
  /// with the screen.
  ///
  /// This value must be greater than or equal to zero.
  ///
  /// See also:
  ///
  ///  * [horizontalScale], which is the scale along the horizontal axis.
  ///  * [verticalScale], which is the scale along the vertical axis.
133
  final double scale;
134

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
  /// The scale implied by the average distance along the horizontal axis
  /// between the pointers in contact with the screen.
  ///
  /// This value must be greater than or equal to zero.
  ///
  /// See also:
  ///
  ///  * [scale], which is the general scale implied by the pointers.
  ///  * [verticalScale], which is the scale along the vertical axis.
  final double horizontalScale;

  /// The scale implied by the average distance along the vertical axis
  /// between the pointers in contact with the screen.
  ///
  /// This value must be greater than or equal to zero.
  ///
  /// See also:
  ///
  ///  * [scale], which is the general scale implied by the pointers.
  ///  * [horizontalScale], which is the scale along the horizontal axis.
  final double verticalScale;

157
  /// The angle implied by the first two pointers to enter in contact with
158 159 160
  /// the screen.
  ///
  /// Expressed in radians.
161 162
  final double rotation;

163 164 165 166 167 168
  /// The number of pointers being tracked by the gesture recognizer.
  ///
  /// Typically this is the number of fingers being used to pan the widget using the gesture
  /// recognizer.
  final int pointerCount;

169
  @override
170 171 172 173 174 175 176 177
  String toString() => 'ScaleUpdateDetails('
    'focalPoint: $focalPoint,'
    ' localFocalPoint: $localFocalPoint,'
    ' scale: $scale,'
    ' horizontalScale: $horizontalScale,'
    ' verticalScale: $verticalScale,'
    ' rotation: $rotation,'
    ' pointerCount: $pointerCount)';
178 179 180 181 182 183 184
}

/// Details for [GestureScaleEndCallback].
class ScaleEndDetails {
  /// Creates details for [GestureScaleEndCallback].
  ///
  /// The [velocity] argument must not be null.
185
  ScaleEndDetails({ this.velocity = Velocity.zero, this.pointerCount = 0 })
186
    : assert(velocity != null);
187 188 189

  /// The velocity of the last pointer to be lifted off of the screen.
  final Velocity velocity;
190

191 192 193 194 195 196
  /// The number of pointers being tracked by the gesture recognizer.
  ///
  /// Typically this is the number of fingers being used to pan the widget using the gesture
  /// recognizer.
  final int pointerCount;

197
  @override
198
  String toString() => 'ScaleEndDetails(velocity: $velocity, pointerCount: $pointerCount)';
199 200
}

201 202
/// Signature for when the pointers in contact with the screen have established
/// a focal point and initial scale of 1.0.
203
typedef GestureScaleStartCallback = void Function(ScaleStartDetails details);
204 205 206

/// Signature for when the pointers in contact with the screen have indicated a
/// new focal point and/or scale.
207
typedef GestureScaleUpdateCallback = void Function(ScaleUpdateDetails details);
208 209

/// Signature for when the pointers are no longer in contact with the screen.
210
typedef GestureScaleEndCallback = void Function(ScaleEndDetails details);
211 212 213 214 215 216

bool _isFlingGesture(Velocity velocity) {
  assert(velocity != null);
  final double speedSquared = velocity.pixelsPerSecond.distanceSquared;
  return speedSquared > kMinFlingVelocity * kMinFlingVelocity;
}
217

218 219 220 221 222

/// Defines a line between two pointers on screen.
///
/// [_LineBetweenPointers] is an abstraction of a line between two pointers in
/// contact with the screen. Used to track the rotation of a scale gesture.
223
class _LineBetweenPointers {
224 225 226 227 228 229 230 231

  /// Creates a [_LineBetweenPointers]. None of the [pointerStartLocation], [pointerStartId]
  /// [pointerEndLocation] and [pointerEndId] must be null. [pointerStartId] and [pointerEndId]
  /// should be different.
  _LineBetweenPointers({
    this.pointerStartLocation = Offset.zero,
    this.pointerStartId = 0,
    this.pointerEndLocation = Offset.zero,
232
    this.pointerEndId = 1,
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
  }) : assert(pointerStartLocation != null && pointerEndLocation != null),
       assert(pointerStartId != null && pointerEndId != null),
       assert(pointerStartId != pointerEndId);

  // The location and the id of the pointer that marks the start of the line.
  final Offset pointerStartLocation;
  final int pointerStartId;

  // The location and the id of the pointer that marks the end of the line.
  final Offset pointerEndLocation;
  final int pointerEndId;

}


248 249 250
/// Recognizes a scale gesture.
///
/// [ScaleGestureRecognizer] tracks the pointers in contact with the screen and
Ian Hickson's avatar
Ian Hickson committed
251 252 253 254
/// calculates their focal point, indicated scale, and rotation. When a focal
/// pointer is established, the recognizer calls [onStart]. As the focal point,
/// scale, rotation change, the recognizer calls [onUpdate]. When the pointers
/// are no longer in contact with the screen, the recognizer calls [onEnd].
255
class ScaleGestureRecognizer extends OneSequenceGestureRecognizer {
256
  /// Create a gesture recognizer for interactions intended for scaling content.
257
  ///
258
  /// {@macro flutter.gestures.GestureRecognizer.supportedDevices}
259
  ScaleGestureRecognizer({
260
    Object? debugOwner,
261 262 263 264
    @Deprecated(
      'Migrate to supportedDevices. '
      'This feature was deprecated after v2.3.0-1.0.pre.',
    )
265
    PointerDeviceKind? kind,
266
    Set<PointerDeviceKind>? supportedDevices,
267 268
    this.dragStartBehavior = DragStartBehavior.down,
  }) : assert(dragStartBehavior != null),
269 270 271 272 273
       super(
         debugOwner: debugOwner,
         kind: kind,
         supportedDevices: supportedDevices,
       );
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292

  /// Determines what point is used as the starting point in all calculations
  /// involving this gesture.
  ///
  /// When set to [DragStartBehavior.down], the scale is calculated starting
  /// from the position where the pointer first contacted the screen.
  ///
  /// When set to [DragStartBehavior.start], the scale is calculated starting
  /// from the position where the scale gesture began. The scale gesture may
  /// begin after the time that the pointer first contacted the screen if there
  /// are multiple listeners competing for the gesture. In that case, the
  /// gesture arena waits to determine whether or not the gesture is a scale
  /// gesture before giving the gesture to this GestureRecognizer. This happens
  /// in the case of nested GestureDetectors, for example.
  ///
  /// Defaults to [DragStartBehavior.down].
  ///
  /// See also:
  ///
293
  /// * https://flutter.dev/docs/development/ui/advanced/gestures#gesture-disambiguation,
294 295
  ///   which provides more information about the gesture arena.
  DragStartBehavior dragStartBehavior;
296

297 298
  /// The pointers in contact with the screen have established a focal point and
  /// initial scale of 1.0.
299 300 301 302 303 304
  ///
  /// This won't be called until the gesture arena has determined that this
  /// GestureRecognizer has won the gesture.
  ///
  /// See also:
  ///
305
  /// * https://flutter.dev/docs/development/ui/advanced/gestures#gesture-disambiguation,
306
  ///   which provides more information about the gesture arena.
307
  GestureScaleStartCallback? onStart;
308 309 310

  /// The pointers in contact with the screen have indicated a new focal point
  /// and/or scale.
311
  GestureScaleUpdateCallback? onUpdate;
312 313

  /// The pointers are no longer in contact with the screen.
314
  GestureScaleEndCallback? onEnd;
315

316
  _ScaleState _state = _ScaleState.ready;
317

318 319 320 321 322 323 324 325 326 327 328 329 330 331
  Matrix4? _lastTransform;

  late Offset _initialFocalPoint;
  late Offset _currentFocalPoint;
  late double _initialSpan;
  late double _currentSpan;
  late double _initialHorizontalSpan;
  late double _currentHorizontalSpan;
  late double _initialVerticalSpan;
  late double _currentVerticalSpan;
  _LineBetweenPointers? _initialLine;
  _LineBetweenPointers? _currentLine;
  late Map<int, Offset> _pointerLocations;
  late List<int> _pointerQueue; // A queue to sort pointers in order of entrance
332
  final Map<int, VelocityTracker> _velocityTrackers = <int, VelocityTracker>{};
333

334
  double get _scaleFactor => _initialSpan > 0.0 ? _currentSpan / _initialSpan : 1.0;
335

336 337 338 339
  double get _horizontalScaleFactor => _initialHorizontalSpan > 0.0 ? _currentHorizontalSpan / _initialHorizontalSpan : 1.0;

  double get _verticalScaleFactor => _initialVerticalSpan > 0.0 ? _currentVerticalSpan / _initialVerticalSpan : 1.0;

340 341 342 343
  double _computeRotationFactor() {
    if (_initialLine == null || _currentLine == null) {
      return 0.0;
    }
344 345 346 347
    final double fx = _initialLine!.pointerStartLocation.dx;
    final double fy = _initialLine!.pointerStartLocation.dy;
    final double sx = _initialLine!.pointerEndLocation.dx;
    final double sy = _initialLine!.pointerEndLocation.dy;
348

349 350 351 352
    final double nfx = _currentLine!.pointerStartLocation.dx;
    final double nfy = _currentLine!.pointerStartLocation.dy;
    final double nsx = _currentLine!.pointerEndLocation.dx;
    final double nsy = _currentLine!.pointerEndLocation.dy;
353 354 355 356 357 358 359

    final double angle1 = math.atan2(fy - sy, fx - sx);
    final double angle2 = math.atan2(nfy - nsy, nfx - nsx);

    return angle2 - angle1;
  }

360
  @override
361
  void addAllowedPointer(PointerDownEvent event) {
362
    super.addAllowedPointer(event);
363
    _velocityTrackers[event.pointer] = VelocityTracker.withKind(event.kind);
364 365
    if (_state == _ScaleState.ready) {
      _state = _ScaleState.possible;
366 367
      _initialSpan = 0.0;
      _currentSpan = 0.0;
368 369 370 371
      _initialHorizontalSpan = 0.0;
      _currentHorizontalSpan = 0.0;
      _initialVerticalSpan = 0.0;
      _currentVerticalSpan = 0.0;
372
      _pointerLocations = <int, Offset>{};
373
      _pointerQueue = <int>[];
374 375 376
    }
  }

377
  @override
Ian Hickson's avatar
Ian Hickson committed
378
  void handleEvent(PointerEvent event) {
379 380 381
    assert(_state != _ScaleState.ready);
    bool didChangeConfiguration = false;
    bool shouldStartIfAccepted = false;
Ian Hickson's avatar
Ian Hickson committed
382
    if (event is PointerMoveEvent) {
383
      final VelocityTracker tracker = _velocityTrackers[event.pointer]!;
384 385
      if (!event.synthesized)
        tracker.addPosition(event.timeStamp, event.position);
Ian Hickson's avatar
Ian Hickson committed
386
      _pointerLocations[event.pointer] = event.position;
387
      shouldStartIfAccepted = true;
388
      _lastTransform = event.transform;
Ian Hickson's avatar
Ian Hickson committed
389 390
    } else if (event is PointerDownEvent) {
      _pointerLocations[event.pointer] = event.position;
391
      _pointerQueue.add(event.pointer);
392 393
      didChangeConfiguration = true;
      shouldStartIfAccepted = true;
394
      _lastTransform = event.transform;
395
    } else if (event is PointerUpEvent || event is PointerCancelEvent) {
Ian Hickson's avatar
Ian Hickson committed
396
      _pointerLocations.remove(event.pointer);
397
      _pointerQueue.remove(event.pointer);
398
      didChangeConfiguration = true;
399
      _lastTransform = event.transform;
400 401
    }

402
    _updateLines();
403
    _update();
404

405
    if (!didChangeConfiguration || _reconfigure(event.pointer))
406
      _advanceStateMachine(shouldStartIfAccepted, event.kind);
407 408 409
    stopTrackingIfPointerNoLongerDown(event);
  }

410
  void _update() {
411
    final int count = _pointerLocations.keys.length;
412 413

    // Compute the focal point
414
    Offset focalPoint = Offset.zero;
415
    for (final int pointer in _pointerLocations.keys)
416
      focalPoint += _pointerLocations[pointer]!;
417
    _currentFocalPoint = count > 0 ? focalPoint / count.toDouble() : Offset.zero;
418

419 420 421
    // 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.
422
    double totalDeviation = 0.0;
423 424
    double totalHorizontalDeviation = 0.0;
    double totalVerticalDeviation = 0.0;
425
    for (final int pointer in _pointerLocations.keys) {
426 427 428
      totalDeviation += (_currentFocalPoint - _pointerLocations[pointer]!).distance;
      totalHorizontalDeviation += (_currentFocalPoint.dx - _pointerLocations[pointer]!.dx).abs();
      totalVerticalDeviation += (_currentFocalPoint.dy - _pointerLocations[pointer]!.dy).abs();
429
    }
430
    _currentSpan = count > 0 ? totalDeviation / count : 0.0;
431 432
    _currentHorizontalSpan = count > 0 ? totalHorizontalDeviation / count : 0.0;
    _currentVerticalSpan = count > 0 ? totalVerticalDeviation / count : 0.0;
433
  }
434

435
  /// Updates [_initialLine] and [_currentLine] accordingly to the situation of
436
  /// the registered pointers.
437 438 439 440 441 442 443
  void _updateLines() {
    final int count = _pointerLocations.keys.length;
    assert(_pointerQueue.length >= count);
    /// In case of just one pointer registered, reconfigure [_initialLine]
    if (count < 2) {
      _initialLine = _currentLine;
    } else if (_initialLine != null &&
444 445
      _initialLine!.pointerStartId == _pointerQueue[0] &&
      _initialLine!.pointerEndId == _pointerQueue[1]) {
446 447 448
      /// Rotation updated, set the [_currentLine]
      _currentLine = _LineBetweenPointers(
        pointerStartId: _pointerQueue[0],
449
        pointerStartLocation: _pointerLocations[_pointerQueue[0]]!,
450
        pointerEndId: _pointerQueue[1],
451
        pointerEndLocation: _pointerLocations[_pointerQueue[1]]!,
452 453 454 455 456
      );
    } else {
      /// A new rotation process is on the way, set the [_initialLine]
      _initialLine = _LineBetweenPointers(
        pointerStartId: _pointerQueue[0],
457
        pointerStartLocation: _pointerLocations[_pointerQueue[0]]!,
458
        pointerEndId: _pointerQueue[1],
459
        pointerEndLocation: _pointerLocations[_pointerQueue[1]]!,
460
      );
461
      _currentLine = _initialLine;
462 463 464
    }
  }

465 466 467
  bool _reconfigure(int pointer) {
    _initialFocalPoint = _currentFocalPoint;
    _initialSpan = _currentSpan;
468
    _initialLine = _currentLine;
469 470
    _initialHorizontalSpan = _currentHorizontalSpan;
    _initialVerticalSpan = _currentVerticalSpan;
471 472
    if (_state == _ScaleState.started) {
      if (onEnd != null) {
473
        final VelocityTracker tracker = _velocityTrackers[pointer]!;
474 475

        Velocity velocity = tracker.getVelocity();
476
        if (_isFlingGesture(velocity)) {
477 478
          final Offset pixelsPerSecond = velocity.pixelsPerSecond;
          if (pixelsPerSecond.distanceSquared > kMaxFlingVelocity * kMaxFlingVelocity)
479
            velocity = Velocity(pixelsPerSecond: (pixelsPerSecond / pixelsPerSecond.distance) * kMaxFlingVelocity);
480
          invokeCallback<void>('onEnd', () => onEnd!(ScaleEndDetails(velocity: velocity, pointerCount: _pointerQueue.length)));
481
        } else {
482
          invokeCallback<void>('onEnd', () => onEnd!(ScaleEndDetails(velocity: Velocity.zero, pointerCount: _pointerQueue.length)));
483
        }
484
      }
485 486
      _state = _ScaleState.accepted;
      return false;
487
    }
488 489
    return true;
  }
490

491
  void _advanceStateMachine(bool shouldStartIfAccepted, PointerDeviceKind pointerDeviceKind) {
492 493
    if (_state == _ScaleState.ready)
      _state = _ScaleState.possible;
494

495 496 497
    if (_state == _ScaleState.possible) {
      final double spanDelta = (_currentSpan - _initialSpan).abs();
      final double focalPointDelta = (_currentFocalPoint - _initialFocalPoint).distance;
498
      if (spanDelta > computeScaleSlop(pointerDeviceKind) || focalPointDelta > computePanSlop(pointerDeviceKind))
499 500
        resolve(GestureDisposition.accepted);
    } else if (_state.index >= _ScaleState.accepted.index) {
501 502 503
      resolve(GestureDisposition.accepted);
    }

504 505 506
    if (_state == _ScaleState.accepted && shouldStartIfAccepted) {
      _state = _ScaleState.started;
      _dispatchOnStartCallbackIfNeeded();
507 508
    }

509
    if (_state == _ScaleState.started && onUpdate != null)
510
      invokeCallback<void>('onUpdate', () {
511
        onUpdate!(ScaleUpdateDetails(
512 513 514 515
          scale: _scaleFactor,
          horizontalScale: _horizontalScaleFactor,
          verticalScale: _verticalScaleFactor,
          focalPoint: _currentFocalPoint,
516
          localFocalPoint: PointerEvent.transformPosition(_lastTransform, _currentFocalPoint),
517
          rotation: _computeRotationFactor(),
518
          pointerCount: _pointerQueue.length,
519
          delta: _currentFocalPoint - _initialFocalPoint,
520 521
        ));
      });
522 523 524 525 526
  }

  void _dispatchOnStartCallbackIfNeeded() {
    assert(_state == _ScaleState.started);
    if (onStart != null)
527
      invokeCallback<void>('onStart', () {
528
        onStart!(ScaleStartDetails(
529 530
          focalPoint: _currentFocalPoint,
          localFocalPoint: PointerEvent.transformPosition(_lastTransform, _currentFocalPoint),
531
          pointerCount: _pointerQueue.length,
532 533
        ));
      });
534 535
  }

536
  @override
537
  void acceptGesture(int pointer) {
538 539 540
    if (_state == _ScaleState.possible) {
      _state = _ScaleState.started;
      _dispatchOnStartCallbackIfNeeded();
541 542 543 544 545 546 547
      if (dragStartBehavior == DragStartBehavior.start) {
        _initialFocalPoint = _currentFocalPoint;
        _initialSpan = _currentSpan;
        _initialLine = _currentLine;
        _initialHorizontalSpan = _currentHorizontalSpan;
        _initialVerticalSpan = _currentVerticalSpan;
      }
548 549 550
    }
  }

551 552 553 554 555
  @override
  void rejectGesture(int pointer) {
    stopTrackingPointer(pointer);
  }

556
  @override
557
  void didStopTrackingLastPointer(int pointer) {
558
    switch (_state) {
559
      case _ScaleState.possible:
560 561
        resolve(GestureDisposition.rejected);
        break;
562
      case _ScaleState.ready:
563
        assert(false); // We should have not seen a pointer yet
564
        break;
565
      case _ScaleState.accepted:
566
        break;
567
      case _ScaleState.started:
568
        assert(false); // We should be in the accepted state when user is done
569 570
        break;
    }
571
    _state = _ScaleState.ready;
572
  }
573

574 575 576 577 578 579
  @override
  void dispose() {
    _velocityTrackers.clear();
    super.dispose();
  }

580
  @override
581
  String get debugDescription => 'scale';
582
}