long_press.dart 13 KB
Newer Older
1 2 3 4
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
import 'arena.dart';
import 'constants.dart';
7
import 'events.dart';
8
import 'recognizer.dart';
9
import 'velocity_tracker.dart';
10

11 12 13
/// Callback signature for [LongPressGestureRecognizer.onLongPress].
///
/// Called when a pointer has remained in contact with the screen at the
14
/// same location for a long period of time.
15
typedef GestureLongPressCallback = void Function();
16

17 18 19 20
/// Callback signature for [LongPressGestureRecognizer.onLongPressUp].
///
/// Called when a pointer stops contacting the screen after a long press
/// gesture was detected.
21 22
typedef GestureLongPressUpCallback = void Function();

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
/// Callback signature for [LongPressGestureRecognizer.onLongPressStart].
///
/// Called when a pointer has remained in contact with the screen at the
/// same location for a long period of time. Also reports the long press down
/// position.
typedef GestureLongPressStartCallback = void Function(LongPressStartDetails details);

/// Callback signature for [LongPressGestureRecognizer.onLongPressMoveUpdate].
///
/// Called when a pointer is moving after being held in contact at the same
/// location for a long period of time. Reports the new position and its offset
/// from the original down position.
typedef GestureLongPressMoveUpdateCallback = void Function(LongPressMoveUpdateDetails details);

/// Callback signature for [LongPressGestureRecognizer.onLongPressEnd].
///
/// Called when a pointer stops contacting the screen after a long press
/// gesture was detected. Also reports the position where the pointer stopped
/// contacting the screen.
typedef GestureLongPressEndCallback = void Function(LongPressEndDetails details);

/// Details for callbacks that use [GestureLongPressStartCallback].
///
/// See also:
///
///  * [LongPressGestureRecognizer.onLongPressStart], which uses [GestureLongPressStartCallback].
///  * [LongPressMoveUpdateDetails], the details for [GestureLongPressMoveUpdateCallback]
///  * [LongPressEndDetails], the details for [GestureLongPressEndCallback].
class LongPressStartDetails {
  /// Creates the details for a [GestureLongPressStartCallback].
  ///
  /// The [globalPosition] argument must not be null.
55 56 57 58 59
  const LongPressStartDetails({
    this.globalPosition = Offset.zero,
    Offset localPosition,
  }) : assert(globalPosition != null),
       localPosition = localPosition ?? globalPosition;
60 61 62

  /// The global position at which the pointer contacted the screen.
  final Offset globalPosition;
63 64 65

  /// The local position at which the pointer contacted the screen.
  final Offset localPosition;
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
}

/// Details for callbacks that use [GestureLongPressMoveUpdateCallback].
///
/// See also:
///
///  * [LongPressGestureRecognizer.onLongPressMoveUpdate], which uses [GestureLongPressMoveUpdateCallback].
///  * [LongPressEndDetails], the details for [GestureLongPressEndCallback]
///  * [LongPressStartDetails], the details for [GestureLongPressStartCallback].
class LongPressMoveUpdateDetails {
  /// Creates the details for a [GestureLongPressMoveUpdateCallback].
  ///
  /// The [globalPosition] and [offsetFromOrigin] arguments must not be null.
  const LongPressMoveUpdateDetails({
    this.globalPosition = Offset.zero,
81
    Offset localPosition,
82
    this.offsetFromOrigin = Offset.zero,
83
    Offset localOffsetFromOrigin,
84
  }) : assert(globalPosition != null),
85 86 87
       assert(offsetFromOrigin != null),
       localPosition = localPosition ?? globalPosition,
       localOffsetFromOrigin = localOffsetFromOrigin ?? offsetFromOrigin;
88 89 90 91

  /// The global position of the pointer when it triggered this update.
  final Offset globalPosition;

92 93 94
  /// The local position of the pointer when it triggered this update.
  final Offset localPosition;

95 96 97 98
  /// A delta offset from the point where the long press drag initially contacted
  /// the screen to the point where the pointer is currently located (the
  /// present [globalPosition]) when this callback is triggered.
  final Offset offsetFromOrigin;
99 100 101 102 103

  /// A local delta offset from the point where the long press drag initially contacted
  /// the screen to the point where the pointer is currently located (the
  /// present [localPosition]) when this callback is triggered.
  final Offset localOffsetFromOrigin;
104 105 106 107 108 109 110 111 112 113 114 115 116
}

/// Details for callbacks that use [GestureLongPressEndCallback].
///
/// See also:
///
///  * [LongPressGestureRecognizer.onLongPressEnd], which uses [GestureLongPressEndCallback].
///  * [LongPressMoveUpdateDetails], the details for [GestureLongPressMoveUpdateCallback]
///  * [LongPressStartDetails], the details for [GestureLongPressStartCallback].
class LongPressEndDetails {
  /// Creates the details for a [GestureLongPressEndCallback].
  ///
  /// The [globalPosition] argument must not be null.
117 118 119
  const LongPressEndDetails({
    this.globalPosition = Offset.zero,
    Offset localPosition,
120
    this.velocity = Velocity.zero,
121 122
  }) : assert(globalPosition != null),
       localPosition = localPosition ?? globalPosition;
123 124 125

