platform_view.dart 27.5 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(_viewController != null);
113
    assert(controller != null);
114
    if (_viewController == controller) {
115
      return;
116
    }
117
    _viewController.removeOnPlatformViewCreatedListener(_onPlatformViewCreated);
118 119 120
    super.controller = controller;
    _viewController = controller;
    _viewController.pointTransformer = (Offset offset) => globalToLocal(offset);
121
    _sizePlatformView();
122 123 124 125 126 127
    if (_viewController.isCreated) {
      markNeedsSemanticsUpdate();
    }
    _viewController.addOnPlatformViewCreatedListener(_onPlatformViewCreated);
  }

128
  /// {@macro flutter.material.Material.clipBehavior}
129 130 131 132 133 134 135 136 137 138 139 140 141
  ///
  /// 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();
    }
  }

142 143
  void _onPlatformViewCreated(int id) {
    markNeedsSemanticsUpdate();
144 145 146 147 148 149 150 151 152 153 154
  }

  @override
  bool get sizedByParent => true;

  @override
  bool get alwaysNeedsCompositing => true;

  @override
  bool get isRepaintBoundary => true;

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

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

166
  Future<void> _sizePlatformView() async {
167 168 169
    // 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).
170
    if (_state == _PlatformViewState.resizing || size.isEmpty) {
171
      return;
172
    }
173 174

    _state = _PlatformViewState.resizing;
175
    markNeedsPaint();
176 177 178 179

    Size targetSize;
    do {
      targetSize = size;
180 181 182 183 184 185
      if (_viewController.isCreated) {
        _currentTextureSize = await _viewController.setSize(targetSize);
      } else {
        await _viewController.create(size: targetSize);
        _currentTextureSize = targetSize;
      }
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 196 197 198 199 200 201 202 203 204
  // Sets the offset of the underlaying platform view on the platform side.
  //
  // 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 251 252
    _clipRectLayer.layer = null;
    super.dispose();
  }
253

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

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

265
  @override
266 267 268 269
  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.
270 271 272
    config.isSemanticBoundary = true;

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

278 279
/// A render object for an iOS UIKit UIView.
///
280
/// {@template flutter.rendering.RenderUiKitView}
281
/// Embedding UIViews is still preview-quality. To enable the preview for an iOS app add a boolean
282 283
/// 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
284
/// [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)
285
/// {@endtemplate}
286 287 288 289 290 291
///
/// [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.
///
292
/// {@macro flutter.rendering.RenderAndroidView.layout}
293
///
294
/// {@macro flutter.rendering.RenderAndroidView.gestures}
295
///
296
/// See also:
297
///
298 299 300 301 302
///  * [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.
  ///
303
  /// The `viewId`, `hitTestBehavior`, and `gestureRecognizers` parameters must not be null.
304
  RenderUiKitView({
305 306 307
    required UiKitViewController viewController,
    required this.hitTestBehavior,
    required Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
308
  }) : assert(viewController != null),
309
       assert(hitTestBehavior != null),
310 311 312 313
       assert(gestureRecognizers != null),
       _viewController = viewController {
    updateGestureRecognizers(gestureRecognizers);
  }
314 315 316 317 318 319


  /// 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].
320 321
  UiKitViewController get viewController => _viewController;
  UiKitViewController _viewController;
322 323
  set viewController(UiKitViewController viewController) {
    assert(viewController != null);
324
    final bool needsSemanticsUpdate = _viewController.id != viewController.id;
325
    _viewController = viewController;
326
    markNeedsPaint();
327 328 329
    if (needsSemanticsUpdate) {
      markNeedsSemanticsUpdate();
    }
330 331 332 333 334 335 336
  }

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

337
  /// {@macro flutter.rendering.PlatformViewRenderBox.updateGestureRecognizers}
338 339 340
  void updateGestureRecognizers(Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers) {
    assert(gestureRecognizers != null);
    assert(
341 342 343 344
      _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.',
    );
345 346 347 348 349 350 351
    if (_factoryTypesSetEquals(gestureRecognizers, _gestureRecognizer?.gestureRecognizerFactories)) {
      return;
    }
    _gestureRecognizer?.dispose();
    _gestureRecognizer = _UiKitViewGestureRecognizer(viewController, gestureRecognizers);
  }

352 353 354 355 356 357 358 359 360
  @override
  bool get sizedByParent => true;

  @override
  bool get alwaysNeedsCompositing => true;

  @override
  bool get isRepaintBoundary => true;

361
  _UiKitViewGestureRecognizer? _gestureRecognizer;
362

363
  PointerEvent? _lastPointerDownEvent;
364

365
  @override
366 367
  Size computeDryLayout(BoxConstraints constraints) {
    return constraints.biggest;
368 369 370 371 372 373
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    context.addLayer(PlatformViewLayer(
      rect: offset & size,
374
      viewId: _viewController.id,
375 376 377 378
    ));
  }

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

  @override
  bool hitTestSelf(Offset position) => hitTestBehavior != PlatformViewHitTestBehavior.transparent;
389 390 391

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

  // This is registered as a global PointerRoute while the render object is attached.
  void _handleGlobalPointerEvent(PointerEvent event) {
    if (event is! PointerDownEvent) {
      return;
    }
404
    if (!(Offset.zero & size).contains(globalToLocal(event.position))) {
405 406
      return;
    }
407
    if ((event.original ?? event) != _lastPointerDownEvent) {
408 409 410 411 412
      // 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();
413
    }
414 415 416
    _lastPointerDownEvent = null;
  }

417 418 419 420 421 422 423
  @override
  void describeSemanticsConfiguration (SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
    config.isSemanticBoundary = true;
    config.platformViewId = _viewController.id;
  }

424 425 426
  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
427
    GestureBinding.instance.pointerRouter.addGlobalRoute(_handleGlobalPointerEvent);
428 429 430 431
  }

  @override
  void detach() {
432
    GestureBinding.instance.pointerRouter.removeGlobalRoute(_handleGlobalPointerEvent);
433
    _gestureRecognizer!.reset();
434 435 436 437 438
    super.detach();
  }
}

