binding.dart 23.1 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:developer';
6

7
import 'package:flutter/foundation.dart';
8
import 'package:flutter/gestures.dart';
9
import 'package:flutter/scheduler.dart';
10
import 'package:flutter/semantics.dart';
Ian Hickson's avatar
Ian Hickson committed
11
import 'package:flutter/services.dart';
12 13

import 'box.dart';
14
import 'debug.dart';
15
import 'mouse_tracker.dart';
16
import 'object.dart';
17
import 'service_extensions.dart';
18
import 'view.dart';
19

Ian Hickson's avatar
Ian Hickson committed
20
export 'package:flutter/gestures.dart' show HitTestResult;
21

22
// Examples can assume:
23
// late BuildContext context;
24

Florian Loitsch's avatar
Florian Loitsch committed
25
/// The glue between the render tree and the Flutter engine.
26
mixin RendererBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureBinding, SemanticsBinding, HitTestable {
27
  @override
Ian Hickson's avatar
Ian Hickson committed
28 29
  void initInstances() {
    super.initInstances();
30
    _instance = this;
31
    _pipelineOwner = PipelineOwner(
32
      onNeedVisualUpdate: ensureVisualUpdate,
33 34
      onSemanticsOwnerCreated: _handleSemanticsOwnerCreated,
      onSemanticsOwnerDisposed: _handleSemanticsOwnerDisposed,
35
    );
36
    platformDispatcher
37
      ..onMetricsChanged = handleMetricsChanged
38
      ..onTextScaleFactorChanged = handleTextScaleFactorChanged
39
      ..onPlatformBrightnessChanged = handlePlatformBrightnessChanged
40 41
      ..onSemanticsEnabledChanged = _handleSemanticsEnabledChanged
      ..onSemanticsAction = _handleSemanticsAction;
Ian Hickson's avatar
Ian Hickson committed
42
    initRenderView();
43
    _handleSemanticsEnabledChanged();
44
    assert(renderView != null);
45
    addPersistentFrameCallback(_handlePersistentFrameCallback);
46
    initMouseTracker();
47 48 49
    if (kIsWeb) {
      addPostFrameCallback(_handleWebFirstFrame);
    }
50 51
  }

52
  /// The current [RendererBinding], if one has been created.
53 54 55 56 57
  ///
  /// Provides access to the features exposed by this mixin. The binding must
  /// be initialized before using this getter; this is typically done by calling
  /// [runApp] or [WidgetsFlutterBinding.ensureInitialized].
  static RendererBinding get instance => BindingBase.checkInstance(_instance);
58
  static RendererBinding? _instance;
59 60 61 62

  @override
  void initServiceExtensions() {
    super.initServiceExtensions();
63

64
    assert(() {
65
      // these service extensions only work in debug mode
66
      registerBoolServiceExtension(
67
        name: RenderingServiceExtensions.invertOversizedImages.name,
68 69 70 71 72 73 74 75 76
        getter: () async => debugInvertOversizedImages,
        setter: (bool value) async {
          if (debugInvertOversizedImages != value) {
            debugInvertOversizedImages = value;
            return _forceRepaint();
          }
          return Future<void>.value();
        },
      );
77
      registerBoolServiceExtension(
78
        name: RenderingServiceExtensions.debugPaint.name,
79
        getter: () async => debugPaintSizeEnabled,
80
        setter: (bool value) {
81
          if (debugPaintSizeEnabled == value) {
82
            return Future<void>.value();
83
          }
84
          debugPaintSizeEnabled = value;
85
          return _forceRepaint();
86
        },
87
      );
88
      registerBoolServiceExtension(
89
        name: RenderingServiceExtensions.debugPaintBaselinesEnabled.name,
90 91
        getter: () async => debugPaintBaselinesEnabled,
        setter: (bool value) {
92
          if (debugPaintBaselinesEnabled == value) {
93
            return Future<void>.value();
94
          }
95 96
          debugPaintBaselinesEnabled = value;
          return _forceRepaint();
97
        },
98 99
      );
      registerBoolServiceExtension(
100
        name: RenderingServiceExtensions.repaintRainbow.name,
101 102 103 104
        getter: () async => debugRepaintRainbowEnabled,
        setter: (bool value) {
          final bool repaint = debugRepaintRainbowEnabled && !value;
          debugRepaintRainbowEnabled = value;
105
          if (repaint) {
106
            return _forceRepaint();
107
          }
108
          return Future<void>.value();
109 110
        },
      );
111
      registerServiceExtension(
112
        name: RenderingServiceExtensions.debugDumpLayerTree.name,
113
        callback: (Map<String, String> parameters) async {
114
          final String data = RendererBinding.instance.renderView.debugLayer?.toStringDeep() ?? 'Layer tree unavailable.';
115 116 117
          return <String, Object>{
            'data': data,
          };
118 119
        },
      );
120
      registerBoolServiceExtension(
121
        name: RenderingServiceExtensions.debugDisableClipLayers.name,
122 123
        getter: () async => debugDisableClipLayers,
        setter: (bool value) {
124
          if (debugDisableClipLayers == value) {
125
            return Future<void>.value();
126
          }
127 128 129 130 131
          debugDisableClipLayers = value;
          return _forceRepaint();
        },
      );
      registerBoolServiceExtension(
132
        name: RenderingServiceExtensions.debugDisablePhysicalShapeLayers.name,
133 134
        getter: () async => debugDisablePhysicalShapeLayers,
        setter: (bool value) {
135
          if (debugDisablePhysicalShapeLayers == value) {
136
            return Future<void>.value();
137
          }
138 139 140 141 142
          debugDisablePhysicalShapeLayers = value;
          return _forceRepaint();
        },
      );
      registerBoolServiceExtension(
143
        name: RenderingServiceExtensions.debugDisableOpacityLayers.name,
144 145
        getter: () async => debugDisableOpacityLayers,
        setter: (bool value) {
146
          if (debugDisableOpacityLayers == value) {
147
            return Future<void>.value();
148
          }
149 150 151 152
          debugDisableOpacityLayers = value;
          return _forceRepaint();
        },
      );
153
      return true;
154
    }());
155

156
    if (!kReleaseMode) {
157
      // these service extensions work in debug or profile mode
158
      registerServiceExtension(
159
        name: RenderingServiceExtensions.debugDumpRenderTree.name,
160
        callback: (Map<String, String> parameters) async {
161
          final String data = RendererBinding.instance.renderView.toStringDeep();
162 163 164
          return <String, Object>{
            'data': data,
          };
165
        },
166
      );
167
      registerServiceExtension(
168
        name: RenderingServiceExtensions.debugDumpSemanticsTreeInTraversalOrder.name,
169 170
        callback: (Map<String, String> parameters) async {
          return <String, Object>{
171
            'data': _generateSemanticsTree(DebugSemanticsDumpOrder.traversalOrder),
172
          };
173 174
        },
      );
175
      registerServiceExtension(
176
        name: RenderingServiceExtensions.debugDumpSemanticsTreeInInverseHitTestOrder.name,
177 178
        callback: (Map<String, String> parameters) async {
          return <String, Object>{
179
            'data': _generateSemanticsTree(DebugSemanticsDumpOrder.inverseHitTest),
180
          };
181 182
        },
      );
183
      registerBoolServiceExtension(
184
        name: RenderingServiceExtensions.profileRenderObjectPaints.name,
185 186
        getter: () async => debugProfilePaintsEnabled,
        setter: (bool value) async {
187
          if (debugProfilePaintsEnabled != value) {
188
            debugProfilePaintsEnabled = value;
189
          }
190 191 192
        },
      );
      registerBoolServiceExtension(
193
        name: RenderingServiceExtensions.profileRenderObjectLayouts.name,
194 195
        getter: () async => debugProfileLayoutsEnabled,
        setter: (bool value) async {
196
          if (debugProfileLayoutsEnabled != value) {
197
            debugProfileLayoutsEnabled = value;
198
          }
199 200
        },
      );
201
    }
202
  }
203

204 205
  /// Creates a [RenderView] object to be the root of the
  /// [RenderObject] rendering tree, and initializes it so that it
206
  /// will be rendered when the next frame is requested.
207 208
  ///
  /// Called automatically when the binding is created.
Ian Hickson's avatar
Ian Hickson committed
209
  void initRenderView() {
210 211 212 213 214
    assert(!_debugIsRenderViewInitialized);
    assert(() {
      _debugIsRenderViewInitialized = true;
      return true;
    }());
215
    renderView = RenderView(configuration: createViewConfiguration(), window: window);
216
    renderView.prepareInitialFrame();
217
  }
218
  bool _debugIsRenderViewInitialized = false;
219

220 221
  /// The object that manages state about currently connected mice, for hover
  /// notification.
222 223
  MouseTracker get mouseTracker => _mouseTracker!;
  MouseTracker? _mouseTracker;
224

225
  /// The render tree's owner, which maintains dirty state for layout,
226
  /// composite, paint, and accessibility semantics.
227
  PipelineOwner get pipelineOwner => _pipelineOwner;
228
  late PipelineOwner _pipelineOwner;
229

Florian Loitsch's avatar
Florian Loitsch committed
230
  /// The render tree that's attached to the output surface.
231
  RenderView get renderView => _pipelineOwner.rootNode! as RenderView;
232 233
  /// Sets the given [RenderView] object (which must not be null), and its tree, to
  /// be the new render tree to display. The previous tree, if any, is detached.
234
  set renderView(RenderView value) {
235
    assert(value != null);
236
    _pipelineOwner.rootNode = value;
237 238
  }

239
  /// Called when the system metrics change.
240
  ///
241
  /// See [dart:ui.PlatformDispatcher.onMetricsChanged].
242
  @protected
243
  @visibleForTesting
Ian Hickson's avatar
Ian Hickson committed
244
  void handleMetricsChanged() {
245
    assert(renderView != null);
246
    renderView.configuration = createViewConfiguration();
247 248 249
    if (renderView.child != null) {
      scheduleForcedFrame();
    }
250 251
  }

252 253
  /// Called when the platform text scale factor changes.
  ///
254
  /// See [dart:ui.PlatformDispatcher.onTextScaleFactorChanged].
255
  @protected
256 257
  void handleTextScaleFactorChanged() { }

258 259
  /// Called when the platform brightness changes.
  ///
260 261 262 263
  /// The current platform brightness can be queried from a Flutter binding or
  /// from a [MediaQuery] widget. The latter is preferred from widgets because
  /// it causes the widget to be automatically rebuilt when the brightness
  /// changes.
264
  ///
265
  /// {@tool snippet}
266
  /// Querying [MediaQuery] directly. Preferred.
267 268
  ///
  /// ```dart
269
  /// final Brightness brightness = MediaQuery.platformBrightnessOf(context);
270
  /// ```
271
  /// {@end-tool}
272
  ///
273
  /// {@tool snippet}
274
  /// Querying [PlatformDispatcher.platformBrightness].
275 276
  ///
  /// ```dart
277
  /// final Brightness brightness = WidgetsBinding.instance.platformDispatcher.platformBrightness;
278
  /// ```
279
  /// {@end-tool}
280
  ///
281
  /// {@tool snippet}
282
  /// Querying [MediaQueryData].
283 284 285 286 287
  ///
  /// ```dart
  /// final MediaQueryData mediaQueryData = MediaQuery.of(context);
  /// final Brightness brightness = mediaQueryData.platformBrightness;
  /// ```
288
  /// {@end-tool}
289
  ///
290
  /// See [dart:ui.PlatformDispatcher.onPlatformBrightnessChanged].
291 292 293
  @protected
  void handlePlatformBrightnessChanged() { }

294 295 296 297 298 299 300 301 302 303 304
  /// Returns a [ViewConfiguration] configured for the [RenderView] based on the
  /// current environment.
  ///
  /// This is called during construction and also in response to changes to the
  /// system metrics.
  ///
  /// Bindings can override this method to change what size or device pixel
  /// ratio the [RenderView] will use. For example, the testing framework uses
  /// this to force the display into 800x600 when a test is run on the device
  /// using `flutter run`.
  ViewConfiguration createViewConfiguration() {
305
    final double devicePixelRatio = window.devicePixelRatio;
306
    return ViewConfiguration(
307
      size: window.physicalSize / devicePixelRatio,
308
      devicePixelRatio: devicePixelRatio,
309
    );
310 311
  }

312
  SemanticsHandle? _semanticsHandle;
313

314 315 316 317 318
  /// Creates a [MouseTracker] which manages state about currently connected
  /// mice, for hover notification.
  ///
  /// Used by testing framework to reinitialize the mouse tracker between tests.
  @visibleForTesting
319
  void initMouseTracker([MouseTracker? tracker]) {
320
    _mouseTracker?.dispose();
321 322 323 324
    _mouseTracker = tracker ?? MouseTracker();
  }

  @override // from GestureBinding
325
  void dispatchEvent(PointerEvent event, HitTestResult? hitTestResult) {
326 327 328 329 330 331 332 333
    _mouseTracker!.updateWithEvent(
      event,
      // Enter and exit events should be triggered with or without buttons
      // pressed. When the button is pressed, normal hit test uses a cached
      // result, but MouseTracker requires that the hit test is re-executed to
      // update the hovering events.
      () => (hitTestResult == null || event is PointerMoveEvent) ? renderView.hitTestMouseTrackers(event.position) : hitTestResult,
    );
334
    super.dispatchEvent(event, hitTestResult);
335 336
  }

337
  void _handleSemanticsEnabledChanged() {
338
    setSemanticsEnabled(platformDispatcher.semanticsEnabled);
339 340
  }

341 342
  /// Whether the render tree associated with this binding should produce a tree
  /// of [SemanticsNode] objects.
343 344
  void setSemanticsEnabled(bool enabled) {
    if (enabled) {
345 346 347 348 349 350 351
      _semanticsHandle ??= _pipelineOwner.ensureSemantics();
    } else {
      _semanticsHandle?.dispose();
      _semanticsHandle = null;
    }
  }

352 353 354 355 356 357
  void _handleWebFirstFrame(Duration _) {
    assert(kIsWeb);
    const MethodChannel methodChannel = MethodChannel('flutter/service_worker');
    methodChannel.invokeMethod<void>('first-frame');
  }

358
  void _handleSemanticsAction(int id, SemanticsAction action, ByteData? args) {
359 360 361 362 363
    _pipelineOwner.semanticsOwner?.performAction(
      id,
      action,
      args != null ? const StandardMessageCodec().decodeMessage(args) : null,
    );
364 365 366 367 368 369 370 371
  }

  void _handleSemanticsOwnerCreated() {
    renderView.scheduleInitialSemantics();
  }

  void _handleSemanticsOwnerDisposed() {
    renderView.clearSemantics();
Hixie's avatar
Hixie committed
372 373
  }

374
  void _handlePersistentFrameCallback(Duration timeStamp) {
375
    drawFrame();
376 377 378 379 380 381 382 383 384 385
    _scheduleMouseTrackerUpdate();
  }

  bool _debugMouseTrackerUpdateScheduled = false;
  void _scheduleMouseTrackerUpdate() {
    assert(!_debugMouseTrackerUpdateScheduled);
    assert(() {
      _debugMouseTrackerUpdateScheduled = true;
      return true;
    }());
386
    SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
387 388 389 390 391
      assert(_debugMouseTrackerUpdateScheduled);
      assert(() {
        _debugMouseTrackerUpdateScheduled = false;
        return true;
      }());
392
      _mouseTracker!.updateAllDevices(renderView.hitTestMouseTrackers);
393
    });