  /// The global position at which the pointer lifted from the screen.
  final Offset globalPosition;
126 127 128

  /// The local position at which the pointer contacted the screen.
  final Offset localPosition;
129 130 131 132 133

  /// The pointer's velocity when it stopped contacting the screen.
  ///
  /// Defaults to zero if not specified in the constructor.
  final Velocity velocity;
134 135
}

136 137
/// Recognizes when the user has pressed down at the same location for a long
/// period of time.
138 139 140 141 142
///
/// The gesture must not deviate in position from its touch down point for 500ms
/// until it's recognized. Once the gesture is accepted, the finger can be
/// moved, triggering [onLongPressMoveUpdate] callbacks, unless the
/// [postAcceptSlopTolerance] constructor argument is specified.
143 144 145 146
///
/// [LongPressGestureRecognizer] competes on pointer events of [kPrimaryButton]
/// only when it has at least one non-null callback. If it has no callbacks, it
/// is a no-op.
147
class LongPressGestureRecognizer extends PrimaryPointerGestureRecognizer {
148 149
  /// Creates a long-press gesture recognizer.
  ///
150 151 152 153 154 155 156 157 158 159 160
  /// Consider assigning the [onLongPressStart] callback after creating this
  /// object.
  ///
  /// The [postAcceptSlopTolerance] argument can be used to specify a maximum
  /// allowed distance for the gesture to deviate from the starting point once
  /// the long press has triggered. If the gesture deviates past that point,
  /// subsequent callbacks ([onLongPressMoveUpdate], [onLongPressUp],
  /// [onLongPressEnd]) will stop. Defaults to null, which means the gesture
  /// can be moved without limit once the long press is accepted.
  LongPressGestureRecognizer({
    double postAcceptSlopTolerance,
161
    PointerDeviceKind kind,
162 163 164 165
    Object debugOwner,
  }) : super(
    deadline: kLongPressTimeout,
    postAcceptSlopTolerance: postAcceptSlopTolerance,
166
    kind: kind,
167 168
    debugOwner: debugOwner,
  );
169 170

  bool _longPressAccepted = false;
171
  OffsetPair _longPressOrigin;
172 173 174
  // The buttons sent by `PointerDownEvent`. If a `PointerMoveEvent` comes with a
  // different set of buttons, the gesture is canceled.
  int _initialButtons;
175

176
  /// Called when a long press gesture by a primary button has been recognized.
177 178 179
  ///
  /// See also:
  ///
180
  ///  * [kPrimaryButton], the button this callback responds to.
181 182
  ///  * [onLongPressStart], which has the same timing but has data for the
  ///    press location.
183
  GestureLongPressCallback onLongPress;
184

185
  /// Called when a long press gesture by a primary button has been recognized.
186 187 188
  ///
  /// See also:
  ///
189 190 191
  ///  * [kPrimaryButton], the button this callback responds to.
  ///  * [onLongPress], which has the same timing but without details.
  ///  * [LongPressStartDetails], which is passed as an argument to this callback.
192 193
  GestureLongPressStartCallback onLongPressStart;

194 195 196 197 198 199 200
  /// Called when moving after the long press by a primary button is recognized.
  ///
  /// See also:
  ///
  ///  * [kPrimaryButton], the button this callback responds to.
  ///  * [LongPressMoveUpdateDetails], which is passed as an argument to this
  ///    callback.
201 202
  GestureLongPressMoveUpdateCallback onLongPressMoveUpdate;

203 204
  /// Called when the pointer stops contacting the screen after a long-press
  /// by a primary button.
205 206 207
  ///
  /// See also:
  ///
208
  ///  * [kPrimaryButton], the button this callback responds to.
209 210
  ///  * [onLongPressEnd], which has the same timing but has data for the up
  ///    gesture location.
211 212
  GestureLongPressUpCallback onLongPressUp;

213 214
  /// Called when the pointer stops contacting the screen after a long-press
  /// by a primary button.
215 216 217
  ///
  /// See also:
  ///
218 219 220 221
  ///  * [kPrimaryButton], the button this callback responds to.
  ///  * [onLongPressUp], which has the same timing, but without details.
  ///  * [LongPressEndDetails], which is passed as an argument to this
  ///    callback.
222 223
  GestureLongPressEndCallback onLongPressEnd;

224 225
  VelocityTracker _velocityTracker;

226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
  @override
  bool isPointerAllowed(PointerDownEvent event) {
    switch (event.buttons) {
      case kPrimaryButton:
        if (onLongPressStart == null &&
            onLongPress == null &&
            onLongPressMoveUpdate == null &&
            onLongPressEnd == null &&
            onLongPressUp == null)
          return false;
        break;
      default:
        return false;
    }
    return super.isPointerAllowed(event);
  }

243
  @override
244
  void didExceedDeadline() {
245
    // Exceeding the deadline puts the gesture in the accepted state.
246
    resolve(GestureDisposition.accepted);
247
    _longPressAccepted = true;
248
    super.acceptGesture(primaryPointer);
249
    _checkLongPressStart();
250 251
  }

252
  @override
Ian Hickson's avatar
Ian Hickson committed
253
  void handlePrimaryPointer(PointerEvent event) {
254 255 256 257 258 259 260 261 262 263 264
    if (!event.synthesized) {
      if (event is PointerDownEvent) {
        _velocityTracker = VelocityTracker();
        _velocityTracker.addPosition(event.timeStamp, event.localPosition);
      }
      if (event is PointerMoveEvent) {
        assert(_velocityTracker != null);
        _velocityTracker.addPosition(event.timeStamp, event.localPosition);
      }
    }

265
    if (event is PointerUpEvent) {
266
      if (_longPressAccepted == true) {
267
        _checkLongPressEnd(event);
268
      } else {
269
        // Pointer is lifted before timeout.
270 271
        resolve(GestureDisposition.rejected);
      }
272 273 274 275
      _reset();
    } else if (event is PointerCancelEvent) {
      _reset();
    } else if (event is PointerDownEvent) {
276
      // The first touch.
277
      _longPressOrigin = OffsetPair.fromEventPosition(event);
278 279 280 281 282 283 284 285 286 287 288 289 290
      _initialButtons = event.buttons;
    } else if (event is PointerMoveEvent) {
      if (event.buttons != _initialButtons) {
        resolve(GestureDisposition.rejected);
        stopTrackingPointer(primaryPointer);
      } else if (_longPressAccepted) {
        _checkLongPressMoveUpdate(event);
      }
    }
  }