// This recognizer constructs gesture recognizers from a set of gesture recognizer factories
439
// it was give, adds all of them to a gesture arena team with the _UiKitViewGestureRecognizer
440 441 442 443
// 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 {
444 445
  _UiKitViewGestureRecognizer(
    this.controller,
446 447
    this.gestureRecognizerFactories
  ) {
448 449
    team = GestureArenaTeam()
      ..captain = this;
450 451
    _gestureRecognizers = gestureRecognizerFactories.map(
      (Factory<OneSequenceGestureRecognizer> recognizerFactory) {
452 453 454 455 456 457 458 459 460 461 462 463 464
        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;
465 466 467 468 469 470 471 472
      },
    ).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;
473
  late Set<OneSequenceGestureRecognizer> _gestureRecognizers;
474 475 476 477

  final UiKitViewController controller;

  @override
478
  void addAllowedPointer(PointerDownEvent event) {
479
    super.addAllowedPointer(event);
480
    for (final OneSequenceGestureRecognizer recognizer in _gestureRecognizers) {
481 482 483 484 485 486 487 488
      recognizer.addPointer(event);
    }
  }

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

  @override
489
  void didStopTrackingLastPointer(int pointer) { }
490 491 492 493 494 495 496 497 498 499 500 501 502

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

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

  @override
  void rejectGesture(int pointer) {
503
    controller.rejectGesture();
504 505 506 507 508
  }

  void reset() {
    resolve(GestureDisposition.rejected);
  }
509 510
}

511
typedef _HandlePointerEvent = Future<void> Function(PointerEvent event);
512

513
// This recognizer constructs gesture recognizers from a set of gesture recognizer factories
514
// it was give, adds all of them to a gesture arena team with the _PlatformViewGestureRecognizer
515
// as the team captain.
516 517 518 519 520 521
// 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,
522 523
    this.gestureRecognizerFactories
  ) {
524 525
    team = GestureArenaTeam()
      ..captain = this;
526
    _gestureRecognizers = gestureRecognizerFactories.map(
527
      (Factory<OneSequenceGestureRecognizer> recognizerFactory) {
528 529 530 531 532 533 534 535 536 537 538 539 540
        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;
541
      },
542
    ).toSet();
543
    _handlePointerEvent = handlePointerEvent;
544 545
  }

546
  late _HandlePointerEvent _handlePointerEvent;
547 548 549

  // 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
550
  // the cached events are dispatched to `_handlePointerEvent`, if we lose the arena we clear the cache for
551
  // the pointer.
552
  final Map<int, List<PointerEvent>> cachedEvents = <int, List<PointerEvent>>{};
553 554

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

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

  @override
565
  void addAllowedPointer(PointerDownEvent event) {
566
    super.addAllowedPointer(event);
567
    for (final OneSequenceGestureRecognizer recognizer in _gestureRecognizers) {
568 569 570 571 572
      recognizer.addPointer(event);
    }
  }

  @override
573
  String get debugDescription => 'Platform view';
574 575

  @override
576
  void didStopTrackingLastPointer(int pointer) { }
