binding.dart 21 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
Ian Hickson's avatar
Ian Hickson committed
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 7
import 'dart:async';
import 'dart:collection';
8
import 'dart:ui' as ui show PointerDataPacket;
Ian Hickson's avatar
Ian Hickson committed
9

10
import 'package:flutter/foundation.dart';
11
import 'package:flutter/scheduler.dart';
Ian Hickson's avatar
Ian Hickson committed
12 13 14

import 'arena.dart';
import 'converter.dart';
15
import 'debug.dart';
Ian Hickson's avatar
Ian Hickson committed
16 17 18
import 'events.dart';
import 'hit_test.dart';
import 'pointer_router.dart';
19
import 'pointer_signal_resolver.dart';
20 21
import 'resampler.dart';

22 23 24 25 26 27
export 'dart:ui' show Offset;

export 'package:flutter/foundation.dart' show DiagnosticsNode, InformationCollector;

export 'arena.dart' show GestureArenaManager;
export 'events.dart' show PointerEvent;
28
export 'hit_test.dart' show HitTestEntry, HitTestResult, HitTestTarget;
29 30 31
export 'pointer_router.dart' show PointerRouter;
export 'pointer_signal_resolver.dart' show PointerSignalResolver;

32
typedef _HandleSampleTimeChangedCallback = void Function();
33

34 35 36 37 38 39 40 41 42
/// Class that implements clock used for sampling.
class SamplingClock {
  /// Returns current time.
  DateTime now() => DateTime.now();

  /// Returns a new stopwatch that uses the current time as reported by `this`.
  Stopwatch stopwatch() => Stopwatch();
}

43 44 45
// Class that handles resampling of touch events for multiple pointer
// devices.
//
46 47
// The `samplingInterval` is used to determine the approximate next
// time for resampling.
48 49 50
// SchedulerBinding's `currentSystemFrameTimeStamp` is used to determine
// sample time.
class _Resampler {
51
  _Resampler(this._handlePointerEvent, this._handleSampleTimeChanged, this._samplingInterval);
52 53 54 55 56 57 58

  // Resamplers used to filter incoming pointer events.
  final Map<int, PointerEventResampler> _resamplers = <int, PointerEventResampler>{};

  // Flag to track if a frame callback has been scheduled.
  bool _frameCallbackScheduled = false;

59
  // Last frame time for resampling.
60 61
  Duration _frameTime = Duration.zero;

62 63 64
  // Time since `_frameTime` was updated.
  Stopwatch _frameTimeAge = Stopwatch();

65 66 67 68 69 70 71 72 73 74
  // Last sample time and time stamp of last event.
  //
  // Only used for debugPrint of resampling margin.
  Duration _lastSampleTime = Duration.zero;
  Duration _lastEventTime = Duration.zero;

  // Callback used to handle pointer events.
  final HandleEventCallback _handlePointerEvent;

  // Callback used to handle sample time changes.
75
  final _HandleSampleTimeChangedCallback _handleSampleTimeChanged;
76

77 78 79 80 81 82
  // Interval used for sampling.
  final Duration _samplingInterval;

  // Timer used to schedule resampling.
  Timer? _timer;

83
  // Add `event` for resampling or dispatch it directly if
84
  // not a touch event.
85
  void addOrDispatch(PointerEvent event) {
86
    final SchedulerBinding scheduler = SchedulerBinding.instance;
87
    assert(scheduler != null);
88
    // Add touch event to resampler or dispatch pointer event directly.
89 90 91 92 93 94 95 96 97 98 99
    if (event.kind == PointerDeviceKind.touch) {
      // Save last event time for debugPrint of resampling margin.
      _lastEventTime = event.timeStamp;

      final PointerEventResampler resampler = _resamplers.putIfAbsent(
        event.device,
        () => PointerEventResampler(),
      );
      resampler.addEvent(event);
    } else {
      _handlePointerEvent(event);
100 101 102 103 104
    }
  }

