binding.dart 33.5 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
import 'dart:async';
6
import 'dart:developer' as developer;
7
import 'dart:ui' show AppLifecycleState, Locale, AccessibilityFeatures;
8
import 'dart:ui' as ui show window;
9

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

16
import 'app.dart';
17
import 'focus_manager.dart';
18
import 'framework.dart';
19
import 'widget_inspector.dart';
20

21 22
export 'dart:ui' show AppLifecycleState, Locale;

23 24
/// Interface for classes that register with the Widgets layer binding.
///
25
/// See [WidgetsBinding.addObserver] and [WidgetsBinding.removeObserver].
26 27 28 29 30
///
/// This class can be extended directly, to get default behaviors for all of the
/// handlers, or can used with the `implements` keyword, in which case all the
/// handlers must be implemented (and the analyzer will list those that have
/// been omitted).
31 32 33 34 35 36 37 38
///
/// ## Sample code
///
/// This [StatefulWidget] implements the parts of the [State] and
/// [WidgetsBindingObserver] protocols necessary to react to application
/// lifecycle messages. See [didChangeAppLifecycleState].
///
/// ```dart
39 40
/// class AppLifecycleReactor extends StatefulWidget {
///   const AppLifecycleReactor({ Key key }) : super(key: key);
41 42
///
///   @override
43
///   _AppLifecycleReactorState createState() => new _AppLifecycleReactorState();
44 45
/// }
///
46
/// class _AppLifecycleReactorState extends State<AppLifecycleReactor> with WidgetsBindingObserver {
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
///   @override
///   void initState() {
///     super.initState();
///     WidgetsBinding.instance.addObserver(this);
///   }
///
///   @override
///   void dispose() {
///     WidgetsBinding.instance.removeObserver(this);
///     super.dispose();
///   }
///
///   AppLifecycleState _notification;
///
///   @override
///   void didChangeAppLifecycleState(AppLifecycleState state) {
///     setState(() { _notification = state; });
///   }
///
///   @override
///   Widget build(BuildContext context) {
///     return new Text('Last notification: $_notification');
///   }
/// }
/// ```
///
/// To respond to other notifications, replace the [didChangeAppLifecycleState]
/// method above with other methods from this class.
75 76 77 78 79 80 81 82 83 84 85 86 87
abstract class WidgetsBindingObserver {
  /// Called when the system tells the app to pop the current route.
  /// For example, on Android, this is called when the user presses
  /// the back button.
  ///
  /// Observers are notified in registration order until one returns
  /// true. If none return true, the application quits.
  ///
  /// Observers are expected to return true if they were able to
  /// handle the notification, for example by closing an active dialog
  /// box, and false otherwise. The [WidgetsApp] widget uses this
  /// mechanism to notify the [Navigator] widget that it should pop
  /// its current route if possible.
88 89 90
  ///
  /// This method exposes the `popRoute` notification from
  /// [SystemChannels.navigation].
91
  Future<bool> didPopRoute() => new Future<bool>.value(false);
92

93 94 95 96
  /// Called when the host tells the app to push a new route onto the
  /// navigator.
  ///
  /// Observers are expected to return true if they were able to
97
  /// handle the notification. Observers are notified in registration
98
  /// order until one returns true.
99 100 101
  ///
  /// This method exposes the `pushRoute` notification from
  /// [SystemChannels.navigation].
102 103
  Future<bool> didPushRoute(String route) => new Future<bool>.value(false);

104 105
  /// Called when the application's dimensions change. For example,
  /// when a phone is rotated.
106
  ///
107 108
  /// This method exposes notifications from [Window.onMetricsChanged].
  ///
109 110 111 112 113 114 115
  /// ## Sample code
  ///
  /// This [StatefulWidget] implements the parts of the [State] and
  /// [WidgetsBindingObserver] protocols necessary to react when the device is
  /// rotated (or otherwise changes dimensions).
  ///
  /// ```dart
116 117
  /// class MetricsReactor extends StatefulWidget {
  ///   const MetricsReactor({ Key key }) : super(key: key);
118 119
  ///
  ///   @override
120
  ///   _MetricsReactorState createState() => new _MetricsReactorState();
121 122
  /// }
  ///
123
  /// class _MetricsReactorState extends State<MetricsReactor> with WidgetsBindingObserver {
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
  ///   @override
  ///   void initState() {
  ///     super.initState();
  ///     WidgetsBinding.instance.addObserver(this);
  ///   }
  ///
  ///   @override
  ///   void dispose() {
  ///     WidgetsBinding.instance.removeObserver(this);
  ///     super.dispose();
  ///   }
  ///
  ///   Size _lastSize;
  ///
  ///   @override
  ///   void didChangeMetrics() {
  ///     setState(() { _lastSize = ui.window.physicalSize; });
  ///   }
  ///
  ///   @override
  ///   Widget build(BuildContext context) {
145
  ///     return new Text('Current size: $_lastSize');
146 147 148 149 150 151 152 153 154 155 156 157
  ///   }
  /// }
  /// ```
  ///
  /// In general, this is unnecessary as the layout system takes care of
  /// automatically recomputing the application geometry when the application
  /// size changes.
  ///
  /// See also:
  ///
  ///  * [MediaQuery.of], which provides a similar service with less
  ///    boilerplate.
158
  void didChangeMetrics() { }
159

160 161 162 163 164 165
  /// Called when the platform's text scale factor changes.
  ///
  /// This typically happens as the result of the user changing system
  /// preferences, and it should affect all of the text sizes in the
  /// application.
  ///
166 167
  /// This method exposes notifications from [Window.onTextScaleFactorChanged].
  ///
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
  /// ## Sample code
  ///
  /// ```dart
  /// class TextScaleFactorReactor extends StatefulWidget {
  ///   const TextScaleFactorReactor({ Key key }) : super(key: key);
  ///
  ///   @override
  ///   _TextScaleFactorReactorState createState() => new _TextScaleFactorReactorState();
  /// }
  ///
  /// class _TextScaleFactorReactorState extends State<TextScaleFactorReactor> with WidgetsBindingObserver {
  ///   @override
  ///   void initState() {
  ///     super.initState();
  ///     WidgetsBinding.instance.addObserver(this);
  ///   }
  ///
  ///   @override
  ///   void dispose() {
  ///     WidgetsBinding.instance.removeObserver(this);
  ///     super.dispose();
  ///   }
  ///
  ///   double _lastTextScaleFactor;
  ///
  ///   @override
  ///   void didChangeTextScaleFactor() {
  ///     setState(() { _lastTextScaleFactor = ui.window.textScaleFactor; });
  ///   }
  ///
  ///   @override
  ///   Widget build(BuildContext context) {
  ///     return new Text('Current scale factor: $_lastTextScaleFactor');
  ///   }
  /// }
  /// ```
  ///
  /// See also:
  ///
  ///  * [MediaQuery.of], which provides a similar service with less
  ///    boilerplate.
  void didChangeTextScaleFactor() { }

211 212 213
  /// Called when the system tells the app that the user's locale has
  /// changed. For example, if the user changes the system language
  /// settings.
214 215
  ///
  /// This method exposes notifications from [Window.onLocaleChanged].
216
  void didChangeLocale(Locale locale) { }
217 218 219

