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


import 'package:flutter/foundation.dart';
7
import 'package:flutter/gestures.dart';
8
import 'package:flutter/scheduler.dart';
9
import 'package:flutter/semantics.dart';
10 11 12 13 14 15
import 'package:flutter/services.dart';

import 'box.dart';
import 'layer.dart';
import 'object.dart';

16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/// How an embedded platform view behave during hit tests.
enum PlatformViewHitTestBehavior {
  /// Opaque targets can be hit by hit tests, causing them to both receive
  /// events within their bounds and prevent targets visually behind them from
  /// also receiving events.
  opaque,

  /// Translucent targets both receive events within their bounds and permit
  /// targets visually behind them to also receive events.
  translucent,

  /// Transparent targets don't receive events within their bounds and permit
  /// targets visually behind them to receive events.
  transparent,
}

32 33 34 35 36 37
enum _PlatformViewState {
  uninitialized,
  resizing,
  ready,
}

38
bool _factoryTypesSetEquals<T>(Set<Factory<T>>? a, Set<Factory<T>>? b) {
39 40 41 42 43 44 45 46 47 48 49 50 51
  if (a == b) {
    return true;
  }
  if (a == null ||  b == null) {
    return false;
  }
  return setEquals(_factoriesTypeSet(a), _factoriesTypeSet(b));
}

Set<Type> _factoriesTypeSet<T>(Set<Factory<T>> factories) {
  return factories.map<Type>((Factory<T> factory) => factory.type).toSet();
}

52 53
/// A render object for an Android view.
///
54
/// Requires Android API level 23 or greater.
55
///
56 57
/// [RenderAndroidView] is responsible for sizing, displaying and passing touch events to an
/// Android [View](https://developer.android.com/reference/android/view/View).
58
///
59
/// {@template flutter.rendering.RenderAndroidView.layout}
60
/// The render object's layout behavior is to fill all available space, the parent of this object must
61
/// provide bounded layout constraints.
62
/// {@endtemplate}
63
///
64
/// {@template flutter.rendering.RenderAndroidView.gestures}
65
/// The render object participates in Flutter's gesture arenas, and dispatches touch events to the
66 67 68 69 70
/// platform view iff it won the arena. Specific gestures that should be dispatched to the platform
/// view can be specified with factories in the `gestureRecognizers` constructor parameter or
/// by calling `updateGestureRecognizers`. If the set of gesture recognizers is empty, the gesture
/// will be dispatched to the platform view iff it was not claimed by any other gesture recognizer.
/// {@endtemplate}
71 72
///
/// See also:
73
///
74 75
///  * [AndroidView] which is a widget that is used to show an Android view.
///  * [PlatformViewsService] which is a service for controlling platform views.
76
class RenderAndroidView extends PlatformViewRenderBox {
77 78
  /// Creates a render object for an Android view.
  RenderAndroidView({
79 80 81
    required AndroidViewController viewController,
    required PlatformViewHitTestBehavior hitTestBehavior,
    required Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
82
    Clip clipBehavior = Clip.hardEdge,
83
  }) : assert(viewController != null),
84
       assert(hitTestBehavior != null),
85
       assert(gestureRecognizers != null),
86 87
       assert(clipBehavior != null),
       _viewController = viewController,
88 89
       _clipBehavior = clipBehavior,
       super(controller: viewController, hitTestBehavior: hitTestBehavior, gestureRecognizers: gestureRecognizers) {
90
    _viewController.pointTransformer = (Offset offset) => globalToLocal(offset);
91
    updateGestureRecognizers(gestureRecognizers);
92
    _viewController.addOnPlatformViewCreatedListener(_onPlatformViewCreated);
93
    this.hitTestBehavior = hitTestBehavior;
94
    _setOffset();
95
  }
96 97 98

  _PlatformViewState _state = _PlatformViewState.uninitialized;

99 100 101 102
  Size? _currentTextureSize;

