binding.dart 32.2 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;
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

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

22 23
/// Interface for classes that register with the Widgets layer binding.
///
24
/// See [WidgetsBinding.addObserver] and [WidgetsBinding.removeObserver].
25 26 27 28 29
///
/// 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).
30 31 32 33 34 35 36 37
///
/// ## Sample code
///
/// This [StatefulWidget] implements the parts of the [State] and
/// [WidgetsBindingObserver] protocols necessary to react to application
/// lifecycle messages. See [didChangeAppLifecycleState].
///
/// ```dart
38 39
/// class AppLifecycleReactor extends StatefulWidget {
///   const AppLifecycleReactor({ Key key }) : super(key: key);
40 41
///
///   @override
42
///   _AppLifecycleReactorState createState() => new _AppLifecycleReactorState();
43 44
/// }
///
45
/// class _AppLifecycleReactorState extends State<AppLifecycleReactor> with WidgetsBindingObserver {
46 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
///   @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.
74 75 76 77 78 79 80 81 82 83 84 85 86
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.
87 88 89
  ///
  /// This method exposes the `popRoute` notification from
  /// [SystemChannels.navigation].
90
  Future<bool> didPopRoute() => new Future<bool>.value(false);
91

92 93 94 95
  /// 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
96
  /// handle the notification. Observers are notified in registration
97
  /// order until one returns true.
98 99 100
  ///
  /// This method exposes the `pushRoute` notification from
  /// [SystemChannels.navigation].
101 102
  Future<bool> didPushRoute(String route) => new Future<bool>.value(false);

103 104
  /// Called when the application's dimensions change. For example,
  /// when a phone is rotated.
105
  ///
106 107
  /// This method exposes notifications from [Window.onMetricsChanged].
  ///
108 109 110 111 112 113 114
  /// ## 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
115 116
  /// class MetricsReactor extends StatefulWidget {
  ///   const MetricsReactor({ Key key }) : super(key: key);
117 118
  ///
  ///   @override
119
  ///   _MetricsReactorState createState() => new _MetricsReactorState();
120 121
  /// }
  ///
122
  /// class _MetricsReactorState extends State<MetricsReactor> with WidgetsBindingObserver {
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
  ///   @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) {
144
  ///     return new Text('Current size: $_lastSize');
145 146 147 148 149 150 151 152 153 154 155 156
  ///   }
  /// }
  /// ```
  ///
  /// 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.
157
  void didChangeMetrics() { }
158

159 160 161 162 163 164
  /// 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.
  ///
165 166
  /// This method exposes notifications from [Window.onTextScaleFactorChanged].
  ///
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
  /// ## 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() { }

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

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

  /// Called when the system is running low on memory.
227 228 229
  ///
  /// This method exposes the `memoryPressure` notification from
  /// [SystemChannels.system].
230
  void didHaveMemoryPressure() { }
Ian Hickson's avatar
Ian Hickson committed
231
}
232

