tap.dart 18.1 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 'package:flutter/foundation.dart';

7
import 'arena.dart';
8
import 'constants.dart';
9
import 'events.dart';
10
import 'recognizer.dart';
11

12
/// Details for [GestureTapDownCallback], such as position
13 14 15 16 17
///
/// See also:
///
///  * [GestureDetector.onTapDown], which receives this information.
///  * [TapGestureRecognizer], which passes this information to one of its callbacks.
18 19 20 21
class TapDownDetails {
  /// Creates details for a [GestureTapDownCallback].
  ///
  /// The [globalPosition] argument must not be null.
22 23
  TapDownDetails({
    this.globalPosition = Offset.zero,
24
    Offset localPosition,
25
    this.kind,
26 27
  }) : assert(globalPosition != null),
       localPosition = localPosition ?? globalPosition;
28 29

  /// The global position at which the pointer contacted the screen.
30
  final Offset globalPosition;
31 32 33

  /// The kind of the device that initiated the event.
  final PointerDeviceKind kind;
34 35 36

  /// The local position at which the pointer contacted the screen.
  final Offset localPosition;
37 38 39 40 41 42 43
}

/// Signature for when a pointer that might cause a tap has contacted the
/// screen.
///
/// The position at which the pointer contacted the screen is available in the
/// `details`.
44 45 46 47 48
///
/// See also:
///
///  * [GestureDetector.onTapDown], which matches this signature.
///  * [TapGestureRecognizer], which uses this signature in one of its callbacks.
49
typedef GestureTapDownCallback = void Function(TapDownDetails details);
50 51

/// Details for [GestureTapUpCallback], such as position.
52 53 54 55 56
///
/// See also:
///
///  * [GestureDetector.onTapUp], which receives this information.
///  * [TapGestureRecognizer], which passes this information to one of its callbacks.
57 58
class TapUpDetails {
  /// The [globalPosition] argument must not be null.
59 60 61 62 63
  TapUpDetails({
    this.globalPosition = Offset.zero,
    Offset localPosition,
  }) : assert(globalPosition != null),
       localPosition = localPosition ?? globalPosition;
64 65

  /// The global position at which the pointer contacted the screen.
66
  final Offset globalPosition;
67 68 69

  /// The local position at which the pointer contacted the screen.
  final Offset localPosition;
70
}
71 72

/// Signature for when a pointer that will trigger a tap has stopped contacting
73 74 75 76
/// the screen.
///
/// The position at which the pointer stopped contacting the screen is available
/// in the `details`.
77 78 79 80 81
///
/// See also:
///
///  * [GestureDetector.onTapUp], which matches this signature.
///  * [TapGestureRecognizer], which uses this signature in one of its callbacks.
82
typedef GestureTapUpCallback = void Function(TapUpDetails details);
83 84

/// Signature for when a tap has occurred.
85 86 87 88 89
///
/// See also:
///
///  * [GestureDetector.onTap], which matches this signature.
///  * [TapGestureRecognizer], which uses this signature in one of its callbacks.
90
typedef GestureTapCallback = void Function();
91 92 93