  bool _isDisposed = false;

103
  /// The Android view controller for the Android view associated with this render object.
104 105 106
  @override
  AndroidViewController get controller => _viewController;

107
  AndroidViewController _viewController;
108

109
  /// Sets a new Android view controller.
110 111
  @override
  set controller(AndroidViewController controller) {
112
    assert(!_isDisposed);
113
    assert(_viewController != null);
114
    assert(controller != null);
115
    if (_viewController == controller) {
116
      return;
117
    }
118
    _viewController.removeOnPlatformViewCreatedListener(_onPlatformViewCreated);
119 120 121
    super.controller = controller;
    _viewController = controller;
    _viewController.pointTransformer = (Offset offset) => globalToLocal(offset);
122
    _sizePlatformView();
123 124 125 126 127 128
    if (_viewController.isCreated) {
      markNeedsSemanticsUpdate();
    }
    _viewController.addOnPlatformViewCreatedListener(_onPlatformViewCreated);
  }

129
  /// {@macro flutter.material.Material.clipBehavior}
130 131 132 133 134 135 136 137 138 139 140 141 142
  ///
  /// Defaults to [Clip.hardEdge], and must not be null.
  Clip get clipBehavior => _clipBehavior;
  Clip _clipBehavior = Clip.hardEdge;
  set clipBehavior(Clip value) {
    assert(value != null);
    if (value != _clipBehavior) {
      _clipBehavior = value;
      markNeedsPaint();
      markNeedsSemanticsUpdate();
    }
  }

143
  void _onPlatformViewCreated(int id) {
144
    assert(!_isDisposed);
145
    markNeedsSemanticsUpdate();
146 147 148 149 150 151 152 153 154 155 156
  }

  @override
  bool get sizedByParent => true;

  @override
  bool get alwaysNeedsCompositing => true;

  @override
  bool get isRepaintBoundary => true;

157 158 159 160 161
  @override
  Size computeDryLayout(BoxConstraints constraints) {
    return constraints.biggest;
  }

162 163
  @override
  void performResize() {
164
    super.performResize();
165 166 167
    _sizePlatformView();
  }

168
  Future<void> _sizePlatformView() async {
169 170 171
    // Android virtual displays cannot have a zero size.
    // Trying to size it to 0 crashes the app, which was happening when starting the app
    // with a locked screen (see: https://github.com/flutter/flutter/issues/20456).
172
    if (_state == _PlatformViewState.resizing || size.isEmpty) {
173
      return;
174
    }
175 176

    _state = _PlatformViewState.resizing;
177
    markNeedsPaint();
178 179 180 181

    Size targetSize;
    do {
      targetSize = size;
182 183 184
      _currentTextureSize = await _viewController.setSize(targetSize);
      if (_isDisposed) {
        return;
185
      }
186 187 188 189 190 191 192 193 194
      // We've resized the platform view to targetSize, but it is possible that
      // while we were resizing the render object's size was changed again.
      // In that case we will resize the platform view again.
    } while (size != targetSize);

    _state = _PlatformViewState.ready;
    markNeedsPaint();
  }

195
  // Sets the offset of the underlying platform view on the platform side.
196 197 198 199 200 201 202 203 204
  //
  // This allows the Android native view to draw the a11y highlights in the same
  // location on the screen as the platform view widget in the Flutter framework.
  //
  // It also allows platform code to obtain the correct position of the Android
  // native view on the screen.
  void _setOffset() {
    SchedulerBinding.instance.addPostFrameCallback((_) async {
      if (!_isDisposed) {
205
        if (attached) {
206
          await _viewController.setOffset(localToGlobal(Offset.zero));
207
        }
208 209 210 211 212 213
        // Schedule a new post frame callback.
        _setOffset();
      }
    });
  }

214 215
  @override
  void paint(PaintingContext context, Offset offset) {
216
    if (_viewController.textureId == null || _currentTextureSize == null) {
217
      return;
218
    }
219

220 221 222 223 224 225 226 227 228 229 230
    // As resizing the Android view happens asynchronously we don't know exactly when is a
    // texture frame with the new size is ready for consumption.
    // TextureLayer is unaware of the texture frame's size and always maps it to the
    // specified rect. If the rect we provide has a different size from the current texture frame's
    // size the texture frame will be scaled.
    // To prevent unwanted scaling artifacts while resizing, clip the texture.
    // This guarantees that the size of the texture frame we're painting is always
    // _currentAndroidTextureSize.
    final bool isTextureLargerThanWidget = _currentTextureSize!.width > size.width ||
                                           _currentTextureSize!.height > size.height;
    if (isTextureLargerThanWidget && clipBehavior != Clip.none) {
231
      _clipRectLayer.layer = context.pushClipRect(
232 233 234 235 236
        true,
        offset,
        offset & size,
        _paintTexture,
        clipBehavior: clipBehavior,
237
        oldLayer: _clipRectLayer.layer,
238
      );
239 240
      return;
    }
241
    _clipRectLayer.layer = null;
242 243 244
    _paintTexture(context, offset);
  }

245 246 247 248
  final LayerHandle<ClipRectLayer> _clipRectLayer = LayerHandle<ClipRectLayer>();

