binding.dart 38.8 KB
Newer Older
1 2 3 4 5
// 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.

import 'dart:async';
6
import 'dart:collection';
7
import 'dart:developer';
8
import 'dart:ui' show AppLifecycleState;
9

10
import 'package:collection/collection.dart' show PriorityQueue, HeapPriorityQueue;
11
import 'package:flutter/foundation.dart';
12
import 'package:flutter/services.dart';
13

14
import 'debug.dart';
15 16
import 'priority.dart';

17
export 'dart:ui' show AppLifecycleState, VoidCallback;
18

19
/// Slows down animations by this factor to help in development.
20 21
double get timeDilation => _timeDilation;
double _timeDilation = 1.0;
22 23 24
/// Setting the time dilation automatically calls [SchedulerBinding.resetEpoch]
/// to ensure that time stamps seen by consumers of the scheduler binding are
/// always increasing.
25
set timeDilation(double value) {
26
  assert(value > 0.0);
27 28 29 30 31 32 33
  if (_timeDilation == value)
    return;
  // We need to resetEpoch first so that we capture start of the epoch with the
  // current time dilation.
  SchedulerBinding.instance?.resetEpoch();
  _timeDilation = value;
}
34

35
/// Signature for frame-related callbacks from the scheduler.
36
///
37
/// The `timeStamp` is the number of milliseconds since the beginning of the
38 39 40
/// scheduler's epoch. Use timeStamp to determine how far to advance animation
/// timelines so that all the animations in the system are synchronized to a
/// common time base.
41
typedef FrameCallback = void Function(Duration timeStamp);
42

43 44 45 46
/// Signature for [Scheduler.scheduleTask] callbacks.
///
/// The type argument `T` is the task's return value. Consider [void] if the
/// task does not return a value.
47
typedef TaskCallback<T> = T Function();
48

49
/// Signature for the [SchedulerBinding.schedulingStrategy] callback. Called
50 51 52 53 54 55 56
/// whenever the system needs to decide whether a task at a given
/// priority needs to be run.
///
/// Return true if a task with the given priority should be executed
/// at this time, false otherwise.
///
/// See also [defaultSchedulingStrategy].
57
typedef SchedulingStrategy = bool Function({ int priority, SchedulerBinding scheduler });
Ian Hickson's avatar
Ian Hickson committed
58

59 60 61
class _TaskEntry<T> {
  _TaskEntry(this.task, this.priority, this.debugLabel, this.flow) {
    // ignore: prefer_asserts_in_initializer_lists
62 63 64 65
    assert(() {
      debugStack = StackTrace.current;
      return true;
    }());
66
    completer = Completer<T>();
67
  }
68
  final TaskCallback<T> task;
69
  final int priority;
70 71
  final String debugLabel;
  final Flow flow;
72 73

  StackTrace debugStack;
74 75 76 77 78 79 80 81 82 83 84
  Completer<T> completer;

  void run() {
    Timeline.timeSync(
      debugLabel ?? 'Scheduled Task',
      () {
        completer.complete(task());
      },
      flow: flow != null ? Flow.step(flow.id) : null,
    );
  }
85
}
86

87
class _FrameCallbackEntry {
88
  _FrameCallbackEntry(this.callback, { bool rescheduling = false }) {
89 90
    assert(() {
      if (rescheduling) {
91
        assert(() {
92
          if (debugCurrentCallbackStack == null) {
93
            throw FlutterError(
94
              'scheduleFrameCallback called with rescheduling true, but no callback is in scope.\n'
95 96 97 98 99 100 101 102 103
              'The "rescheduling" argument should only be set to true if the '
              'callback is being reregistered from within the callback itself, '
              'and only then if the callback itself is entirely synchronous. '
              'If this is the initial registration of the callback, or if the '
              'callback is asynchronous, then do not use the "rescheduling" '
              'argument.'
            );
          }
          return true;
104
        }());
105
        debugStack = debugCurrentCallbackStack;
106
      } else {
107
        // TODO(ianh): trim the frames from this library, so that the call to scheduleFrameCallback is the top one
108
        debugStack = StackTrace.current;
109 110
      }
      return true;
111
    }());
112
  }
113

114
  final FrameCallback callback;
115 116 117

  static StackTrace debugCurrentCallbackStack;
  StackTrace debugStack;
118 119
}

120 121 122 123 124 125 126 127
/// The various phases that a [SchedulerBinding] goes through during
/// [SchedulerBinding.handleBeginFrame].
///
/// This is exposed by [SchedulerBinding.schedulerPhase].
///
/// The values of this enum are ordered in the same order as the phases occur,
/// so their relative index values can be compared to each other.
///
128
/// See also the discussion at [WidgetsBinding.drawFrame].
129 130 131 132 133 134 135 136 137
enum SchedulerPhase {
  /// No frame is being processed. Tasks (scheduled by
  /// [WidgetsBinding.scheduleTask]), microtasks (scheduled by
  /// [scheduleMicrotask]), [Timer] callbacks, event handlers (e.g. from user
  /// input), and other callbacks (e.g. from [Future]s, [Stream]s, and the like)
  /// may be executing.
  idle,

