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

import 'dart:ui';

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

import 'box.dart';
import 'layer.dart';
14
import 'mouse_cursor.dart';
15
import 'mouse_tracking.dart';
16 17 18
import 'object.dart';


19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/// 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,
}

35 36 37 38 39 40
enum _PlatformViewState {
  uninitialized,
  resizing,
  ready,
}

41
bool _factoryTypesSetEquals<T>(Set<Factory<T>>? a, Set<Factory<T>>? b) {
42 43 44 45 46 47 48 49 50 51 52 53 54
  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();
}

55 56
/// A render object for an Android view.
///
57 58
/// Requires Android API level 20 or greater.
///
59 60
/// [RenderAndroidView] is responsible for sizing, displaying and passing touch events to an
/// Android [View](https://developer.android.com/reference/android/view/View).
61
///
62
/// {@template flutter.rendering.RenderAndroidView.layout}
63
/// The render object's layout behavior is to fill all available space, the parent of this object must
64
/// provide bounded layout constraints.
65
/// {@endtemplate}
66
///
67
/// {@template flutter.rendering.RenderAndroidView.gestures}
68
/// The render object participates in Flutter's gesture arenas, and dispatches touch events to the
69 70 71 72 73
/// 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}
74 75
///
/// See also:
76
///
77 78
///  * [AndroidView] which is a widget that is used to show an Android view.
///  * [PlatformViewsService] which is a service for controlling platform views.
79
class RenderAndroidView extends RenderBox with _PlatformViewGestureMixin {
80 81 82

  /// Creates a render object for an Android view.
  RenderAndroidView({
83 84 85
    required AndroidViewController viewController,
    required PlatformViewHitTestBehavior hitTestBehavior,
    required Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
86
    Clip clipBehavior = Clip.hardEdge,
87
  }) : assert(viewController != null),
88
       assert(hitTestBehavior != null),
89
       assert(gestureRecognizers != null),
90 91 92
       assert(clipBehavior != null),
       _viewController = viewController,
       _clipBehavior = clipBehavior {
93
    _viewController.pointTransformer = (Offset offset) => globalToLocal(offset);
94
    updateGestureRecognizers(gestureRecognizers);
95
    _viewController.addOnPlatformViewCreatedListener(_onPlatformViewCreated);
96
    this.hitTestBehavior = hitTestBehavior;
97
  }
98 99 100 101 102 103 104 105 106 107 108

  _PlatformViewState _state = _PlatformViewState.uninitialized;

  /// The Android view controller for the Android view associated with this render object.
  AndroidViewController get viewcontroller => _viewController;
  AndroidViewController _viewController;
  /// Sets a new Android view controller.
  ///
  /// `viewController` must not be null.
  set viewController(AndroidViewController viewController) {
    assert(_viewController != null);
109
    assert(viewController != null);
110 111
    if (_viewController == viewController)
      return;
112
    _viewController.removeOnPlatformViewCreatedListener(_onPlatformViewCreated);
113 114
    _viewController = viewController;
    _sizePlatformView();
115 116 117 118 119 120
    if (_viewController.isCreated) {
      markNeedsSemanticsUpdate();
    }
    _viewController.addOnPlatformViewCreatedListener(_onPlatformViewCreated);
  }

121
  /// {@macro flutter.material.Material.clipBehavior}
122 123 124 125 126 127 128 129 130 131 132 133 134
  ///
  /// 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();
    }
  }

135 136
  void _onPlatformViewCreated(int id) {
    markNeedsSemanticsUpdate();
137 138
  }

139
  /// {@template flutter.rendering.RenderAndroidView.updateGestureRecognizers}
140
  /// Updates which gestures should be forwarded to the platform view.
141
  ///
142 143
  /// 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
144 145
  /// gesture arena, the entire pointer event sequence starting from the pointer down event
  /// will be dispatched to the Android view.
146 147 148 149 150
  ///
  /// 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.
151
  /// {@endtemplate}
152 153 154 155
  ///
  /// Any active gesture arena the Android view participates in is rejected when the
  /// set of gesture recognizers is changed.
  void updateGestureRecognizers(Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers) {
156
    _updateGestureRecognizersWithCallBack(gestureRecognizers, _viewController.dispatchPointerEvent);
157 158
  }