577 578 579 580

  @override
  void handleEvent(PointerEvent event) {
    if (!forwardedPointers.contains(event.pointer)) {
581
      _cacheEvent(event);
582
    } else {
583
      _handlePointerEvent(event);
584 585 586 587 588 589
    }
    stopTrackingIfPointerNoLongerDown(event);
  }

  @override
  void acceptGesture(int pointer) {
590
    _flushPointerCache(pointer);
591 592 593 594 595 596 597 598 599
    forwardedPointers.add(pointer);
  }

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

600
  void _cacheEvent(PointerEvent event) {
601 602 603
    if (!cachedEvents.containsKey(event.pointer)) {
      cachedEvents[event.pointer] = <PointerEvent> [];
    }
604
    cachedEvents[event.pointer]!.add(event);
605 606
  }

607 608
  void _flushPointerCache(int pointer) {
    cachedEvents.remove(pointer)?.forEach(_handlePointerEvent);
609 610 611 612 613 614 615 616 617 618 619 620 621 622
  }

  @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);
623 624 625
  }
}

626 627
/// A render object for embedding a platform view.
///
628 629 630
/// [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 {
631 632 633 634
  /// Creating a render object for a [PlatformViewSurface].
  ///
  /// The `controller` parameter must not be null.
  PlatformViewRenderBox({
635 636 637
    required PlatformViewController controller,
    required PlatformViewHitTestBehavior hitTestBehavior,
    required Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
638 639 640 641
  }) :  assert(controller != null && controller.viewId != null && controller.viewId > -1),
        assert(hitTestBehavior != null),
        assert(gestureRecognizers != null),
        _controller = controller {
642 643 644
    this.hitTestBehavior = hitTestBehavior;
    updateGestureRecognizers(gestureRecognizers);
  }
645

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

654
    if (_controller == controller) {
655 656 657
      return;
    }
    final bool needsSemanticsUpdate = _controller.viewId != controller.viewId;
658 659
    _controller = controller;
    markNeedsPaint();
660 661 662 663 664
    if (needsSemanticsUpdate) {
      markNeedsSemanticsUpdate();
    }
  }

665 666 667 668 669 670 671 672 673 674 675 676 677
  /// {@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}
678 679 680
  ///
  /// Any active gesture arena the `PlatformView` participates in is rejected when the
  /// set of gesture recognizers is changed.
681 682
  void updateGestureRecognizers(Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers) {
    _updateGestureRecognizersWithCallBack(gestureRecognizers, _controller.dispatchPointerEvent);
683 684
  }

685 686 687 688 689 690 691 692 693 694
  @override
  bool get sizedByParent => true;

  @override
  bool get alwaysNeedsCompositing => true;

  @override
  bool get isRepaintBoundary => true;

  @override
695 696
  Size computeDryLayout(BoxConstraints constraints) {
    return constraints.biggest;
697 698 699 700 701 702
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    assert(_controller.viewId != null);
    context.addLayer(PlatformViewLayer(
703 704 705
      rect: offset & size,
      viewId: _controller.viewId,
    ));
706 707 708
  }

  @override
709
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
710 711 712 713 714 715
    super.describeSemanticsConfiguration(config);
    assert(_controller.viewId != null);
    config.isSemanticBoundary = true;
    config.platformViewId = _controller.viewId;
  }
}
716 717

/// The Mixin handling the pointer events and gestures of a platform view render box.
718
mixin _PlatformViewGestureMixin on RenderBox implements MouseTrackerAnnotation {
719 720

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

732
  _HandlePointerEvent? _handlePointerEvent;
733

734
  /// {@macro  flutter.rendering.RenderAndroidView.updateGestureRecognizers}
735 736 737
  ///
  /// Any active gesture arena the `PlatformView` participates in is rejected when the
  /// set of gesture recognizers is changed.
738
  void _updateGestureRecognizersWithCallBack(Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers, _HandlePointerEvent handlePointerEvent) {
739 740
    assert(gestureRecognizers != null);
    assert(
741 742 743 744
      _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.',
    );
745 746 747 748
    if (_factoryTypesSetEquals(gestureRecognizers, _gestureRecognizer?.gestureRecognizerFactories)) {
      return;
    }
    _gestureRecognizer?.dispose();
749
    _gestureRecognizer = _PlatformViewGestureRecognizer(handlePointerEvent, gestureRecognizers);
750
    _handlePointerEvent = handlePointerEvent;
751 752
  }

753
  _PlatformViewGestureRecognizer? _gestureRecognizer;
754 755

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

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

767
  @override
768
  PointerEnterEventListener? get onEnter => null;
769 770

  @override
771
  PointerExitEventListener? get onExit => null;
772 773 774 775

  @override
  MouseCursor get cursor => MouseCursor.uncontrolled;

776 777 778
  @override
  bool get validForMouseTracker => true;

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

  @override
  void detach() {
791
    _gestureRecognizer!.reset();
792 793 794
    super.detach();
  }
}