  @override
  void dispose() {
249
    _isDisposed = true;
250
    _clipRectLayer.layer = null;
251
    _viewController.removeOnPlatformViewCreatedListener(_onPlatformViewCreated);
252 253
    super.dispose();
  }
254

255
  void _paintTexture(PaintingContext context, Offset offset) {
256
    if (_currentTextureSize == null) {
257
      return;
258
    }
259

260
    context.addLayer(TextureLayer(
261
      rect: offset & _currentTextureSize!,
262
      textureId: _viewController.textureId!,
263 264
    ));
  }
265

266
  @override
267 268 269 270
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    // Don't call the super implementation since `platformViewId` should
    // be set only when the platform view is created, but the concept of
    // a "created" platform view belongs to this subclass.
271 272 273
    config.isSemanticBoundary = true;

    if (_viewController.isCreated) {
274
      config.platformViewId = _viewController.viewId;
275 276
    }
  }
277 278
}

279 280
/// A render object for an iOS UIKit UIView.
///
281
/// {@template flutter.rendering.RenderUiKitView}
282
/// Embedding UIViews is still preview-quality. To enable the preview for an iOS app add a boolean
283 284
/// field with the key 'io.flutter.embedded_views_preview' and the value set to 'YES' to the
/// application's Info.plist file. A list of open issued with embedding UIViews is available on
285
/// [Github](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3A%22a%3A+platform-views%22+label%3Aplatform-ios+sort%3Acreated-asc)
286
/// {@endtemplate}
287 288 289 290 291 292
///
/// [RenderUiKitView] is responsible for sizing and displaying an iOS
/// [UIView](https://developer.apple.com/documentation/uikit/uiview).
///
/// UIViews are added as sub views of the FlutterView and are composited by Quartz.
///
293
/// {@macro flutter.rendering.RenderAndroidView.layout}
294
///
295
/// {@macro flutter.rendering.RenderAndroidView.gestures}
296
///
297
/// See also:
298
///
299 300 301 302 303
///  * [UiKitView] which is a widget that is used to show a UIView.
///  * [PlatformViewsService] which is a service for controlling platform views.
class RenderUiKitView extends RenderBox {
  /// Creates a render object for an iOS UIView.
  ///
304
  /// The `viewId`, `hitTestBehavior`, and `gestureRecognizers` parameters must not be null.
305
  RenderUiKitView({
306 307 308
    required UiKitViewController viewController,
    required this.hitTestBehavior,
    required Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
309
  }) : assert(viewController != null),
310
       assert(hitTestBehavior != null),
311 312 313 314
       assert(gestureRecognizers != null),
       _viewController = viewController {
    updateGestureRecognizers(gestureRecognizers);
  }
315 316 317 318 319 320