  /// Called when the system puts the app in the background or returns
  /// the app to the foreground.
220 221 222
  ///
  /// An example of implementing this method is provided in the class-level
  /// documentation for the [WidgetsBindingObserver] class.
223 224
  ///
  /// This method exposes notifications from [SystemChannels.lifecycle].
225
  void didChangeAppLifecycleState(AppLifecycleState state) { }
226 227

  /// Called when the system is running low on memory.
228 229 230
  ///
  /// This method exposes the `memoryPressure` notification from
  /// [SystemChannels.system].
231
  void didHaveMemoryPressure() { }
232 233 234 235 236 237

  /// Called when the system changes the set of currently active accessibility
  /// features.
  ///
  /// This method exposes notifications from [Window.onAccessibilityFeaturesChanged].
  void didChangeAccessibilityFeatures() {}
Ian Hickson's avatar
Ian Hickson committed
238
}
239

240
/// The glue between the widgets layer and the Flutter engine.
241
abstract class WidgetsBinding extends BindingBase with SchedulerBinding, GestureBinding, RendererBinding {
242 243 244 245
  // This class is intended to be used as a mixin, and should not be
  // extended directly.
  factory WidgetsBinding._() => null;

246
  @override
247
  void initInstances() {
Ian Hickson's avatar
Ian Hickson committed
248 249
    super.initInstances();
    _instance = this;
250
    buildOwner.onBuildScheduled = _handleBuildScheduled;
Ian Hickson's avatar
Ian Hickson committed
251
    ui.window.onLocaleChanged = handleLocaleChanged;
252
    ui.window.onAccessibilityFeaturesChanged = handleAccessibilityFeaturesChanged;
253 254
    SystemChannels.navigation.setMethodCallHandler(_handleNavigationInvocation);
    SystemChannels.system.setMessageHandler(_handleSystemMessage);
255 256
  }

257
  /// The current [WidgetsBinding], if one has been created.
258 259 260
  ///
  /// If you need the binding to be constructed before calling [runApp],
  /// you can ensure a Widget binding has been constructed by calling the
261 262 263
  /// `WidgetsFlutterBinding.ensureInitialized()` function.
  static WidgetsBinding get instance => _instance;
  static WidgetsBinding _instance;
264

265 266 267 268
  @override
  void initServiceExtensions() {
    super.initServiceExtensions();

269 270
    registerSignalServiceExtension(
      name: 'debugDumpApp',
271
      callback: () { debugDumpApp(); return debugPrintDone; }
272 273
    );

274 275
    registerBoolServiceExtension(
      name: 'showPerformanceOverlay',
276
      getter: () => new Future<bool>.value(WidgetsApp.showPerformanceOverlayOverride),
277 278
      setter: (bool value) {
        if (WidgetsApp.showPerformanceOverlayOverride == value)
279
          return new Future<Null>.value();
280
        WidgetsApp.showPerformanceOverlayOverride = value;
281
        return _forceRebuild();
282 283
      }
    );
284 285 286

    registerBoolServiceExtension(
      name: 'debugAllowBanner',
287
      getter: () => new Future<bool>.value(WidgetsApp.debugAllowBannerOverride),
288 289
      setter: (bool value) {
        if (WidgetsApp.debugAllowBannerOverride == value)
290
          return new Future<Null>.value();
291
        WidgetsApp.debugAllowBannerOverride = value;
292
        return _forceRebuild();
293 294
      }
    );
295

296 297
    // This service extension is deprecated and will be removed by 7/1/2018.
    // Use ext.flutter.inspector.show instead.
298 299 300 301 302 303 304 305 306 307
    registerBoolServiceExtension(
        name: 'debugWidgetInspector',
        getter: () async => WidgetsApp.debugShowWidgetInspectorOverride,
        setter: (bool value) {
          if (WidgetsApp.debugShowWidgetInspectorOverride == value)
            return new Future<Null>.value();
          WidgetsApp.debugShowWidgetInspectorOverride = value;
          return _forceRebuild();
        }
    );
308 309

    WidgetInspectorService.instance.initServiceExtensions(registerServiceExtension);
310 311
  }

312 313 314 315 316 317 318 319
  Future<Null> _forceRebuild() {
    if (renderViewElement != null) {
      buildOwner.reassemble(renderViewElement);
      return endOfFrame;
    }
    return new Future<Null>.value();
  }

320 321 322 323
  /// The [BuildOwner] in charge of executing the build pipeline for the
  /// widget tree rooted at this binding.
  BuildOwner get buildOwner => _buildOwner;
  final BuildOwner _buildOwner = new BuildOwner();
Ian Hickson's avatar
Ian Hickson committed
324

325
  /// The object in charge of the focus tree.
326
  ///
327 328
  /// Rarely used directly. Instead, consider using [FocusScope.of] to obtain
  /// the [FocusScopeNode] for a given [BuildContext].
329
  ///
330
  /// See [FocusManager] for more details.
331
  FocusManager get focusManager => _buildOwner.focusManager;
332

333
  final List<WidgetsBindingObserver> _observers = <WidgetsBindingObserver>[];
Ian Hickson's avatar
Ian Hickson committed
334

335 336 337 338 339 340 341 342 343 344 345 346
  /// Registers the given object as a binding observer. Binding
  /// observers are notified when various application events occur,
  /// for example when the system locale changes. Generally, one
  /// widget in the widget tree registers itself as a binding
  /// observer, and converts the system state into inherited widgets.
  ///
  /// For example, the [WidgetsApp] widget registers as a binding
  /// observer and passes the screen size to a [MediaQuery] widget
  /// each time it is built, which enables other widgets to use the
  /// [MediaQuery.of] static method and (implicitly) the
  /// [InheritedWidget] mechanism to be notified whenever the screen
  /// size changes (e.g. whenever the screen rotates).
347 348 349 350 351
  ///
  /// See also:
  ///
  ///  * [removeObserver], to release the resources reserved by this method.
  ///  * [WidgetsBindingObserver], which has an example of using this method.
352 353 354 355 356
  void addObserver(WidgetsBindingObserver observer) => _observers.add(observer);