159 160 161 162 163 164 165 166 167
  @override
  bool get sizedByParent => true;

  @override
  bool get alwaysNeedsCompositing => true;

  @override
  bool get isRepaintBoundary => true;

168 169 170 171 172
  @override
  Size computeDryLayout(BoxConstraints constraints) {
    return constraints.biggest;
  }

173 174
  @override
  void performResize() {
175
    super.performResize();
176 177 178
    _sizePlatformView();
  }

179
  late Size _currentAndroidViewSize;
180

181
  Future<void> _sizePlatformView() async {
182 183 184 185
    // 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).
    if (_state == _PlatformViewState.resizing || size.isEmpty) {
186 187 188 189
      return;
    }

    _state = _PlatformViewState.resizing;
190
    markNeedsPaint();
191 192 193 194

    Size targetSize;
    do {
      targetSize = size;
195 196
      await _viewController.setSize(targetSize);
      _currentAndroidViewSize = targetSize;
197 198 199 200 201 202 203 204 205 206 207 208 209 210
      // 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();
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    if (_viewController.textureId == null)
      return;

211 212
    // Clip the texture if it's going to paint out of the bounds of the renter box
    // (see comment in _paintTexture for an explanation of when this happens).
213
    if ((size.width < _currentAndroidViewSize.width || size.height < _currentAndroidViewSize.height) && clipBehavior != Clip.none) {
214 215
      _clipRectLayer = context.pushClipRect(true, offset, offset & size, _paintTexture, clipBehavior: clipBehavior,
          oldLayer: _clipRectLayer);
216 217
      return;
    }
218
    _clipRectLayer = null;
219 220 221
    _paintTexture(context, offset);
  }

222 223
  ClipRectLayer? _clipRectLayer;

224 225 226 227 228 229 230 231 232 233
  void _paintTexture(PaintingContext context, Offset offset) {
    // 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 we freeze the texture frame, until
    // we know that a frame with the new size is in the buffer.
    // This guarantees that the size of the texture frame we're painting is always
    // _currentAndroidViewSize.
234
    context.addLayer(TextureLayer(
235
      rect: offset & _currentAndroidViewSize,
236
      textureId: _viewController.textureId!,
237
      freeze: _state == _PlatformViewState.resizing,
238 239
    ));
  }
240

241 242 243 244 245 246 247
  @override
  void describeSemanticsConfiguration (SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);

    config.isSemanticBoundary = true;

    if (_viewController.isCreated) {
248
      config.platformViewId = _viewController.viewId;
249 250
    }
  }
251 252
}

253 254
/// A render object for an iOS UIKit UIView.
///
255
/// {@template flutter.rendering.RenderUiKitView}
256
/// Embedding UIViews is still preview-quality. To enable the preview for an iOS app add a boolean
257 258
/// 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
259
/// [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)
260
/// {@endtemplate}
261 262 263 264 265 266
///
/// [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.
///
267
/// {@macro flutter.rendering.RenderAndroidView.layout}
268
///
269
/// {@macro flutter.rendering.RenderAndroidView.gestures}
270
///
271
/// See also:
272
///
273 274 275 276 277
///  * [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.
  ///
278
  /// The `viewId`, `hitTestBehavior`, and `gestureRecognizers` parameters must not be null.
279
  RenderUiKitView({
280 281 282
    required UiKitViewController viewController,
    required this.hitTestBehavior,
    required Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
283
  }) : assert(viewController != null),
284
       assert(hitTestBehavior != null),
285 286 287 288
       assert(gestureRecognizers != null),
       _viewController = viewController {
    updateGestureRecognizers(gestureRecognizers);
  }
289 290 291 292 293 294


  /// 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].
295 296
  UiKitViewController get viewController => _viewController;
  UiKitViewController _viewController;
297 298
  set viewController(UiKitViewController viewController) {
    assert(viewController != null);
299
    final bool needsSemanticsUpdate = _viewController.id != viewController.id;
300
    _viewController = viewController;
301
    markNeedsPaint();
302 303 304
    if (needsSemanticsUpdate) {
      markNeedsSemanticsUpdate();
    }
305 306 307 308 309 310 311
  }

  /// 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;

312
  /// {@macro flutter.rendering.RenderAndroidView.updateGestureRecognizers}