394 395
  }

396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
  int _firstFrameDeferredCount = 0;
  bool _firstFrameSent = false;

  /// Whether frames produced by [drawFrame] are sent to the engine.
  ///
  /// If false the framework will do all the work to produce a frame,
  /// but the frame is never sent to the engine to actually appear on screen.
  ///
  /// See also:
  ///
  ///  * [deferFirstFrame], which defers when the first frame is sent to the
  ///    engine.
  bool get sendFramesToEngine => _firstFrameSent || _firstFrameDeferredCount == 0;

  /// Tell the framework to not send the first frames to the engine until there
  /// is a corresponding call to [allowFirstFrame].
  ///
  /// Call this to perform asynchronous initialization work before the first
  /// frame is rendered (which takes down the splash screen). The framework
  /// will still do all the work to produce frames, but those frames are never
  /// sent to the engine and will not appear on screen.
  ///
  /// Calling this has no effect after the first frame has been sent to the
  /// engine.
  void deferFirstFrame() {
    assert(_firstFrameDeferredCount >= 0);
    _firstFrameDeferredCount += 1;
  }

  /// Called after [deferFirstFrame] to tell the framework that it is ok to
  /// send the first frame to the engine now.
  ///
  /// For best performance, this method should only be called while the
  /// [schedulerPhase] is [SchedulerPhase.idle].
  ///
  /// This method may only be called once for each corresponding call
  /// to [deferFirstFrame].
  void allowFirstFrame() {
    assert(_firstFrameDeferredCount > 0);
    _firstFrameDeferredCount -= 1;
    // Always schedule a warm up frame even if the deferral count is not down to
    // zero yet since the removal of a deferral may uncover new deferrals that
    // are lower in the widget tree.
439
    if (!_firstFrameSent) {
440
      scheduleWarmUpFrame();
441
    }
442 443 444 445 446 447 448 449 450 451 452
  }

  /// Call this to pretend that no frames have been sent to the engine yet.
  ///
  /// This is useful for tests that want to call [deferFirstFrame] and
  /// [allowFirstFrame] since those methods only have an effect if no frames
  /// have been sent to the engine yet.
  void resetFirstFrameSent() {
    _firstFrameSent = false;
  }

