scale.dart 17.4 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 40
  ScaleStartDetails({ this.focalPoint = Offset.zero, Offset localFocalPoint, })
    : 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
  @override
64
  String toString() => 'ScaleStartDetails(focalPoint: $focalPoint, localFocalPoint: $localFocalPoint)';
65 66 67 68 69 70
}

/// Details for [GestureScaleUpdateCallback].
class ScaleUpdateDetails {
  /// Creates details for [GestureScaleUpdateCallback].
  ///
71 72
  /// The [focalPoint], [scale], [horizontalScale], [verticalScale], [rotation]
  /// arguments must not be null. The [scale], [horizontalScale], and [verticalScale]
73
  /// argument must be greater than or equal to zero.
74
  ScaleUpdateDetails({
75
    this.focalPoint = Offset.zero,
76
    Offset localFocalPoint,
77
    this.scale = 1.0,
78 79
    this.horizontalScale = 1.0,
    this.verticalScale = 1.0,
80
    this.rotation = 0.0,
81
  }) : assert(focalPoint != null),
82
       assert(scale != null && scale >= 0.0),
83 84
       assert(horizontalScale != null && horizontalScale >= 0.0),
       assert(verticalScale != null && verticalScale >= 0.0),
85 86
       assert(rotation != null),
       localFocalPoint = localFocalPoint ?? focalPoint;
87

88 89 90
  /// The focal point of the pointers in contact with the screen.
  ///
  /// Reported in global coordinates.
91 92 93 94 95
  ///
  /// See also:
  ///
  ///  * [localFocalPoint], which is the same value reported in local
  ///    coordinates.
96
  final Offset focalPoint;
97

98 99 100 101 102 103 104 105 106 107 108
  /// 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;

109 110 111 112 113 114 115 116 117
  /// 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.
118
  final double scale;
119

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
  /// 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;

142
  /// The angle implied by the first two pointers to enter in contact with
143 144 145
  /// the screen.
  ///
  /// Expressed in radians.
146 147
  final double rotation;

148
  @override
149
  String toString() => 'ScaleUpdateDetails(focalPoint: $focalPoint, localFocalPoint: $localFocalPoint, scale: $scale, horizontalScale: $horizontalScale, verticalScale: $verticalScale, rotation: $rotation)';
150 151 152 153 154 155 156
}

/// Details for [GestureScaleEndCallback].
class ScaleEndDetails {
  /// Creates details for [GestureScaleEndCallback].
  ///
  /// The [velocity] argument must not be null.
157
  ScaleEndDetails({ this.velocity = Velocity.zero })
158
    : assert(velocity != null);
159 160 161

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

  @override
  String toString() => 'ScaleEndDetails(velocity: $velocity)';
165 166
}

167 168
/// Signature for when the pointers in contact with the screen have established
/// a focal point and initial scale of 1.0.
169
typedef GestureScaleStartCallback = void Function(ScaleStartDetails details);
170 171 172

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

/// Signature for when the pointers are no longer in contact with the screen.
176
typedef GestureScaleEndCallback = void Function(ScaleEndDetails details);
177 178 179 180 181 182

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

184 185 186 187 188 189 190 191 192 193 194 195 196 197

/// 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.
class _LineBetweenPointers{

  /// 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,
198
    this.pointerEndId = 1,
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
  }) : 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;

}


214 215 216
/// Recognizes a scale gesture.
///
/// [ScaleGestureRecognizer] tracks the pointers in contact with the screen and
Ian Hickson's avatar
Ian Hickson committed
217 218 219 220
/// 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].
221
class ScaleGestureRecognizer extends OneSequenceGestureRecognizer {
222
  /// Create a gesture recognizer for interactions intended for scaling content.
223 224 225 226 227 228
  ///
  /// {@macro flutter.gestures.gestureRecognizer.kind}
  ScaleGestureRecognizer({
    Object debugOwner,
    PointerDeviceKind kind,
  }) : super(debugOwner: debugOwner, kind: kind);
229

230 231
  /// The pointers in contact with the screen have established a focal point and
  /// initial scale of 1.0.
232
  GestureScaleStartCallback onStart;
233 234 235

  /// The pointers in contact with the screen have indicated a new focal point
  /// and/or scale.
236
  GestureScaleUpdateCallback onUpdate;
237 238