  /// Unregisters the given observer. This should be used sparingly as
  /// it is relatively expensive (O(N) in the number of registered
  /// observers).
357 358 359 360 361
  ///
  /// See also:
  ///
  ///  * [addObserver], for the method that adds observers in the first place.
  ///  * [WidgetsBindingObserver], which has an example of using this method.
362 363
  bool removeObserver(WidgetsBindingObserver observer) => _observers.remove(observer);

364
  @override
Ian Hickson's avatar
Ian Hickson committed
365 366
  void handleMetricsChanged() {
    super.handleMetricsChanged();
367
    for (WidgetsBindingObserver observer in _observers)
368
      observer.didChangeMetrics();
Ian Hickson's avatar
Ian Hickson committed
369 370
  }

371 372 373 374 375 376 377
  @override
  void handleTextScaleFactorChanged() {
    super.handleTextScaleFactorChanged();
    for (WidgetsBindingObserver observer in _observers)
      observer.didChangeTextScaleFactor();
  }

378 379 380 381 382 383 384
  @override
  void handleAccessibilityFeaturesChanged() {
    super.handleAccessibilityFeaturesChanged();
    for (WidgetsBindingObserver observer in _observers)
      observer.didChangeAccessibilityFeatures();
  }

385
  /// Called when the system locale changes.
386 387 388
  ///
  /// Calls [dispatchLocaleChanged] to notify the binding observers.
  ///
389
  /// See [Window.onLocaleChanged].
390 391
  @protected
  @mustCallSuper
Ian Hickson's avatar
Ian Hickson committed
392 393 394 395
  void handleLocaleChanged() {
    dispatchLocaleChanged(ui.window.locale);
  }

396 397 398
  /// Notify all the observers that the locale has changed (using
  /// [WidgetsBindingObserver.didChangeLocale]), giving them the
  /// `locale` argument.
399 400 401
  ///
  /// This is called by [handleLocaleChanged] when the [Window.onLocaleChanged]
  /// notification is received.
402 403
  @protected
  @mustCallSuper
404
  void dispatchLocaleChanged(Locale locale) {
405
    for (WidgetsBindingObserver observer in _observers)
Ian Hickson's avatar
Ian Hickson committed
406 407 408
      observer.didChangeLocale(locale);
  }

409 410 411 412 413
  /// Notify all the observers that the active set of [AccessibilityFeatures]
  /// has changed (using [WidgetsBindingObserver.didChangeAccessibilityFeatures]),
  /// giving them the `features` argument.
  ///
  /// This is called by [handleAccessibilityFeaturesChanged] when the
414
  /// [Window.onAccessibilityFeaturesChanged] notification is received.
415 416 417 418 419 420 421
  @protected
  @mustCallSuper
  void dispatchAccessibilityFeaturesChanged() {
    for (WidgetsBindingObserver observer in _observers)
      observer.didChangeAccessibilityFeatures();
  }

422
  /// Called when the system pops the current route.
423 424
  ///
  /// This first notifies the binding observers (using
425 426 427 428
  /// [WidgetsBindingObserver.didPopRoute]), in registration order, until one
  /// returns true, meaning that it was able to handle the request (e.g. by
  /// closing a dialog box). If none return true, then the application is shut
  /// down by calling [SystemNavigator.pop].
429 430 431 432
  ///
  /// [WidgetsApp] uses this in conjunction with a [Navigator] to
  /// cause the back button to close dialog boxes, return from modal
  /// pages, and so forth.
433 434 435
  ///
  /// This method exposes the `popRoute` notification from
  /// [SystemChannels.navigation].
436
  @protected
437
  Future<Null> handlePopRoute() async {
438
    for (WidgetsBindingObserver observer in new List<WidgetsBindingObserver>.from(_observers)) {
439
      if (await observer.didPopRoute())
440
        return;
Ian Hickson's avatar
Ian Hickson committed
441
    }
442
    SystemNavigator.pop();
Ian Hickson's avatar
Ian Hickson committed
443
  }
Hixie's avatar
Hixie committed
444

445 446
  /// Called when the host tells the app to push a new route onto the
  /// navigator.
447 448 449 450 451 452 453 454
  ///
  /// This notifies the binding observers (using
  /// [WidgetsBindingObserver.didPushRoute]), in registration order, until one
  /// returns true, meaning that it was able to handle the request (e.g. by
  /// opening a dialog box). If none return true, then nothing happens.
  ///
  /// This method exposes the `pushRoute` notification from
  /// [SystemChannels.navigation].
455 456
  @protected
  @mustCallSuper
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
  Future<Null> handlePushRoute(String route) async {
    for (WidgetsBindingObserver observer in new List<WidgetsBindingObserver>.from(_observers)) {
      if (await observer.didPushRoute(route))
        return;
    }
  }