Ian Hickson's avatar
Ian Hickson committed
453
  /// Pump the rendering pipeline to generate a frame.
454
  ///
455
  /// This method is called by [handleDrawFrame], which itself is called
456
  /// automatically by the engine when it is time to lay out and paint a frame.
457 458 459 460
  ///
  /// Each frame consists of the following phases:
  ///
  /// 1. The animation phase: The [handleBeginFrame] method, which is registered
461 462 463 464 465
  /// with [PlatformDispatcher.onBeginFrame], invokes all the transient frame
  /// callbacks registered with [scheduleFrameCallback], in 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.
466
  ///
467 468 469 470
  /// 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.
471
  ///
472
  /// After [handleBeginFrame], [handleDrawFrame], which is registered with
473 474 475
  /// [dart:ui.PlatformDispatcher.onDrawFrame], is called, which invokes all the
  /// persistent frame callbacks, of which the most notable is this method,
  /// [drawFrame], which proceeds as follows:
476 477
  ///
  /// 3. The layout phase: All the dirty [RenderObject]s in the system are laid
478 479 480
  /// out (see [RenderObject.performLayout]). See [RenderObject.markNeedsLayout]
  /// for further details on marking an object dirty for layout.
  ///
481
  /// 4. The compositing bits phase: The compositing bits on any dirty