233
/// The glue between the widgets layer and the Flutter engine.
234
abstract class WidgetsBinding extends BindingBase with SchedulerBinding, GestureBinding, RendererBinding {
235 236 237 238
  // This class is intended to be used as a mixin, and should not be
  // extended directly.
  factory WidgetsBinding._() => null;

239
  @override
240
  void initInstances() {
Ian Hickson's avatar
Ian Hickson committed
241 242
    super.initInstances();
    _instance = this;
243
    buildOwner.onBuildScheduled = _handleBuildScheduled;
Ian Hickson's avatar
Ian Hickson committed
244
    ui.window.onLocaleChanged = handleLocaleChanged;
245 246
    SystemChannels.navigation.setMethodCallHandler(_handleNavigationInvocation);
    SystemChannels.system.setMessageHandler(_handleSystemMessage);
247 248
  }

249
  /// The current [WidgetsBinding], if one has been created.
250 251 252
  ///
  /// If you need the binding to be constructed before calling [runApp],
  /// you can ensure a Widget binding has been constructed by calling the
253 254 255
  /// `WidgetsFlutterBinding.ensureInitialized()` function.
  static WidgetsBinding get instance => _instance;
  static WidgetsBinding _instance;
256

257 258 259 260
  @override
  void initServiceExtensions() {
    super.initServiceExtensions();

261 262
    registerSignalServiceExtension(
      name: 'debugDumpApp',
263
      callback: () { debugDumpApp(); return debugPrintDone; }
264 265
    );

266 267
    registerBoolServiceExtension(
      name: 'showPerformanceOverlay',
268
      getter: () => new Future<bool>.value(WidgetsApp.showPerformanceOverlayOverride),
269 270
      setter: (bool value) {
        if (WidgetsApp.showPerformanceOverlayOverride == value)
271
          return new Future<Null>.value();
272
        WidgetsApp.showPerformanceOverlayOverride = value;
273
        return _forceRebuild();
274 275
      }
    );
276 277 278

    registerBoolServiceExtension(
      name: 'debugAllowBanner',
279
      getter: () => new Future<bool>.value(WidgetsApp.debugAllowBannerOverride),
280 281
      setter: (bool value) {
        if (WidgetsApp.debugAllowBannerOverride == value)
282
          return new Future<Null>.value();
283
        WidgetsApp.debugAllowBannerOverride = value;
284
        return _forceRebuild();
285 286
      }
    );
287 288 289 290 291 292 293 294 295 296 297

    registerBoolServiceExtension(
        name: 'debugWidgetInspector',
        getter: () async => WidgetsApp.debugShowWidgetInspectorOverride,
        setter: (bool value) {
          if (WidgetsApp.debugShowWidgetInspectorOverride == value)
            return new Future<Null>.value();
          WidgetsApp.debugShowWidgetInspectorOverride = value;
          return _forceRebuild();
        }
    );
298 299
  }

300 301 302 303 304 305 306 307
  Future<Null> _forceRebuild() {
    if (renderViewElement != null) {
      buildOwner.reassemble(renderViewElement);
      return endOfFrame;
    }
    return new Future<Null>.value();
  }

308 309 310 311
  /// 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
312

313
  /// The object in charge of the focus tree.
314
  ///
315 316
  /// Rarely used directly. Instead, consider using [FocusScope.of] to obtain
  /// the [FocusScopeNode] for a given [BuildContext].
317
  ///
318
  /// See [FocusManager] for more details.
319
  FocusManager get focusManager => _buildOwner.focusManager;
320

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

323 324 325 326 327 328 329 330 331 332 333 334
  /// 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).
335 336 337 338 339
  ///
  /// See also:
  ///
  ///  * [removeObserver], to release the resources reserved by this method.
  ///  * [WidgetsBindingObserver], which has an example of using this method.
340 341 342 343 344
  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).
345 346 347 348 349
  ///
  /// See also:
  ///
  ///  * [addObserver], for the method that adds observers in the first place.
  ///  * [WidgetsBindingObserver], which has an example of using this method.
350 351
  bool removeObserver(WidgetsBindingObserver observer) => _observers.remove(observer);

352
  @override
Ian Hickson's avatar
Ian Hickson committed
353 354
  void handleMetricsChanged() {
    super.handleMetricsChanged();
355
    for (WidgetsBindingObserver observer in _observers)
356
      observer.didChangeMetrics();
Ian Hickson's avatar
Ian Hickson committed
357 358
  }

359 360 361 362 363 364 365
  @override
  void handleTextScaleFactorChanged() {
    super.handleTextScaleFactorChanged();
    for (WidgetsBindingObserver observer in _observers)
      observer.didChangeTextScaleFactor();
  }

366
  /// Called when the system locale changes.
367 368 369
  ///
  /// Calls [dispatchLocaleChanged] to notify the binding observers.
  ///
370
  /// See [Window.onLocaleChanged].
371 372
  @protected
  @mustCallSuper