  /// The unique identifier of the UIView controlled by this controller.
  ///
  /// Typically generated by [PlatformViewsRegistry.getNextPlatformViewId], the UIView
  /// must have been created by calling [PlatformViewsService.initUiKitView].
321 322
  UiKitViewController get viewController => _viewController;
  UiKitViewController _viewController;
323 324 325 326 327 328 329
  set viewController(UiKitViewController value) {
    assert(value != null);
    if (_viewController == value) {
      return;
    }
    final bool needsSemanticsUpdate = _viewController.id != value.id;
    _viewController = value;
330
    markNeedsPaint();
331 332 333
    if (needsSemanticsUpdate) {
      markNeedsSemanticsUpdate();
    }
334 335 336 337 338 339 340
  }

  /// How to behave during hit testing.
  // The implicit setter is enough here as changing this value will just affect
  // any newly arriving events there's nothing we need to invalidate.
  PlatformViewHitTestBehavior hitTestBehavior;

341
  /// {@macro flutter.rendering.PlatformViewRenderBox.updateGestureRecognizers}
342 343 344
  void updateGestureRecognizers(Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers) {
    assert(gestureRecognizers != null);
    assert(
345 346 347 348
      _factoriesTypeSet(gestureRecognizers).length == gestureRecognizers.length,
      'There were multiple gesture recognizer factories for the same type, there must only be a single '
      'gesture recognizer factory for each gesture recognizer type.',
    );
349 350 351 352 353 354 355
    if (_factoryTypesSetEquals(gestureRecognizers, _gestureRecognizer?.gestureRecognizerFactories)) {
      return;
    }
    _gestureRecognizer?.dispose();
    _gestureRecognizer = _UiKitViewGestureRecognizer(viewController, gestureRecognizers);
  }

356 357 358 359 360 361 362 363 364
  @override
  bool get sizedByParent => true;

  @override
  bool get alwaysNeedsCompositing => true;

  @override
  bool get isRepaintBoundary => true;

365
  _UiKitViewGestureRecognizer? _gestureRecognizer;
366

367
  PointerEvent? _lastPointerDownEvent;
368

369
  @override
370 371
  Size computeDryLayout(BoxConstraints constraints) {
    return constraints.biggest;
372 373 374 375 376 377
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    context.addLayer(PlatformViewLayer(
      rect: offset & size,
378
      viewId: _viewController.id,
379 380 381 382
    ));
  }

  @override
383
  bool hitTest(BoxHitTestResult result, { Offset? position }) {
384
    if (hitTestBehavior == PlatformViewHitTestBehavior.transparent || !size.contains(position!)) {
385
      return false;
386
    }
387 388 389 390 391 392
    result.add(BoxHitTestEntry(this, position));
    return hitTestBehavior == PlatformViewHitTestBehavior.opaque;
  }

  @override
  bool hitTestSelf(Offset position) => hitTestBehavior != PlatformViewHitTestBehavior.transparent;
393 394 395

  @override
  void handleEvent(PointerEvent event, HitTestEntry entry) {
396 397 398
    if (event is! PointerDownEvent) {
      return;
    }
399
    _gestureRecognizer!.addPointer(event);
400
    _lastPointerDownEvent = event.original ?? event;
401 402 403 404 405 406 407
  }