  // Sample and dispatch events.
  //
105
  // The `samplingOffset` is relative to the current frame time, which
106
  // can be in the past when we're not actively resampling.
107
  //
108 109
  // The `samplingClock` is the clock used to determine frame time age.
  void sample(Duration samplingOffset, SamplingClock clock) {
110
    final SchedulerBinding scheduler = SchedulerBinding.instance;
111 112
    assert(scheduler != null);

113 114 115 116 117 118 119 120 121
    // Initialize `_frameTime` if needed. This will be used for periodic
    // sampling when frame callbacks are not received.
    if (_frameTime == Duration.zero) {
      _frameTime = Duration(milliseconds: clock.now().millisecondsSinceEpoch);
      _frameTimeAge = clock.stopwatch()..start();
    }

    // Schedule periodic resampling if `_timer` is not already active.
    if (_timer?.isActive != true) {
122
      _timer = Timer.periodic(_samplingInterval, (_) => _onSampleTimeChanged());
123 124 125 126 127 128 129 130 131 132 133
    }

    // Calculate the effective frame time by taking the number
    // of sampling intervals since last time `_frameTime` was
    // updated into account. This allows us to advance sample
    // time without having to receive frame callbacks.
    final int samplingIntervalUs = _samplingInterval.inMicroseconds;
    final int elapsedIntervals = _frameTimeAge.elapsedMicroseconds ~/ samplingIntervalUs;
    final int elapsedUs = elapsedIntervals * samplingIntervalUs;
    final Duration frameTime = _frameTime + Duration(microseconds: elapsedUs);

134 135 136 137
    // Determine sample time by adding the offset to the current
    // frame time. This is expected to be in the past and not
    // result in any dispatched events unless we're actively
    // resampling events.
138
    final Duration sampleTime = frameTime + samplingOffset;
139

140 141
    // Determine next sample time by adding the sampling interval
    // to the current sample time.
142
    final Duration nextSampleTime = sampleTime + _samplingInterval;
143

144 145 146
    // Iterate over active resamplers and sample pointer events for
    // current sample time.
    for (final PointerEventResampler resampler in _resamplers.values) {
147
      resampler.sample(sampleTime, nextSampleTime, _handlePointerEvent);
148 149 150 151 152 153 154 155 156 157
    }

    // Remove inactive resamplers.
    _resamplers.removeWhere((int key, PointerEventResampler resampler) {
      return !resampler.hasPendingEvents && !resampler.isDown;
    });

    // Save last sample time for debugPrint of resampling margin.
    _lastSampleTime = sampleTime;

158 159 160 161 162 163
    // Early out if another call to `sample` isn't needed.
    if (_resamplers.isEmpty) {
      _timer!.cancel();
      return;
    }

164
    // Schedule a frame callback if another call to `sample` is needed.
165
    if (!_frameCallbackScheduled) {
166
      _frameCallbackScheduled = true;
167 168 169
      // Add a post frame callback as this avoids producing unnecessary
      // frames but ensures that sampling phase is adjusted to frame
      // time when frames are produced.
170
      scheduler.addPostFrameCallback((_) {
171 172 173 174 175
        _frameCallbackScheduled = false;
        // We use `currentSystemFrameTimeStamp` here as it's critical that
        // sample time is in the same clock as the event time stamps, and
        // never adjusted or scaled like `currentFrameTimeStamp`.
        _frameTime = scheduler.currentSystemFrameTimeStamp;
176 177 178 179 180 181
        _frameTimeAge.reset();
        // Reset timer to match phase of latest frame callback.
        _timer?.cancel();
        _timer = Timer.periodic(_samplingInterval, (_) => _onSampleTimeChanged());
        // Trigger an immediate sample time change.
        _onSampleTimeChanged();
182 183 184 185 186 187 188 189 190 191
      });
    }
  }

  // Stop all resampling and dispatched any queued events.
  void stop() {
    for (final PointerEventResampler resampler in _resamplers.values) {
      resampler.stop(_handlePointerEvent);
    }
    _resamplers.clear();
192
    _frameTime = Duration.zero;
193
    _timer?.cancel();
194 195 196 197 198 199
  }

  void _onSampleTimeChanged() {
    assert(() {
      if (debugPrintResamplingMargin) {
        final Duration resamplingMargin = _lastEventTime - _lastSampleTime;
200
        debugPrint('$resamplingMargin');
201 202 203 204
      }
      return true;
    }());
    _handleSampleTimeChanged();
205 206 207 208 209 210 211 212 213 214
  }
}