  void _checkLongPressStart() {
    assert(_initialButtons == kPrimaryButton);
291 292 293 294 295
    if (onLongPressStart != null) {
      final LongPressStartDetails details = LongPressStartDetails(
        globalPosition: _longPressOrigin.global,
        localPosition: _longPressOrigin.local,
      );
296 297
      invokeCallback<void>('onLongPressStart',
        () => onLongPressStart(details));
298
    }
299 300 301 302 303 304 305 306
    if (onLongPress != null)
      invokeCallback<void>('onLongPress', onLongPress);
  }

  void _checkLongPressMoveUpdate(PointerEvent event) {
    assert(_initialButtons == kPrimaryButton);
    final LongPressMoveUpdateDetails details = LongPressMoveUpdateDetails(
      globalPosition: event.position,
307 308 309
      localPosition: event.localPosition,
      offsetFromOrigin: event.position - _longPressOrigin.global,
      localOffsetFromOrigin: event.localPosition - _longPressOrigin.local,
310 311 312 313 314 315 316 317
    );
    if (onLongPressMoveUpdate != null)
      invokeCallback<void>('onLongPressMoveUpdate',
        () => onLongPressMoveUpdate(details));
  }

  void _checkLongPressEnd(PointerEvent event) {
    assert(_initialButtons == kPrimaryButton);
318 319 320

    final VelocityEstimate estimate = _velocityTracker.getVelocityEstimate();
    final Velocity velocity = estimate == null ? Velocity.zero : Velocity(pixelsPerSecond: estimate.pixelsPerSecond);
321 322
    final LongPressEndDetails details = LongPressEndDetails(
      globalPosition: event.position,
323
      localPosition: event.localPosition,
324
      velocity: velocity,
325
    );
326 327

    _velocityTracker = null;
328 329 330 331 332 333 334 335 336 337
    if (onLongPressEnd != null)
      invokeCallback<void>('onLongPressEnd', () => onLongPressEnd(details));
    if (onLongPressUp != null)
      invokeCallback<void>('onLongPressUp', onLongPressUp);
  }

  void _reset() {
    _longPressAccepted = false;
    _longPressOrigin = null;
    _initialButtons = null;
338
    _velocityTracker = null;
339 340 341 342 343 344 345 346
  }

  @override
  void resolve(GestureDisposition disposition) {
    if (_longPressAccepted && disposition == GestureDisposition.rejected) {
      // This can happen if the gesture has been canceled. For example when
      // the buttons have changed.
      _reset();
347
    }
348
    super.resolve(disposition);
349
  }
350

351 352 353 354 355 356
  @override
  void acceptGesture(int pointer) {
    // Winning the arena isn't important here since it may happen from a sweep.
    // Explicitly exceeding the deadline puts the gesture in accepted state.
  }

357
  @override
358
  String get debugDescription => 'long press';
359
}