  // This is registered as a global PointerRoute while the render object is attached.
  void _handleGlobalPointerEvent(PointerEvent event) {
    if (event is! PointerDownEvent) {
      return;
    }
408
    if (!(Offset.zero & size).contains(globalToLocal(event.position))) {
409 410
      return;
    }
411
    if ((event.original ?? event) != _lastPointerDownEvent) {
412 413 414 415 416
      // The pointer event is in the bounds of this render box, but we didn't get it in handleEvent.
      // This means that the pointer event was absorbed by a different render object.
      // Since on the platform side the FlutterTouchIntercepting view is seeing all events that are
      // within its bounds we need to tell it to reject the current touch sequence.
      _viewController.rejectGesture();
417
    }
418 419 420
    _lastPointerDownEvent = null;
  }

421 422 423 424 425 426 427
  @override
  void describeSemanticsConfiguration (SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
    config.isSemanticBoundary = true;
    config.platformViewId = _viewController.id;
  }

428 429 430
  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
431
    GestureBinding.instance.pointerRouter.addGlobalRoute(_handleGlobalPointerEvent);
432 433 434 435
  }

  @override
  void detach() {
436
    GestureBinding.instance.pointerRouter.removeGlobalRoute(_handleGlobalPointerEvent);
437
    _gestureRecognizer!.reset();
438 439 440 441 442
    super.detach();
  }
}

// This recognizer constructs gesture recognizers from a set of gesture recognizer factories
443
// it was give, adds all of them to a gesture arena team with the _UiKitViewGestureRecognizer
444 445 446 447
// as the team captain.
// When the team wins a gesture the recognizer notifies the engine that it should release
// the touch sequence to the embedded UIView.
class _UiKitViewGestureRecognizer extends OneSequenceGestureRecognizer {
448 449
  _UiKitViewGestureRecognizer(
    this.controller,
450 451
    this.gestureRecognizerFactories
  ) {
452 453
    team = GestureArenaTeam()
      ..captain = this;
454 455
    _gestureRecognizers = gestureRecognizerFactories.map(
      (Factory<OneSequenceGestureRecognizer> recognizerFactory) {
456 457 458 459 460 461 462 463 464 465 466 467 468
        final OneSequenceGestureRecognizer gestureRecognizer = recognizerFactory.constructor();
        gestureRecognizer.team = team;
        // The below gesture recognizers requires at least one non-empty callback to
        // compete in the gesture arena.
        // https://github.com/flutter/flutter/issues/35394#issuecomment-562285087
        if (gestureRecognizer is LongPressGestureRecognizer) {
          gestureRecognizer.onLongPress ??= (){};
        } else if (gestureRecognizer is DragGestureRecognizer) {
          gestureRecognizer.onDown ??= (_){};
        } else if (gestureRecognizer is TapGestureRecognizer) {
          gestureRecognizer.onTapDown ??= (_){};
        }
        return gestureRecognizer;
469 470 471 472 473 474 475 476
      },
    ).toSet();
  }

  // We use OneSequenceGestureRecognizers as they support gesture arena teams.
  // TODO(amirh): get a list of GestureRecognizers here.
  // https://github.com/flutter/flutter/issues/20953
  final Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizerFactories;
477
  late Set<OneSequenceGestureRecognizer> _gestureRecognizers;
478 479 480 481

  final UiKitViewController controller;

  @override
482
  void addAllowedPointer(PointerDownEvent event) {
483
    super.addAllowedPointer(event);
484
    for (final OneSequenceGestureRecognizer recognizer in _gestureRecognizers) {
485 486 487 488 489 490 491 492
      recognizer.addPointer(event);
    }
  }

  @override
  String get debugDescription => 'UIKit view';

  @override
493
  void didStopTrackingLastPointer(int pointer) { }
494 495 496 497 498 499 500 501 502 503 504 505 506

  @override
  void handleEvent(PointerEvent event) {
    stopTrackingIfPointerNoLongerDown(event);
  }

  @override
  void acceptGesture(int pointer) {
    controller.acceptGesture();
  }

  @override
  void rejectGesture(int pointer) {
507
    controller.rejectGesture();
508 509 510 511 512
  }

  void reset() {
    resolve(GestureDisposition.rejected);
  }
513 514
}

515
typedef _HandlePointerEvent = Future<void> Function(PointerEvent event);
516