/// Signature for when the pointer that previously triggered a
/// [GestureTapDownCallback] will not end up causing a tap.
94 95 96 97 98
///
/// See also:
///
///  * [GestureDetector.onTapCancel], which matches this signature.
///  * [TapGestureRecognizer], which uses this signature in one of its callbacks.
99
typedef GestureTapCancelCallback = void Function();
100

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
/// A base class for gesture recognizers that recognize taps.
///
/// Gesture recognizers take part in gesture arenas to enable potential gestures
/// to be disambiguated from each other. This process is managed by a
/// [GestureArenaManager].
///
/// A tap is defined as a sequence of events that starts with a down, followed
/// by optional moves, then ends with an up. All move events must contain the
/// same `buttons` as the down event, and must not be too far from the initial
/// position. The gesture is rejected on any violation, a cancel event, or
/// if any other recognizers wins the arena. It is accepted only when it is the
/// last member of the arena.
///
/// The [BaseTapGestureRecognizer] considers all the pointers involved in the
/// pointer event sequence as contributing to one gesture. For this reason,
/// extra pointer interactions during a tap sequence are not recognized as
/// additional taps. For example, down-1, down-2, up-1, up-2 produces only one
/// tap on up-1.
///
/// The [BaseTapGestureRecognizer] can not be directly used, since it does not
/// define which buttons to accept, or what to do when a tap happens. If you
/// want to build a custom tap recognizer, extend this class by overriding
/// [isPointerAllowed] and the handler methods.
///
/// See also:
///
///  * [TapGestureRecognizer], a ready-to-use tap recognizer that recognizes
///    taps of the primary button and taps of the secondary button.
///  * [ModalBarrier], a widget that uses a custom tap recognizer that accepts
///    any buttons.
abstract class BaseTapGestureRecognizer extends PrimaryPointerGestureRecognizer {
  /// Creates a tap gesture recognizer.
  BaseTapGestureRecognizer({ Object debugOwner })
    : super(deadline: kPressTimeout , debugOwner: debugOwner);

  bool _sentTapDown = false;
  bool _wonArenaForPrimaryPointer = false;

  PointerDownEvent _down;
  PointerUpEvent _up;

  /// A pointer has contacted the screen, which might be the start of a tap.
  ///
  /// This triggers after the down event, once a short timeout ([deadline]) has
  /// elapsed, or once the gesture has won the arena, whichever comes first.
  ///
  /// The parameter `down` is the down event of the primary pointer that started
  /// the tap sequence.
  ///
  /// If this recognizer doesn't win the arena, [handleTapCancel] is called next.
  /// Otherwise, [handleTapUp] is called next.
  @protected
  void handleTapDown({ PointerDownEvent down });

  /// A pointer has stopped contacting the screen, which is recognized as a tap.
  ///
  /// This triggers on the up event, if the recognizer wins the arena with it
  /// or has previously won.
  ///
  /// The parameter `down` is the down event of the primary pointer that started
  /// the tap sequence, and `up` is the up event that ended the tap sequence.
  ///
  /// If this recognizer doesn't win the arena, [handleTapCancel] is called
  /// instead.
  @protected
  void handleTapUp({ PointerDownEvent down, PointerUpEvent up });

  /// A pointer that previously triggered [handleTapDown] will not end up
  /// causing a tap.
  ///
  /// This triggers once the gesture loses the arena, if [handleTapDown] has
  /// been previously triggered.
  ///
  /// The parameter `down` is the down event of the primary pointer that started
  /// the tap sequence; `cancel` is the cancel event, which might be null;
  /// `reason` is a short description of the cause if `cancel` is null, which
  /// can be "forced" if other gestures won the arena, or "spontaneous"
  /// otherwise.
  ///
  /// If this recognizer wins the arena, [handleTapUp] is called instead.
  @protected
  void handleTapCancel({ PointerDownEvent down, PointerCancelEvent cancel, String reason });

  @override
  void addAllowedPointer(PointerDownEvent event) {
    if (state == GestureRecognizerState.ready) {
      // `_down` must be assigned in this method instead of `handlePrimaryPointer`,
      // because `acceptGesture` might be called before `handlePrimaryPointer`,
      // which relies on `_down` to call `handleTapDown`.
      _down = event;
    }
    super.addAllowedPointer(event);
  }

  @override
  void handlePrimaryPointer(PointerEvent event) {
    if (event is PointerUpEvent) {
      _up = event;
      _checkUp();
    } else if (event is PointerCancelEvent) {
      resolve(GestureDisposition.rejected);
      if (_sentTapDown) {
        _checkCancel(event, '');
      }
      _reset();
    } else if (event.buttons != _down.buttons) {
      resolve(GestureDisposition.rejected);
      stopTrackingPointer(primaryPointer);
    }
  }