// The default sampling offset.
//
// Sampling offset is relative to presentation time. If we produce frames
// 16.667 ms before presentation and input rate is ~60hz, worst case latency
// is 33.334 ms. This however assumes zero latency from the input driver.
// 4.666 ms margin is added for this.
const Duration _defaultSamplingOffset = Duration(milliseconds: -38);
Ian Hickson's avatar
Ian Hickson committed
215

216 217 218
// The sampling interval.
//
// Sampling interval is used to determine the approximate time for subsequent
219 220
// sampling. This is used to sample events when frame callbacks are not
// being received and decide if early processing of up and removed events
221 222 223
// is appropriate. 16667 us for 60hz sampling interval.
const Duration _samplingInterval = Duration(microseconds: 16667);

224
/// A binding for the gesture subsystem.
225 226 227 228 229 230
///
/// ## Lifecycle of pointer events and the gesture arena
///
/// ### [PointerDownEvent]
///
/// When a [PointerDownEvent] is received by the [GestureBinding] (from
231
/// [dart:ui.PlatformDispatcher.onPointerDataPacket], as interpreted by the
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
/// [PointerEventConverter]), a [hitTest] is performed to determine which
/// [HitTestTarget] nodes are affected. (Other bindings are expected to
/// implement [hitTest] to defer to [HitTestable] objects. For example, the
/// rendering layer defers to the [RenderView] and the rest of the render object
/// hierarchy.)
///
/// The affected nodes then are given the event to handle ([dispatchEvent] calls
/// [HitTestTarget.handleEvent] for each affected node). If any have relevant
/// [GestureRecognizer]s, they provide the event to them using
/// [GestureRecognizer.addPointer]. This typically causes the recognizer to
/// register with the [PointerRouter] to receive notifications regarding the
/// pointer in question.
///
/// Once the hit test and dispatching logic is complete, the event is then
/// passed to the aforementioned [PointerRouter], which passes it to any objects
/// that have registered interest in that event.
///
/// Finally, the [gestureArena] is closed for the given pointer
/// ([GestureArenaManager.close]), which begins the process of selecting a
/// gesture to win that pointer.
///
/// ### Other events
///
/// A pointer that is [PointerEvent.down] may send further events, such as
/// [PointerMoveEvent], [PointerUpEvent], or [PointerCancelEvent]. These are
257 258 259
/// sent to the same [HitTestTarget] nodes as were found when the
/// [PointerDownEvent] was received (even if they have since been disposed; it is
/// the responsibility of those objects to be aware of that possibility).
260 261 262 263 264 265
///
/// Then, the events are routed to any still-registered entrants in the
/// [PointerRouter]'s table for that pointer.
///
/// When a [PointerUpEvent] is received, the [GestureArenaManager.sweep] method
/// is invoked to force the gesture arena logic to terminate if necessary.
266
mixin GestureBinding on BindingBase implements HitTestable, HitTestDispatcher, HitTestTarget {
267
  @override
Ian Hickson's avatar
Ian Hickson committed
268 269 270
  void initInstances() {
    super.initInstances();
    _instance = this;
271
    platformDispatcher.onPointerDataPacket = _handlePointerDataPacket;
Ian Hickson's avatar
Ian Hickson committed
272 273
  }

274 275 276 277 278 279 280 281
  /// The singleton instance of this object.
  ///
  /// Provides access to the features exposed by this mixin. The binding must
  /// be initialized before using this getter; this is typically done by calling
  /// [runApp] or [WidgetsFlutterBinding.ensureInitialized].
  static GestureBinding get instance => BindingBase.checkInstance(_instance);
  static GestureBinding? _instance;

282 283 284 285 286 287
  @override
  void unlocked() {
    super.unlocked();
    _flushPointerEventQueue();
  }

288
  final Queue<PointerEvent> _pendingPointerEvents = Queue<PointerEvent>();
289

290
  void _handlePointerDataPacket(ui.PointerDataPacket packet) {
291 292
    // We convert pointer data to logical pixels so that e.g. the touch slop can be
    // defined in a device-independent manner.
293
    _pendingPointerEvents.addAll(PointerEventConverter.expand(packet.data, window.devicePixelRatio));
294
    if (!locked) {
295
      _flushPointerEventQueue();
296
    }
297 298 299 300
  }

  /// Dispatch a [PointerCancelEvent] for the given pointer soon.
  ///
301
  /// The pointer event will be dispatched before the next pointer event and
302 303
  /// before the end of the microtask but not within this function call.
  void cancelPointer(int pointer) {
304
    if (_pendingPointerEvents.isEmpty && !locked) {
305
      scheduleMicrotask(_flushPointerEventQueue);
306
    }
307
    _pendingPointerEvents.addFirst(PointerCancelEvent(pointer: pointer));
Ian Hickson's avatar
Ian Hickson committed
308 309
  }

310 311
  void _flushPointerEventQueue() {
    assert(!locked);
312

313
    while (_pendingPointerEvents.isNotEmpty) {
314
      handlePointerEvent(_pendingPointerEvents.removeFirst());
315
    }
316 317
  }

Ian Hickson's avatar
Ian Hickson committed
318
  /// A router that routes all pointer events received from the engine.
319
  final PointerRouter pointerRouter = PointerRouter();
Ian Hickson's avatar
Ian Hickson committed
320 321 322

  /// The gesture arenas used for disambiguating the meaning of sequences of
  /// pointer events.
323
  final GestureArenaManager gestureArena = GestureArenaManager();
Ian Hickson's avatar
Ian Hickson committed
324

325 326
  /// The resolver used for determining which widget handles a
  /// [PointerSignalEvent].
327 328
  final PointerSignalResolver pointerSignalResolver = PointerSignalResolver();

Ian Hickson's avatar
Ian Hickson committed
329 330 331 332
  /// State for all pointers which are currently down.
  ///
  /// The state of hovering pointers is not tracked because that would require
  /// hit-testing on every frame.
333
  final Map<int, HitTestResult> _hitTests = <int, HitTestResult>{};
Ian Hickson's avatar
Ian Hickson committed
334

335 336 337 338 339 340 341 342 343 344 345
  /// Dispatch an event to the targets found by a hit test on its position.
  ///
  /// This method sends the given event to [dispatchEvent] based on event types:
  ///
  ///  * [PointerDownEvent]s and [PointerSignalEvent]s are dispatched to the
  ///    result of a new [hitTest].
  ///  * [PointerUpEvent]s and [PointerMoveEvent]s are dispatched to the result of hit test of the
  ///    preceding [PointerDownEvent]s.
  ///  * [PointerHoverEvent]s, [PointerAddedEvent]s, and [PointerRemovedEvent]s
  ///    are dispatched without a hit test result.
  void handlePointerEvent(PointerEvent event) {
346
    assert(!locked);
347 348 349

    if (resamplingEnabled) {
      _resampler.addOrDispatch(event);
350
      _resampler.sample(samplingOffset, _samplingClock);
351 352 353 354 355 356 357 358 359 360
      return;
    }

    // Stop resampler if resampling is not enabled. This is a no-op if
    // resampling was never enabled.
    _resampler.stop();
    _handlePointerEventImmediately(event);
  }

  void _handlePointerEventImmediately(PointerEvent event) {
361
    HitTestResult? hitTestResult;
362
    if (event is PointerDownEvent || event is PointerSignalEvent || event is PointerHoverEvent || event is PointerPanZoomStartEvent) {
Ian Hickson's avatar
Ian Hickson committed
363
      assert(!_hitTests.containsKey(event.pointer));
364 365
      hitTestResult = HitTestResult();
      hitTest(hitTestResult, event.position);
366
      if (event is PointerDownEvent || event is PointerPanZoomStartEvent) {
367 368
        _hitTests[event.pointer] = hitTestResult;
      }
369
      assert(() {
370
        if (debugPrintHitTestResults) {
371
          debugPrint('$event: $hitTestResult');
372
        }
373
        return true;
374
      }());
375
    } else if (event is PointerUpEvent || event is PointerCancelEvent || event is PointerPanZoomEndEvent) {
376
      hitTestResult = _hitTests.remove(event.pointer);
377
    } else if (event.down || event is PointerPanZoomUpdateEvent) {
378
      // Because events that occur with the pointer down (like
379
      // [PointerMoveEvent]s) should be dispatched to the same place that their
380 381 382 383 384 385
      // initial PointerDownEvent was, we want to re-use the path we found when
      // the pointer went down, rather than do hit detection each time we get
      // such an event.
      hitTestResult = _hitTests[event.pointer];
    }
    assert(() {
386
      if (debugPrintMouseHoverEvents && event is PointerHoverEvent) {
387
        debugPrint('$event');
388
      }
389 390 391 392 393
      return true;
    }());
    if (hitTestResult != null ||
        event is PointerAddedEvent ||
        event is PointerRemovedEvent) {
394
      assert(event.position != null);
395
      dispatchEvent(event, hitTestResult);
Ian Hickson's avatar
Ian Hickson committed
396 397 398 399
    }
  }

  /// Determine which [HitTestTarget] objects are located at a given position.
400
  @override // from HitTestable
401
  void hitTest(HitTestResult result, Offset position) {
402
    result.add(HitTestEntry(this));
Ian Hickson's avatar
Ian Hickson committed
403 404
  }

405
  /// Dispatch an event to [pointerRouter] and the path of a hit test result.
406
  ///
407 408 409 410
  /// The `event` is routed to [pointerRouter]. If the `hitTestResult` is not
  /// null, the event is also sent to every [HitTestTarget] in the entries of the
  /// given [HitTestResult]. Any exceptions from the handlers are caught.
  ///
411 412
  /// The `hitTestResult` argument may only be null for [PointerAddedEvent]s or
  /// [PointerRemovedEvent]s.
413
  @override // from HitTestDispatcher
414
  @pragma('vm:notify-debugger-on-exception')
415
  void dispatchEvent(PointerEvent event, HitTestResult? hitTestResult) {
416
    assert(!locked);
417 418 419
    // No hit test information implies that this is a [PointerAddedEvent] or
    // [PointerRemovedEvent]. These events are specially routed here; other
    // events will be routed through the `handleEvent` below.
420
    if (hitTestResult == null) {
421
      assert(event is PointerAddedEvent || event is PointerRemovedEvent);
422 423 424 425 426 427 428
      try {
        pointerRouter.route(event);
      } catch (exception, stack) {
        FlutterError.reportError(FlutterErrorDetailsForPointerEventDispatcher(
          exception: exception,
          stack: stack,
          library: 'gesture library',
429
          context: ErrorDescription('while dispatching a non-hit-tested pointer event'),
430
          event: event,
431 432 433
          informationCollector: () => <DiagnosticsNode>[
            DiagnosticsProperty<PointerEvent>('Event', event, style: DiagnosticsTreeStyle.errorProperty),
          ],
434 435 436 437
        ));
      }
      return;
    }
438
    for (final HitTestEntry entry in hitTestResult.path) {
439
      try {
440
        entry.target.handleEvent(event.transformed(entry.transform), entry);
441
      } catch (exception, stack) {
442
        FlutterError.reportError(FlutterErrorDetailsForPointerEventDispatcher(
443 444 445
          exception: exception,
          stack: stack,
          library: 'gesture library',
446
          context: ErrorDescription('while dispatching a pointer event'),
447 448
          event: event,
          hitTestEntry: entry,
449 450 451 452
          informationCollector: () => <DiagnosticsNode>[
            DiagnosticsProperty<PointerEvent>('Event', event, style: DiagnosticsTreeStyle.errorProperty),
            DiagnosticsProperty<HitTestTarget>('Target', entry.target, style: DiagnosticsTreeStyle.errorProperty),
          ],
453
        ));
454 455
      }
    }
Ian Hickson's avatar
Ian Hickson committed
456 457
  }

458
  @override // from HitTestTarget
Ian Hickson's avatar
Ian Hickson committed
459 460
  void handleEvent(PointerEvent event, HitTestEntry entry) {
    pointerRouter.route(event);
461
    if (event is PointerDownEvent || event is PointerPanZoomStartEvent) {
Ian Hickson's avatar
Ian Hickson committed
462
      gestureArena.close(event.pointer);
463
    } else if (event is PointerUpEvent || event is PointerPanZoomEndEvent) {
Ian Hickson's avatar
Ian Hickson committed
464
      gestureArena.sweep(event.pointer);
465 466
    } else if (event is PointerSignalEvent) {
      pointerSignalResolver.resolve(event);
Ian Hickson's avatar
Ian Hickson committed
467 468
    }
  }
469

470 471 472 473 474 475 476 477 478 479
  /// Reset states of [GestureBinding].
  ///
  /// This clears the hit test records.
  ///
  /// This is typically called between tests.
  @protected
  void resetGestureBinding() {
    _hitTests.clear();
  }

480 481 482 483 484 485
  /// Overrides the sampling clock for debugging and testing.
  ///
  /// This value is ignored in non-debug builds.
  @protected
  SamplingClock? get debugSamplingClock => null;

486 487
  void _handleSampleTimeChanged() {
    if (!locked) {
488
      if (resamplingEnabled) {
489
        _resampler.sample(samplingOffset, _samplingClock);
490 491 492 493
      }
      else {
        _resampler.stop();
      }
494 495 496
    }
  }

497 498 499 500
  SamplingClock get _samplingClock {
    SamplingClock value = SamplingClock();
    assert(() {
      final SamplingClock? debugValue = debugSamplingClock;
501
      if (debugValue != null) {
502
        value = debugValue;
503
      }
504 505 506 507 508
      return true;
    }());
    return value;
  }

509 510 511
  // Resampler used to filter incoming pointer events when resampling
  // is enabled.
  late final _Resampler _resampler = _Resampler(
512
    _handlePointerEventImmediately,
513
    _handleSampleTimeChanged,
514
    _samplingInterval,
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
  );

  /// Enable pointer event resampling for touch devices by setting
  /// this to true.
  ///
  /// Resampling results in smoother touch event processing at the
  /// cost of some added latency. Devices with low frequency sensors
  /// or when the frequency is not a multiple of the display frequency
  /// (e.g., 120Hz input and 90Hz display) benefit from this.
  ///
  /// This is typically set during application initialization but
  /// can be adjusted dynamically in case the application only
  /// wants resampling for some period of time.
  bool resamplingEnabled = false;

  /// Offset relative to current frame time that should be used for
  /// resampling. The [samplingOffset] is expected to be negative.
  /// Non-negative [samplingOffset] is allowed but will effectively
  /// disable resampling.
  Duration samplingOffset = _defaultSamplingOffset;
Ian Hickson's avatar
Ian Hickson committed
535
}
536 537