  /// The transient callbacks (scheduled by
138
  /// [WidgetsBinding.scheduleFrameCallback]) are currently executing.
139
  ///
140 141 142
  /// Typically, these callbacks handle updating objects to new animation
  /// states.
  ///
143
  /// See [SchedulerBinding.handleBeginFrame].
144 145
  transientCallbacks,

146 147 148 149 150 151 152
  /// Microtasks scheduled during the processing of transient callbacks are
  /// current executing.
  ///
  /// This may include, for instance, callbacks from futures resulted during the
  /// [transientCallbacks] phase.
  midFrameMicrotasks,

153 154 155 156
  /// The persistent callbacks (scheduled by
  /// [WidgetsBinding.addPersistentFrameCallback]) are currently executing.
  ///
  /// Typically, this is the build/layout/paint pipeline. See
157
  /// [WidgetsBinding.drawFrame] and [SchedulerBinding.handleDrawFrame].
158 159 160 161 162 163 164
  persistentCallbacks,

  /// The post-frame callbacks (scheduled by
  /// [WidgetsBinding.addPostFrameCallback]) are currently executing.
  ///
  /// Typically, these callbacks handle cleanup and scheduling of work for the
  /// next frame.
165
  ///
166
  /// See [SchedulerBinding.handleDrawFrame].
167 168 169
  postFrameCallbacks,
}