  Future<dynamic> _handleNavigationInvocation(MethodCall methodCall) {
    switch (methodCall.method) {
      case 'popRoute':
        return handlePopRoute();
      case 'pushRoute':
        return handlePushRoute(methodCall.arguments);
    }
    return new Future<Null>.value();
472 473
  }

474
  @override
475
  void handleAppLifecycleStateChanged(AppLifecycleState state) {
476
    super.handleAppLifecycleStateChanged(state);
477
    for (WidgetsBindingObserver observer in _observers)
478 479 480
      observer.didChangeAppLifecycleState(state);
  }

481 482 483 484 485 486 487 488 489 490 491 492 493
  /// Called when the operating system notifies the application of a memory
  /// pressure situation.
  ///
  /// Notifies all the observers using
  /// [WidgetsBindingObserver.didHaveMemoryPressure].
  ///
  /// This method exposes the `memoryPressure` notification from
  /// [SystemChannels.system].
  void handleMemoryPressure() {
    for (WidgetsBindingObserver observer in _observers)
      observer.didHaveMemoryPressure();
  }

494 495
  Future<Null> _handleSystemMessage(Object systemMessage) async {
    final Map<String, dynamic> message = systemMessage;
496
    final String type = message['type'];
497 498 499 500
    switch (type) {
      case 'memoryPressure':
        handleMemoryPressure();
        break;
501 502 503 504
    }
    return null;
  }

505
  bool _needToReportFirstFrame = true;
506 507
  int _deferFirstFrameReportCount = 0;
  bool get _reportFirstFrame => _deferFirstFrameReportCount == 0;
508

509 510 511 512 513 514 515 516 517
  /// Whether the first frame has finished rendering.
  ///
  /// Only valid in profile and debug builds, it can't be used in release
  /// builds.
  /// It can be deferred using [deferFirstFrameReport] and
  /// [allowFirstFrameReport].
  /// The value is set at the end of the call to [drawFrame].
  bool get debugDidSendFirstFrameEvent => !_needToReportFirstFrame;

518 519
  /// Tell the framework not to report the frame it is building as a "useful"
  /// first frame until there is a corresponding call to [allowFirstFrameReport].
520 521
  ///
  /// This is used by [WidgetsApp] to report the first frame.
522 523
  //
  // TODO(ianh): This method should only be available in debug and profile modes.
524 525 526
  void deferFirstFrameReport() {
    assert(_deferFirstFrameReportCount >= 0);
    _deferFirstFrameReportCount += 1;
527 528
  }

529 530 531 532 533 534 535 536 537 538 539 540 541 542
  /// When called after [deferFirstFrameReport]: tell the framework to report
  /// the frame it is building as a "useful" first frame.
  ///
  /// This method may only be called once for each corresponding call
  /// to [deferFirstFrameReport].
  ///
  /// This is used by [WidgetsApp] to report the first frame.
  //
  // TODO(ianh): This method should only be available in debug and profile modes.
  void allowFirstFrameReport() {
    assert(_deferFirstFrameReportCount >= 1);
    _deferFirstFrameReportCount -= 1;
  }

543
  void _handleBuildScheduled() {
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    // If we're in the process of building dirty elements, then changes
    // should not trigger a new frame.
    assert(() {
      if (debugBuildingDirtyElements) {
        throw new FlutterError(
          'Build scheduled during frame.\n'
          'While the widget tree was being built, laid out, and painted, '
          'a new frame was scheduled to rebuild the widget tree. '
          'This might be because setState() was called from a layout or '
          'paint callback. '
          'If a change is needed to the widget tree, it should be applied '
          'as the tree is being built. Scheduling a change for the subsequent '
          'frame instead results in an interface that lags behind by one frame. '
          'If this was done to make your build dependent on a size measured at '
          'layout time, consider using a LayoutBuilder, CustomSingleChildLayout, '
          'or CustomMultiChildLayout. If, on the other hand, the one frame delay '
          'is the desired effect, for example because this is an '
          'animation, consider scheduling the frame in a post-frame callback '
          'using SchedulerBinding.addPostFrameCallback or '
          'using an AnimationController to trigger the animation.'
        );
      }
      return true;
567
    }());
568
    ensureVisualUpdate();
569 570
  }

571 572 573 574 575 576 577 578
  /// Whether we are currently in a frame. This is used to verify
  /// that frames are not scheduled redundantly.
  ///
  /// This is public so that test frameworks can change it.
  ///
  /// This flag is not used in release builds.
  @protected
  bool debugBuildingDirtyElements = false;
579

580 581
  /// Pump the build and rendering pipeline to generate a frame.
  ///
582
  /// This method is called by [handleDrawFrame], which itself is called
583 584 585 586 587 588
  /// automatically by the engine when when it is time to lay out and paint a
  /// frame.
  ///
  /// Each frame consists of the following phases:
  ///
  /// 1. The animation phase: The [handleBeginFrame] method, which is registered
Ian Hickson's avatar
Ian Hickson committed
589
  /// with [Window.onBeginFrame], invokes all the transient frame callbacks
590
  /// registered with [scheduleFrameCallback], in
591 592 593 594
  /// registration order. This includes all the [Ticker] instances that are
  /// driving [AnimationController] objects, which means all of the active
  /// [Animation] objects tick at this point.
  ///
595 596 597 598
  /// 2. Microtasks: After [handleBeginFrame] returns, any microtasks that got
  /// scheduled by transient frame callbacks get to run. This typically includes
  /// callbacks for futures from [Ticker]s and [AnimationController]s that
  /// completed this frame.
599
  ///
600
  /// After [handleBeginFrame], [handleDrawFrame], which is registered with
Ian Hickson's avatar
Ian Hickson committed
601
  /// [Window.onDrawFrame], is called, which invokes all the persistent frame
602 603 604 605
  /// callbacks, of which the most notable is this method, [drawFrame], which
  /// proceeds as follows:
  ///
  /// 3. The build phase: All the dirty [Element]s in the widget tree are
606 607 608 609
  /// rebuilt (see [State.build]). See [State.setState] for further details on
  /// marking a widget dirty for building. See [BuildOwner] for more information
  /// on this step.
  ///
610
  /// 4. The layout phase: All the dirty [RenderObject]s in the system are laid
611 612 613
  /// out (see [RenderObject.performLayout]). See [RenderObject.markNeedsLayout]
  /// for further details on marking an object dirty for layout.
  ///
614
  /// 5. The compositing bits phase: The compositing bits on any dirty
615 616 617
  /// [RenderObject] objects are updated. See
  /// [RenderObject.markNeedsCompositingBitsUpdate].
  ///
618
  /// 6. The paint phase: All the dirty [RenderObject]s in the system are
619 620 621 622
  /// repainted (see [RenderObject.paint]). This generates the [Layer] tree. See
  /// [RenderObject.markNeedsPaint] for further details on marking an object
  /// dirty for paint.
  ///
623
  /// 7. The compositing phase: The layer tree is turned into a [Scene] and
624 625
  /// sent to the GPU.
  ///
626
  /// 8. The semantics phase: All the dirty [RenderObject]s in the system have
Ian Hickson's avatar
Ian Hickson committed
627
  /// their semantics updated (see [RenderObject.semanticsAnnotator]). This
628 629 630 631
  /// generates the [SemanticsNode] tree. See
  /// [RenderObject.markNeedsSemanticsUpdate] for further details on marking an
  /// object dirty for semantics.
  ///
632
  /// For more details on steps 4-8, see [PipelineOwner].
633
  ///
634
  /// 9. The finalization phase in the widgets layer: The widgets tree is
635 636 637 638
  /// finalized. This causes [State.dispose] to be invoked on any objects that
  /// were removed from the widgets tree this frame. See
  /// [BuildOwner.finalizeTree] for more details.
  ///
639 640 641
  /// 10. The finalization phase in the scheduler layer: After [drawFrame]
  /// returns, [handleDrawFrame] then invokes post-frame callbacks (registered
  /// with [addPostFrameCallback]).
642 643
  //
  // When editing the above, also update rendering/binding.dart's copy.
644
  @override
645
  void drawFrame() {
646 647 648 649
    assert(!debugBuildingDirtyElements);
    assert(() {
      debugBuildingDirtyElements = true;
      return true;
650
    }());
651
    try {
652 653
      if (renderViewElement != null)
        buildOwner.buildScope(renderViewElement);
654
      super.drawFrame();
655 656 657 658 659
      buildOwner.finalizeTree();
    } finally {
      assert(() {
        debugBuildingDirtyElements = false;
        return true;
660
      }());
661
    }
662
    // TODO(ianh): Following code should not be included in release mode, only profile and debug modes.
663
    // See https://github.com/dart-lang/sdk/issues/27192
664 665 666 667
    if (_needToReportFirstFrame && _reportFirstFrame) {
      developer.Timeline.instantSync('Widgets completed first useful frame');
      developer.postEvent('Flutter.FirstFrame', <String, dynamic>{});
      _needToReportFirstFrame = false;
668
    }
669
  }
670 671 672