517
// This recognizer constructs gesture recognizers from a set of gesture recognizer factories
518
// it was give, adds all of them to a gesture arena team with the _PlatformViewGestureRecognizer
519
// as the team captain.
520 521 522 523 524 525
// As long as the gesture arena is unresolved, the recognizer caches all pointer events.
// When the team wins, the recognizer sends all the cached pointer events to `_handlePointerEvent`, and
// sets itself to a "forwarding mode" where it will forward any new pointer event to `_handlePointerEvent`.
class _PlatformViewGestureRecognizer extends OneSequenceGestureRecognizer {
  _PlatformViewGestureRecognizer(
    _HandlePointerEvent handlePointerEvent,
526 527
    this.gestureRecognizerFactories
  ) {
528 529
    team = GestureArenaTeam()
      ..captain = this;
530
    _gestureRecognizers = gestureRecognizerFactories.map(
531
      (Factory<OneSequenceGestureRecognizer> recognizerFactory) {
532 533 534 535 536 537 538 539 540 541 542 543 544
        final OneSequenceGestureRecognizer gestureRecognizer = recognizerFactory.constructor();
        gestureRecognizer.team = team;
        // The below gesture recognizers requires at least one non-empty callback to
        // compete in the gesture arena.
        // https://github.com/flutter/flutter/issues/35394#issuecomment-562285087
        if (gestureRecognizer is LongPressGestureRecognizer) {
          gestureRecognizer.onLongPress ??= (){};
        } else if (gestureRecognizer is DragGestureRecognizer) {
          gestureRecognizer.onDown ??= (_){};
        } else if (gestureRecognizer is TapGestureRecognizer) {
          gestureRecognizer.onTapDown ??= (_){};
        }
        return gestureRecognizer;
545
      },
546
    ).toSet();
547
    _handlePointerEvent = handlePointerEvent;
548 549
  }

550
  late _HandlePointerEvent _handlePointerEvent;
551 552 553

  // Maps a pointer to a list of its cached pointer events.
  // Before the arena for a pointer is resolved all events are cached here, if we win the arena
554
  // the cached events are dispatched to `_handlePointerEvent`, if we lose the arena we clear the cache for
555
  // the pointer.
556
  final Map<int, List<PointerEvent>> cachedEvents = <int, List<PointerEvent>>{};
557 558

  // Pointer for which we have already won the arena, events for pointers in this set are
559
  // immediately dispatched to `_handlePointerEvent`.
560
  final Set<int> forwardedPointers = <int>{};
561 562 563 564

  // We use OneSequenceGestureRecognizers as they support gesture arena teams.
  // TODO(amirh): get a list of GestureRecognizers here.
  // https://github.com/flutter/flutter/issues/20953
565
  final Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizerFactories;
566
  late Set<OneSequenceGestureRecognizer> _gestureRecognizers;
567 568

  @override
569
  void addAllowedPointer(PointerDownEvent event) {
570
    super.addAllowedPointer(event);
571
    for (final OneSequenceGestureRecognizer recognizer in _gestureRecognizers) {
572 573 574 575 576
      recognizer.addPointer(event);
    }
  }

  @override
577
  String get debugDescription => 'Platform view';
578 579

  @override
580
  void didStopTrackingLastPointer(int pointer) { }
581 582 583 584

  @override
  void handleEvent(PointerEvent event) {
    if (!forwardedPointers.contains(event.pointer)) {
585
      _cacheEvent(event);
586
    } else {
587
      _handlePointerEvent(event);
588 589 590 591 592 593
    }
    stopTrackingIfPointerNoLongerDown(event);
  }

  @override
  void acceptGesture(int pointer) {
594
    _flushPointerCache(pointer);
595 596 597 598 599 600 601 602 603
    forwardedPointers.add(pointer);
  }