/// Variant of [FlutterErrorDetails] with extra fields for the gesture
538
/// library's binding's pointer event dispatcher ([GestureBinding.dispatchEvent]).
539 540 541 542 543 544 545
class FlutterErrorDetailsForPointerEventDispatcher extends FlutterErrorDetails {
  /// Creates a [FlutterErrorDetailsForPointerEventDispatcher] object with the given
  /// arguments setting the object's properties.
  ///
  /// The gesture library calls this constructor when catching an exception
  /// that will subsequently be reported using [FlutterError.onError].
  const FlutterErrorDetailsForPointerEventDispatcher({
546 547 548 549
    required super.exception,
    super.stack,
    super.library,
    super.context,
550 551
    this.event,
    this.hitTestEntry,
552 553 554
    super.informationCollector,
    super.silent,
  });
555 556

  /// The pointer event that was being routed when the exception was raised.
557
  final PointerEvent? event;
558 559

  /// The hit test result entry for the object whose handleEvent method threw
560
  /// the exception. May be null if no hit test entry is associated with the
561 562
  /// event (e.g. [PointerHoverEvent]s, [PointerAddedEvent]s, and
  /// [PointerRemovedEvent]s).
563
  ///
564 565
  /// The target object itself is given by the [HitTestEntry.target] property of
  /// the hitTestEntry object.
566
  final HitTestEntry? hitTestEntry;
567
}