  @override
  void resolve(GestureDisposition disposition) {
    if (_wonArenaForPrimaryPointer && disposition == GestureDisposition.rejected) {
      // This can happen if the gesture has been canceled. For example, when
      // the pointer has exceeded the touch slop, the buttons have been changed,
      // or if the recognizer is disposed.
      assert(_sentTapDown);
      _checkCancel(null, 'spontaneous');
      _reset();
    }
    super.resolve(disposition);
  }

  @override
  void didExceedDeadline() {
    _checkDown();
  }

  @override
  void acceptGesture(int pointer) {
    super.acceptGesture(pointer);
    if (pointer == primaryPointer) {
      _checkDown();
      _wonArenaForPrimaryPointer = true;
      _checkUp();
    }
  }

  @override
  void rejectGesture(int pointer) {
    super.rejectGesture(pointer);
    if (pointer == primaryPointer) {
      // Another gesture won the arena.
      assert(state != GestureRecognizerState.possible);
      if (_sentTapDown)
        _checkCancel(null, 'forced');
      _reset();
    }
  }

  void _checkDown() {
    if (_sentTapDown) {
      return;
    }
    handleTapDown(down: _down);
    _sentTapDown = true;
  }

  void _checkUp() {
    if (!_wonArenaForPrimaryPointer || _up == null) {
      return;
    }
    handleTapUp(down: _down, up: _up);
    _reset();
  }

  void _checkCancel(PointerCancelEvent event, String note) {
    handleTapCancel(down: _down, cancel: event, reason: note);
  }

  void _reset() {
    _sentTapDown = false;
    _wonArenaForPrimaryPointer = false;
    _up = null;
    _down = null;
  }

  @override
  String get debugDescription => 'base tap';

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(FlagProperty('wonArenaForPrimaryPointer', value: _wonArenaForPrimaryPointer, ifTrue: 'won arena'));
    properties.add(DiagnosticsProperty<Offset>('finalPosition', _up?.position, defaultValue: null));
    properties.add(DiagnosticsProperty<Offset>('finalLocalPosition', _up?.localPosition, defaultValue: _up?.position));
    properties.add(DiagnosticsProperty<int>('button', _down?.buttons, defaultValue: null));
    properties.add(FlagProperty('sentTapDown', value: _sentTapDown, ifTrue: 'sent tap down'));
  }
}

