binding.dart 23 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
import 'dart:ui' as ui show SemanticsUpdate;
7

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

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

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

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

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

50
  /// The current [RendererBinding], if one has been created.
51 52 53 54 55
  ///
  /// 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);
56
  static RendererBinding? _instance;
57 58 59 60

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

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

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

202 203
  late final PipelineManifold _manifold = _BindingPipelineManifold(this);

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
    _pipelineOwner.rootNode = value;
236 237
  }

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

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

256 257
  /// Called when the platform brightness changes.
  ///
258 259 260 261
  /// 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.
262
  ///
263
  /// {@tool snippet}
264
  /// Querying [MediaQuery] directly. Preferred.
265 266
  ///
  /// ```dart
267
  /// final Brightness brightness = MediaQuery.platformBrightnessOf(context);
268
  /// ```
269
  /// {@end-tool}
270
  ///
271
  /// {@tool snippet}
272
  /// Querying [PlatformDispatcher.platformBrightness].
273 274
  ///
  /// ```dart
275
  /// final Brightness brightness = WidgetsBinding.instance.platformDispatcher.platformBrightness;
276
  /// ```
277
  /// {@end-tool}
278
  ///
279
  /// {@tool snippet}
280
  /// Querying [MediaQueryData].
281 282 283 284 285
  ///
  /// ```dart
  /// final MediaQueryData mediaQueryData = MediaQuery.of(context);
  /// final Brightness brightness = mediaQueryData.platformBrightness;
  /// ```
286
  /// {@end-tool}
287
  ///
288
  /// See [dart:ui.PlatformDispatcher.onPlatformBrightnessChanged].
289 290 291
  @protected
  void handlePlatformBrightnessChanged() { }

292 293 294 295 296 297 298 299 300 301 302
  /// 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() {
303
    final double devicePixelRatio = window.devicePixelRatio;
304
    return ViewConfiguration(
305
      size: window.physicalSize / devicePixelRatio,
306
      devicePixelRatio: devicePixelRatio,
307
    );
308 309
  }

310 311 312 313 314
  /// 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
315
  void initMouseTracker([MouseTracker? tracker]) {
316
    _mouseTracker?.dispose();
317 318 319 320
    _mouseTracker = tracker ?? MouseTracker();
  }

  @override // from GestureBinding
321
  void dispatchEvent(PointerEvent event, HitTestResult? hitTestResult) {
322 323 324 325 326 327 328 329
    _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,
    );
330
    super.dispatchEvent(event, hitTestResult);
331 332
  }

333 334 335
  @override
  void performSemanticsAction(SemanticsActionEvent action) {
    _pipelineOwner.semanticsOwner?.performAction(action.nodeId, action.type, action.arguments);
336 337 338 339 340 341
  }

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

342 343 344 345
  void _handleSemanticsUpdate(ui.SemanticsUpdate update) {
    renderView.updateSemantics(update);
  }

346 347
  void _handleSemanticsOwnerDisposed() {
    renderView.clearSemantics();
Hixie's avatar
Hixie committed
348 349
  }

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

356
  void _handlePersistentFrameCallback(Duration timeStamp) {
357
    drawFrame();
358 359 360 361 362 363 364 365 366 367
    _scheduleMouseTrackerUpdate();
  }

  bool _debugMouseTrackerUpdateScheduled = false;
  void _scheduleMouseTrackerUpdate() {
    assert(!_debugMouseTrackerUpdateScheduled);
    assert(() {
      _debugMouseTrackerUpdateScheduled = true;
      return true;
    }());
368
    SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
369 370 371 372 373
      assert(_debugMouseTrackerUpdateScheduled);
      assert(() {
        _debugMouseTrackerUpdateScheduled = false;
        return true;
      }());
374
      _mouseTracker!.updateAllDevices(renderView.hitTestMouseTrackers);
375
    });
376 377
  }

378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 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
  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.
421
    if (!_firstFrameSent) {
422
      scheduleWarmUpFrame();
423
    }
424 425 426 427 428 429 430 431 432 433 434
  }

  /// 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
435
  /// Pump the rendering pipeline to generate a frame.
436
  ///
437
  /// This method is called by [handleDrawFrame], which itself is called
438
  /// automatically by the engine when it is time to lay out and paint a frame.
439 440 441 442
  ///
  /// Each frame consists of the following phases:
  ///
  /// 1. The animation phase: The [handleBeginFrame] method, which is registered
443 444 445 446 447
  /// 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.
448
  ///
449 450 451 452
  /// 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.
453
  ///
454
  /// After [handleBeginFrame], [handleDrawFrame], which is registered with
455 456 457
  /// [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:
458 459
  ///
  /// 3. The layout phase: All the dirty [RenderObject]s in the system are laid
460 461 462
  /// out (see [RenderObject.performLayout]). See [RenderObject.markNeedsLayout]
  /// for further details on marking an object dirty for layout.
  ///
463
  /// 4. The compositing bits phase: The compositing bits on any dirty
464 465 466
  /// [RenderObject] objects are updated. See
  /// [RenderObject.markNeedsCompositingBitsUpdate].
  ///
467
  /// 5. The paint phase: All the dirty [RenderObject]s in the system are