  @override
  void rejectGesture(int pointer) {
    stopTrackingPointer(pointer);
    cachedEvents.remove(pointer);
  }

604
  void _cacheEvent(PointerEvent event) {
605 606 607
    if (!cachedEvents.containsKey(event.pointer)) {
      cachedEvents[event.pointer] = <PointerEvent> [];
    }
608
    cachedEvents[event.pointer]!.add(event);
609 610
  }

611 612
  void _flushPointerCache(int pointer) {
    cachedEvents.remove(pointer)?.forEach(_handlePointerEvent);
613 614 615 616 617 618 619 620 621 622 623 624 625 626
  }

  @override
  void stopTrackingPointer(int pointer) {
    super.stopTrackingPointer(pointer);
    forwardedPointers.remove(pointer);
  }

  void reset() {
    forwardedPointers.forEach(super.stopTrackingPointer);
    forwardedPointers.clear();
    cachedEvents.keys.forEach(super.stopTrackingPointer);
    cachedEvents.clear();
    resolve(GestureDisposition.rejected);
627 628 629
  }
}

630 631
/// A render object for embedding a platform view.
///
632 633 634
/// [PlatformViewRenderBox] presents a platform view by adding a [PlatformViewLayer] layer,
/// integrates it with the gesture arenas system and adds relevant semantic nodes to the semantics tree.
class PlatformViewRenderBox extends RenderBox with _PlatformViewGestureMixin {
635 636 637 638
  /// Creating a render object for a [PlatformViewSurface].
  ///
  /// The `controller` parameter must not be null.
  PlatformViewRenderBox({
639 640 641
    required PlatformViewController controller,
    required PlatformViewHitTestBehavior hitTestBehavior,
    required Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
642 643 644 645
  }) :  assert(controller != null && controller.viewId != null && controller.viewId > -1),
        assert(hitTestBehavior != null),
        assert(gestureRecognizers != null),
        _controller = controller {
646 647 648
    this.hitTestBehavior = hitTestBehavior;
    updateGestureRecognizers(gestureRecognizers);
  }
649

650 651 652
  /// The controller for this render object.
  PlatformViewController get controller => _controller;
  PlatformViewController _controller;
653
  /// This value must not be null, and setting it to a new value will result in a repaint.
654
  set controller(covariant PlatformViewController controller) {
655 656 657
    assert(controller != null);
    assert(controller.viewId != null && controller.viewId > -1);

658
    if (_controller == controller) {
659 660 661
      return;
    }
    final bool needsSemanticsUpdate = _controller.viewId != controller.viewId;
662 663
    _controller = controller;
    markNeedsPaint();
664 665 666 667 668
    if (needsSemanticsUpdate) {
      markNeedsSemanticsUpdate();
    }
  }

669 670 671 672 673 674 675 676 677 678 679 680 681
  /// {@template flutter.rendering.PlatformViewRenderBox.updateGestureRecognizers}
  /// Updates which gestures should be forwarded to the platform view.
  ///
  /// Gesture recognizers created by factories in this set participate in the gesture arena for each
  /// pointer that was put down on the render box. If any of the recognizers on this list wins the
  /// gesture arena, the entire pointer event sequence starting from the pointer down event
  /// will be dispatched to the Android view.
  ///
  /// The `gestureRecognizers` property must not contain more than one factory with the same [Factory.type].
  ///
  /// Setting a new set of gesture recognizer factories with the same [Factory.type]s as the current
  /// set has no effect, because the factories' constructors would have already been called with the previous set.
  /// {@endtemplate}
682 683 684
  ///
  /// Any active gesture arena the `PlatformView` participates in is rejected when the
  /// set of gesture recognizers is changed.
685 686
  void updateGestureRecognizers(Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers) {
    _updateGestureRecognizersWithCallBack(gestureRecognizers, _controller.dispatchPointerEvent);
687 688
  }

689 690 691 692 693 694 695 696 697 698
  @override
  bool get sizedByParent => true;