170
/// Scheduler for running the following:
171
///
172
/// * _Transient callbacks_, triggered by the system's [Window.onBeginFrame]
173 174 175 176
///   callback, for synchronizing the application's behavior to the system's
///   display. For example, [Ticker]s and [AnimationController]s trigger from
///   these.
///
177
/// * _Persistent callbacks_, triggered by the system's [Window.onDrawFrame]
178 179 180 181 182
///   callback, for updating the system's display after transient callbacks have
///   executed. For example, the rendering layer uses this to drive its
///   rendering pipeline.
///
/// * _Post-frame callbacks_, which are run after persistent callbacks, just
183
///   before returning from the [Window.onDrawFrame] callback.
184
///
185 186 187
/// * Non-rendering tasks, to be run between frames. These are given a
///   priority and are executed in priority order according to a
///   [schedulingStrategy].
188
mixin SchedulerBinding on BindingBase, ServicesBinding {
189
  @override
Ian Hickson's avatar
Ian Hickson committed
190 191 192
  void initInstances() {
    super.initInstances();
    _instance = this;
193 194
    window.onBeginFrame = _handleBeginFrame;
    window.onDrawFrame = _handleDrawFrame;
195
    SystemChannels.lifecycle.setMessageHandler(_handleLifecycleMessage);
196
  }
197

198 199 200
  /// The current [SchedulerBinding], if one has been created.
  static SchedulerBinding get instance => _instance;
  static SchedulerBinding _instance;
Ian Hickson's avatar
Ian Hickson committed
201

202 203 204
  @override
  void initServiceExtensions() {
    super.initServiceExtensions();
205

206
    if (!kReleaseMode) {
207 208 209 210 211 212 213 214
      registerNumericServiceExtension(
        name: 'timeDilation',
        getter: () async => timeDilation,
        setter: (double value) async {
          timeDilation = value;
        },
      );
    }
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
  /// Whether the application is visible, and if so, whether it is currently
  /// interactive.
  ///
  /// This is set by [handleAppLifecycleStateChanged] when the
  /// [SystemChannels.lifecycle] notification is dispatched.
  ///
  /// The preferred way to watch for changes to this value is using
  /// [WidgetsBindingObserver.didChangeAppLifecycleState].
  AppLifecycleState get lifecycleState => _lifecycleState;
  AppLifecycleState _lifecycleState;

  /// Called when the application lifecycle state changes.
  ///
  /// Notifies all the observers using
  /// [WidgetsBindingObserver.didChangeAppLifecycleState].
  ///
  /// This method exposes notifications from [SystemChannels.lifecycle].
  @protected
  @mustCallSuper
  void handleAppLifecycleStateChanged(AppLifecycleState state) {
    assert(state != null);
    _lifecycleState = state;
    switch (state) {
      case AppLifecycleState.resumed:
      case AppLifecycleState.inactive:
        _setFramesEnabledState(true);
        break;
      case AppLifecycleState.paused:
      case AppLifecycleState.suspending:
        _setFramesEnabledState(false);
        break;
    }
  }

251
  Future<String> _handleLifecycleMessage(String message) async {
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
    handleAppLifecycleStateChanged(_parseAppLifecycleMessage(message));
    return null;
  }

  static AppLifecycleState _parseAppLifecycleMessage(String message) {
    switch (message) {
      case 'AppLifecycleState.paused':
        return AppLifecycleState.paused;
      case 'AppLifecycleState.resumed':
        return AppLifecycleState.resumed;
      case 'AppLifecycleState.inactive':
        return AppLifecycleState.inactive;
      case 'AppLifecycleState.suspending':
        return AppLifecycleState.suspending;
    }
    return null;
  }

270
  /// The strategy to use when deciding whether to run a task or not.
271
  ///
272
  /// Defaults to [defaultSchedulingStrategy].
Ian Hickson's avatar
Ian Hickson committed
273
  SchedulingStrategy schedulingStrategy = defaultSchedulingStrategy;
274

275
  static int _taskSorter (_TaskEntry<dynamic> e1, _TaskEntry<dynamic> e2) {
Hixie's avatar
Hixie committed
276 277
    return -e1.priority.compareTo(e2.priority);
  }
278
  final PriorityQueue<_TaskEntry<dynamic>> _taskQueue = HeapPriorityQueue<_TaskEntry<dynamic>>(_taskSorter);
279

280 281 282 283 284 285 286
  /// Schedules the given `task` with the given `priority` and returns a
  /// [Future] that completes to the `task`'s eventual return value.
  ///
  /// The `debugLabel` and `flow` are used to report the task to the [Timeline],
  /// for use when profiling.
  ///
  /// ## Processing model
287 288 289 290 291 292
  ///
  /// Tasks will be executed between frames, in priority order,
  /// excluding tasks that are skipped by the current
  /// [schedulingStrategy]. Tasks should be short (as in, up to a
  /// millisecond), so as to not cause the regular frame callbacks to
  /// get delayed.
293 294 295 296 297 298 299 300 301 302
  ///
  /// If an animation is running, including, for instance, a [ProgressIndicator]
  /// indicating that there are pending tasks, then tasks with a priority below
  /// [Priority.animation] won't run (at least, not with the
  /// [defaultSchedulingStrategy]; this can be configured using
  /// [schedulingStrategy]).
  Future<T> scheduleTask<T>(TaskCallback<T> task, Priority priority, {
    String debugLabel,
    Flow flow,
  }) {
303
    final bool isFirstTask = _taskQueue.isEmpty;
304
    final _TaskEntry<T> entry = _TaskEntry<T>(
305 306 307 308 309 310
      task,
      priority.value,
      debugLabel,
      flow,
    );
    _taskQueue.add(entry);
311 312
    if (isFirstTask && !locked)
      _ensureEventLoopCallback();
313
    return entry.completer.future;
314 315 316 317 318 319
  }

  @override
  void unlocked() {
    super.unlocked();
    if (_taskQueue.isNotEmpty)
320
      _ensureEventLoopCallback();
321 322
  }

323 324 325
  // Whether this scheduler already requested to be called from the event loop.
  bool _hasRequestedAnEventLoopCallback = false;

326
  // Ensures that the scheduler services a task scheduled by [scheduleTask].
327
  void _ensureEventLoopCallback() {
328
    assert(!locked);
329
    assert(_taskQueue.isNotEmpty);
330 331 332
    if (_hasRequestedAnEventLoopCallback)
      return;
    _hasRequestedAnEventLoopCallback = true;
333
    Timer.run(_runTasks);
334 335
  }

336 337
  // Scheduled by _ensureEventLoopCallback.
  void _runTasks() {
338
    _hasRequestedAnEventLoopCallback = false;
339 340
    if (handleEventLoopCallback())
      _ensureEventLoopCallback(); // runs next task when there's time
341 342
  }

343 344 345 346 347 348 349 350 351 352 353 354
  /// Execute the highest-priority task, if it is of a high enough priority.
  ///
  /// Returns true if a task was executed and there are other tasks remaining
  /// (even if they are not high-enough priority).
  ///
  /// Returns false if no task was executed, which can occur if there are no
  /// tasks scheduled, if the scheduler is [locked], or if the highest-priority
  /// task is of too low a priority given the current [schedulingStrategy].
  ///
  /// Also returns false if there are no tasks remaining.
  @visibleForTesting
  bool handleEventLoopCallback() {
355
    if (_taskQueue.isEmpty || locked)
356
      return false;
357
    final _TaskEntry<dynamic> entry = _taskQueue.first;
Ian Hickson's avatar
Ian Hickson committed
358
    if (schedulingStrategy(priority: entry.priority, scheduler: this)) {
359
      try {
360 361
        _taskQueue.removeFirst();
        entry.run();
362 363 364 365 366 367
      } catch (exception, exceptionStack) {
        StackTrace callbackStack;
        assert(() {
          callbackStack = entry.debugStack;
          return true;
        }());
368
        FlutterError.reportError(FlutterErrorDetails(
369 370 371 372 373 374 375 376 377 378 379 380 381
          exception: exception,
          stack: exceptionStack,
          library: 'scheduler library',
          context: 'during a task callback',
          informationCollector: (callbackStack == null) ? null : (StringBuffer information) {
            information.writeln(
              '\nThis exception was thrown in the context of a task callback. '
              'When the task callback was _registered_ (as opposed to when the '
              'exception was thrown), this was the stack:'
            );
            FlutterError.defaultStackFilter(callbackStack.toString().trimRight().split('\n')).forEach(information.writeln);
          }
        ));
382
      }
383
      return _taskQueue.isNotEmpty;
384
    }
385
    return false;
386 387
  }

388
  int _nextFrameCallbackId = 0; // positive
389
  Map<int, _FrameCallbackEntry> _transientCallbacks = <int, _FrameCallbackEntry>{};
390
  final Set<int> _removedIds = HashSet<int>();
391

392 393 394
  /// The current number of transient frame callbacks scheduled.
  ///
  /// This is reset to zero just before all the currently scheduled
395
  /// transient callbacks are called, at the start of a frame.
396 397 398 399
  ///
  /// This number is primarily exposed so that tests can verify that
  /// there are no unexpected transient callbacks still registered
  /// after a test's resources have been gracefully disposed.
400 401
  int get transientCallbackCount => _transientCallbacks.length;

402
  /// Schedules the given transient frame callback.
403
  ///
404
  /// Adds the given callback to the list of frame callbacks and ensures that a
405
  /// frame is scheduled.
406
  ///
407 408 409 410 411 412 413 414
  /// If this is a one-off registration, ignore the `rescheduling` argument.
  ///
  /// If this is a callback that will be reregistered each time it fires, then
  /// when you reregister the callback, set the `rescheduling` argument to true.
  /// This has no effect in release builds, but in debug builds, it ensures that
  /// the stack trace that is stored for this callback is the original stack
  /// trace for when the callback was _first_ registered, rather than the stack
  /// trace for when the callback is reregistered. This makes it easier to track
415
  /// down the original reason that a particular callback was called. If
416 417
  /// `rescheduling` is true, the call must be in the context of a frame
  /// callback.
418 419 420
  ///
  /// Callbacks registered with this method can be canceled using
  /// [cancelFrameCallbackWithId].
421
  int scheduleFrameCallback(FrameCallback callback, { bool rescheduling = false }) {
422
    scheduleFrame();
423
    _nextFrameCallbackId += 1;
424
    _transientCallbacks[_nextFrameCallbackId] = _FrameCallbackEntry(callback, rescheduling: rescheduling);
425 426 427
    return _nextFrameCallbackId;
  }

428
  /// Cancels the transient frame callback with the given [id].
429 430
  ///
  /// Removes the given callback from the list of frame callbacks. If a frame
431 432
  /// has been requested, this does not also cancel that request.
  ///
433
  /// Transient frame callbacks are those registered using
434
  /// [scheduleFrameCallback].
435
  void cancelFrameCallbackWithId(int id) {
436 437 438 439 440
    assert(id > 0);
    _transientCallbacks.remove(id);
    _removedIds.add(id);
  }

441 442 443
  /// Asserts that there are no registered transient callbacks; if
  /// there are, prints their locations and throws an exception.
  ///
444
  /// A transient frame callback is one that was registered with
445
  /// [scheduleFrameCallback].
446
  ///
447 448 449
  /// This is expected to be called at the end of tests (the
  /// flutter_test framework does it automatically in normal cases).
  ///
450
  /// Call this method when you expect there to be no transient
451 452 453 454
  /// callbacks registered, in an assert statement with a message that
  /// you want printed when a transient callback is registered:
  ///
  /// ```dart
455
  /// assert(SchedulerBinding.instance.debugAssertNoTransientCallbacks(
456 457 458 459 460 461 462 463
  ///   'A leak of transient callbacks was detected while doing foo.'
  /// ));
  /// ```
  ///
  /// Does nothing if asserts are disabled. Always returns true.
  bool debugAssertNoTransientCallbacks(String reason) {
    assert(() {
      if (transientCallbackCount > 0) {
464 465 466 467
        // We cache the values so that we can produce them later
        // even if the information collector is called after
        // the problem has been resolved.
        final int count = transientCallbackCount;
468 469
        final Map<int, _FrameCallbackEntry> callbacks = Map<int, _FrameCallbackEntry>.from(_transientCallbacks);
        FlutterError.reportError(FlutterErrorDetails(
470 471 472
          exception: reason,
          library: 'scheduler library',
          informationCollector: (StringBuffer information) {
473
            if (count == 1) {
474 475
              information.writeln(
                'There was one transient callback left. '
476
                'The stack trace for when it was registered is as follows:'
477 478 479
              );
            } else {
              information.writeln(
480
                'There were $count transient callbacks left. '
481 482 483
                'The stack traces for when they were registered are as follows:'
              );
            }
484
            for (int id in callbacks.keys) {
485
              final _FrameCallbackEntry entry = callbacks[id];
486
              information.writeln('── callback $id ──');
487
              FlutterError.defaultStackFilter(entry.debugStack.toString().trimRight().split('\n')).forEach(information.writeln);
488 489 490 491 492
            }
          }
        ));
      }
      return true;
493
    }());
494 495 496
    return true;
  }

497 498 499
  /// Prints the stack for where the current transient callback was registered.
  ///
  /// A transient frame callback is one that was registered with
500
  /// [scheduleFrameCallback].
501 502 503
  ///
  /// When called in debug more and in the context of a transient callback, this
  /// function prints the stack trace from where the current transient callback
504
  /// was registered (i.e. where it first called [scheduleFrameCallback]).
505 506 507 508 509 510 511 512 513
  ///
  /// When called in debug mode in other contexts, it prints a message saying
  /// that this function was not called in the context a transient callback.
  ///
  /// In release mode, this function does nothing.
  ///
  /// To call this function, use the following code:
  ///
  /// ```dart
514
  /// SchedulerBinding.debugPrintTransientCallbackRegistrationStack();
515 516 517 518 519 520 521 522 523 524 525 526 527 528
  /// ```
  static void debugPrintTransientCallbackRegistrationStack() {
    assert(() {
      if (_FrameCallbackEntry.debugCurrentCallbackStack != null) {
        debugPrint('When the current transient callback was registered, this was the stack:');
        debugPrint(
          FlutterError.defaultStackFilter(
            _FrameCallbackEntry.debugCurrentCallbackStack.toString().trimRight().split('\n')
          ).join('\n')
        );
      } else {
        debugPrint('No transient callback is currently executing.');
      }
      return true;
529
    }());
530 531
  }

532
  final List<FrameCallback> _persistentCallbacks = <FrameCallback>[];
533

534 535
  /// Adds a persistent frame callback.
  ///
536
  /// Persistent callbacks are called after transient
537
  /// (non-persistent) frame callbacks.
538
  ///
539 540 541 542
  /// Does *not* request a new frame. Conceptually, persistent frame
  /// callbacks are observers of "begin frame" events. Since they are
  /// executed after the transient frame callbacks they can drive the
  /// rendering pipeline.
543 544 545
  ///
  /// Persistent frame callbacks cannot be unregistered. Once registered, they
  /// are called for every frame for the lifetime of the application.
546
  void addPersistentFrameCallback(FrameCallback callback) {
547 548 549
    _persistentCallbacks.add(callback);
  }

550
  final List<FrameCallback> _postFrameCallbacks = <FrameCallback>[];
551 552 553

  /// Schedule a callback for the end of this frame.
  ///
554
  /// Does *not* request a new frame.
555
  ///
556 557 558 559 560 561
  /// This callback is run during a frame, just after the persistent
  /// frame callbacks (which is when the main rendering pipeline has
  /// been flushed). If a frame is in progress and post-frame
  /// callbacks haven't been executed yet, then the registered
  /// callback is still executed during the frame. Otherwise, the
  /// registered callback is executed during the next frame.
562
  ///
563 564
  /// The callbacks are executed in the order in which they have been
  /// added.
565 566
  ///
  /// Post-frame callbacks cannot be unregistered. They are called exactly once.
567 568 569 570 571
  ///
  /// See also:
  ///
  ///  * [scheduleFrameCallback], which registers a callback for the start of
  ///    the next frame.
572
  void addPostFrameCallback(FrameCallback callback) {
573 574 575
    _postFrameCallbacks.add(callback);
  }

576
  Completer<void> _nextFrameCompleter;
577 578 579 580 581 582 583 584 585 586

  /// Returns a Future that completes after the frame completes.
  ///
  /// If this is called between frames, a frame is immediately scheduled if
  /// necessary. If this is called during a frame, the Future completes after
  /// the current frame.
  ///
  /// If the device's screen is currently turned off, this may wait a very long
  /// time, since frames are not scheduled while the device's screen is turned
  /// off.
587
  Future<void> get endOfFrame {
588 589 590
    if (_nextFrameCompleter == null) {
      if (schedulerPhase == SchedulerPhase.idle)
        scheduleFrame();
591
      _nextFrameCompleter = Completer<void>();
592 593 594 595 596 597 598 599
      addPostFrameCallback((Duration timeStamp) {
        _nextFrameCompleter.complete();
        _nextFrameCompleter = null;
      });
    }
    return _nextFrameCompleter.future;
  }

600
  /// Whether this scheduler has requested that [handleBeginFrame] be called soon.
601
  bool get hasScheduledFrame => _hasScheduledFrame;
602
  bool _hasScheduledFrame = false;
603

604 605 606
  /// The phase that the scheduler is currently operating under.
  SchedulerPhase get schedulerPhase => _schedulerPhase;
  SchedulerPhase _schedulerPhase = SchedulerPhase.idle;
607

608 609 610 611 612 613 614 615 616 617 618 619 620 621
  /// Whether frames are currently being scheduled when [scheduleFrame] is called.
  ///
  /// This value depends on the value of the [lifecycleState].
  bool get framesEnabled => _framesEnabled;

  bool _framesEnabled = true;
  void _setFramesEnabledState(bool enabled) {
    if (_framesEnabled == enabled)
      return;
    _framesEnabled = enabled;
    if (enabled)
      scheduleFrame();
  }

622 623
  /// Schedules a new frame using [scheduleFrame] if this object is not
  /// currently producing a frame.
624
  ///
625 626 627 628 629 630 631 632 633 634
  /// Calling this method ensures that [handleDrawFrame] will eventually be
  /// called, unless it's already in progress.
  ///
  /// This has no effect if [schedulerPhase] is
  /// [SchedulerPhase.transientCallbacks] or [SchedulerPhase.midFrameMicrotasks]
  /// (because a frame is already being prepared in that case), or
  /// [SchedulerPhase.persistentCallbacks] (because a frame is actively being
  /// rendered in that case). It will schedule a frame if the [schedulerPhase]
  /// is [SchedulerPhase.idle] (in between frames) or
  /// [SchedulerPhase.postFrameCallbacks] (after a frame).
635
  void ensureVisualUpdate() {
636 637 638 639 640 641 642 643 644 645
    switch (schedulerPhase) {
      case SchedulerPhase.idle:
      case SchedulerPhase.postFrameCallbacks:
        scheduleFrame();
        return;
      case SchedulerPhase.transientCallbacks:
      case SchedulerPhase.midFrameMicrotasks:
      case SchedulerPhase.persistentCallbacks:
        return;
    }
646
  }
647

648
  /// If necessary, schedules a new frame by calling
649
  /// [Window.scheduleFrame].
650 651
  ///
  /// After this is called, the engine will (eventually) call
652 653 654 655 656 657
  /// [handleBeginFrame]. (This call might be delayed, e.g. if the device's
  /// screen is turned off it will typically be delayed until the screen is on
  /// and the application is visible.) Calling this during a frame forces
  /// another frame to be scheduled, even if the current frame has not yet
  /// completed.
  ///
658 659 660 661 662 663 664 665
  /// Scheduled frames are serviced when triggered by a "Vsync" signal provided
  /// by the operating system. The "Vsync" signal, or vertical synchronization
  /// signal, was historically related to the display refresh, at a time when
  /// hardware physically moved a beam of electrons vertically between updates
  /// of the display. The operation of contemporary hardware is somewhat more
  /// subtle and complicated, but the conceptual "Vsync" refresh signal continue
  /// to be used to indicate when applications should update their rendering.
  ///
666 667
  /// To have a stack trace printed to the console any time this function
  /// schedules a frame, set [debugPrintScheduleFrameStacks] to true.
668 669 670 671 672 673 674
  ///
  /// See also:
  ///
  ///  * [scheduleForcedFrame], which ignores the [lifecycleState] when
  ///    scheduling a frame.
  ///  * [scheduleWarmUpFrame], which ignores the "Vsync" signal entirely and
  ///    triggers a frame immediately.
675
  void scheduleFrame() {
676
    if (_hasScheduledFrame || !_framesEnabled)
677
      return;
678 679 680 681
    assert(() {
      if (debugPrintScheduleFrameStacks)
        debugPrintStack(label: 'scheduleFrame() called. Current phase is $schedulerPhase.');
      return true;
682
    }());
683
    window.scheduleFrame();
684 685
    _hasScheduledFrame = true;
  }
686

687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
  /// Schedules a new frame by calling [Window.scheduleFrame].
  ///
  /// After this is called, the engine will call [handleBeginFrame], even if
  /// frames would normally not be scheduled by [scheduleFrame] (e.g. even if
  /// the device's screen is turned off).
  ///
  /// The framework uses this to force a frame to be rendered at the correct
  /// size when the phone is rotated, so that a correctly-sized rendering is
  /// available when the screen is turned back on.
  ///
  /// To have a stack trace printed to the console any time this function
  /// schedules a frame, set [debugPrintScheduleFrameStacks] to true.
  ///
  /// Prefer using [scheduleFrame] unless it is imperative that a frame be
  /// scheduled immediately, since using [scheduleForceFrame] will cause
  /// significantly higher battery usage when the device should be idle.
  ///
  /// Consider using [scheduleWarmUpFrame] instead if the goal is to update the
  /// rendering as soon as possible (e.g. at application startup).
  void scheduleForcedFrame() {
    if (_hasScheduledFrame)
      return;
    assert(() {
      if (debugPrintScheduleFrameStacks)
        debugPrintStack(label: 'scheduleForcedFrame() called. Current phase is $schedulerPhase.');
      return true;
    }());
714
    window.scheduleFrame();
715 716 717 718 719 720 721 722 723 724 725
    _hasScheduledFrame = true;
  }

  bool _warmUpFrame = false;

  /// Schedule a frame to run as soon as possible, rather than waiting for
  /// the engine to request a frame in response to a system "Vsync" signal.
  ///
  /// This is used during application startup so that the first frame (which is
  /// likely to be quite expensive) gets a few extra milliseconds to run.
  ///
726 727
  /// Locks events dispatching until the scheduled frame has completed.
  ///
728 729 730
  /// If a frame has already been scheduled with [scheduleFrame] or
  /// [scheduleForcedFrame], this call may delay that frame.
  ///
731 732 733
  /// If any scheduled frame has already begun or if another
  /// [scheduleWarmUpFrame] was already called, this call will be ignored.
  ///
734 735
  /// Prefer [scheduleFrame] to update the display in normal operation.
  void scheduleWarmUpFrame() {
736 737 738
    if (_warmUpFrame || schedulerPhase != SchedulerPhase.idle)
      return;

739
    _warmUpFrame = true;
740 741
    Timeline.startSync('Warm-up frame');
    final bool hadScheduledFrame = _hasScheduledFrame;
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
    // We use timers here to ensure that microtasks flush in between.
    Timer.run(() {
      assert(_warmUpFrame);
      handleBeginFrame(null);
    });
    Timer.run(() {
      assert(_warmUpFrame);
      handleDrawFrame();
      // We call resetEpoch after this frame so that, in the hot reload case,
      // the very next frame pretends to have occurred immediately after this
      // warm-up frame. The warm-up frame's timestamp will typically be far in
      // the past (the time of the last real frame), so if we didn't reset the
      // epoch we would see a sudden jump from the old time in the warm-up frame
      // to the new time in the "real" frame. The biggest problem with this is
      // that implicit animations end up being triggered at the old time and
      // then skipping every frame and finishing in the new time.
      resetEpoch();
      _warmUpFrame = false;
      if (hadScheduledFrame)
        scheduleFrame();
    });
763 764 765 766 767 768 769

    // Lock events so touch events etc don't insert themselves until the
    // scheduled frame has finished.
    lockEvents(() async {
      await endOfFrame;
      Timeline.finishSync();
    });
770 771
  }

772
  Duration _firstRawTimeStampInEpoch;
773 774
  Duration _epochStart = Duration.zero;
  Duration _lastRawTimeStamp = Duration.zero;
775

776
  /// Prepares the scheduler for a non-monotonic change to how time stamps are
777
  /// calculated.
778 779 780 781 782 783 784 785
  ///
  /// Callbacks received from the scheduler assume that their time stamps are
  /// monotonically increasing. The raw time stamp passed to [handleBeginFrame]
  /// is monotonic, but the scheduler might adjust those time stamps to provide
  /// [timeDilation]. Without careful handling, these adjusts could cause time
  /// to appear to run backwards.
  ///
  /// The [resetEpoch] function ensures that the time stamps are monotonic by
786
  /// resetting the base time stamp used for future time stamp adjustments to the
787 788 789 790
  /// current value. For example, if the [timeDilation] decreases, rather than
  /// scaling down the [Duration] since the beginning of time, [resetEpoch] will
  /// ensure that we only scale down the duration since [resetEpoch] was called.
  ///
791 792
  /// Setting [timeDilation] calls [resetEpoch] automatically. You don't need to
  /// call [resetEpoch] yourself.
793 794 795 796 797 798 799 800 801 802 803 804 805 806
  void resetEpoch() {
    _epochStart = _adjustForEpoch(_lastRawTimeStamp);
    _firstRawTimeStampInEpoch = null;
  }

  /// Adjusts the given time stamp into the current epoch.
  ///
  /// This both offsets the time stamp to account for when the epoch started
  /// (both in raw time and in the epoch's own time line) and scales the time
  /// stamp to reflect the time dilation in the current epoch.
  ///
  /// These mechanisms together combine to ensure that the durations we give
  /// during frame callbacks are monotonically increasing.
  Duration _adjustForEpoch(Duration rawTimeStamp) {
807
    final Duration rawDurationSinceEpoch = _firstRawTimeStampInEpoch == null ? Duration.zero : rawTimeStamp - _firstRawTimeStampInEpoch;
808
    return Duration(microseconds: (rawDurationSinceEpoch.inMicroseconds / timeDilation).round() + _epochStart.inMicroseconds);
809 810
  }

811 812 813 814 815 816 817 818 819 820
  /// The time stamp for the frame currently being processed.
  ///
  /// This is only valid while [handleBeginFrame] is running, i.e. while a frame
  /// is being produced.
  Duration get currentFrameTimeStamp {
    assert(_currentFrameTimeStamp != null);
    return _currentFrameTimeStamp;
  }
  Duration _currentFrameTimeStamp;

821
  int _profileFrameNumber = 0;
822
  final Stopwatch _profileFrameStopwatch = Stopwatch();
823
  String _debugBanner;
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
  bool _ignoreNextEngineDrawFrame = false;

  void _handleBeginFrame(Duration rawTimeStamp) {
    if (_warmUpFrame) {
      assert(!_ignoreNextEngineDrawFrame);
      _ignoreNextEngineDrawFrame = true;
      return;
    }
    handleBeginFrame(rawTimeStamp);
  }

  void _handleDrawFrame() {
    if (_ignoreNextEngineDrawFrame) {
      _ignoreNextEngineDrawFrame = false;
      return;
    }
    handleDrawFrame();
  }
842

843
  /// Called by the engine to prepare the framework to produce a new frame.
844
  ///
845 846 847 848
  /// This function calls all the transient frame callbacks registered by
  /// [scheduleFrameCallback]. It then returns, any scheduled microtasks are run
  /// (e.g. handlers for any [Future]s resolved by transient frame callbacks),
  /// and [handleDrawFrame] is called to continue the frame.
849 850 851 852 853 854 855 856 857
  ///
  /// If the given time stamp is null, the time stamp from the last frame is
  /// reused.
  ///
  /// To have a banner shown at the start of every frame in debug mode, set
  /// [debugPrintBeginFrameBanner] to true. The banner will be printed to the
  /// console using [debugPrint] and will contain the frame number (which
  /// increments by one for each frame), and the time stamp of the frame. If the
  /// given time stamp was null, then the string "warm-up frame" is shown
858 859 860
  /// instead of the time stamp. This allows frames eagerly pushed by the
  /// framework to be distinguished from those requested by the engine in
  /// response to the "Vsync" signal from the operating system.
861 862 863 864 865
  ///
  /// You can also show a banner at the end of every frame by setting
  /// [debugPrintEndFrameBanner] to true. This allows you to distinguish log
  /// statements printed during a frame from those printed between frames (e.g.
  /// in response to events or timers).
866
  void handleBeginFrame(Duration rawTimeStamp) {
867
    Timeline.startSync('Frame', arguments: timelineWhitelistArguments);
868
    _firstRawTimeStampInEpoch ??= rawTimeStamp;
869 870 871 872
    _currentFrameTimeStamp = _adjustForEpoch(rawTimeStamp ?? _lastRawTimeStamp);
    if (rawTimeStamp != null)
      _lastRawTimeStamp = rawTimeStamp;

873 874 875 876 877 878
    profile(() {
      _profileFrameNumber += 1;
      _profileFrameStopwatch.reset();
      _profileFrameStopwatch.start();
    });

879
    assert(() {
880
      if (debugPrintBeginFrameBanner || debugPrintEndFrameBanner) {
881
        final StringBuffer frameTimeStampDescription = StringBuffer();
882 883 884 885 886
        if (rawTimeStamp != null) {
          _debugDescribeTimeStamp(_currentFrameTimeStamp, frameTimeStampDescription);
        } else {
          frameTimeStampDescription.write('(warm-up frame)');
        }
887
        _debugBanner = '▄▄▄▄▄▄▄▄ Frame ${_profileFrameNumber.toString().padRight(7)}   ${frameTimeStampDescription.toString().padLeft(18)} ▄▄▄▄▄▄▄▄';
888
        if (debugPrintBeginFrameBanner)
889
          debugPrint(_debugBanner);
890
      }
891
      return true;
892
    }());
893

894
    assert(schedulerPhase == SchedulerPhase.idle);
895
    _hasScheduledFrame = false;
896 897
    try {
      // TRANSIENT FRAME CALLBACKS
898
      Timeline.startSync('Animate', arguments: timelineWhitelistArguments);
899
      _schedulerPhase = SchedulerPhase.transientCallbacks;
900 901 902 903 904 905 906 907 908 909 910
      final Map<int, _FrameCallbackEntry> callbacks = _transientCallbacks;
      _transientCallbacks = <int, _FrameCallbackEntry>{};
      callbacks.forEach((int id, _FrameCallbackEntry callbackEntry) {
        if (!_removedIds.contains(id))
          _invokeFrameCallback(callbackEntry.callback, _currentFrameTimeStamp, callbackEntry.debugStack);
      });
      _removedIds.clear();
    } finally {
      _schedulerPhase = SchedulerPhase.midFrameMicrotasks;
    }
  }
911

912 913 914 915 916 917 918 919 920 921 922
  /// Called by the engine to produce a new frame.
  ///
  /// This method is called immediately after [handleBeginFrame]. It calls all
  /// the callbacks registered by [addPersistentFrameCallback], which typically
  /// drive the rendering pipeline, and then calls the callbacks registered by
  /// [addPostFrameCallback].
  ///
  /// See [handleBeginFrame] for a discussion about debugging hooks that may be
  /// useful when working with frame callbacks.
  void handleDrawFrame() {
    assert(_schedulerPhase == SchedulerPhase.midFrameMicrotasks);
923
    Timeline.finishSync(); // end the "Animate" phase
924
    try {
925
      // PERSISTENT FRAME CALLBACKS
926
      _schedulerPhase = SchedulerPhase.persistentCallbacks;
927 928 929 930
      for (FrameCallback callback in _persistentCallbacks)
        _invokeFrameCallback(callback, _currentFrameTimeStamp);

      // POST-FRAME CALLBACKS
931
      _schedulerPhase = SchedulerPhase.postFrameCallbacks;
932
      final List<FrameCallback> localPostFrameCallbacks =
933
          List<FrameCallback>.from(_postFrameCallbacks);
934 935 936 937
      _postFrameCallbacks.clear();
      for (FrameCallback callback in localPostFrameCallbacks)
        _invokeFrameCallback(callback, _currentFrameTimeStamp);
    } finally {
938
      _schedulerPhase = SchedulerPhase.idle;
939 940 941 942 943
      Timeline.finishSync(); // end the Frame
      profile(() {
        _profileFrameStopwatch.stop();
        _profileFramePostEvent();
      });
944 945
      assert(() {
        if (debugPrintEndFrameBanner)
946 947
          debugPrint('▀' * _debugBanner.length);
        _debugBanner = null;
948
        return true;
949
      }());
950
      _currentFrameTimeStamp = null;
951
    }
952 953
  }

954 955 956 957 958 959 960 961
  void _profileFramePostEvent() {
    postEvent('Flutter.Frame', <String, dynamic>{
      'number': _profileFrameNumber,
      'startTime': _currentFrameTimeStamp.inMicroseconds,
      'elapsed': _profileFrameStopwatch.elapsedMicroseconds
    });
  }

962 963 964 965
  static void _debugDescribeTimeStamp(Duration timeStamp, StringBuffer buffer) {
    if (timeStamp.inDays > 0)
      buffer.write('${timeStamp.inDays}d ');
    if (timeStamp.inHours > 0)
966
      buffer.write('${timeStamp.inHours - timeStamp.inDays * Duration.hoursPerDay}h ');
967
    if (timeStamp.inMinutes > 0)
968
      buffer.write('${timeStamp.inMinutes - timeStamp.inHours * Duration.minutesPerHour}m ');
969
    if (timeStamp.inSeconds > 0)
970 971 972
      buffer.write('${timeStamp.inSeconds - timeStamp.inMinutes * Duration.secondsPerMinute}s ');
    buffer.write('${timeStamp.inMilliseconds - timeStamp.inSeconds * Duration.millisecondsPerSecond}');
    final int microseconds = timeStamp.inMicroseconds - timeStamp.inMilliseconds * Duration.microsecondsPerMillisecond;
973 974 975 976 977
    if (microseconds > 0)
      buffer.write('.${microseconds.toString().padLeft(3, "0")}');
    buffer.write('ms');
  }

978
  // Calls the given [callback] with [timestamp] as argument.
979 980 981 982 983
  //
  // Wraps the callback in a try/catch and forwards any error to
  // [debugSchedulerExceptionHandler], if set. If not set, then simply prints
  // the error.
  void _invokeFrameCallback(FrameCallback callback, Duration timeStamp, [ StackTrace callbackStack ]) {
984
    assert(callback != null);
985
    assert(_FrameCallbackEntry.debugCurrentCallbackStack == null);
986
    assert(() { _FrameCallbackEntry.debugCurrentCallbackStack = callbackStack; return true; }());
987 988
    try {
      callback(timeStamp);
989
    } catch (exception, exceptionStack) {
990
      FlutterError.reportError(FlutterErrorDetails(
991
        exception: exception,
992
        stack: exceptionStack,
993
        library: 'scheduler library',
994
        context: 'during a scheduler callback',
995
        informationCollector: (callbackStack == null) ? null : (StringBuffer information) {
996 997 998 999 1000 1001
          information.writeln(
            '\nThis exception was thrown in the context of a scheduler callback. '
            'When the scheduler callback was _registered_ (as opposed to when the '
            'exception was thrown), this was the stack:'
          );
          FlutterError.defaultStackFilter(callbackStack.toString().trimRight().split('\n')).forEach(information.writeln);
1002
        }
1003
      ));
1004
    }
1005
    assert(() { _FrameCallbackEntry.debugCurrentCallbackStack = null; return true; }());
1006
  }
1007 1008
}

1009
/// The default [SchedulingStrategy] for [SchedulerBinding.schedulingStrategy].
1010 1011 1012 1013
///
/// If there are any frame callbacks registered, only runs tasks with
/// a [Priority] of [Priority.animation] or higher. Otherwise, runs
/// all tasks.
1014
bool defaultSchedulingStrategy({ int priority, SchedulerBinding scheduler }) {
Ian Hickson's avatar
Ian Hickson committed
1015
  if (scheduler.transientCallbackCount > 0)
1016
    return priority >= Priority.animation.value;
Ian Hickson's avatar
Ian Hickson committed
1017
  return true;
1018
}