Ian Hickson's avatar
Ian Hickson committed
373 374 375 376
  void handleLocaleChanged() {
    dispatchLocaleChanged(ui.window.locale);
  }

377 378 379
  /// Notify all the observers that the locale has changed (using
  /// [WidgetsBindingObserver.didChangeLocale]), giving them the
  /// `locale` argument.
380 381 382
  ///
  /// This is called by [handleLocaleChanged] when the [Window.onLocaleChanged]
  /// notification is received.
383 384
  @protected
  @mustCallSuper
385
  void dispatchLocaleChanged(Locale locale) {
386
    for (WidgetsBindingObserver observer in _observers)
Ian Hickson's avatar
Ian Hickson committed
387 388 389
      observer.didChangeLocale(locale);
  }

390
  /// Called when the system pops the current route.
391 392
  ///
  /// This first notifies the binding observers (using
393 394 395 396
  /// [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].
397 398 399 400
  ///
  /// [WidgetsApp] uses this in conjunction with a [Navigator] to
  /// cause the back button to close dialog boxes, return from modal
  /// pages, and so forth.
401 402 403
  ///
  /// This method exposes the `popRoute` notification from
  /// [SystemChannels.navigation].
404
  @protected
405
  Future<Null> handlePopRoute() async {
406
    for (WidgetsBindingObserver observer in new List<WidgetsBindingObserver>.from(_observers)) {
407
      if (await observer.didPopRoute())
408
        return;
Ian Hickson's avatar
Ian Hickson committed
409
    }
410
    SystemNavigator.pop();
Ian Hickson's avatar
Ian Hickson committed
411
  }
Hixie's avatar
Hixie committed
412

413 414
  /// Called when the host tells the app to push a new route onto the
  /// navigator.
415 416 417 418 419 420 421 422
  ///
  /// 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].
423 424
  @protected
  @mustCallSuper
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
  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();
440 441
  }

442
  @override
443
  void handleAppLifecycleStateChanged(AppLifecycleState state) {
444
    super.handleAppLifecycleStateChanged(state);
445
    for (WidgetsBindingObserver observer in _observers)
446 447 448
      observer.didChangeAppLifecycleState(state);
  }

449 450 451 452 453 454 455 456 457 458 459 460 461
  /// 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();
  }

462 463
  Future<Null> _handleSystemMessage(Object systemMessage) async {
    final Map<String, dynamic> message = systemMessage;
464
    final String type = message['type'];
465 466 467 468
    switch (type) {
      case 'memoryPressure':
        handleMemoryPressure();
        break;
469 470 471 472
    }
    return null;
  }

473
  bool _needToReportFirstFrame = true;
474 475
  int _deferFirstFrameReportCount = 0;
  bool get _reportFirstFrame => _deferFirstFrameReportCount == 0;
476

477 478 479 480 481 482 483 484 485
  /// 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;

486 487
  /// Tell the framework not to report the frame it is building as a "useful"
  /// first frame until there is a corresponding call to [allowFirstFrameReport].
488 489
  ///
  /// This is used by [WidgetsApp] to report the first frame.
490 491
  //
  // TODO(ianh): This method should only be available in debug and profile modes.
492 493 494
  void deferFirstFrameReport() {
    assert(_deferFirstFrameReportCount >= 0);
    _deferFirstFrameReportCount += 1;
495 496
  }

497 498 499 500 501 502 503 504 505 506 507 508 509 510
  /// 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;
  }

511
  void _handleBuildScheduled() {
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
    // 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;
535
    }());
536
    ensureVisualUpdate();
537 538
  }

539 540 541 542 543 544 545 546
  /// 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;
547

548 549
  /// Pump the build and rendering pipeline to generate a frame.
  ///
550
  /// This method is called by [handleDrawFrame], which itself is called
551 552 553 554 555 556
  /// 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
557
  /// with [Window.onBeginFrame], invokes all the transient frame callbacks
558
  /// registered with [scheduleFrameCallback], in
559 560 561 562
  /// 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.
  ///