313 314 315 316 317 318 319 320 321 322 323 324 325
  void updateGestureRecognizers(Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers) {
    assert(gestureRecognizers != null);
    assert(
    _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.',);
    if (_factoryTypesSetEquals(gestureRecognizers, _gestureRecognizer?.gestureRecognizerFactories)) {
      return;
    }
    _gestureRecognizer?.dispose();
    _gestureRecognizer = _UiKitViewGestureRecognizer(viewController, gestureRecognizers);
  }

326 327 328 329 330 331 332 333 334
  @override
  bool get sizedByParent => true;

  @override
  bool get alwaysNeedsCompositing => true;

  @override
  bool get isRepaintBoundary => true;

335
  _UiKitViewGestureRecognizer? _gestureRecognizer;
336

337
  PointerEvent? _lastPointerDownEvent;
338

339
  @override
340 341
  Size computeDryLayout(BoxConstraints constraints) {
    return constraints.biggest;
342 343 344 345 346 347
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    context.addLayer(PlatformViewLayer(
      rect: offset & size,
348
      viewId: _viewController.id,
349 350 351 352
    ));
  }

  @override
353 354
  bool hitTest(BoxHitTestResult result, { Offset? position }) {
    if (hitTestBehavior == PlatformViewHitTestBehavior.transparent || !size.contains(position!))
355 356 357 358 359 360 361
      return false;
    result.add(BoxHitTestEntry(this, position));
    return hitTestBehavior == PlatformViewHitTestBehavior.opaque;
  }

  @override
  bool hitTestSelf(Offset position) => hitTestBehavior != PlatformViewHitTestBehavior.transparent;
362 363 364

  @override
  void handleEvent(PointerEvent event, HitTestEntry entry) {
365 366 367
    if (event is! PointerDownEvent) {
      return;
    }
368
    _gestureRecognizer!.addPointer(event);
369
    _lastPointerDownEvent = event.original ?? event;
370 371 372 373 374 375 376
  }

  // This is registered as a global PointerRoute while the render object is attached.
  void _handleGlobalPointerEvent(PointerEvent event) {
    if (event is! PointerDownEvent) {
      return;
    }
377
    if (!(Offset.zero & size).contains(globalToLocal(event.position))) {
378 379
      return;
    }
380
    if ((event.original ?? event) != _lastPointerDownEvent) {
381 382 383 384 385
      // 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();
386
    }
387 388 389
    _lastPointerDownEvent = null;
  }

390 391 392 393 394 395 396
  @override
  void describeSemanticsConfiguration (SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
    config.isSemanticBoundary = true;
    config.platformViewId = _viewController.id;
  }

397 398 399
  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
400
    GestureBinding.instance!.pointerRouter.addGlobalRoute(_handleGlobalPointerEvent);
401 402 403 404
  }

  @override
  void detach() {
405 406
    GestureBinding.instance!.pointerRouter.removeGlobalRoute(_handleGlobalPointerEvent);
    _gestureRecognizer!.reset();
407 408 409 410 411 412 413 414 415 416
    super.detach();
  }
}

// This recognizer constructs gesture recognizers from a set of gesture recognizer factories
// it was give, adds all of them to a gesture arena team with the _UiKitViewGesturrRecognizer
// 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 {
417 418 419
  _UiKitViewGestureRecognizer(
    this.controller,
    this.gestureRecognizerFactories, {
420
    PointerDeviceKind? kind,
421
  }) : super(kind: kind) {
422 423
    team = GestureArenaTeam()
      ..captain = this;
424 425
    _gestureRecognizers = gestureRecognizerFactories.map(
      (Factory<OneSequenceGestureRecognizer> recognizerFactory) {
426 427 428 429 430 431 432 433 434 435 436 437 438
        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;
439 440 441 442 443 444 445 446 447
      },
    ).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;
448
  late Set<OneSequenceGestureRecognizer> _gestureRecognizers;
449 450 451 452

  final UiKitViewController controller;

  @override
453
  void addAllowedPointer(PointerDownEvent event) {
454
    startTrackingPointer(event.pointer, event.transform);
455
    for (final OneSequenceGestureRecognizer recognizer in _gestureRecognizers) {
456 457 458 459 460 461 462 463
      recognizer.addPointer(event);
    }
  }

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

  @override
464
  void didStopTrackingLastPointer(int pointer) { }
465 466 467 468 469 470 471 472 473 474 475 476 477

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

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

  @override
  void rejectGesture(int pointer) {
478
    controller.rejectGesture();
479 480 481 482 483
  }

  void reset() {
    resolve(GestureDisposition.rejected);
  }
484 485
}