482 483 484
  /// [RenderObject] objects are updated. See
  /// [RenderObject.markNeedsCompositingBitsUpdate].
  ///
485
  /// 5. The paint phase: All the dirty [RenderObject]s in the system are
486 487 488 489
  /// repainted (see [RenderObject.paint]). This generates the [Layer] tree. See
  /// [RenderObject.markNeedsPaint] for further details on marking an object
  /// dirty for paint.
  ///
490
  /// 6. The compositing phase: The layer tree is turned into a [Scene] and
491 492
  /// sent to the GPU.
  ///
493
  /// 7. The semantics phase: All the dirty [RenderObject]s in the system have
494
  /// their semantics updated. This generates the [SemanticsNode] tree. See
495 496 497
  /// [RenderObject.markNeedsSemanticsUpdate] for further details on marking an
  /// object dirty for semantics.
  ///
498
  /// For more details on steps 3-7, see [PipelineOwner].
499
  ///
500 501
  /// 8. The finalization phase: After [drawFrame] returns, [handleDrawFrame]
  /// then invokes post-frame callbacks (registered with [addPostFrameCallback]).
502 503
  ///
  /// Some bindings (for example, the [WidgetsBinding]) add extra steps to this
504
  /// list (for example, see [WidgetsBinding.drawFrame]).