293 294
/// Recognizes taps.
///
295 296
/// Gesture recognizers take part in gesture arenas to enable potential gestures
/// to be disambiguated from each other. This process is managed by a
297
/// [GestureArenaManager].
298
///
299 300 301
/// [TapGestureRecognizer] considers all the pointers involved in the pointer
/// event sequence as contributing to one gesture. For this reason, extra
/// pointer interactions during a tap sequence are not recognized as additional
302
/// taps. For example, down-1, down-2, up-1, up-2 produces only one tap on up-1.
303
///
304 305 306 307
/// [TapGestureRecognizer] competes on pointer events of [kPrimaryButton] only
/// when it has at least one non-null `onTap*` callback, and events of
/// [kSecondaryButton] only when it has at least one non-null `onSecondaryTap*`
/// callback. If it has no callbacks, it is a no-op.
308
///
309 310
/// See also:
///
311
///  * [GestureDetector.onTap], which uses this recognizer.
312
///  * [MultiTapGestureRecognizer]
313
class TapGestureRecognizer extends BaseTapGestureRecognizer {
314
  /// Creates a tap gesture recognizer.
315
  TapGestureRecognizer({ Object debugOwner }) : super(debugOwner: debugOwner);
316

317 318
  /// A pointer has contacted the screen at a particular location with a primary
  /// button, which might be the start of a tap.
319
  ///
320 321
  /// This triggers after the down event, once a short timeout ([deadline]) has
  /// elapsed, or once the gestures has won the arena, whichever comes first.
322
  ///
323
  /// If this recognizer doesn't win the arena, [onTapCancel] is called next.
324 325 326 327
  /// Otherwise, [onTapUp] is called next.
  ///
  /// See also:
  ///
328 329 330
  ///  * [kPrimaryButton], the button this callback responds to.
  ///  * [onSecondaryTapDown], a similar callback but for a secondary button.
  ///  * [TapDownDetails], which is passed as an argument to this callback.
331
  ///  * [GestureDetector.onTapDown], which exposes this callback.
332
  GestureTapDownCallback onTapDown;
333

334 335
  /// A pointer has stopped contacting the screen at a particular location,
  /// which is recognized as a tap of a primary button.
336
  ///
337 338
  /// This triggers on the up event, if the recognizer wins the arena with it
  /// or has previously won, immediately followed by [onTap].
339
  ///
340
  /// If this recognizer doesn't win the arena, [onTapCancel] is called instead.
341 342 343
  ///
  /// See also:
  ///
344 345
  ///  * [kPrimaryButton], the button this callback responds to.
  ///  * [onSecondaryTapUp], a similar callback but for a secondary button.
346
  ///  * [TapUpDetails], which is passed as an argument to this callback.
347
  ///  * [GestureDetector.onTapUp], which exposes this callback.
Hixie's avatar
Hixie committed
348
  GestureTapUpCallback onTapUp;
349

350 351
  /// A pointer has stopped contacting the screen, which is recognized as a tap
  /// of a primary button.
352
  ///
353 354
  /// This triggers on the up event, if the recognizer wins the arena with it
  /// or has previously won, immediately following [onTap].
355
  ///
356
  /// If this recognizer doesn't win the arena, [onTapCancel] is called instead.
357 358 359
  ///
  /// See also:
  ///
360 361
  ///  * [kPrimaryButton], the button this callback responds to.
  ///  * [onTapUp], which has the same timing but with details.
362
  ///  * [GestureDetector.onTap], which exposes this callback.
363
  GestureTapCallback onTap;
364

365
  /// A pointer that previously triggered [onTapDown] will not end up causing
366
  /// a tap.
367
  ///
368 369
  /// This triggers once the gesture loses the arena, if [onTapDown] has
  /// previously been triggered.
370
  ///
371 372
  /// If this recognizer wins the arena, [onTapUp] and [onTap] are called
  /// instead.
373 374 375
  ///
  /// See also:
  ///
376 377
  ///  * [kPrimaryButton], the button this callback responds to.
  ///  * [onSecondaryTapCancel], a similar callback but for a secondary button.
378
  ///  * [GestureDetector.onTapCancel], which exposes this callback.
379
  GestureTapCancelCallback onTapCancel;
380

381 382
  /// A pointer has contacted the screen at a particular location with a
  /// secondary button, which might be the start of a secondary tap.
383
  ///
384 385
  /// This triggers after the down event, once a short timeout ([deadline]) has
  /// elapsed, or once the gestures has won the arena, whichever comes first.
386
  ///
387 388
  /// If this recognizer doesn't win the arena, [onSecondaryTapCancel] is called
  /// next. Otherwise, [onSecondaryTapUp] is called next.
389 390 391 392
  ///
  /// See also:
  ///
  ///  * [kSecondaryButton], the button this callback responds to.
Dan Field's avatar
Dan Field committed
393
  ///  * [onTapDown], a similar callback but for a primary button.
394 395 396 397
  ///  * [TapDownDetails], which is passed as an argument to this callback.
  ///  * [GestureDetector.onSecondaryTapDown], which exposes this callback.
  GestureTapDownCallback onSecondaryTapDown;

398 399
  /// A pointer has stopped contacting the screen at a particular location,
  /// which is recognized as a tap of a secondary button.
400
  ///
401 402
  /// This triggers on the up event, if the recognizer wins the arena with it
  /// or has previously won.
403
  ///
404
  /// If this recognizer doesn't win the arena, [onSecondaryTapCancel] is called
405 406 407 408 409
  /// instead.
  ///
  /// See also:
  ///
  ///  * [kSecondaryButton], the button this callback responds to.
Dan Field's avatar
Dan Field committed
410
  ///  * [onTapUp], a similar callback but for a primary button.
411 412 413 414
  ///  * [TapUpDetails], which is passed as an argument to this callback.
  ///  * [GestureDetector.onSecondaryTapUp], which exposes this callback.
  GestureTapUpCallback onSecondaryTapUp;

415
  /// A pointer that previously triggered [onSecondaryTapDown] will not end up
416 417
  /// causing a tap.
  ///
418 419
  /// This triggers once the gesture loses the arena, if [onSecondaryTapDown]
  /// has previously been triggered.
420
  ///
421
  /// If this recognizer wins the arena, [onSecondaryTapUp] is called instead.
422 423 424 425
  ///
  /// See also:
  ///
  ///  * [kSecondaryButton], the button this callback responds to.
Dan Field's avatar
Dan Field committed
426
  ///  * [onTapCancel], a similar callback but for a primary button.
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
  ///  * [GestureDetector.onTapCancel], which exposes this callback.
  GestureTapCancelCallback onSecondaryTapCancel;