468 469 470 471
  /// repainted (see [RenderObject.paint]). This generates the [Layer] tree. See
  /// [RenderObject.markNeedsPaint] for further details on marking an object
  /// dirty for paint.
  ///
472
  /// 6. The compositing phase: The layer tree is turned into a [Scene] and
473 474
  /// sent to the GPU.
  ///
475
  /// 7. The semantics phase: All the dirty [RenderObject]s in the system have
476
  /// their semantics updated. This generates the [SemanticsNode] tree. See
477 478 479
  /// [RenderObject.markNeedsSemanticsUpdate] for further details on marking an
  /// object dirty for semantics.
  ///
480
  /// For more details on steps 3-7, see [PipelineOwner].
481
  ///
482 483
  /// 8. The finalization phase: After [drawFrame] returns, [handleDrawFrame]
  /// then invokes post-frame callbacks (registered with [addPostFrameCallback]).
484 485
  ///
  /// Some bindings (for example, the [WidgetsBinding]) add extra steps to this
486
  /// list (for example, see [WidgetsBinding.drawFrame]).
487 488
  //
  // When editing the above, also update widgets/binding.dart's copy.
Ian Hickson's avatar
Ian Hickson committed
489
  @protected
490
  void drawFrame() {
491 492 493
    pipelineOwner.flushLayout();
    pipelineOwner.flushCompositingBits();
    pipelineOwner.flushPaint();
494 495 496 497 498
    if (sendFramesToEngine) {
      renderView.compositeFrame(); // this sends the bits to the GPU
      pipelineOwner.flushSemantics(); // this also sends the semantics to the OS.
      _firstFrameSent = true;
    }
499 500
  }

501
  @override
502
  Future<void> performReassemble() async {
503
    await super.performReassemble();
504
    if (BindingBase.debugReassembleConfig?.widgetName == null) {
Ian Hickson's avatar
Ian Hickson committed
505
      if (!kReleaseMode) {
506 507 508 509 510 511 512 513
        Timeline.startSync('Preparing Hot Reload (layout)');
      }
      try {
        renderView.reassemble();
      } finally {
        if (!kReleaseMode) {
          Timeline.finishSync();
        }
514
      }
515
    }
516
    scheduleWarmUpFrame();
517
    await endOfFrame;
518 519
  }

520
  @override
521
  void hitTest(HitTestResult result, Offset position) {
522
    renderView.hitTest(result, position: position);
523
    super.hitTest(result, position);
524
  }
525

526
  Future<void> _forceRepaint() {
527
    late RenderObjectVisitor visitor;
528 529 530 531
    visitor = (RenderObject child) {
      child.markNeedsPaint();
      child.visitChildren(visitor);
    };
532
    instance.renderView.visitChildren(visitor);
533
    return endOfFrame;
534
  }
535
}
536

Florian Loitsch's avatar
Florian Loitsch committed
537
/// Prints a textual representation of the entire render tree.
538
void debugDumpRenderTree() {
539
  debugPrint(RendererBinding.instance.renderView.toStringDeep());
540
}
541

Florian Loitsch's avatar
Florian Loitsch committed
542
/// Prints a textual representation of the entire layer tree.
543
void debugDumpLayerTree() {
544
  debugPrint(RendererBinding.instance.renderView.debugLayer?.toStringDeep());
Ian Hickson's avatar
Ian Hickson committed
545 546
}

Hixie's avatar
Hixie committed
547 548
/// Prints a textual representation of the entire semantics tree.
/// This will only work if there is a semantics client attached.
549 550 551 552
/// 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.
553 554 555 556 557 558 559 560 561 562 563 564 565
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
566 567
}

Ian Hickson's avatar
Ian Hickson committed
568 569
/// A concrete binding for applications that use the Rendering framework
/// directly. This is the glue that binds the framework to the Flutter engine.
570
///
571 572 573 574 575 576 577 578 579 580 581
/// 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.
///
582 583 584
/// 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
585
/// that layer's binding (see [WidgetsFlutterBinding]).
586
class RenderingFlutterBinding extends BindingBase with GestureBinding, SchedulerBinding, ServicesBinding, SemanticsBinding, PaintingBinding, RendererBinding {
587 588 589 590
  /// 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.
591 592 593
  ///
  /// This binding does not automatically schedule any frames. Callers are
  /// responsible for deciding when to first call [scheduleFrame].
594
  RenderingFlutterBinding({ RenderBox? root }) {
Ian Hickson's avatar
Ian Hickson committed
595 596
    renderView.child = root;
  }
597 598 599 600 601 602 603 604 605 606

  /// 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() {
607
    if (RendererBinding._instance == null) {
608
      RenderingFlutterBinding();
609
    }
610 611
    return RendererBinding.instance;
  }
612
}
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635

/// A [PipelineManifold] implementation that is backed by the [RendererBinding].
class _BindingPipelineManifold extends ChangeNotifier implements PipelineManifold {
  _BindingPipelineManifold(this._binding) {
    _binding.addSemanticsEnabledListener(notifyListeners);
  }

  final RendererBinding _binding;

  @override
  void requestVisualUpdate() {
    _binding.ensureVisualUpdate();
  }

  @override
  bool get semanticsEnabled => _binding.semanticsEnabled;

  @override
  void dispose() {
    _binding.removeSemanticsEnabledListener(notifyListeners);
    super.dispose();
  }
}