  /// The [Element] that is at the root of the hierarchy (and which wraps the
  /// [RenderView] object at the root of the rendering hierarchy).
673 674
  ///
  /// This is initialized the first time [runApp] is called.
675 676
  Element get renderViewElement => _renderViewElement;
  Element _renderViewElement;
677 678 679 680 681 682 683 684

  /// Takes a widget and attaches it to the [renderViewElement], creating it if
  /// necessary.
  ///
  /// This is called by [runApp] to configure the widget tree.
  ///
  /// See also [RenderObjectToWidgetAdapter.attachToRenderTree].
  void attachRootWidget(Widget rootWidget) {
685 686
    _renderViewElement = new RenderObjectToWidgetAdapter<RenderBox>(
      container: renderView,
687
      debugShortDescription: '[root]',
688
      child: rootWidget
689
    ).attachToRenderTree(buildOwner, renderViewElement);
690
  }
691 692

  @override
693
  Future<Null> performReassemble() {
694
    deferFirstFrameReport();
695 696
    if (renderViewElement != null)
      buildOwner.reassemble(renderViewElement);
697 698 699 700 701 702
    // TODO(hansmuller): eliminate the value variable after analyzer bug
    // https://github.com/flutter/flutter/issues/11646 is fixed.
    final Future<Null> value = super.performReassemble();
    return value.then((Null _) {
      allowFirstFrameReport();
    });
703
  }
704
}
Hixie's avatar
Hixie committed
705