  @override
  bool isPointerAllowed(PointerDownEvent event) {
    switch (event.buttons) {
      case kPrimaryButton:
        if (onTapDown == null &&
            onTap == null &&
            onTapUp == null &&
            onTapCancel == null)
          return false;
        break;
      case kSecondaryButton:
        if (onSecondaryTapDown == null &&
            onSecondaryTapUp == null &&
            onSecondaryTapCancel == null)
          return false;
        break;
      default:
        return false;
    }
    return super.isPointerAllowed(event);
  }

452
  @protected
453
  @override
454
  void handleTapDown({PointerDownEvent down}) {
455
    final TapDownDetails details = TapDownDetails(
456 457 458
      globalPosition: down.position,
      localPosition: down.localPosition,
      kind: getKindForPointer(down.pointer),
459
    );
460
    switch (down.buttons) {
461 462 463 464 465 466 467 468 469 470
      case kPrimaryButton:
        if (onTapDown != null)
          invokeCallback<void>('onTapDown', () => onTapDown(details));
        break;
      case kSecondaryButton:
        if (onSecondaryTapDown != null)
          invokeCallback<void>('onSecondaryTapDown',
            () => onSecondaryTapDown(details));
        break;
      default:
Hixie's avatar
Hixie committed
471 472 473
    }
  }

474 475 476
  @protected
  @override
  void handleTapUp({PointerDownEvent down, PointerUpEvent up}) {
477
    final TapUpDetails details = TapUpDetails(
478 479
      globalPosition: up.position,
      localPosition: up.localPosition,
480
    );
481
    switch (down.buttons) {
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
      case kPrimaryButton:
        if (onTapUp != null)
          invokeCallback<void>('onTapUp', () => onTapUp(details));
        if (onTap != null)
          invokeCallback<void>('onTap', onTap);
        break;
      case kSecondaryButton:
        if (onSecondaryTapUp != null)
          invokeCallback<void>('onSecondaryTapUp',
            () => onSecondaryTapUp(details));
        break;
      default:
    }
  }

497 498 499
  @protected
  @override
  void handleTapCancel({PointerDownEvent down, PointerCancelEvent cancel, String reason}) {
500
    final String note = reason == '' ? reason : '$reason ';
501
    switch (down.buttons) {
502 503 504 505 506 507 508 509 510 511
      case kPrimaryButton:
        if (onTapCancel != null)
          invokeCallback<void>('${note}onTapCancel', onTapCancel);
        break;
      case kSecondaryButton:
        if (onSecondaryTapCancel != null)
          invokeCallback<void>('${note}onSecondaryTapCancel',
            onSecondaryTapCancel);
        break;
      default:
512 513
    }
  }
514

515
  @override
516
  String get debugDescription => 'tap';
517
}