486
typedef _HandlePointerEvent = Future<void> Function(PointerEvent event);
487

488
// This recognizer constructs gesture recognizers from a set of gesture recognizer factories
489
// it was give, adds all of them to a gesture arena team with the _PlatformViewGestureRecognizer
490
// as the team captain.
491 492 493 494 495 496
// 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,
497
    this.gestureRecognizerFactories, {
498
    PointerDeviceKind? kind,
499
  }) : super(kind: kind) {
500 501
    team = GestureArenaTeam()
      ..captain = this;
502
    _gestureRecognizers = gestureRecognizerFactories.map(
503
      (Factory<OneSequenceGestureRecognizer> recognizerFactory) {
504 505 506 507 508 509 510 511 512 513 514 515 516
        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;
517
      },
518
    ).toSet();
519
    _handlePointerEvent = handlePointerEvent;
520 521
  }

522
  late _HandlePointerEvent _handlePointerEvent;
523 524 525

  // 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
526
  // the cached events are dispatched to `_handlePointerEvent`, if we lose the arena we clear the cache for
527
  // the pointer.
528
  final Map<int, List<PointerEvent>> cachedEvents = <int, List<PointerEvent>>{};
529 530

  // Pointer for which we have already won the arena, events for pointers in this set are
531
  // immediately dispatched to `_handlePointerEvent`.
532
  final Set<int> forwardedPointers = <int>{};
533 534 535 536

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

  @override
541
  void addAllowedPointer(PointerDownEvent event) {
542
    startTrackingPointer(event.pointer, event.transform);
543
    for (final OneSequenceGestureRecognizer recognizer in _gestureRecognizers) {
544 545 546 547 548
      recognizer.addPointer(event);
    }
  }

  @override
549
  String get debugDescription => 'Platform view';
550 551

  @override
552
  void didStopTrackingLastPointer(int pointer) { }
553 554 555 556

  @override
  void handleEvent(PointerEvent event) {
    if (!forwardedPointers.contains(event.pointer)) {
557
      _cacheEvent(event);
558
    } else {
559
      _handlePointerEvent(event);
560 561 562 563 564 565
    }
    stopTrackingIfPointerNoLongerDown(event);
  }

  @override
  void acceptGesture(int pointer) {
566
    _flushPointerCache(pointer);
567 568 569 570 571 572 573 574 575
    forwardedPointers.add(pointer);
  }

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

576
  void _cacheEvent(PointerEvent event) {
577 578 579
    if (!cachedEvents.containsKey(event.pointer)) {
      cachedEvents[event.pointer] = <PointerEvent> [];
    }
580
    cachedEvents[event.pointer]!.add(event);
581 582
  }

583 584
  void _flushPointerCache(int pointer) {
    cachedEvents.remove(pointer)?.forEach(_handlePointerEvent);
585 586 587 588 589 590 591 592 593 594 595 596 597 598
  }

  @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);
599 600 601
  }
}

602 603
/// A render object for embedding a platform view.
///
604 605 606
/// [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 {
607 608 609 610 611

  /// Creating a render object for a [PlatformViewSurface].
  ///
  /// The `controller` parameter must not be null.
  PlatformViewRenderBox({
612 613 614
    required PlatformViewController controller,
    required PlatformViewHitTestBehavior hitTestBehavior,
    required Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
615 616 617 618
  }) :  assert(controller != null && controller.viewId != null && controller.viewId > -1),
        assert(hitTestBehavior != null),
        assert(gestureRecognizers != null),
        _controller = controller {
619 620 621
    this.hitTestBehavior = hitTestBehavior;
    updateGestureRecognizers(gestureRecognizers);
  }
622 623 624 625 626 627 628 629 630 631 632 633

  /// Sets the [controller] for this render object.
  ///
  /// This value must not be null, and setting it to a new value will result in a repaint.
  set controller(PlatformViewController controller) {
    assert(controller != null);
    assert(controller.viewId != null && controller.viewId > -1);

    if ( _controller == controller) {
      return;
    }
    final bool needsSemanticsUpdate = _controller.viewId != controller.viewId;
634 635
    _controller = controller;
    markNeedsPaint();
636 637 638 639 640
    if (needsSemanticsUpdate) {
      markNeedsSemanticsUpdate();
    }
  }