706
/// Inflate the given widget and attach it to the screen.
707
///
708 709 710 711 712
/// The widget is given constraints during layout that force it to fill the
/// entire screen. If you wish to align your widget to one side of the screen
/// (e.g., the top), consider using the [Align] widget. If you wish to center
/// your widget, you can also use the [Center] widget
///
713 714 715 716 717 718
/// Calling [runApp] again will detach the previous root widget from the screen
/// and attach the given widget in its place. The new widget tree is compared
/// against the previous widget tree and any differences are applied to the
/// underlying render tree, similar to what happens when a [StatefulWidget]
/// rebuilds after calling [State.setState].
///
719
/// Initializes the binding using [WidgetsFlutterBinding] if necessary.
720 721 722 723 724 725 726 727 728
///
/// See also:
///
/// * [WidgetsBinding.attachRootWidget], which creates the root widget for the
///   widget hierarchy.
/// * [RenderObjectToWidgetAdapter.attachToRenderTree], which creates the root
///   element for the element hierarchy.
/// * [WidgetsBinding.handleBeginFrame], which pumps the widget pipeline to
///   ensure the widget, element, and render trees are all built.
Hixie's avatar
Hixie committed
729
void runApp(Widget app) {
730 731
  WidgetsFlutterBinding.ensureInitialized()
    ..attachRootWidget(app)
732
    ..scheduleWarmUpFrame();
Hixie's avatar
Hixie committed
733 734
}