563 564 565 566
  /// 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.
567
  ///
568
  /// After [handleBeginFrame], [handleDrawFrame], which is registered with
Ian Hickson's avatar
Ian Hickson committed
569
  /// [Window.onDrawFrame], is called, which invokes all the persistent frame
570 571 572 573
  /// 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
574 575 576 577
  /// 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.
  ///
578
  /// 4. The layout phase: All the dirty [RenderObject]s in the system are laid
579 580 581
  /// out (see [RenderObject.performLayout]). See [RenderObject.markNeedsLayout]
  /// for further details on marking an object dirty for layout.
  ///
582
  /// 5. The compositing bits phase: The compositing bits on any dirty
583 584 585
  /// [RenderObject] objects are updated. See
  /// [RenderObject.markNeedsCompositingBitsUpdate].
  ///
586
  /// 6. The paint phase: All the dirty [RenderObject]s in the system are
587 588 589 590
  /// repainted (see [RenderObject.paint]). This generates the [Layer] tree. See
  /// [RenderObject.markNeedsPaint] for further details on marking an object
  /// dirty for paint.
  ///
591
  /// 7. The compositing phase: The layer tree is turned into a [Scene] and
592 593
  /// sent to the GPU.
  ///
594
  /// 8. The semantics phase: All the dirty [RenderObject]s in the system have
Ian Hickson's avatar
Ian Hickson committed
595
  /// their semantics updated (see [RenderObject.semanticsAnnotator]). This
596 597 598 599
  /// generates the [SemanticsNode] tree. See
  /// [RenderObject.markNeedsSemanticsUpdate] for further details on marking an
  /// object dirty for semantics.
  ///
600
  /// For more details on steps 4-8, see [PipelineOwner].
601
  ///
602
  /// 9. The finalization phase in the widgets layer: The widgets tree is
603 604 605 606
  /// 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.
  ///
607 608 609
  /// 10. The finalization phase in the scheduler layer: After [drawFrame]
  /// returns, [handleDrawFrame] then invokes post-frame callbacks (registered
  /// with [addPostFrameCallback]).
610 611
  //
  // When editing the above, also update rendering/binding.dart's copy.
612
  @override
613
  void drawFrame() {
614 615 616 617
    assert(!debugBuildingDirtyElements);
    assert(() {
      debugBuildingDirtyElements = true;
      return true;
618
    }());
619
    try {
620 621
      if (renderViewElement != null)
        buildOwner.buildScope(renderViewElement);
622
      super.drawFrame();
623 624 625 626 627
      buildOwner.finalizeTree();
    } finally {
      assert(() {
        debugBuildingDirtyElements = false;
        return true;
628
      }());
629
    }
630
    // TODO(ianh): Following code should not be included in release mode, only profile and debug modes.
631
    // See https://github.com/dart-lang/sdk/issues/27192
632 633 634 635
    if (_needToReportFirstFrame && _reportFirstFrame) {
      developer.Timeline.instantSync('Widgets completed first useful frame');
      developer.postEvent('Flutter.FirstFrame', <String, dynamic>{});
      _needToReportFirstFrame = false;
636
    }
637
  }
638 639 640

  /// The [Element] that is at the root of the hierarchy (and which wraps the
  /// [RenderView] object at the root of the rendering hierarchy).
641 642
  ///
  /// This is initialized the first time [runApp] is called.
643 644
  Element get renderViewElement => _renderViewElement;
  Element _renderViewElement;
645 646 647 648 649 650 651 652

  /// 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) {
653 654
    _renderViewElement = new RenderObjectToWidgetAdapter<RenderBox>(
      container: renderView,
655
      debugShortDescription: '[root]',
656
      child: rootWidget
657
    ).attachToRenderTree(buildOwner, renderViewElement);
658
  }
659 660

  @override
661
  Future<Null> performReassemble() {
662
    deferFirstFrameReport();
663 664
    if (renderViewElement != null)
      buildOwner.reassemble(renderViewElement);
665 666 667 668 669 670
    // 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();
    });