  /// The pointers are no longer in contact with the screen.
239
  GestureScaleEndCallback onEnd;
240

241
  _ScaleState _state = _ScaleState.ready;
242

243 244
  Matrix4 _lastTransform;

245 246
  Offset _initialFocalPoint;
  Offset _currentFocalPoint;
247 248
  double _initialSpan;
  double _currentSpan;
249 250 251 252
  double _initialHorizontalSpan;
  double _currentHorizontalSpan;
  double _initialVerticalSpan;
  double _currentVerticalSpan;
253 254
  _LineBetweenPointers _initialLine;
  _LineBetweenPointers _currentLine;
255
  Map<int, Offset> _pointerLocations;
256
  List<int> _pointerQueue; // A queue to sort pointers in order of entrance
257
  final Map<int, VelocityTracker> _velocityTrackers = <int, VelocityTracker>{};
258

259
  double get _scaleFactor => _initialSpan > 0.0 ? _currentSpan / _initialSpan : 1.0;
260

261 262 263 264
  double get _horizontalScaleFactor => _initialHorizontalSpan > 0.0 ? _currentHorizontalSpan / _initialHorizontalSpan : 1.0;

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

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
  double _computeRotationFactor() {
    if (_initialLine == null || _currentLine == null) {
      return 0.0;
    }
    final double fx = _initialLine.pointerStartLocation.dx;
    final double fy = _initialLine.pointerStartLocation.dy;
    final double sx = _initialLine.pointerEndLocation.dx;
    final double sy = _initialLine.pointerEndLocation.dy;

    final double nfx = _currentLine.pointerStartLocation.dx;
    final double nfy = _currentLine.pointerStartLocation.dy;
    final double nsx = _currentLine.pointerEndLocation.dx;
    final double nsy = _currentLine.pointerEndLocation.dy;

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

    return angle2 - angle1;
  }

285
  @override
286
  void addAllowedPointer(PointerEvent event) {
287
    startTrackingPointer(event.pointer, event.transform);
288
    _velocityTrackers[event.pointer] = VelocityTracker();
289 290
    if (_state == _ScaleState.ready) {
      _state = _ScaleState.possible;
291 292
      _initialSpan = 0.0;
      _currentSpan = 0.0;
293 294 295 296
      _initialHorizontalSpan = 0.0;
      _currentHorizontalSpan = 0.0;
      _initialVerticalSpan = 0.0;
      _currentVerticalSpan = 0.0;
297
      _pointerLocations = <int, Offset>{};
298
      _pointerQueue = <int>[];
299 300 301
    }
  }

302
  @override
Ian Hickson's avatar
Ian Hickson committed
303
  void handleEvent(PointerEvent event) {
304 305 306
    assert(_state != _ScaleState.ready);
    bool didChangeConfiguration = false;
    bool shouldStartIfAccepted = false;
Ian Hickson's avatar
Ian Hickson committed
307
    if (event is PointerMoveEvent) {
308
      final VelocityTracker tracker = _velocityTrackers[event.pointer];
309
      assert(tracker != null);
310 311
      if (!event.synthesized)
        tracker.addPosition(event.timeStamp, event.position);
Ian Hickson's avatar
Ian Hickson committed
312
      _pointerLocations[event.pointer] = event.position;
313
      shouldStartIfAccepted = true;
314
      _lastTransform = event.transform;
Ian Hickson's avatar
Ian Hickson committed
315 316
    } else if (event is PointerDownEvent) {
      _pointerLocations[event.pointer] = event.position;
317
      _pointerQueue.add(event.pointer);
318 319
      didChangeConfiguration = true;
      shouldStartIfAccepted = true;
320
      _lastTransform = event.transform;
321
    } else if (event is PointerUpEvent || event is PointerCancelEvent) {
Ian Hickson's avatar
Ian Hickson committed
322
      _pointerLocations.remove(event.pointer);
323
      _pointerQueue.remove(event.pointer);
324
      didChangeConfiguration = true;
325
      _lastTransform = event.transform;
326 327
    }

328
    _updateLines();
329
    _update();
330

331 332
    if (!didChangeConfiguration || _reconfigure(event.pointer))
      _advanceStateMachine(shouldStartIfAccepted);
333 334 335
    stopTrackingIfPointerNoLongerDown(event);
  }

336
  void _update() {
337
    final int count = _pointerLocations.keys.length;
338 339

    // Compute the focal point
340
    Offset focalPoint = Offset.zero;
341
    for (final int pointer in _pointerLocations.keys)
342 343
      focalPoint += _pointerLocations[pointer];
    _currentFocalPoint = count > 0 ? focalPoint / count.toDouble() : Offset.zero;
344

345 346 347
    // 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.
348
    double totalDeviation = 0.0;
349 350
    double totalHorizontalDeviation = 0.0;
    double totalVerticalDeviation = 0.0;
351
    for (final int pointer in _pointerLocations.keys) {
352
      totalDeviation += (_currentFocalPoint - _pointerLocations[pointer]).distance;
353 354 355
      totalHorizontalDeviation += (_currentFocalPoint.dx - _pointerLocations[pointer].dx).abs();
      totalVerticalDeviation += (_currentFocalPoint.dy - _pointerLocations[pointer].dy).abs();
    }
356
    _currentSpan = count > 0 ? totalDeviation / count : 0.0;
357 358
    _currentHorizontalSpan = count > 0 ? totalHorizontalDeviation / count : 0.0;
    _currentVerticalSpan = count > 0 ? totalVerticalDeviation / count : 0.0;
359
  }
360

361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
  /// Updates [_initialLine] and [_currentLine] accordingly to the situation of
  /// the registered pointers
  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 &&
      _initialLine.pointerStartId == _pointerQueue[0] &&
      _initialLine.pointerEndId == _pointerQueue[1]) {
      /// Rotation updated, set the [_currentLine]
      _currentLine = _LineBetweenPointers(
        pointerStartId: _pointerQueue[0],
        pointerStartLocation: _pointerLocations[_pointerQueue[0]],
        pointerEndId: _pointerQueue[1],
377
        pointerEndLocation: _pointerLocations[_pointerQueue[1]],
378 379 380 381 382 383 384
      );
    } else {
      /// A new rotation process is on the way, set the [_initialLine]
      _initialLine = _LineBetweenPointers(
        pointerStartId: _pointerQueue[0],
        pointerStartLocation: _pointerLocations[_pointerQueue[0]],
        pointerEndId: _pointerQueue[1],
385
        pointerEndLocation: _pointerLocations[_pointerQueue[1]],
386 387 388 389 390
      );
      _currentLine = null;
    }
  }