735
/// Print a string representation of the currently running app.
736
void debugDumpApp() {
737
  assert(WidgetsBinding.instance != null);
Hixie's avatar
Hixie committed
738
  String mode = 'RELEASE MODE';
739
  assert(() { mode = 'CHECKED MODE'; return true; }());
740
  debugPrint('${WidgetsBinding.instance.runtimeType} - $mode');
741 742 743 744 745
  if (WidgetsBinding.instance.renderViewElement != null) {
    debugPrint(WidgetsBinding.instance.renderViewElement.toStringDeep());
  } else {
    debugPrint('<no tree currently mounted>');
  }
746 747
}

748 749 750 751 752 753 754 755
/// A bridge from a [RenderObject] to an [Element] tree.
///
/// The given container is the [RenderObject] that the [Element] tree should be
/// inserted into. It must be a [RenderObject] that implements the
/// [RenderObjectWithChildMixin] protocol. The type argument `T` is the kind of
/// [RenderObject] that the container expects as its child.
///
/// Used by [runApp] to bootstrap applications.
Hixie's avatar
Hixie committed
756
class RenderObjectToWidgetAdapter<T extends RenderObject> extends RenderObjectWidget {
757 758 759
  /// Creates a bridge from a [RenderObject] to an [Element] tree.
  ///
  /// Used by [WidgetsBinding] to attach the root widget to the [RenderView].
760 761
  RenderObjectToWidgetAdapter({
    this.child,
762
    this.container,
763
    this.debugShortDescription
764
  }) : super(key: new GlobalObjectKey(container));
Hixie's avatar
Hixie committed
765

766
  /// The widget below this widget in the tree.
767 768
  ///
  /// {@macro flutter.widgets.child}
Hixie's avatar
Hixie committed
769
  final Widget child;
770

771
  /// The [RenderObject] that is the parent of the [Element] created by this widget.
Hixie's avatar
Hixie committed
772
  final RenderObjectWithChildMixin<T> container;
773

774
  /// A short description of this widget used by debugging aids.
775
  final String debugShortDescription;
Hixie's avatar
Hixie committed
776

777
  @override
Hixie's avatar
Hixie committed
778 779
  RenderObjectToWidgetElement<T> createElement() => new RenderObjectToWidgetElement<T>(this);

780
  @override
781
  RenderObjectWithChildMixin<T> createRenderObject(BuildContext context) => container;
Hixie's avatar
Hixie committed
782

783
  @override
784
  void updateRenderObject(BuildContext context, RenderObject renderObject) { }
785

786 787
  /// Inflate this widget and actually set the resulting [RenderObject] as the
  /// child of [container].
788 789
  ///
  /// If `element` is null, this function will create a new element. Otherwise,
790
  /// the given element will have an update scheduled to switch to this widget.
791 792
  ///
  /// Used by [runApp] to bootstrap applications.
793
  RenderObjectToWidgetElement<T> attachToRenderTree(BuildOwner owner, [RenderObjectToWidgetElement<T> element]) {
794 795
    if (element == null) {
      owner.lockState(() {
796
        element = createElement();
797
        assert(element != null);
798
        element.assignOwner(owner);
799 800
      });
      owner.buildScope(element, () {
801
        element.mount(null, null);
802 803
      });
    } else {
804 805
      element._newWidget = this;
      element.markNeedsBuild();
806
    }
807 808
    return element;
  }
809

810
  @override
811
  String toStringShort() => debugShortDescription ?? super.toStringShort();
Hixie's avatar
Hixie committed
812 813
}