  @override
  bool get alwaysNeedsCompositing => true;

  @override
  bool get isRepaintBoundary => true;

  @override
699 700
  Size computeDryLayout(BoxConstraints constraints) {
    return constraints.biggest;
701 702 703 704 705 706
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    assert(_controller.viewId != null);
    context.addLayer(PlatformViewLayer(
707 708 709
      rect: offset & size,
      viewId: _controller.viewId,
    ));
710 711 712
  }

  @override
713
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
714 715 716 717 718 719
    super.describeSemanticsConfiguration(config);
    assert(_controller.viewId != null);
    config.isSemanticBoundary = true;
    config.platformViewId = _controller.viewId;
  }
}
720 721

/// The Mixin handling the pointer events and gestures of a platform view render box.
722
mixin _PlatformViewGestureMixin on RenderBox implements MouseTrackerAnnotation {
723 724

  /// How to behave during hit testing.
725 726 727 728
  // Changing _hitTestBehavior might affect which objects are considered hovered over.
  set hitTestBehavior(PlatformViewHitTestBehavior value) {
    if (value != _hitTestBehavior) {
      _hitTestBehavior = value;
729
      if (owner != null) {
730
        markNeedsPaint();
731
      }
732 733
    }
  }
734
  PlatformViewHitTestBehavior? _hitTestBehavior;
735

736
  _HandlePointerEvent? _handlePointerEvent;
737

738
  /// {@macro flutter.rendering.RenderAndroidView.updateGestureRecognizers}
739 740 741
  ///
  /// Any active gesture arena the `PlatformView` participates in is rejected when the
  /// set of gesture recognizers is changed.
742
  void _updateGestureRecognizersWithCallBack(Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers, _HandlePointerEvent handlePointerEvent) {
743 744
    assert(gestureRecognizers != null);
    assert(
745 746 747 748
      _factoriesTypeSet(gestureRecognizers).length == gestureRecognizers.length,
      'There were multiple gesture recognizer factories for the same type, there must only be a single '
      'gesture recognizer factory for each gesture recognizer type.',
    );
749 750 751 752
    if (_factoryTypesSetEquals(gestureRecognizers, _gestureRecognizer?.gestureRecognizerFactories)) {
      return;
    }
    _gestureRecognizer?.dispose();
753
    _gestureRecognizer = _PlatformViewGestureRecognizer(handlePointerEvent, gestureRecognizers);
754
    _handlePointerEvent = handlePointerEvent;
755 756
  }

757
  _PlatformViewGestureRecognizer? _gestureRecognizer;
758 759

  @override
760
  bool hitTest(BoxHitTestResult result, { required Offset position }) {
761
    if (_hitTestBehavior == PlatformViewHitTestBehavior.transparent || !size.contains(position)) {
762 763 764
      return false;
    }
    result.add(BoxHitTestEntry(this, position));
765
    return _hitTestBehavior == PlatformViewHitTestBehavior.opaque;
766 767 768
  }

  @override
769
  bool hitTestSelf(Offset position) => _hitTestBehavior != PlatformViewHitTestBehavior.transparent;
770

771
  @override
772
  PointerEnterEventListener? get onEnter => null;
773 774

  @override
775
  PointerExitEventListener? get onExit => null;
776 777 778 779

  @override
  MouseCursor get cursor => MouseCursor.uncontrolled;

780 781 782
  @override
  bool get validForMouseTracker => true;

783 784 785
  @override
  void handleEvent(PointerEvent event, HitTestEntry entry) {
    if (event is PointerDownEvent) {
786
      _gestureRecognizer!.addPointer(event);
787
    }
788 789 790
    if (event is PointerHoverEvent) {
      _handlePointerEvent?.call(event);
    }
791 792 793 794
  }

  @override
  void detach() {
795
    _gestureRecognizer!.reset();
796 797 798
    super.detach();
  }
}