641
  /// {@macro  flutter.rendering.RenderAndroidView.updateGestureRecognizers}
642 643 644
  ///
  /// Any active gesture arena the `PlatformView` participates in is rejected when the
  /// set of gesture recognizers is changed.
645 646
  void updateGestureRecognizers(Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers) {
    _updateGestureRecognizersWithCallBack(gestureRecognizers, _controller.dispatchPointerEvent);
647 648
  }

649 650 651 652 653 654 655 656 657 658 659 660
  PlatformViewController _controller;

  @override
  bool get sizedByParent => true;

  @override
  bool get alwaysNeedsCompositing => true;

  @override
  bool get isRepaintBoundary => true;

  @override
661 662
  Size computeDryLayout(BoxConstraints constraints) {
    return constraints.biggest;
663 664 665 666 667 668
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    assert(_controller.viewId != null);
    context.addLayer(PlatformViewLayer(
669 670 671
      rect: offset & size,
      viewId: _controller.viewId,
    ));
672 673 674 675 676 677 678 679 680 681
  }

  @override
  void describeSemanticsConfiguration (SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
    assert(_controller.viewId != null);
    config.isSemanticBoundary = true;
    config.platformViewId = _controller.viewId;
  }
}
682 683

/// The Mixin handling the pointer events and gestures of a platform view render box.
684
mixin _PlatformViewGestureMixin on RenderBox implements MouseTrackerAnnotation {
685 686

  /// How to behave during hit testing.
687 688 689 690 691
  // Changing _hitTestBehavior might affect which objects are considered hovered over.
  set hitTestBehavior(PlatformViewHitTestBehavior value) {
    if (value != _hitTestBehavior) {
      _hitTestBehavior = value;
      if (owner != null)
692
        markNeedsPaint();
693 694
    }
  }
695
  PlatformViewHitTestBehavior? _hitTestBehavior;
696

697
  _HandlePointerEvent? _handlePointerEvent;
698

699
  /// {@macro  flutter.rendering.RenderAndroidView.updateGestureRecognizers}
700 701 702
  ///
  /// Any active gesture arena the `PlatformView` participates in is rejected when the
  /// set of gesture recognizers is changed.
703
  void _updateGestureRecognizersWithCallBack(Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers, _HandlePointerEvent handlePointerEvent) {
704 705 706 707 708 709 710 711 712
    assert(gestureRecognizers != null);
    assert(
    _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.',);
    if (_factoryTypesSetEquals(gestureRecognizers, _gestureRecognizer?.gestureRecognizerFactories)) {
      return;
    }
    _gestureRecognizer?.dispose();
713
    _gestureRecognizer = _PlatformViewGestureRecognizer(handlePointerEvent, gestureRecognizers);
714
    _handlePointerEvent = handlePointerEvent;
715 716
  }

717
  _PlatformViewGestureRecognizer? _gestureRecognizer;
718 719

  @override
720
  bool hitTest(BoxHitTestResult result, { required Offset position }) {
721
    if (_hitTestBehavior == PlatformViewHitTestBehavior.transparent || !size.contains(position)) {
722 723 724
      return false;
    }
    result.add(BoxHitTestEntry(this, position));
725
    return _hitTestBehavior == PlatformViewHitTestBehavior.opaque;
726 727 728
  }

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

731
  @override
732
  PointerEnterEventListener? get onEnter => null;
733 734

  @override
735
  PointerExitEventListener? get onExit => null;
736 737 738 739

  @override
  MouseCursor get cursor => MouseCursor.uncontrolled;

740 741 742
  @override
  bool get validForMouseTracker => true;

743 744 745
  @override
  void handleEvent(PointerEvent event, HitTestEntry entry) {
    if (event is PointerDownEvent) {
746
      _gestureRecognizer!.addPointer(event);
747
    }
748 749 750
    if (event is PointerHoverEvent) {
      _handlePointerEvent?.call(event);
    }
751 752 753 754
  }

  @override
  void detach() {
755
    _gestureRecognizer!.reset();
756 757 758
    super.detach();
  }
}