814 815 816 817 818
/// A [RootRenderObjectElement] that is hosted by a [RenderObject].
///
/// This element class is the instantiation of a [RenderObjectToWidgetAdapter]
/// widget. It can be used only as the root of an [Element] tree (it cannot be
/// mounted into another [Element]; it's parent must be null).
Hixie's avatar
Hixie committed
819
///
820 821
/// In typical usage, it will be instantiated for a [RenderObjectToWidgetAdapter]
/// whose container is the [RenderView] that connects to the Flutter engine. In
Hixie's avatar
Hixie committed
822
/// this usage, it is normally instantiated by the bootstrapping logic in the
823
/// [WidgetsFlutterBinding] singleton created by [runApp].
824
class RenderObjectToWidgetElement<T extends RenderObject> extends RootRenderObjectElement {
825 826 827 828 829
  /// Creates an element that is hosted by a [RenderObject].
  ///
  /// The [RenderObject] created by this element is not automatically set as a
  /// child of the hosting [RenderObject]. To actually attach this element to
  /// the render tree, call [RenderObjectToWidgetAdapter.attachToRenderTree].
Hixie's avatar
Hixie committed
830 831
  RenderObjectToWidgetElement(RenderObjectToWidgetAdapter<T> widget) : super(widget);

832
  @override
833 834
  RenderObjectToWidgetAdapter<T> get widget => super.widget;

Hixie's avatar
Hixie committed
835 836
  Element _child;

837
  static const Object _rootChildSlot = Object();
Hixie's avatar
Hixie committed
838

839
  @override
Hixie's avatar
Hixie committed
840 841 842 843 844
  void visitChildren(ElementVisitor visitor) {
    if (_child != null)
      visitor(_child);
  }

845
  @override
846
  void forgetChild(Element child) {
847 848 849 850
    assert(child == _child);
    _child = null;
  }

851
  @override
Hixie's avatar
Hixie committed
852
  void mount(Element parent, dynamic newSlot) {
Hixie's avatar
Hixie committed
853
    assert(parent == null);
Hixie's avatar
Hixie committed
854
    super.mount(parent, newSlot);
855
    _rebuild();
Hixie's avatar
Hixie committed
856 857
  }

858
  @override
Hixie's avatar
Hixie committed
859 860 861
  void update(RenderObjectToWidgetAdapter<T> newWidget) {
    super.update(newWidget);
    assert(widget == newWidget);
862 863 864
    _rebuild();
  }

865 866 867 868 869 870
  // When we are assigned a new widget, we store it here
  // until we are ready to update to it.
  Widget _newWidget;

  @override
  void performRebuild() {
Ian Hickson's avatar
Ian Hickson committed
871 872 873 874 875 876 877
    if (_newWidget != null) {
      // _newWidget can be null if, for instance, we were rebuilt
      // due to a reassemble.
      final Widget newWidget = _newWidget;
      _newWidget = null;
      update(newWidget);
    }
878 879 880 881
    super.performRebuild();
    assert(_newWidget == null);
  }

882 883 884 885 886
  void _rebuild() {
    try {
      _child = updateChild(_child, widget.child, _rootChildSlot);
      assert(_child != null);
    } catch (exception, stack) {
887
      final FlutterErrorDetails details = new FlutterErrorDetails(
888 889 890 891
        exception: exception,
        stack: stack,
        library: 'widgets library',
        context: 'attaching to the render tree'
892 893 894
      );
      FlutterError.reportError(details);
      final Widget error = ErrorWidget.builder(details);
895 896
      _child = updateChild(null, error, _rootChildSlot);
    }
Hixie's avatar
Hixie committed
897 898
  }

899
  @override
Hixie's avatar
Hixie committed
900 901
  RenderObjectWithChildMixin<T> get renderObject => super.renderObject;

902
  @override
Hixie's avatar
Hixie committed
903
  void insertChildRenderObject(RenderObject child, dynamic slot) {
Ian Hickson's avatar
Ian Hickson committed
904
    assert(slot == _rootChildSlot);
905
    assert(renderObject.debugValidateChild(child));
Hixie's avatar
Hixie committed
906 907 908
    renderObject.child = child;
  }

909
  @override
Adam Barth's avatar
Adam Barth committed
910 911 912 913
  void moveChildRenderObject(RenderObject child, dynamic slot) {
    assert(false);
  }

914
  @override
Hixie's avatar
Hixie committed
915 916 917 918
  void removeChildRenderObject(RenderObject child) {
    assert(renderObject.child == child);
    renderObject.child = null;
  }
Adam Barth's avatar
Adam Barth committed
919
}
920 921 922

/// A concrete binding for applications based on the Widgets framework.
/// This is the glue that binds the framework to the Flutter engine.
923
class WidgetsFlutterBinding extends BindingBase with GestureBinding, ServicesBinding, SchedulerBinding, PaintingBinding, RendererBinding, WidgetsBinding {
924 925 926 927 928

  /// Returns an instance of the [WidgetsBinding], creating and
  /// initializing it if necessary. If one is created, it will be a
  /// [WidgetsFlutterBinding]. If one was previously initialized, then
  /// it will at least implement [WidgetsBinding].
929 930 931
  ///
  /// You only need to call this method if you need the binding to be
  /// initialized before calling [runApp].
932 933 934 935 936
  ///
  /// In the `flutter_test` framework, [testWidgets] initializes the
  /// binding instance to a [TestWidgetsFlutterBinding], not a
  /// [WidgetsFlutterBinding].
  static WidgetsBinding ensureInitialized() {
937 938 939
    if (WidgetsBinding.instance == null)
      new WidgetsFlutterBinding();
    return WidgetsBinding.instance;
940 941
  }
}