391 392 393
  bool _reconfigure(int pointer) {
    _initialFocalPoint = _currentFocalPoint;
    _initialSpan = _currentSpan;
394
    _initialLine = _currentLine;
395 396
    _initialHorizontalSpan = _currentHorizontalSpan;
    _initialVerticalSpan = _currentVerticalSpan;
397 398 399 400 401 402
    if (_state == _ScaleState.started) {
      if (onEnd != null) {
        final VelocityTracker tracker = _velocityTrackers[pointer];
        assert(tracker != null);

        Velocity velocity = tracker.getVelocity();
403
        if (_isFlingGesture(velocity)) {
404 405
          final Offset pixelsPerSecond = velocity.pixelsPerSecond;
          if (pixelsPerSecond.distanceSquared > kMaxFlingVelocity * kMaxFlingVelocity)
406 407
            velocity = Velocity(pixelsPerSecond: (pixelsPerSecond / pixelsPerSecond.distance) * kMaxFlingVelocity);
          invokeCallback<void>('onEnd', () => onEnd(ScaleEndDetails(velocity: velocity)));
408
        } else {
409
          invokeCallback<void>('onEnd', () => onEnd(ScaleEndDetails(velocity: Velocity.zero)));
410
        }
411
      }
412 413
      _state = _ScaleState.accepted;
      return false;
414
    }
415 416
    return true;
  }
417

418 419 420
  void _advanceStateMachine(bool shouldStartIfAccepted) {
    if (_state == _ScaleState.ready)
      _state = _ScaleState.possible;
421

422 423 424 425 426 427
    if (_state == _ScaleState.possible) {
      final double spanDelta = (_currentSpan - _initialSpan).abs();
      final double focalPointDelta = (_currentFocalPoint - _initialFocalPoint).distance;
      if (spanDelta > kScaleSlop || focalPointDelta > kPanSlop)
        resolve(GestureDisposition.accepted);
    } else if (_state.index >= _ScaleState.accepted.index) {
428 429 430
      resolve(GestureDisposition.accepted);
    }

431 432 433
    if (_state == _ScaleState.accepted && shouldStartIfAccepted) {
      _state = _ScaleState.started;
      _dispatchOnStartCallbackIfNeeded();
434 435
    }

436
    if (_state == _ScaleState.started && onUpdate != null)
437 438 439 440 441 442
      invokeCallback<void>('onUpdate', () {
        onUpdate(ScaleUpdateDetails(
          scale: _scaleFactor,
          horizontalScale: _horizontalScaleFactor,
          verticalScale: _verticalScaleFactor,
          focalPoint: _currentFocalPoint,
443
          localFocalPoint: PointerEvent.transformPosition(_lastTransform, _currentFocalPoint),
444 445 446
          rotation: _computeRotationFactor(),
        ));
      });
447 448 449 450 451
  }

  void _dispatchOnStartCallbackIfNeeded() {
    assert(_state == _ScaleState.started);
    if (onStart != null)
452 453 454 455 456 457
      invokeCallback<void>('onStart', () {
        onStart(ScaleStartDetails(
          focalPoint: _currentFocalPoint,
          localFocalPoint: PointerEvent.transformPosition(_lastTransform, _currentFocalPoint),
        ));
      });
458 459
  }

460
  @override
461
  void acceptGesture(int pointer) {
462 463 464
    if (_state == _ScaleState.possible) {
      _state = _ScaleState.started;
      _dispatchOnStartCallbackIfNeeded();
465 466 467
    }
  }

468 469 470 471 472
  @override
  void rejectGesture(int pointer) {
    stopTrackingPointer(pointer);
  }

473
  @override
474
  void didStopTrackingLastPointer(int pointer) {
475
    switch (_state) {
476
      case _ScaleState.possible:
477 478
        resolve(GestureDisposition.rejected);
        break;
479
      case _ScaleState.ready:
480
        assert(false); // We should have not seen a pointer yet
481
        break;
482
      case _ScaleState.accepted:
483
        break;
484
      case _ScaleState.started:
485
        assert(false); // We should be in the accepted state when user is done
486 487
        break;
    }
488
    _state = _ScaleState.ready;
489
  }
490

491 492 493 494 495 496
  @override
  void dispose() {
    _velocityTrackers.clear();
    super.dispose();
  }

497
  @override
498
  String get debugDescription => 'scale';
499
}