671
  }
672
}
Hixie's avatar
Hixie committed
673

674
/// Inflate the given widget and attach it to the screen.
675
///
676 677 678 679 680
/// 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
///
681 682 683 684 685 686
/// 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].
///
687
/// Initializes the binding using [WidgetsFlutterBinding] if necessary.
688 689 690 691 692 693 694 695 696
///
/// 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
697
void runApp(Widget app) {
698 699
  WidgetsFlutterBinding.ensureInitialized()
    ..attachRootWidget(app)
700
    ..scheduleWarmUpFrame();
Hixie's avatar
Hixie committed
701 702
}

703
/// Print a string representation of the currently running app.
704
void debugDumpApp() {
705
  assert(WidgetsBinding.instance != null);
Hixie's avatar
Hixie committed
706
  String mode = 'RELEASE MODE';
707
  assert(() { mode = 'CHECKED MODE'; return true; }());
708
  debugPrint('${WidgetsBinding.instance.runtimeType} - $mode');
709 710 711 712 713
  if (WidgetsBinding.instance.renderViewElement != null) {
    debugPrint(WidgetsBinding.instance.renderViewElement.toStringDeep());
  } else {
    debugPrint('<no tree currently mounted>');
  }
714 715
}

716 717 718 719 720 721 722 723
/// 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
724
class RenderObjectToWidgetAdapter<T extends RenderObject> extends RenderObjectWidget {
725 726 727
  /// Creates a bridge from a [RenderObject] to an [Element] tree.
  ///
  /// Used by [WidgetsBinding] to attach the root widget to the [RenderView].
728 729
  RenderObjectToWidgetAdapter({
    this.child,
730
    this.container,
731
    this.debugShortDescription
732
  }) : super(key: new GlobalObjectKey(container));
Hixie's avatar
Hixie committed
733

734
  /// The widget below this widget in the tree.
735 736
  ///
  /// {@macro flutter.widgets.child}
Hixie's avatar
Hixie committed
737
  final Widget child;
738

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

742
  /// A short description of this widget used by debugging aids.
743
  final String debugShortDescription;
Hixie's avatar
Hixie committed
744

745
  @override
Hixie's avatar
Hixie committed
746 747
  RenderObjectToWidgetElement<T> createElement() => new RenderObjectToWidgetElement<T>(this);

748
  @override
749
  RenderObjectWithChildMixin<T> createRenderObject(BuildContext context) => container;
Hixie's avatar
Hixie committed
750

751
  @override
752
  void updateRenderObject(BuildContext context, RenderObject renderObject) { }
753

754 755
  /// Inflate this widget and actually set the resulting [RenderObject] as the
  /// child of [container].
756 757
  ///
  /// If `element` is null, this function will create a new element. Otherwise,
758
  /// the given element will have an update scheduled to switch to this widget.
759 760
  ///
  /// Used by [runApp] to bootstrap applications.
761
  RenderObjectToWidgetElement<T> attachToRenderTree(BuildOwner owner, [RenderObjectToWidgetElement<T> element]) {
762 763
    if (element == null) {
      owner.lockState(() {
764
        element = createElement();
765
        assert(element != null);
766
        element.assignOwner(owner);
767 768
      });
      owner.buildScope(element, () {
769
        element.mount(null, null);
770 771
      });
    } else {
772 773
      element._newWidget = this;
      element.markNeedsBuild();
774
    }
775 776
    return element;
  }
777

778
  @override
779
  String toStringShort() => debugShortDescription ?? super.toStringShort();
Hixie's avatar
Hixie committed
780 781
}