505 506
  //
  // When editing the above, also update widgets/binding.dart's copy.
Ian Hickson's avatar
Ian Hickson committed
507
  @protected
508
  void drawFrame() {
509
    assert(renderView != null);
510 511 512
    pipelineOwner.flushLayout();
    pipelineOwner.flushCompositingBits();
    pipelineOwner.flushPaint();
513 514 515 516 517
    if (sendFramesToEngine) {
      renderView.compositeFrame(); // this sends the bits to the GPU
      pipelineOwner.flushSemantics(); // this also sends the semantics to the OS.
      _firstFrameSent = true;
    }
518 519
  }

520
  @override
521
  Future<void> performReassemble() async {
522
    await super.performReassemble();
523
    if (BindingBase.debugReassembleConfig?.widgetName == null) {
Ian Hickson's avatar
Ian Hickson committed
524
      if (!kReleaseMode) {
525 526 527 528 529 530 531 532
        Timeline.startSync('Preparing Hot Reload (layout)');
      }
      try {
        renderView.reassemble();
      } finally {
        if (!kReleaseMode) {
          Timeline.finishSync();
        }
533
      }
534
    }
535
    scheduleWarmUpFrame();
536
    await endOfFrame;
537 538
  }

539
  @override
540
  void hitTest(HitTestResult result, Offset position) {
541
    assert(renderView != null);
542 543
    assert(result != null);
    assert(position != null);
544
    renderView.hitTest(result, position: position);
545
    super.hitTest(result, position);
546
  }
547