782 783 784 785 786
/// 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
787
///
788 789
/// 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
790
/// this usage, it is normally instantiated by the bootstrapping logic in the
791
/// [WidgetsFlutterBinding] singleton created by [runApp].
792
class RenderObjectToWidgetElement<T extends RenderObject> extends RootRenderObjectElement {
793 794 795 796 797
  /// 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
798 799
  RenderObjectToWidgetElement(RenderObjectToWidgetAdapter<T> widget) : super(widget);

800
  @override
801 802
  RenderObjectToWidgetAdapter<T> get widget => super.widget;

Hixie's avatar
Hixie committed
803 804
  Element _child;

805
  static const Object _rootChildSlot = const Object();
Hixie's avatar
Hixie committed
806

807
  @override
Hixie's avatar
Hixie committed
808 809 810 811 812
  void visitChildren(ElementVisitor visitor) {
    if (_child != null)
      visitor(_child);
  }

813
  @override
814
  void forgetChild(Element child) {
815 816 817 818
    assert(child == _child);
    _child = null;
  }

819
  @override
Hixie's avatar
Hixie committed
820
  void mount(Element parent, dynamic newSlot) {
Hixie's avatar
Hixie committed
821
    assert(parent == null);
Hixie's avatar
Hixie committed
822
    super.mount(parent, newSlot);
823
    _rebuild();
Hixie's avatar
Hixie committed
824 825
  }

826
  @override
Hixie's avatar
Hixie committed
827 828 829
  void update(RenderObjectToWidgetAdapter<T> newWidget) {
    super.update(newWidget);
    assert(widget == newWidget);
830 831 832
    _rebuild();
  }

833 834 835 836 837 838
  // 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
839 840 841 842 843 844 845
    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);
    }
846 847 848 849
    super.performRebuild();
    assert(_newWidget == null);
  }

850 851 852 853 854
  void _rebuild() {
    try {
      _child = updateChild(_child, widget.child, _rootChildSlot);
      assert(_child != null);
    } catch (exception, stack) {
855
      final FlutterErrorDetails details = new FlutterErrorDetails(
856 857 858 859
        exception: exception,
        stack: stack,
        library: 'widgets library',
        context: 'attaching to the render tree'
860 861 862
      );
      FlutterError.reportError(details);
      final Widget error = ErrorWidget.builder(details);
863 864
      _child = updateChild(null, error, _rootChildSlot);
    }
Hixie's avatar
Hixie committed
865 866
  }

867
  @override
Hixie's avatar
Hixie committed
868 869
  RenderObjectWithChildMixin<T> get renderObject => super.renderObject;

870
  @override
Hixie's avatar
Hixie committed
871
  void insertChildRenderObject(RenderObject child, dynamic slot) {
Ian Hickson's avatar
Ian Hickson committed
872
    assert(slot == _rootChildSlot);
873
    assert(renderObject.debugValidateChild(child));
Hixie's avatar
Hixie committed
874 875 876
    renderObject.child = child;
  }

877
  @override
Adam Barth's avatar
Adam Barth committed
878 879 880 881
  void moveChildRenderObject(RenderObject child, dynamic slot) {
    assert(false);
  }

882
  @override
Hixie's avatar
Hixie committed
883 884 885 886
  void removeChildRenderObject(RenderObject child) {
    assert(renderObject.child == child);
    renderObject.child = null;
  }
Adam Barth's avatar
Adam Barth committed
887
}
888 889 890

/// A concrete binding for applications based on the Widgets framework.
/// This is the glue that binds the framework to the Flutter engine.
891
class WidgetsFlutterBinding extends BindingBase with GestureBinding, ServicesBinding, SchedulerBinding, PaintingBinding, RendererBinding, WidgetsBinding {
892 893 894 895 896

  /// 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].
897 898 899
  ///
  /// You only need to call this method if you need the binding to be
  /// initialized before calling [runApp].
900 901 902 903 904
  ///
  /// In the `flutter_test` framework, [testWidgets] initializes the
  /// binding instance to a [TestWidgetsFlutterBinding], not a
  /// [WidgetsFlutterBinding].
  static WidgetsBinding ensureInitialized() {
905 906 907
    if (WidgetsBinding.instance == null)
      new WidgetsFlutterBinding();
    return WidgetsBinding.instance;
908 909
  }
}