548
  Future<void> _forceRepaint() {
549
    late RenderObjectVisitor visitor;
550 551 552 553
    visitor = (RenderObject child) {
      child.markNeedsPaint();
      child.visitChildren(visitor);
    };
554
    instance.renderView.visitChildren(visitor);
555
    return endOfFrame;
556
  }
557
}
558

Florian Loitsch's avatar
Florian Loitsch committed
559
/// Prints a textual representation of the entire render tree.
560
void debugDumpRenderTree() {
561
  debugPrint(RendererBinding.instance.renderView.toStringDeep());
562
}
563

Florian Loitsch's avatar
Florian Loitsch committed
564
/// Prints a textual representation of the entire layer tree.
565
void debugDumpLayerTree() {
566
  debugPrint(RendererBinding.instance.renderView.debugLayer?.toStringDeep());
Ian Hickson's avatar
Ian Hickson committed
567 568
}

Hixie's avatar
Hixie committed
569 570
/// Prints a textual representation of the entire semantics tree.
/// This will only work if there is a semantics client attached.
571 572 573 574
/// Otherwise, a notice that no semantics are available will be printed.
///
/// The order in which the children of a [SemanticsNode] will be printed is
/// controlled by the [childOrder] parameter.
575 576 577 578 579 580 581 582 583 584 585 586 587
void debugDumpSemanticsTree([DebugSemanticsDumpOrder childOrder = DebugSemanticsDumpOrder.traversalOrder]) {
  debugPrint(_generateSemanticsTree(childOrder));
}

String _generateSemanticsTree(DebugSemanticsDumpOrder childOrder) {
  final String? tree = RendererBinding.instance.renderView.debugSemantics?.toStringDeep(childOrder: childOrder);
  if (tree != null) {
    return tree;
  }
  return 'Semantics not generated.\n'
    'For performance reasons, the framework only generates semantics when asked to do so by the platform.\n'
    'Usually, platforms only ask for semantics when assistive technologies (like screen readers) are running.\n'
    'To generate semantics, try turning on an assistive technology (like VoiceOver or TalkBack) on your device.';
Hixie's avatar
Hixie committed
588 589
}

Ian Hickson's avatar
Ian Hickson committed
590 591
/// A concrete binding for applications that use the Rendering framework
/// directly. This is the glue that binds the framework to the Flutter engine.
592
///
593 594 595 596 597 598 599 600 601 602 603
/// When using the rendering framework directly, this binding, or one that
/// implements the same interfaces, must be used. The following
/// mixins are used to implement this binding:
///
/// * [GestureBinding], which implements the basics of hit testing.
/// * [SchedulerBinding], which introduces the concepts of frames.
/// * [ServicesBinding], which provides access to the plugin subsystem.
/// * [SemanticsBinding], which supports accessibility.
/// * [PaintingBinding], which enables decoding images.
/// * [RendererBinding], which handles the render tree.
///
604 605 606
/// You would only use this binding if you are writing to the
/// rendering layer directly. If you are writing to a higher-level
/// library, such as the Flutter Widgets library, then you would use
607
/// that layer's binding (see [WidgetsFlutterBinding]).
608
class RenderingFlutterBinding extends BindingBase with GestureBinding, SchedulerBinding, ServicesBinding, SemanticsBinding, PaintingBinding, RendererBinding {
609 610 611 612
  /// Creates a binding for the rendering layer.
  ///
  /// The `root` render box is attached directly to the [renderView] and is
  /// given constraints that require it to fill the window.
613 614 615
  ///
  /// This binding does not automatically schedule any frames. Callers are
  /// responsible for deciding when to first call [scheduleFrame].
616
  RenderingFlutterBinding({ RenderBox? root }) {
617
    assert(renderView != null);
Ian Hickson's avatar
Ian Hickson committed
618 619
    renderView.child = root;
  }
620 621 622 623 624 625 626 627 628 629

  /// Returns an instance of the binding that implements
  /// [RendererBinding]. If no binding has yet been initialized, the
  /// [RenderingFlutterBinding] class is used to create and initialize
  /// one.
  ///
  /// You need to call this method before using the rendering framework
  /// if you are using it directly. If you are using the widgets framework,
  /// see [WidgetsFlutterBinding.ensureInitialized].
  static RendererBinding ensureInitialized() {
630
    if (RendererBinding._instance == null) {
631
      RenderingFlutterBinding();
632
    }
633 634
    return RendererBinding.instance;
  }
635
}