Flutter iOS Embedder
FlutterViewController.mm
Go to the documentation of this file.
1 // Copyright 2013 The Flutter Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #define FML_USED_ON_EMBEDDER
6 
8 
9 #import <os/log.h>
10 #include <memory>
11 
12 #include "flutter/common/constants.h"
13 #include "flutter/fml/memory/weak_ptr.h"
14 #include "flutter/fml/message_loop.h"
15 #include "flutter/fml/platform/darwin/platform_version.h"
16 #include "flutter/runtime/ptrace_check.h"
17 #include "flutter/shell/common/thread_host.h"
18 #import "flutter/shell/platform/darwin/common/InternalFlutterSwiftCommon/InternalFlutterSwiftCommon.h"
38 #import "flutter/shell/platform/embedder/embedder.h"
39 #import "flutter/third_party/spring_animation/spring_animation.h"
40 
42 
43 static constexpr int kMicrosecondsPerSecond = 1000 * 1000;
44 static constexpr CGFloat kScrollViewContentSize = 2.0;
45 
46 static NSString* const kFlutterRestorationStateAppData = @"FlutterRestorationStateAppData";
47 
48 NSNotificationName const FlutterSemanticsUpdateNotification = @"FlutterSemanticsUpdate";
49 NSNotificationName const FlutterViewControllerWillDealloc = @"FlutterViewControllerWillDealloc";
50 NSNotificationName const FlutterViewControllerHideHomeIndicator =
51  @"FlutterViewControllerHideHomeIndicator";
52 NSNotificationName const FlutterViewControllerShowHomeIndicator =
53  @"FlutterViewControllerShowHomeIndicator";
54 
55 // Struct holding data to help adapt system mouse/trackpad events to embedder events.
56 typedef struct MouseState {
57  // Current coordinate of the mouse cursor in physical device pixels.
58  CGPoint location = CGPointZero;
59 
60  // Last reported translation for an in-flight pan gesture in physical device pixels.
61  CGPoint last_translation = CGPointZero;
63 
64 // This is left a FlutterBinaryMessenger privately for now to give people a chance to notice the
65 // change. Unfortunately unless you have Werror turned on, incompatible pointers as arguments are
66 // just a warning.
68  UIScrollViewDelegate,
69  FlutterKeyboardInsetManagerDelegate>
70 // TODO(dkwingsmt): Make the view ID property public once the iOS shell
71 // supports multiple views.
72 // https://github.com/flutter/flutter/issues/138168
73 @property(nonatomic, readonly) int64_t viewIdentifier;
74 
75 // We keep a separate reference to this and create it ahead of time because we want to be able to
76 // set up a shell along with its platform view before the view has to appear.
77 @property(nonatomic, strong) FlutterView* flutterView;
78 @property(nonatomic, strong) void (^flutterViewRenderedCallback)(void);
79 
80 @property(nonatomic, strong) FlutterSplashScreenManager* splashScreenManager;
81 
82 @property(nonatomic, assign) UIInterfaceOrientationMask orientationPreferences;
83 @property(nonatomic, assign) UIStatusBarStyle statusBarStyle;
84 @property(nonatomic, assign) BOOL initialized;
85 @property(nonatomic, assign) BOOL engineNeedsLaunch;
86 @property(nonatomic, assign) BOOL awokenFromNib;
87 
88 @property(nonatomic, readwrite, getter=isDisplayingFlutterUI) BOOL displayingFlutterUI;
89 @property(nonatomic, assign) BOOL isHomeIndicatorHidden;
90 @property(nonatomic, assign) BOOL isPresentingViewControllerAnimating;
91 
92 // Internal state backing override of UIView.prefersStatusBarHidden.
93 @property(nonatomic, assign) BOOL flutterPrefersStatusBarHidden;
94 
95 @property(nonatomic, strong) NSMutableSet<NSNumber*>* ongoingTouches;
96 // This scroll view is a workaround to accommodate iOS 13 and higher. There isn't a way to get
97 // touches on the status bar to trigger scrolling to the top of a scroll view. We place a
98 // UIScrollView with height zero and a content offset so we can get those events. See also:
99 // https://github.com/flutter/flutter/issues/35050
100 @property(nonatomic, strong) UIScrollView* scrollView;
101 
102 /**
103  * Whether we should ignore viewport metrics updates during rotation transition.
104  */
105 @property(nonatomic, assign) BOOL shouldIgnoreViewportMetricsUpdatesDuringRotation;
106 /**
107  * Keyboard animation properties
108  */
109 
110 /// Timestamp after which a scroll inertia cancel event should be inferred.
111 @property(nonatomic, assign) NSTimeInterval scrollInertiaEventStartline;
112 
113 /// When an iOS app is running in emulation on an Apple Silicon Mac, trackpad input goes through
114 /// a translation layer, and events are not received with precise deltas. Due to this, we can't
115 /// rely on checking for a stationary trackpad event. Fortunately, AppKit will send an event of
116 /// type UIEventTypeScroll following a scroll when inertia should stop. This field is needed to
117 /// estimate if such an event represents the natural end of scrolling inertia or a user-initiated
118 /// cancellation.
119 @property(nonatomic, assign) NSTimeInterval scrollInertiaEventAppKitDeadline;
120 
121 /// The size of the FlutterView's frame, as determined by auto-layout,
122 /// before Flutter's custom auto-resizing constraints are applied.
123 @property(nonatomic, assign) CGSize sizeBeforeAutoResized;
124 
125 /*
126  * Mouse and trackpad gesture recognizers
127  */
128 // Mouse and trackpad hover
129 @property(nonatomic, strong)
130  UIHoverGestureRecognizer* hoverGestureRecognizer API_AVAILABLE(ios(13.4));
131 // Mouse wheel scrolling
132 @property(nonatomic, strong)
133  UIPanGestureRecognizer* discreteScrollingPanGestureRecognizer API_AVAILABLE(ios(13.4));
134 // Trackpad and Magic Mouse scrolling
135 @property(nonatomic, strong)
136  UIPanGestureRecognizer* continuousScrollingPanGestureRecognizer API_AVAILABLE(ios(13.4));
137 // Trackpad pinching
138 @property(nonatomic, strong)
139  UIPinchGestureRecognizer* pinchGestureRecognizer API_AVAILABLE(ios(13.4));
140 // Trackpad rotating
141 @property(nonatomic, strong)
142  UIRotationGestureRecognizer* rotationGestureRecognizer API_AVAILABLE(ios(13.4));
143 
144 /// Creates and registers plugins used by this view controller.
145 - (void)addInternalPlugins;
146 - (void)deregisterNotifications;
147 
148 /// Called when the first frame has been rendered. Invokes any registered first-frame callback.
149 - (void)onFirstFrameRendered;
150 
151 /// Handles updating viewport metrics on keyboard animation.
152 
153 @end
154 
155 @implementation FlutterViewController {
156  flutter::ViewportMetrics _viewportMetrics;
158  FlutterSplashScreenManager* _splashScreenManager;
159 }
160 
161 // Synthesize properties with an overridden getter/setter.
162 @synthesize viewOpaque = _viewOpaque;
163 @synthesize displayingFlutterUI = _displayingFlutterUI;
164 
165 - (FlutterSplashScreenManager*)splashScreenManager {
166  if (!_splashScreenManager) {
167  _splashScreenManager = [[FlutterSplashScreenManager alloc] init];
168  }
169  return _splashScreenManager;
170 }
171 
172 // TODO(dkwingsmt): https://github.com/flutter/flutter/issues/138168
173 // No backing ivar is currently required; when multiple views are supported, we'll need to
174 // synthesize the ivar and store the view identifier.
175 @dynamic viewIdentifier;
176 
177 #pragma mark - Manage and override all designated initializers
178 
179 - (instancetype)initWithEngine:(FlutterEngine*)engine
180  nibName:(nullable NSString*)nibName
181  bundle:(nullable NSBundle*)nibBundle {
182  FML_CHECK(engine) << "initWithEngine:nibName:bundle: must be called with non-nil engine";
183  self = [super initWithNibName:nibName bundle:nibBundle];
184  if (self) {
185  _viewOpaque = YES;
186  if (engine.viewController) {
187  NSString* errorMessage =
188  [NSString stringWithFormat:
189  @"The supplied FlutterEngine %@ is already used with FlutterViewController "
190  "instance %@. One instance of the FlutterEngine can only be attached to "
191  "one FlutterViewController at a time. Set FlutterEngine.viewController to "
192  "nil before attaching it to another FlutterViewController.",
193  engine.description, engine.viewController.description];
194  [FlutterLogger logError:errorMessage];
195  }
196  _engine = engine;
197  _engineNeedsLaunch = NO;
198  _flutterView = [[FlutterView alloc] initWithDelegate:_engine
199  opaque:self.isViewOpaque
200  enableWideGamut:engine.project.isWideGamutEnabled];
201  _ongoingTouches = [[NSMutableSet alloc] init];
202 
203  // TODO(cbracken): https://github.com/flutter/flutter/issues/157140
204  // Eliminate method calls in initializers and dealloc.
205  [self performCommonViewControllerInitialization];
206  [engine setViewController:self];
207  }
208 
209  return self;
210 }
211 
212 - (instancetype)initWithProject:(FlutterDartProject*)project
213  nibName:(NSString*)nibName
214  bundle:(NSBundle*)nibBundle {
215  self = [super initWithNibName:nibName bundle:nibBundle];
216  if (self) {
217  // TODO(cbracken): https://github.com/flutter/flutter/issues/157140
218  // Eliminate method calls in initializers and dealloc.
219  [self sharedSetupWithProject:project initialRoute:nil];
220  }
221 
222  return self;
223 }
224 
225 - (instancetype)initWithProject:(FlutterDartProject*)project
226  initialRoute:(NSString*)initialRoute
227  nibName:(NSString*)nibName
228  bundle:(NSBundle*)nibBundle {
229  self = [super initWithNibName:nibName bundle:nibBundle];
230  if (self) {
231  // TODO(cbracken): https://github.com/flutter/flutter/issues/157140
232  // Eliminate method calls in initializers and dealloc.
233  [self sharedSetupWithProject:project initialRoute:initialRoute];
234  }
235 
236  return self;
237 }
238 
239 - (instancetype)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil {
240  return [self initWithProject:nil nibName:nil bundle:nil];
241 }
242 
243 - (instancetype)initWithCoder:(NSCoder*)aDecoder {
244  self = [super initWithCoder:aDecoder];
245  return self;
246 }
247 
248 - (void)awakeFromNib {
249  [super awakeFromNib];
250  self.awokenFromNib = YES;
251  if (!self.engine) {
252  [self sharedSetupWithProject:nil initialRoute:nil];
253  }
254 }
255 
256 - (instancetype)init {
257  return [self initWithProject:nil nibName:nil bundle:nil];
258 }
259 
260 - (void)sharedSetupWithProject:(nullable FlutterDartProject*)project
261  initialRoute:(nullable NSString*)initialRoute {
262  id appDelegate = FlutterSharedApplication.application.delegate;
264  if ([appDelegate respondsToSelector:@selector(takeLaunchEngine)]) {
265  if (self.nibName) {
266  // Only grab the launch engine if it was created with a nib.
267  // FlutterViewControllers created from nibs can't specify their initial
268  // routes so it's safe to take it.
269  engine = [appDelegate takeLaunchEngine];
270  } else {
271  // If we registered plugins with a FlutterAppDelegate without a xib, throw
272  // away the engine that was registered through the FlutterAppDelegate.
273  // That's not a valid usage of the API.
274  [appDelegate takeLaunchEngine];
275  }
276  }
277  if (!engine) {
278  // Need the project to get settings for the view. Initializing it here means
279  // the Engine class won't initialize it later.
280  if (!project) {
281  project = [[FlutterDartProject alloc] init];
282  }
283 
284  engine = [[FlutterEngine alloc] initWithName:@"io.flutter"
285  project:project
286  allowHeadlessExecution:self.engineAllowHeadlessExecution
287  restorationEnabled:self.restorationIdentifier != nil];
288  }
289  if (!engine) {
290  return;
291  }
292 
293  _viewOpaque = YES;
294  _engine = engine;
295  _flutterView = [[FlutterView alloc] initWithDelegate:_engine
296  opaque:_viewOpaque
297  enableWideGamut:engine.project.isWideGamutEnabled];
298  [_engine createShell:nil libraryURI:nil initialRoute:initialRoute];
299 
300  // We call this from the FlutterViewController instead of the FlutterEngine directly because this
301  // is only needed when the FlutterEngine is implicit. If it's not implicit there's no need for
302  // them to have a callback to expose the engine since they created the FlutterEngine directly.
303  // This is the earliest this can be called because it depends on the shell being created.
304  BOOL performedCallback = [_engine performImplicitEngineCallback];
305 
306  // TODO(vashworth): Deprecate, see https://github.com/flutter/flutter/issues/176424
308  respondsToSelector:@selector(pluginRegistrant)]) {
309  NSObject<FlutterPluginRegistrant>* pluginRegistrant =
310  [FlutterSharedApplication.application.delegate performSelector:@selector(pluginRegistrant)];
311  [pluginRegistrant registerWithRegistry:self];
312  performedCallback = YES;
313  }
314  // When migrated to scenes, the FlutterViewController from the storyboard is initialized after the
315  // application launch events. Therefore, plugins may not be registered yet since they're expected
316  // to be registered during the implicit engine callbacks. As a workaround, send the app launch
317  // events after the application callbacks.
318  if (self.awokenFromNib && performedCallback && FlutterSharedApplication.hasSceneDelegate &&
319  [appDelegate isKindOfClass:[FlutterAppDelegate class]]) {
320  id applicationLifeCycleDelegate = ((FlutterAppDelegate*)appDelegate).lifeCycleDelegate;
321  [applicationLifeCycleDelegate
322  sceneFallbackWillFinishLaunchingApplication:FlutterSharedApplication.application];
323  [applicationLifeCycleDelegate
324  sceneFallbackDidFinishLaunchingApplication:FlutterSharedApplication.application];
325  }
326 
327  _engineNeedsLaunch = YES;
328  _ongoingTouches = [[NSMutableSet alloc] init];
329 
330  // TODO(cbracken): https://github.com/flutter/flutter/issues/157140
331  // Eliminate method calls in initializers and dealloc.
332  [self.splashScreenManager loadDefaultSplashScreenView];
333  [self performCommonViewControllerInitialization];
334 }
335 
336 - (BOOL)isViewOpaque {
337  return _viewOpaque;
338 }
339 
340 - (void)setViewOpaque:(BOOL)value {
341  _viewOpaque = value;
342  if (self.flutterView.layer.opaque != value) {
343  self.flutterView.layer.opaque = value;
344  [self.flutterView.layer setNeedsLayout];
345  }
346 }
347 
348 #pragma mark - Common view controller initialization tasks
349 
350 - (void)performCommonViewControllerInitialization {
351  if (_initialized) {
352  return;
353  }
354 
355  _initialized = YES;
356  _orientationPreferences = UIInterfaceOrientationMaskAll;
357  _statusBarStyle = UIStatusBarStyleDefault;
358 
359  _accessibilityFeatures = [[FlutterAccessibilityFeatures alloc] init];
360  _displayLinkManager = FlutterDisplayLinkManager.shared;
361  _keyboardInsetManager =
362  [[FlutterKeyboardInsetManager alloc] initWithDelegate:self
363  displayLinkManager:_displayLinkManager];
364 
365  // TODO(cbracken): https://github.com/flutter/flutter/issues/157140
366  // Eliminate method calls in initializers and dealloc.
367  [self setUpNotificationCenterObservers];
368 }
369 
370 - (void)setUpNotificationCenterObservers {
371  NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
372  [center addObserver:self
373  selector:@selector(onOrientationPreferencesUpdated:)
374  name:@(flutter::kOrientationUpdateNotificationName)
375  object:nil];
376 
377  [center addObserver:self
378  selector:@selector(onPreferredStatusBarStyleUpdated:)
379  name:@(flutter::kOverlayStyleUpdateNotificationName)
380  object:nil];
381 
383  [self setUpApplicationLifecycleNotifications:center];
384  } else {
385  [self setUpSceneLifecycleNotifications:center];
386  }
387 
388  [center addObserver:self
389  selector:@selector(keyboardWillChangeFrame:)
390  name:UIKeyboardWillChangeFrameNotification
391  object:nil];
392 
393  [center addObserver:self
394  selector:@selector(keyboardWillShowNotification:)
395  name:UIKeyboardWillShowNotification
396  object:nil];
397 
398  [center addObserver:self
399  selector:@selector(keyboardWillBeHidden:)
400  name:UIKeyboardWillHideNotification
401  object:nil];
402 
403  for (NSString* notification in [self.accessibilityFeatures observedNotificationNames]) {
404  [center addObserver:self
405  selector:@selector(onAccessibilityStatusChanged:)
406  name:notification
407  object:nil];
408  }
409 
410  [center addObserver:self
411  selector:@selector(onUserSettingsChanged:)
412  name:UIContentSizeCategoryDidChangeNotification
413  object:nil];
414 
415  [center addObserver:self
416  selector:@selector(onHideHomeIndicatorNotification:)
417  name:FlutterViewControllerHideHomeIndicator
418  object:nil];
419 
420  [center addObserver:self
421  selector:@selector(onShowHomeIndicatorNotification:)
422  name:FlutterViewControllerShowHomeIndicator
423  object:nil];
424 }
425 
426 - (void)setUpSceneLifecycleNotifications:(NSNotificationCenter*)center API_AVAILABLE(ios(13.0)) {
427  [center addObserver:self
428  selector:@selector(sceneBecameActive:)
429  name:UISceneDidActivateNotification
430  object:nil];
431 
432  [center addObserver:self
433  selector:@selector(sceneWillResignActive:)
434  name:UISceneWillDeactivateNotification
435  object:nil];
436 
437  [center addObserver:self
438  selector:@selector(sceneWillDisconnect:)
439  name:UISceneDidDisconnectNotification
440  object:nil];
441 
442  [center addObserver:self
443  selector:@selector(sceneDidEnterBackground:)
444  name:UISceneDidEnterBackgroundNotification
445  object:nil];
446 
447  [center addObserver:self
448  selector:@selector(sceneWillEnterForeground:)
449  name:UISceneWillEnterForegroundNotification
450  object:nil];
451 }
452 
453 - (void)setUpApplicationLifecycleNotifications:(NSNotificationCenter*)center {
454  [center addObserver:self
455  selector:@selector(applicationBecameActive:)
456  name:UIApplicationDidBecomeActiveNotification
457  object:nil];
458 
459  [center addObserver:self
460  selector:@selector(applicationWillResignActive:)
461  name:UIApplicationWillResignActiveNotification
462  object:nil];
463 
464  [center addObserver:self
465  selector:@selector(applicationWillTerminate:)
466  name:UIApplicationWillTerminateNotification
467  object:nil];
468 
469  [center addObserver:self
470  selector:@selector(applicationDidEnterBackground:)
471  name:UIApplicationDidEnterBackgroundNotification
472  object:nil];
473 
474  [center addObserver:self
475  selector:@selector(applicationWillEnterForeground:)
476  name:UIApplicationWillEnterForegroundNotification
477  object:nil];
478 }
479 
480 - (void)setInitialRoute:(NSString*)route {
481  [self.engine.navigationChannel invokeMethod:@"setInitialRoute" arguments:route];
482 }
483 
484 - (void)popRoute {
485  [self.engine.navigationChannel invokeMethod:@"popRoute" arguments:nil];
486 }
487 
488 - (void)pushRoute:(NSString*)route {
489  [self.engine.navigationChannel invokeMethod:@"pushRoute" arguments:route];
490 }
491 
492 #pragma mark - Loading the view
493 
494 static UIView* GetViewOrPlaceholder(UIView* existing_view) {
495  if (existing_view) {
496  return existing_view;
497  }
498 
499  auto placeholder = [[UIView alloc] init];
500 
501  placeholder.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
502  placeholder.backgroundColor = UIColor.systemBackgroundColor;
503  placeholder.autoresizesSubviews = YES;
504 
505  // Only add the label when we know we have failed to enable tracing (and it was necessary).
506  // Otherwise, a spurious warning will be shown in cases where an engine cannot be initialized for
507  // other reasons.
508  if (flutter::GetTracingResult() == flutter::TracingResult::kDisabled) {
509  auto messageLabel = [[UILabel alloc] init];
510  messageLabel.numberOfLines = 0u;
511  messageLabel.textAlignment = NSTextAlignmentCenter;
512  messageLabel.autoresizingMask =
513  UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
514  messageLabel.text =
515  @"In iOS 14+, debug mode Flutter apps can only be launched from Flutter tooling, "
516  @"IDEs with Flutter plugins or from Xcode.\n\nAlternatively, build in profile or release "
517  @"modes to enable launching from the home screen.";
518  [placeholder addSubview:messageLabel];
519  }
520 
521  return placeholder;
522 }
523 
524 - (void)loadView {
525  self.view = GetViewOrPlaceholder(self.flutterView);
526  self.view.multipleTouchEnabled = YES;
527  self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
528 
529  [self installSplashScreenViewIfNecessary];
530 
531  // Create and set up the scroll view.
532  UIScrollView* scrollView = [[UIScrollView alloc] init];
533  scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
534  // The color shouldn't matter since it is offscreen.
535  scrollView.backgroundColor = UIColor.whiteColor;
536  scrollView.delegate = self;
537  // This is an arbitrary small size.
538  scrollView.contentSize = CGSizeMake(kScrollViewContentSize, kScrollViewContentSize);
539  // This is an arbitrary offset that is not CGPointZero.
540  scrollView.contentOffset = CGPointMake(kScrollViewContentSize, kScrollViewContentSize);
541 
542  [self.view addSubview:scrollView];
543  self.scrollView = scrollView;
544 }
545 
546 - (flutter::PointerData)generatePointerDataForFake {
547  flutter::PointerData pointer_data;
548  pointer_data.Clear();
549  pointer_data.kind = flutter::PointerData::DeviceKind::kTouch;
550  // `UITouch.timestamp` is defined as seconds since system startup. Synthesized events can get this
551  // time with `NSProcessInfo.systemUptime`. See
552  // https://developer.apple.com/documentation/uikit/uitouch/1618144-timestamp?language=objc
553  pointer_data.time_stamp = [[NSProcessInfo processInfo] systemUptime] * kMicrosecondsPerSecond;
554  return pointer_data;
555 }
556 
557 - (BOOL)scrollViewShouldScrollToTop:(UIScrollView*)scrollView {
558  if (!self.engine) {
559  return NO;
560  }
561  if (self.isViewLoaded) {
562  // Status bar taps before the UI is visible should be ignored.
563  [self.engine onStatusBarTap];
564  }
565  return NO;
566 }
567 
568 #pragma mark - Managing launch views
569 
570 - (void)installSplashScreenViewIfNecessary {
571  // The splash screen is automatically loaded during initialization (if configured), but should
572  // only be shown during the cold start of the application when we're the root view controller.
573  //
574  // If we are being presented modally or pushed onto a navigation controller later,
575  // remove the splash screen immediately to avoid a jarring visual transition.
576  if (self.splashScreenView && (self.isBeingPresented || self.isMovingToParentViewController)) {
577  // Explicitly remove from superview to bypass the fade-out animation.
578  [self.splashScreenView removeFromSuperview];
579  self.splashScreenView = nil;
580  return;
581  }
582 
583  // Cold start. Install the splash screen. It will removed in onFirstFrameRendered.
584  [self.splashScreenManager installSplashScreenViewAsSubviewOf:self.view];
585 }
586 
587 + (BOOL)automaticallyNotifiesObserversOfDisplayingFlutterUI {
588  return NO;
589 }
590 
591 - (void)setDisplayingFlutterUI:(BOOL)displayingFlutterUI {
592  if (_displayingFlutterUI != displayingFlutterUI) {
593  if (displayingFlutterUI == YES) {
594  if (!self.viewIfLoaded.window) {
595  return;
596  }
597  }
598  [self willChangeValueForKey:@"displayingFlutterUI"];
599  _displayingFlutterUI = displayingFlutterUI;
600  [self didChangeValueForKey:@"displayingFlutterUI"];
601  }
602 }
603 
604 - (void)callViewRenderedCallback {
605  self.displayingFlutterUI = YES;
606  if (self.flutterViewRenderedCallback) {
607  self.flutterViewRenderedCallback();
608  self.flutterViewRenderedCallback = nil;
609  }
610 }
611 
612 - (void)onFirstFrameRendered {
613  if (self.splashScreenView) {
614  __weak FlutterViewController* weakSelf = self;
615  [self.splashScreenManager removeSplashScreenWithCompletion:^{
616  [weakSelf callViewRenderedCallback];
617  }];
618  } else {
619  [self callViewRenderedCallback];
620  }
621 }
622 
623 - (void)installFirstFrameCallback {
624  if (!self.engine) {
625  return;
626  }
627  __weak FlutterViewController* weakSelf = self;
628  [self.engine installFirstFrameCallback:^{
629  [weakSelf onFirstFrameRendered];
630  }];
631 }
632 
633 #pragma mark - Properties
634 
635 - (int64_t)viewIdentifier {
636  // TODO(dkwingsmt): Fill the view ID property with the correct value once the
637  // iOS shell supports multiple views.
638  return flutter::kFlutterImplicitViewId;
639 }
640 
641 - (BOOL)loadDefaultSplashScreenView {
642  return [self.splashScreenManager loadDefaultSplashScreenView];
643 }
644 
645 - (UIView*)splashScreenView {
646  return self.splashScreenManager.splashScreenView;
647 }
648 
649 - (void)setSplashScreenView:(UIView*)view {
650  self.splashScreenManager.splashScreenView = view;
651 }
652 
653 - (void)setFlutterViewDidRenderCallback:(void (^)(void))callback {
654  _flutterViewRenderedCallback = callback;
655 }
656 
657 - (UISceneActivationState)activationState {
658  return self.flutterWindowSceneIfViewLoaded.activationState;
659 }
660 
661 - (BOOL)stateIsActive {
662  // [UIApplication sharedApplication API is not available for app extension.
663  UIApplication* flutterApplication = FlutterSharedApplication.application;
664 
665  if (flutterApplication) {
666  return [self isApplicationStateMatching:UIApplicationStateActive
667  withApplication:flutterApplication];
668  }
669  return [self isSceneStateMatching:UISceneActivationStateForegroundActive];
670 }
671 
672 - (BOOL)stateIsForeground {
673  // [UIApplication sharedApplication API is not available for app extension.
674  UIApplication* flutterApplication = FlutterSharedApplication.application;
675 
676  if (flutterApplication) {
677  return [self isApplicationStateMatching:UIApplicationStateActive
678  withApplication:flutterApplication] ||
679  [self isApplicationStateMatching:UIApplicationStateInactive
680  withApplication:flutterApplication];
681  }
682  return [self isSceneStateMatching:UISceneActivationStateForegroundActive] ||
683  [self isSceneStateMatching:UISceneActivationStateForegroundInactive];
684 }
685 
686 - (BOOL)stateIsBackground {
687  // [UIApplication sharedApplication API is not available for app extension.
688  UIApplication* flutterApplication = FlutterSharedApplication.application;
689 
690  if (flutterApplication) {
691  return [self isApplicationStateMatching:UIApplicationStateBackground
692  withApplication:flutterApplication];
693  }
694  return [self isSceneStateMatching:UISceneActivationStateBackground];
695 }
696 
697 - (BOOL)shouldHandleSceneNotification:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
698  if (notification.object == nil) {
699  return YES;
700  }
701  UIWindowScene* scene = self.flutterWindowSceneIfViewLoaded;
702  if (scene == nil) {
703  return YES;
704  }
705  return notification.object == scene;
706 }
707 
708 - (BOOL)isApplicationStateMatching:(UIApplicationState)match
709  withApplication:(UIApplication*)application {
710  switch (application.applicationState) {
711  case UIApplicationStateActive:
712  case UIApplicationStateInactive:
713  case UIApplicationStateBackground:
714  return application.applicationState == match;
715  }
716 }
717 
718 - (BOOL)isSceneStateMatching:(UISceneActivationState)match API_AVAILABLE(ios(13.0)) {
719  switch (self.activationState) {
720  case UISceneActivationStateForegroundActive:
721  case UISceneActivationStateUnattached:
722  case UISceneActivationStateForegroundInactive:
723  case UISceneActivationStateBackground:
724  return self.activationState == match;
725  }
726 }
727 
728 #pragma mark - Surface creation and teardown updates
729 
730 - (void)surfaceUpdated:(BOOL)appeared {
731  if (!self.engine) {
732  return;
733  }
734 
735  // NotifyCreated/NotifyDestroyed are synchronous and require hops between the UI and raster
736  // thread.
737  if (appeared) {
738  [self installFirstFrameCallback];
739  self.platformViewsController.flutterView = self.flutterView;
740  self.platformViewsController.flutterViewController = self;
741  [self.engine notifyViewCreated];
742  } else {
743  self.displayingFlutterUI = NO;
744  [self.engine notifyViewDestroyed];
745  self.platformViewsController.flutterView = nil;
746  self.platformViewsController.flutterViewController = nil;
747  }
748 }
749 
750 // Creates the surface if the viewport is sized.
751 //
752 // Callers must guarantee GPU access is permitted since UIApplication reports
753 // UIApplicationStateBackground while willEnterForeground is delivered, so the application state
754 // can't be enforced here.
755 - (void)createSurfaceIfReady {
756  if (!self.engine || !_viewportMetrics.physical_width) {
757  return;
758  }
759  [self surfaceUpdated:YES];
760 }
761 
762 #pragma mark - UIViewController lifecycle notifications
763 
764 - (void)viewDidLoad {
765  TRACE_EVENT0("flutter", "viewDidLoad");
766 
767  if (self.engine && self.engineNeedsLaunch) {
768  [self.engine launchEngine:nil libraryURI:nil entrypointArgs:nil];
769  [self.engine setViewController:self];
770  self.engineNeedsLaunch = NO;
771  } else if (self.engine.viewController == self) {
772  [self.engine attachView];
773  }
774 
775  // Register internal plugins.
776  [self addInternalPlugins];
777 
778  if (@available(iOS 13.4, *)) {
779  _hoverGestureRecognizer =
780  [[UIHoverGestureRecognizer alloc] initWithTarget:self action:@selector(hoverEvent:)];
781  _hoverGestureRecognizer.delegate = self;
782  [self.flutterView addGestureRecognizer:_hoverGestureRecognizer];
783 
784  _discreteScrollingPanGestureRecognizer =
785  [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(discreteScrollEvent:)];
786  _discreteScrollingPanGestureRecognizer.allowedScrollTypesMask = UIScrollTypeMaskDiscrete;
787  // Disallowing all touch types. If touch events are allowed here, touches to the screen will be
788  // consumed by the UIGestureRecognizer instead of being passed through to flutter via
789  // touchesBegan. Trackpad and mouse scrolls are sent by the platform as scroll events rather
790  // than touch events, so they will still be received.
791  _discreteScrollingPanGestureRecognizer.allowedTouchTypes = @[];
792  _discreteScrollingPanGestureRecognizer.delegate = self;
793  [self.flutterView addGestureRecognizer:_discreteScrollingPanGestureRecognizer];
794  _continuousScrollingPanGestureRecognizer =
795  [[UIPanGestureRecognizer alloc] initWithTarget:self
796  action:@selector(continuousScrollEvent:)];
797  _continuousScrollingPanGestureRecognizer.allowedScrollTypesMask = UIScrollTypeMaskContinuous;
798  _continuousScrollingPanGestureRecognizer.allowedTouchTypes = @[];
799  _continuousScrollingPanGestureRecognizer.delegate = self;
800  [self.flutterView addGestureRecognizer:_continuousScrollingPanGestureRecognizer];
801  _pinchGestureRecognizer =
802  [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchEvent:)];
803  _pinchGestureRecognizer.allowedTouchTypes = @[];
804  _pinchGestureRecognizer.delegate = self;
805  [self.flutterView addGestureRecognizer:_pinchGestureRecognizer];
806  _rotationGestureRecognizer = [[UIRotationGestureRecognizer alloc] init];
807  _rotationGestureRecognizer.allowedTouchTypes = @[];
808  _rotationGestureRecognizer.delegate = self;
809  [self.flutterView addGestureRecognizer:_rotationGestureRecognizer];
810  }
811 
812  [super viewDidLoad];
813 }
814 
815 - (void)addInternalPlugins {
816  self.keyboardManager = [[FlutterKeyboardManager alloc] init];
817  __weak FlutterViewController* weakSelf = self;
818  FlutterSendKeyEvent sendEvent =
819  ^(const FlutterKeyEvent& event, FlutterKeyEventCallback callback, void* userData) {
820  [weakSelf.engine sendKeyEvent:event callback:callback userData:userData];
821  };
822  [self.keyboardManager
823  addPrimaryResponder:[[FlutterEmbedderKeyResponder alloc] initWithSendEvent:sendEvent]];
824  FlutterChannelKeyResponder* responder =
825  [[FlutterChannelKeyResponder alloc] initWithChannel:self.engine.keyEventChannel];
826  [self.keyboardManager addPrimaryResponder:responder];
827  FlutterTextInputPlugin* textInputPlugin = self.engine.textInputPlugin;
828  if (textInputPlugin != nil) {
829  [self.keyboardManager addSecondaryResponder:textInputPlugin];
830  }
831  if (self.engine.viewController == self) {
832  [textInputPlugin setUpIndirectScribbleInteraction:self];
833  }
834 }
835 
836 - (void)removeInternalPlugins {
837  self.keyboardManager = nil;
838 }
839 
840 - (void)viewWillAppear:(BOOL)animated {
841  TRACE_EVENT0("flutter", "viewWillAppear");
842  if (self.engine.viewController == self) {
843  // Send platform settings to Flutter, e.g., platform brightness.
844  [self onUserSettingsChanged:nil];
845 
846  // Only recreate surface on subsequent appearances when viewport metrics are known.
847  // First time surface creation is done on viewDidLayoutSubviews.
848  [self createSurfaceIfReady];
849  [self.engine.lifecycleChannel sendMessage:@"AppLifecycleState.inactive"];
850  [self.engine.restorationPlugin markRestorationComplete];
851  }
852 
853  [super viewWillAppear:animated];
854 }
855 
856 - (void)viewDidAppear:(BOOL)animated {
857  TRACE_EVENT0("flutter", "viewDidAppear");
858  if (self.engine.viewController == self) {
859  [self onUserSettingsChanged:nil];
860  [self onAccessibilityStatusChanged:nil];
861 
862  if (self.stateIsActive) {
863  [self.engine.lifecycleChannel sendMessage:@"AppLifecycleState.resumed"];
864  }
865  }
866  [super viewDidAppear:animated];
867 }
868 
869 - (void)viewWillDisappear:(BOOL)animated {
870  TRACE_EVENT0("flutter", "viewWillDisappear");
871  if (self.engine.viewController == self) {
872  [self.engine.lifecycleChannel sendMessage:@"AppLifecycleState.inactive"];
873  }
874  [super viewWillDisappear:animated];
875 }
876 
877 - (void)viewDidDisappear:(BOOL)animated {
878  TRACE_EVENT0("flutter", "viewDidDisappear");
879  if (self.engine.viewController == self) {
880  [self.keyboardInsetManager hideKeyboardImmediately];
881  [self surfaceUpdated:NO];
882  [self.engine.lifecycleChannel sendMessage:@"AppLifecycleState.paused"];
883  [self flushOngoingTouches];
884  [self.engine notifyLowMemory];
885  }
886 
887  [super viewDidDisappear:animated];
888 }
889 
890 - (void)viewWillTransitionToSize:(CGSize)size
891  withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
892  [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
893 
894  // We delay the viewport metrics update for half of rotation transition duration, to address
895  // a bug with distorted aspect ratio.
896  // See: https://github.com/flutter/flutter/issues/16322
897  //
898  // This approach does not fully resolve all distortion problem. But instead, it reduces the
899  // rotation distortion roughly from 4x to 2x. The most distorted frames occur in the middle
900  // of the transition when it is rotating the fastest, making it hard to notice.
901 
902  NSTimeInterval transitionDuration = coordinator.transitionDuration;
903  // Do not delay viewport metrics update if zero transition duration.
904  if (transitionDuration == 0) {
905  return;
906  }
907 
908  __weak FlutterViewController* weakSelf = self;
909  _shouldIgnoreViewportMetricsUpdatesDuringRotation = YES;
910  dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
911  static_cast<int64_t>(transitionDuration / 2.0 * NSEC_PER_SEC)),
912  dispatch_get_main_queue(), ^{
913  FlutterViewController* strongSelf = weakSelf;
914  if (!strongSelf) {
915  return;
916  }
917 
918  // `viewWillTransitionToSize` is only called after the previous rotation is
919  // complete. So there won't be race condition for this flag.
920  strongSelf.shouldIgnoreViewportMetricsUpdatesDuringRotation = NO;
921  [strongSelf updateViewportMetricsIfNeeded];
922  });
923 }
924 
925 - (void)flushOngoingTouches {
926  if (self.engine && self.ongoingTouches.count > 0) {
927  auto packet = std::make_unique<flutter::PointerDataPacket>(self.ongoingTouches.count);
928  size_t pointer_index = 0;
929  // If the view controller is going away, we want to flush cancel all the ongoing
930  // touches to the framework so nothing gets orphaned.
931  for (NSNumber* device in self.ongoingTouches) {
932  // Create fake PointerData to balance out each previously started one for the framework.
933  flutter::PointerData pointer_data = [self generatePointerDataForFake];
934 
935  pointer_data.change = flutter::PointerData::Change::kCancel;
936  pointer_data.device = device.longLongValue;
937  pointer_data.pointer_identifier = 0;
938  pointer_data.view_id = self.viewIdentifier;
939 
940  // Anything we put here will be arbitrary since there are no touches.
941  pointer_data.physical_x = 0;
942  pointer_data.physical_y = 0;
943  pointer_data.physical_delta_x = 0.0;
944  pointer_data.physical_delta_y = 0.0;
945  pointer_data.pressure = 1.0;
946  pointer_data.pressure_max = 1.0;
947 
948  packet->SetPointerData(pointer_index++, pointer_data);
949  }
950 
951  [self.ongoingTouches removeAllObjects];
952  [self.engine dispatchPointerDataPacket:std::move(packet)];
953  }
954 }
955 
956 - (void)deregisterNotifications {
957  [[NSNotificationCenter defaultCenter] postNotificationName:FlutterViewControllerWillDealloc
958  object:self
959  userInfo:nil];
960  [[NSNotificationCenter defaultCenter] removeObserver:self];
961 }
962 
963 - (void)dealloc {
964  // TODO(cbracken): https://github.com/flutter/flutter/issues/157140
965  // Eliminate method calls in initializers and dealloc.
966  [self removeInternalPlugins];
967  [self deregisterNotifications];
968 
969  [self.keyboardInsetManager invalidate];
970 
971  // TODO(cbracken): https://github.com/flutter/flutter/issues/156222
972  // Ensure all delegates are weak and remove this.
973  _scrollView.delegate = nil;
974  _hoverGestureRecognizer.delegate = nil;
975  _discreteScrollingPanGestureRecognizer.delegate = nil;
976  _continuousScrollingPanGestureRecognizer.delegate = nil;
977  _pinchGestureRecognizer.delegate = nil;
978  _rotationGestureRecognizer.delegate = nil;
979 }
980 
981 #pragma mark - Application lifecycle notifications
982 
983 - (void)applicationBecameActive:(NSNotification*)notification {
984  TRACE_EVENT0("flutter", "applicationBecameActive");
985  [self appOrSceneBecameActive];
986 }
987 
988 - (void)applicationWillResignActive:(NSNotification*)notification {
989  TRACE_EVENT0("flutter", "applicationWillResignActive");
990  [self appOrSceneWillResignActive];
991 }
992 
993 - (void)applicationWillTerminate:(NSNotification*)notification {
994  [self appOrSceneWillTerminate];
995 }
996 
997 - (void)applicationDidEnterBackground:(NSNotification*)notification {
998  TRACE_EVENT0("flutter", "applicationDidEnterBackground");
999  [self appOrSceneDidEnterBackground];
1000 }
1001 
1002 - (void)applicationWillEnterForeground:(NSNotification*)notification {
1003  TRACE_EVENT0("flutter", "applicationWillEnterForeground");
1004  [self appOrSceneWillEnterForeground];
1005 }
1006 
1007 #pragma mark - Scene lifecycle notifications
1008 
1009 - (void)sceneBecameActive:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1010  if (![self shouldHandleSceneNotification:notification]) {
1011  return;
1012  }
1013  TRACE_EVENT0("flutter", "sceneBecameActive");
1014  [self appOrSceneBecameActive];
1015 }
1016 
1017 - (void)sceneWillResignActive:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1018  if (![self shouldHandleSceneNotification:notification]) {
1019  return;
1020  }
1021  TRACE_EVENT0("flutter", "sceneWillResignActive");
1022  [self appOrSceneWillResignActive];
1023 }
1024 
1025 - (void)sceneWillDisconnect:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1026  if (![self shouldHandleSceneNotification:notification]) {
1027  return;
1028  }
1029  [self appOrSceneWillTerminate];
1030 }
1031 
1032 - (void)sceneDidEnterBackground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1033  if (![self shouldHandleSceneNotification:notification]) {
1034  return;
1035  }
1036  TRACE_EVENT0("flutter", "sceneDidEnterBackground");
1037  [self appOrSceneDidEnterBackground];
1038 }
1039 
1040 - (void)sceneWillEnterForeground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1041  if (![self shouldHandleSceneNotification:notification]) {
1042  return;
1043  }
1044  TRACE_EVENT0("flutter", "sceneWillEnterForeground");
1045  [self appOrSceneWillEnterForeground];
1046 }
1047 
1048 #pragma mark - Lifecycle shared
1049 
1050 - (void)appOrSceneBecameActive {
1051  self.keyboardInsetManager.isKeyboardInOrTransitioningFromBackground = NO;
1052  [self performSelector:@selector(goToApplicationLifecycle:)
1053  withObject:@"AppLifecycleState.resumed"
1054  afterDelay:0.0f];
1055 }
1056 
1057 - (void)appOrSceneWillResignActive {
1058  [NSObject cancelPreviousPerformRequestsWithTarget:self
1059  selector:@selector(goToApplicationLifecycle:)
1060  object:@"AppLifecycleState.resumed"];
1061  [self goToApplicationLifecycle:@"AppLifecycleState.inactive"];
1062 }
1063 
1064 - (void)appOrSceneWillTerminate {
1065  [self goToApplicationLifecycle:@"AppLifecycleState.detached"];
1066  [self.engine destroyContext];
1067 }
1068 
1069 - (void)appOrSceneDidEnterBackground {
1070  self.keyboardInsetManager.isKeyboardInOrTransitioningFromBackground = YES;
1071  [self surfaceUpdated:NO];
1072  [self goToApplicationLifecycle:@"AppLifecycleState.paused"];
1073 }
1074 
1075 - (void)appOrSceneWillEnterForeground {
1076  [self createSurfaceIfReady];
1077  [self goToApplicationLifecycle:@"AppLifecycleState.inactive"];
1078 }
1079 
1080 // Make this transition only while this current view controller is visible.
1081 - (void)goToApplicationLifecycle:(nonnull NSString*)state {
1082  // Accessing self.view will create the view. Instead use viewIfLoaded
1083  // to check whether the view is attached to window.
1084  if (self.viewIfLoaded.window) {
1085  [self.engine.lifecycleChannel sendMessage:state];
1086  }
1087 }
1088 
1089 #pragma mark - Touch event handling
1090 
1091 static flutter::PointerData::Change PointerDataChangeFromUITouchPhase(UITouchPhase phase) {
1092  switch (phase) {
1093  case UITouchPhaseBegan:
1094  return flutter::PointerData::Change::kDown;
1095  case UITouchPhaseMoved:
1096  case UITouchPhaseStationary:
1097  // There is no EVENT_TYPE_POINTER_STATIONARY. So we just pass a move type
1098  // with the same coordinates
1099  return flutter::PointerData::Change::kMove;
1100  case UITouchPhaseEnded:
1101  return flutter::PointerData::Change::kUp;
1102  case UITouchPhaseCancelled:
1103  return flutter::PointerData::Change::kCancel;
1104  default:
1105  // TODO(53695): Handle the `UITouchPhaseRegion`... enum values.
1106  FML_DLOG(INFO) << "Unhandled touch phase: " << phase;
1107  break;
1108  }
1109 
1110  return flutter::PointerData::Change::kCancel;
1111 }
1112 
1113 static flutter::PointerData::DeviceKind DeviceKindFromTouchType(UITouch* touch) {
1114  switch (touch.type) {
1115  case UITouchTypeDirect:
1116  case UITouchTypeIndirect:
1117  return flutter::PointerData::DeviceKind::kTouch;
1118  case UITouchTypeStylus:
1119  return flutter::PointerData::DeviceKind::kStylus;
1120  case UITouchTypeIndirectPointer:
1121  return flutter::PointerData::DeviceKind::kMouse;
1122  default:
1123  FML_DLOG(INFO) << "Unhandled touch type: " << touch.type;
1124  break;
1125  }
1126 
1127  return flutter::PointerData::DeviceKind::kTouch;
1128 }
1129 
1130 // Dispatches the UITouches to the engine. Usually, the type of change of the touch is determined
1131 // from the UITouch's phase. However, FlutterAppDelegate fakes touches to ensure that touch events
1132 // in the status bar area are available to framework code. The change type (optional) of the faked
1133 // touch is specified in the second argument.
1134 - (void)dispatchTouches:(NSSet*)touches
1135  pointerDataChangeOverride:(flutter::PointerData::Change*)overridden_change
1136  event:(UIEvent*)event {
1137  if (!self.engine) {
1138  return;
1139  }
1140 
1141  // If the UIApplicationSupportsIndirectInputEvents in Info.plist returns YES, then the platform
1142  // dispatches indirect pointer touches (trackpad clicks) as UITouch with a type of
1143  // UITouchTypeIndirectPointer and different identifiers for each click. They are translated into
1144  // Flutter pointer events with type of kMouse and different device IDs. These devices must be
1145  // terminated with kRemove events when the touches end, otherwise they will keep triggering hover
1146  // events.
1147  //
1148  // If the UIApplicationSupportsIndirectInputEvents in Info.plist returns NO, then the platform
1149  // dispatches indirect pointer touches (trackpad clicks) as UITouch with a type of
1150  // UITouchTypeIndirectPointer and different identifiers for each click. They are translated into
1151  // Flutter pointer events with type of kTouch and different device IDs. Removing these devices is
1152  // neither necessary nor harmful.
1153  //
1154  // Therefore Flutter always removes these devices. The touches_to_remove_count tracks how many
1155  // remove events are needed in this group of touches to properly allocate space for the packet.
1156  // The remove event of a touch is synthesized immediately after its normal event.
1157  //
1158  // See also:
1159  // https://developer.apple.com/documentation/uikit/pointer_interactions?language=objc
1160  // https://developer.apple.com/documentation/bundleresources/information_property_list/uiapplicationsupportsindirectinputevents?language=objc
1161  NSUInteger touches_to_remove_count = 0;
1162  for (UITouch* touch in touches) {
1163  if (touch.phase == UITouchPhaseEnded || touch.phase == UITouchPhaseCancelled) {
1164  touches_to_remove_count++;
1165  }
1166  }
1167 
1168  const CGFloat scale = self.flutterScreenIfViewLoaded.scale;
1169  auto packet =
1170  std::make_unique<flutter::PointerDataPacket>(touches.count + touches_to_remove_count);
1171 
1172  size_t pointer_index = 0;
1173 
1174  for (UITouch* touch in touches) {
1175  CGPoint windowCoordinates = [touch locationInView:self.view];
1176 
1177  flutter::PointerData pointer_data;
1178  pointer_data.Clear();
1179 
1180  constexpr int kMicrosecondsPerSecond = 1000 * 1000;
1181  pointer_data.time_stamp = touch.timestamp * kMicrosecondsPerSecond;
1182 
1183  pointer_data.change = overridden_change != nullptr
1184  ? *overridden_change
1185  : PointerDataChangeFromUITouchPhase(touch.phase);
1186 
1187  pointer_data.kind = DeviceKindFromTouchType(touch);
1188 
1189  pointer_data.device = reinterpret_cast<int64_t>(touch);
1190 
1191  pointer_data.view_id = self.viewIdentifier;
1192 
1193  // Pointer will be generated in pointer_data_packet_converter.cc.
1194  pointer_data.pointer_identifier = 0;
1195 
1196  pointer_data.physical_x = windowCoordinates.x * scale;
1197  pointer_data.physical_y = windowCoordinates.y * scale;
1198 
1199  // Delta will be generated in pointer_data_packet_converter.cc.
1200  pointer_data.physical_delta_x = 0.0;
1201  pointer_data.physical_delta_y = 0.0;
1202 
1203  NSNumber* deviceKey = [NSNumber numberWithLongLong:pointer_data.device];
1204  // Track touches that began and not yet stopped so we can flush them
1205  // if the view controller goes away.
1206  switch (pointer_data.change) {
1207  case flutter::PointerData::Change::kDown:
1208  [self.ongoingTouches addObject:deviceKey];
1209  break;
1210  case flutter::PointerData::Change::kCancel:
1211  case flutter::PointerData::Change::kUp:
1212  [self.ongoingTouches removeObject:deviceKey];
1213  break;
1214  case flutter::PointerData::Change::kHover:
1215  case flutter::PointerData::Change::kMove:
1216  // We're only tracking starts and stops.
1217  break;
1218  case flutter::PointerData::Change::kAdd:
1219  case flutter::PointerData::Change::kRemove:
1220  // We don't use kAdd/kRemove.
1221  break;
1222  case flutter::PointerData::Change::kPanZoomStart:
1223  case flutter::PointerData::Change::kPanZoomUpdate:
1224  case flutter::PointerData::Change::kPanZoomEnd:
1225  // We don't send pan/zoom events here
1226  break;
1227  }
1228 
1229  // pressure_min is always 0.0
1230  pointer_data.pressure = touch.force;
1231  pointer_data.pressure_max = touch.maximumPossibleForce;
1232  pointer_data.radius_major = touch.majorRadius;
1233  pointer_data.radius_min = touch.majorRadius - touch.majorRadiusTolerance;
1234  pointer_data.radius_max = touch.majorRadius + touch.majorRadiusTolerance;
1235 
1236  // iOS Documentation: altitudeAngle
1237  // A value of 0 radians indicates that the stylus is parallel to the surface. The value of
1238  // this property is Pi/2 when the stylus is perpendicular to the surface.
1239  //
1240  // PointerData Documentation: tilt
1241  // The angle of the stylus, in radians in the range:
1242  // 0 <= tilt <= pi/2
1243  // giving the angle of the axis of the stylus, relative to the axis perpendicular to the input
1244  // surface (thus 0.0 indicates the stylus is orthogonal to the plane of the input surface,
1245  // while pi/2 indicates that the stylus is flat on that surface).
1246  //
1247  // Discussion:
1248  // The ranges are the same. Origins are swapped.
1249  pointer_data.tilt = M_PI_2 - touch.altitudeAngle;
1250 
1251  // iOS Documentation: azimuthAngleInView:
1252  // With the tip of the stylus touching the screen, the value of this property is 0 radians
1253  // when the cap end of the stylus (that is, the end opposite of the tip) points along the
1254  // positive x axis of the device's screen. The azimuth angle increases as the user swings the
1255  // cap end of the stylus in a clockwise direction around the tip.
1256  //
1257  // PointerData Documentation: orientation
1258  // The angle of the stylus, in radians in the range:
1259  // -pi < orientation <= pi
1260  // giving the angle of the axis of the stylus projected onto the input surface, relative to
1261  // the positive y-axis of that surface (thus 0.0 indicates the stylus, if projected onto that
1262  // surface, would go from the contact point vertically up in the positive y-axis direction, pi
1263  // would indicate that the stylus would go down in the negative y-axis direction; pi/4 would
1264  // indicate that the stylus goes up and to the right, -pi/2 would indicate that the stylus
1265  // goes to the left, etc).
1266  //
1267  // Discussion:
1268  // Sweep direction is the same. Phase of M_PI_2.
1269  pointer_data.orientation = [touch azimuthAngleInView:nil] - M_PI_2;
1270 
1271  if (@available(iOS 13.4, *)) {
1272  if (event != nullptr) {
1273  pointer_data.buttons = (((event.buttonMask & UIEventButtonMaskPrimary) > 0)
1274  ? flutter::PointerButtonMouse::kPointerButtonMousePrimary
1275  : 0) |
1276  (((event.buttonMask & UIEventButtonMaskSecondary) > 0)
1277  ? flutter::PointerButtonMouse::kPointerButtonMouseSecondary
1278  : 0);
1279  }
1280  }
1281 
1282  packet->SetPointerData(pointer_index++, pointer_data);
1283 
1284  if (touch.phase == UITouchPhaseEnded || touch.phase == UITouchPhaseCancelled) {
1285  flutter::PointerData remove_pointer_data = pointer_data;
1286  remove_pointer_data.change = flutter::PointerData::Change::kRemove;
1287  packet->SetPointerData(pointer_index++, remove_pointer_data);
1288  }
1289  }
1290 
1291  [self.engine dispatchPointerDataPacket:std::move(packet)];
1292 }
1293 
1294 - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
1295  [self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event];
1296 }
1297 
1298 - (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
1299  [self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event];
1300 }
1301 
1302 - (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
1303  [self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event];
1304 }
1305 
1306 - (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event {
1307  [self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event];
1308 }
1309 
1310 - (void)forceTouchesCancelled:(NSSet*)touches {
1311  flutter::PointerData::Change cancel = flutter::PointerData::Change::kCancel;
1312  [self dispatchTouches:touches pointerDataChangeOverride:&cancel event:nullptr];
1313 }
1314 
1315 - (BOOL)platformViewShouldAcceptTouchAtTouchBeganLocation:(CGPoint)location {
1316  flutter::PointData point{location.x, location.y};
1317  return [self.engine platformViewShouldAcceptTouchAtTouchBeganLocation:point
1318  viewId:self.viewIdentifier];
1319 }
1320 
1321 #pragma mark - Handle view resizing
1322 
1323 - (void)updateViewportMetricsIfNeeded {
1324  if (_shouldIgnoreViewportMetricsUpdatesDuringRotation) {
1325  return;
1326  }
1327  if (self.engine.viewController == self) {
1328  [self.engine updateViewportMetrics:_viewportMetrics];
1329  }
1330 }
1331 
1332 - (void)viewDidLayoutSubviews {
1333  CGRect viewBounds = self.view.bounds;
1334  CGFloat scale = self.flutterScreenIfViewLoaded.scale;
1335 
1336  // Purposefully place this not visible.
1337  self.scrollView.frame = CGRectMake(0.0, 0.0, viewBounds.size.width, 0.0);
1338  self.scrollView.contentOffset = CGPointMake(kScrollViewContentSize, kScrollViewContentSize);
1339 
1340  // First time since creation that the dimensions of its view is known.
1341  bool firstViewBoundsUpdate = !_viewportMetrics.physical_width;
1342  _viewportMetrics.device_pixel_ratio = scale;
1343  [self setViewportMetricsSize];
1344  [self checkAndUpdateAutoResizeConstraints];
1345  [self setViewportMetricsPaddings];
1346  [self updateViewportMetricsIfNeeded];
1347  [self updateEngineDisplays];
1348 
1349  // There is no guarantee that UIKit will layout subviews when the application/scene is in the
1350  // foreground. Creating the surface when backgrounded will cause app termination, so in that
1351  // scenario, skip it here, and leave surface creation to appOrSceneWillEnterForeground.
1352  // This must run after updateViewportMetrics so that the surface creation tasks are queued after
1353  // the viewport metrics update tasks.
1354  if (firstViewBoundsUpdate && self.stateIsForeground) {
1355  [self createSurfaceIfReady];
1356  }
1357 }
1358 
1359 // Asks the engine to send updated display information to the framework, e.g. when the view is first
1360 // placed in a window, or moves between the inner and outer displays of a device with multiple
1361 // built-in displays. The engine skips the update if the display information has not changed.
1362 - (void)updateEngineDisplays {
1363  if (self.engine.viewController != self) {
1364  return;
1365  }
1366  [self.engine updateDisplays];
1367 }
1368 
1369 - (BOOL)isAutoResizable {
1370  return self.flutterView.autoResizable;
1371 }
1372 
1373 - (void)setAutoResizable:(BOOL)value {
1374  self.flutterView.autoResizable = value;
1375  self.flutterView.contentMode = UIViewContentModeCenter;
1376 }
1377 
1378 - (void)checkAndUpdateAutoResizeConstraints {
1379  if (!self.isAutoResizable) {
1380  return;
1381  }
1382 
1383  [self updateAutoResizeConstraints];
1384 }
1385 
1386 /**
1387  * Updates the FlutterAutoResizeLayoutConstraints based on the view's
1388  * current frame.
1389  *
1390  * This method is invoked during viewDidLayoutSubviews, at which point the
1391  * view has completed its subview layout and applied any existing Auto Layout
1392  * constraints.
1393  *
1394  * Initially, the view's frame is used to determine the maximum size allowed
1395  * by the native layout system. This size is then used to establish the viewport
1396  * constraints for the Flutter engine.
1397  *
1398  * A critical consideration is that this initial frame-based sizing is only
1399  * applicable if FlutterAutoResizeLayoutConstraints have not yet been applied
1400  * by Flutter. Once Flutter applies its own FlutterAutoResizeLayoutConstraints,
1401  * these constraints will subsequently dictate the view's frame.
1402  *
1403  * This interaction imposes a limitation: native layout constraints that are
1404  * updated after Flutter has applied its auto-resize constraints may not
1405  * function as expected or properly influence the FlutterView's size.
1406  */
1407 - (void)updateAutoResizeConstraints {
1408  BOOL hasBeenAutoResized = NO;
1409  for (NSLayoutConstraint* constraint in self.view.constraints) {
1410  if ([constraint isKindOfClass:[FlutterAutoResizeLayoutConstraint class]]) {
1411  hasBeenAutoResized = YES;
1412  break;
1413  }
1414  }
1415  if (!hasBeenAutoResized) {
1416  self.sizeBeforeAutoResized = self.view.frame.size;
1417  }
1418 
1419  CGFloat maxWidth = self.sizeBeforeAutoResized.width;
1420  CGFloat maxHeight = self.sizeBeforeAutoResized.height;
1421  CGFloat minWidth = self.sizeBeforeAutoResized.width;
1422  CGFloat minHeight = self.sizeBeforeAutoResized.height;
1423 
1424  // maxWidth or maxHeight may be 0 when the width/height are ambiguous, eg. for
1425  // unsized widgets
1426  if (maxWidth == 0) {
1427  maxWidth = CGFLOAT_MAX;
1428  [FlutterLogger
1429  logWarning:
1430  @"Warning: The outermost widget in the autoresizable Flutter view is unsized or has "
1431  @"ambiguous dimensions, causing the host native view's width to be 0. The autoresizing "
1432  @"logic is setting the viewport constraint to unbounded DBL_MAX to prevent "
1433  @"rendering failure. Please ensure your top-level Flutter widget has explicit "
1434  @"constraints (e.g., using SizedBox or Container)."];
1435  }
1436  if (maxHeight == 0) {
1437  maxHeight = CGFLOAT_MAX;
1438  [FlutterLogger
1439  logWarning:
1440  @"Warning: The outermost widget in the autoresizable Flutter view is unsized or has "
1441  @"ambiguous dimensions, causing the host native view's width to be 0. The autoresizing "
1442  @"logic is setting the viewport constraint to unbounded DBL_MAX to prevent "
1443  @"rendering failure. Please ensure your top-level Flutter widget has explicit "
1444  @"constraints (e.g., using SizedBox or Container)."];
1445  }
1446  _viewportMetrics.physical_min_width_constraint = minWidth * _viewportMetrics.device_pixel_ratio;
1447  _viewportMetrics.physical_max_width_constraint = maxWidth * _viewportMetrics.device_pixel_ratio;
1448  _viewportMetrics.physical_min_height_constraint = minHeight * _viewportMetrics.device_pixel_ratio;
1449  _viewportMetrics.physical_max_height_constraint = maxHeight * _viewportMetrics.device_pixel_ratio;
1450 }
1451 
1452 - (void)viewSafeAreaInsetsDidChange {
1453  [self setViewportMetricsPaddings];
1454  [self updateViewportMetricsIfNeeded];
1455  [super viewSafeAreaInsetsDidChange];
1456 }
1457 
1458 // Set _viewportMetrics physical size.
1459 - (void)setViewportMetricsSize {
1460  UIScreen* screen = self.flutterScreenIfViewLoaded;
1461  if (!screen) {
1462  return;
1463  }
1464 
1465  CGFloat scale = screen.scale;
1466  _viewportMetrics.physical_width = self.view.bounds.size.width * scale;
1467  _viewportMetrics.physical_height = self.view.bounds.size.height * scale;
1468  // TODO(louisehsu): update for https://github.com/flutter/flutter/issues/169147
1469  _viewportMetrics.physical_min_width_constraint = _viewportMetrics.physical_width;
1470  _viewportMetrics.physical_max_width_constraint = _viewportMetrics.physical_width;
1471  _viewportMetrics.physical_min_height_constraint = _viewportMetrics.physical_height;
1472  _viewportMetrics.physical_max_height_constraint = _viewportMetrics.physical_height;
1473 }
1474 
1475 // Set _viewportMetrics physical paddings.
1476 //
1477 // Viewport paddings represent the iOS safe area insets.
1478 - (void)setViewportMetricsPaddings {
1479  UIScreen* screen = self.flutterScreenIfViewLoaded;
1480  if (!screen) {
1481  return;
1482  }
1483 
1484  CGFloat scale = screen.scale;
1485  _viewportMetrics.physical_padding_top = self.view.safeAreaInsets.top * scale;
1486  _viewportMetrics.physical_padding_left = self.view.safeAreaInsets.left * scale;
1487  _viewportMetrics.physical_padding_right = self.view.safeAreaInsets.right * scale;
1488  _viewportMetrics.physical_padding_bottom = self.view.safeAreaInsets.bottom * scale;
1489 }
1490 
1491 #pragma mark - Keyboard events
1492 
1493 - (void)keyboardWillShowNotification:(NSNotification*)notification {
1494  // Immediately prior to a docked keyboard being shown or when a keyboard goes from
1495  // undocked/floating to docked, this notification is triggered. This notification also happens
1496  // when Minimized/Expanded Shortcuts bar is dropped after dragging (the keyboard's end frame will
1497  // be CGRectZero).
1498  [self.keyboardInsetManager handleKeyboardNotification:notification];
1499 }
1500 
1501 - (void)keyboardWillChangeFrame:(NSNotification*)notification {
1502  // Immediately prior to a change in keyboard frame, this notification is triggered.
1503  // Sometimes when the keyboard is being hidden or undocked, this notification's keyboard's end
1504  // frame is not yet entirely out of screen, which is why we also use
1505  // UIKeyboardWillHideNotification.
1506  [self.keyboardInsetManager handleKeyboardNotification:notification];
1507 }
1508 
1509 - (void)keyboardWillBeHidden:(NSNotification*)notification {
1510  // When keyboard is hidden or undocked, this notification will be triggered.
1511  // This notification might not occur when the keyboard is changed from docked to floating, which
1512  // is why we also use UIKeyboardWillChangeFrameNotification.
1513  [self.keyboardInsetManager handleKeyboardNotification:notification];
1514 }
1515 
1516 - (void)handlePressEvent:(FlutterUIPressProxy*)press
1517  nextAction:(void (^)())next API_AVAILABLE(ios(13.4)) {
1518  if (@available(iOS 13.4, *)) {
1519  } else {
1520  next();
1521  return;
1522  }
1523  [self.keyboardManager handlePress:press nextAction:next];
1524 }
1525 
1526 // The documentation for presses* handlers (implemented below) is entirely
1527 // unclear about how to handle the case where some, but not all, of the presses
1528 // are handled here. I've elected to call super separately for each of the
1529 // presses that aren't handled, but it's not clear if this is correct. It may be
1530 // that iOS intends for us to either handle all or none of the presses, and pass
1531 // the original set to super. I have not yet seen multiple presses in the set in
1532 // the wild, however, so I suspect that the API is built for a tvOS remote or
1533 // something, and perhaps only one ever appears in the set on iOS from a
1534 // keyboard.
1535 //
1536 // We define separate superPresses* overrides to avoid implicitly capturing self in the blocks
1537 // passed to the presses* methods below.
1538 
1539 - (void)superPressesBegan:(NSSet<UIPress*>*)presses withEvent:(UIPressesEvent*)event {
1540  [super pressesBegan:presses withEvent:event];
1541 }
1542 
1543 - (void)superPressesChanged:(NSSet<UIPress*>*)presses withEvent:(UIPressesEvent*)event {
1544  [super pressesChanged:presses withEvent:event];
1545 }
1546 
1547 - (void)superPressesEnded:(NSSet<UIPress*>*)presses withEvent:(UIPressesEvent*)event {
1548  [super pressesEnded:presses withEvent:event];
1549 }
1550 
1551 - (void)superPressesCancelled:(NSSet<UIPress*>*)presses withEvent:(UIPressesEvent*)event {
1552  [super pressesCancelled:presses withEvent:event];
1553 }
1554 
1555 // If you substantially change these presses overrides, consider also changing
1556 // the similar ones in FlutterTextInputPlugin. They need to be overridden in
1557 // both places to capture keys both inside and outside of a text field, but have
1558 // slightly different implementations.
1559 
1560 - (void)pressesBegan:(NSSet<UIPress*>*)presses
1561  withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
1562  if (@available(iOS 13.4, *)) {
1563  __weak FlutterViewController* weakSelf = self;
1564  for (UIPress* press in presses) {
1565  [self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press event:event]
1566  nextAction:^() {
1567  [weakSelf superPressesBegan:[NSSet setWithObject:press] withEvent:event];
1568  }];
1569  }
1570  } else {
1571  [super pressesBegan:presses withEvent:event];
1572  }
1573 }
1574 
1575 - (void)pressesChanged:(NSSet<UIPress*>*)presses
1576  withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
1577  if (@available(iOS 13.4, *)) {
1578  __weak FlutterViewController* weakSelf = self;
1579  for (UIPress* press in presses) {
1580  [self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press event:event]
1581  nextAction:^() {
1582  [weakSelf superPressesChanged:[NSSet setWithObject:press] withEvent:event];
1583  }];
1584  }
1585  } else {
1586  [super pressesChanged:presses withEvent:event];
1587  }
1588 }
1589 
1590 - (void)pressesEnded:(NSSet<UIPress*>*)presses
1591  withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
1592  if (@available(iOS 13.4, *)) {
1593  __weak FlutterViewController* weakSelf = self;
1594  for (UIPress* press in presses) {
1595  [self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press event:event]
1596  nextAction:^() {
1597  [weakSelf superPressesEnded:[NSSet setWithObject:press] withEvent:event];
1598  }];
1599  }
1600  } else {
1601  [super pressesEnded:presses withEvent:event];
1602  }
1603 }
1604 
1605 - (void)pressesCancelled:(NSSet<UIPress*>*)presses
1606  withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
1607  if (@available(iOS 13.4, *)) {
1608  __weak FlutterViewController* weakSelf = self;
1609  for (UIPress* press in presses) {
1610  [self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press event:event]
1611  nextAction:^() {
1612  [weakSelf superPressesCancelled:[NSSet setWithObject:press] withEvent:event];
1613  }];
1614  }
1615  } else {
1616  [super pressesCancelled:presses withEvent:event];
1617  }
1618 }
1619 
1620 #pragma mark - Orientation updates
1621 
1622 - (void)onOrientationPreferencesUpdated:(NSNotification*)notification {
1623  // Notifications may not be on the iOS UI thread
1624  __weak FlutterViewController* weakSelf = self;
1625  dispatch_async(dispatch_get_main_queue(), ^{
1626  NSDictionary* info = notification.userInfo;
1627  NSNumber* update = info[@(flutter::kOrientationUpdateNotificationKey)];
1628  if (update == nil) {
1629  return;
1630  }
1631  [weakSelf performOrientationUpdate:update.unsignedIntegerValue];
1632  });
1633 }
1634 
1635 - (void)requestGeometryUpdateForWindowScenes:(NSSet<UIScene*>*)windowScenes
1636  API_AVAILABLE(ios(16.0)) {
1637  for (UIScene* windowScene in windowScenes) {
1638  FML_DCHECK([windowScene isKindOfClass:[UIWindowScene class]]);
1639  UIWindowSceneGeometryPreferencesIOS* preference = [[UIWindowSceneGeometryPreferencesIOS alloc]
1640  initWithInterfaceOrientations:self.orientationPreferences];
1641  [(UIWindowScene*)windowScene
1642  requestGeometryUpdateWithPreferences:preference
1643  errorHandler:^(NSError* error) {
1644  os_log_error(OS_LOG_DEFAULT,
1645  "Failed to change device orientation: %@", error);
1646  }];
1647  [self setNeedsUpdateOfSupportedInterfaceOrientations];
1648  }
1649 }
1650 
1651 - (void)performOrientationUpdate:(UIInterfaceOrientationMask)new_preferences {
1652  if (new_preferences != self.orientationPreferences) {
1653  self.orientationPreferences = new_preferences;
1654 
1655  if (@available(iOS 16.0, *)) {
1656  UIApplication* flutterApplication = FlutterSharedApplication.application;
1657  NSSet<UIScene*>* scenes = [NSSet set];
1658  if (flutterApplication) {
1659  scenes = [flutterApplication.connectedScenes
1660  filteredSetUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(
1661  id scene, NSDictionary* bindings) {
1662  return [scene isKindOfClass:[UIWindowScene class]];
1663  }]];
1664  } else if (self.flutterWindowSceneIfViewLoaded) {
1665  scenes = [NSSet setWithObject:self.flutterWindowSceneIfViewLoaded];
1666  }
1667  [self requestGeometryUpdateForWindowScenes:scenes];
1668  } else {
1669  UIInterfaceOrientationMask currentInterfaceOrientation = 0;
1670  UIWindowScene* windowScene = self.flutterWindowSceneIfViewLoaded;
1671  if (!windowScene) {
1672  [FlutterLogger
1673  logWarning:
1674  @"Accessing the interface orientation when the window scene is unavailable."];
1675  return;
1676  }
1677  currentInterfaceOrientation = 1 << windowScene.interfaceOrientation;
1678  if (!(self.orientationPreferences & currentInterfaceOrientation)) {
1679  [UIViewController attemptRotationToDeviceOrientation];
1680  // Force orientation switch if the current orientation is not allowed
1681  if (self.orientationPreferences & UIInterfaceOrientationMaskPortrait) {
1682  // This is no official API but more like a workaround / hack (using
1683  // key-value coding on a read-only property). This might break in
1684  // the future, but currently it´s the only way to force an orientation change
1685  [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationPortrait)
1686  forKey:@"orientation"];
1687  } else if (self.orientationPreferences & UIInterfaceOrientationMaskPortraitUpsideDown) {
1688  [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationPortraitUpsideDown)
1689  forKey:@"orientation"];
1690  } else if (self.orientationPreferences & UIInterfaceOrientationMaskLandscapeLeft) {
1691  [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeLeft)
1692  forKey:@"orientation"];
1693  } else if (self.orientationPreferences & UIInterfaceOrientationMaskLandscapeRight) {
1694  [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeRight)
1695  forKey:@"orientation"];
1696  }
1697  }
1698  }
1699  }
1700 }
1701 
1702 - (void)onHideHomeIndicatorNotification:(NSNotification*)notification {
1703  self.isHomeIndicatorHidden = YES;
1704 }
1705 
1706 - (void)onShowHomeIndicatorNotification:(NSNotification*)notification {
1707  self.isHomeIndicatorHidden = NO;
1708 }
1709 
1710 - (void)setIsHomeIndicatorHidden:(BOOL)hideHomeIndicator {
1711  if (hideHomeIndicator != _isHomeIndicatorHidden) {
1712  _isHomeIndicatorHidden = hideHomeIndicator;
1713  [self setNeedsUpdateOfHomeIndicatorAutoHidden];
1714  }
1715 }
1716 
1717 - (BOOL)prefersHomeIndicatorAutoHidden {
1718  return self.isHomeIndicatorHidden;
1719 }
1720 
1721 - (BOOL)shouldAutorotate {
1722  return YES;
1723 }
1724 
1725 - (NSUInteger)supportedInterfaceOrientations {
1726  return self.orientationPreferences;
1727 }
1728 
1729 #pragma mark - Accessibility
1730 
1731 - (void)onAccessibilityStatusChanged:(NSNotification*)notification {
1732  if (!self.engine) {
1733  return;
1734  }
1735  BOOL enabled = NO;
1736  int32_t flags = [self.accessibilityFeatures flags];
1737 #if TARGET_OS_SIMULATOR
1738  // There doesn't appear to be any way to determine whether the accessibility
1739  // inspector is enabled on the simulator. We conservatively always turn on the
1740  // accessibility bridge in the simulator, but never assistive technology.
1741  enabled = YES;
1742 #else
1743  _isVoiceOverRunning = [self.accessibilityFeatures isVoiceOverRunning];
1744  enabled = _isVoiceOverRunning || [self.accessibilityFeatures isSwitchControlRunning] ||
1745  [self.accessibilityFeatures isSpeakScreenEnabled];
1746 #endif
1747  [self.engine enableSemantics:enabled withFlags:flags];
1748 }
1749 
1750 - (BOOL)accessibilityPerformEscape {
1751  FlutterMethodChannel* navigationChannel = self.engine.navigationChannel;
1752  if (navigationChannel) {
1753  [self popRoute];
1754  return YES;
1755  }
1756  return NO;
1757 }
1758 
1759 #pragma mark - Set user settings
1760 
1761 - (void)traitCollectionDidChange:(UITraitCollection*)previousTraitCollection {
1762  [super traitCollectionDidChange:previousTraitCollection];
1763  [self onUserSettingsChanged:nil];
1764 
1765  // Since this method can get triggered by changes in device orientation, reset and recalculate the
1766  // instrinsic size.
1767  if (self.isAutoResizable) {
1768  [self.flutterView resetIntrinsicContentSize];
1769  }
1770 }
1771 
1772 - (void)onUserSettingsChanged:(NSNotification*)notification {
1773  [self.engine.settingsChannel sendMessage:@{
1774  @"textScaleFactor" : @(self.textScaleFactor),
1775  @"alwaysUse24HourFormat" : @(FlutterHourFormat.isAlwaysUse24HourFormat),
1776  @"platformBrightness" : self.brightnessMode,
1777  @"platformContrast" : self.contrastMode,
1778  @"nativeSpellCheckServiceDefined" : @YES,
1779  @"supportsShowingSystemContextMenu" : @(self.supportsShowingSystemContextMenu)
1780  }];
1781 }
1782 
1783 - (CGFloat)textScaleFactor {
1784  UIApplication* flutterApplication = FlutterSharedApplication.application;
1785  if (flutterApplication == nil) {
1786  [FlutterLogger logWarning:@"Dynamic content size update is not supported in app extension."];
1787  return 1.0;
1788  }
1789 
1790  UIContentSizeCategory category = flutterApplication.preferredContentSizeCategory;
1791  // The delta is computed by approximating Apple's typography guidelines:
1792  // https://developer.apple.com/ios/human-interface-guidelines/visual-design/typography/
1793  //
1794  // Specifically:
1795  // Non-accessibility sizes for "body" text are:
1796  const CGFloat xs = 14;
1797  const CGFloat s = 15;
1798  const CGFloat m = 16;
1799  const CGFloat l = 17;
1800  const CGFloat xl = 19;
1801  const CGFloat xxl = 21;
1802  const CGFloat xxxl = 23;
1803 
1804  // Accessibility sizes for "body" text are:
1805  const CGFloat ax1 = 28;
1806  const CGFloat ax2 = 33;
1807  const CGFloat ax3 = 40;
1808  const CGFloat ax4 = 47;
1809  const CGFloat ax5 = 53;
1810 
1811  // We compute the scale as relative difference from size L (large, the default size), where
1812  // L is assumed to have scale 1.0.
1813  if ([category isEqualToString:UIContentSizeCategoryExtraSmall]) {
1814  return xs / l;
1815  } else if ([category isEqualToString:UIContentSizeCategorySmall]) {
1816  return s / l;
1817  } else if ([category isEqualToString:UIContentSizeCategoryMedium]) {
1818  return m / l;
1819  } else if ([category isEqualToString:UIContentSizeCategoryLarge]) {
1820  return 1.0;
1821  } else if ([category isEqualToString:UIContentSizeCategoryExtraLarge]) {
1822  return xl / l;
1823  } else if ([category isEqualToString:UIContentSizeCategoryExtraExtraLarge]) {
1824  return xxl / l;
1825  } else if ([category isEqualToString:UIContentSizeCategoryExtraExtraExtraLarge]) {
1826  return xxxl / l;
1827  } else if ([category isEqualToString:UIContentSizeCategoryAccessibilityMedium]) {
1828  return ax1 / l;
1829  } else if ([category isEqualToString:UIContentSizeCategoryAccessibilityLarge]) {
1830  return ax2 / l;
1831  } else if ([category isEqualToString:UIContentSizeCategoryAccessibilityExtraLarge]) {
1832  return ax3 / l;
1833  } else if ([category isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraLarge]) {
1834  return ax4 / l;
1835  } else if ([category isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraExtraLarge]) {
1836  return ax5 / l;
1837  } else {
1838  return 1.0;
1839  }
1840 }
1841 
1842 - (BOOL)supportsShowingSystemContextMenu {
1843  if (@available(iOS 16.0, *)) {
1844  return YES;
1845  } else {
1846  return NO;
1847  }
1848 }
1849 
1850 // The brightness mode of the platform, e.g., light or dark, expressed as a string that
1851 // is understood by the Flutter framework. See the settings
1852 // system channel for more information.
1853 - (NSString*)brightnessMode {
1854  UIUserInterfaceStyle style = self.traitCollection.userInterfaceStyle;
1855 
1856  if (style == UIUserInterfaceStyleDark) {
1857  return @"dark";
1858  } else {
1859  return @"light";
1860  }
1861 }
1862 
1863 // The contrast mode of the platform, e.g., normal or high, expressed as a string that is
1864 // understood by the Flutter framework. See the settings system channel for more
1865 // information.
1866 - (NSString*)contrastMode {
1867  UIAccessibilityContrast contrast = self.traitCollection.accessibilityContrast;
1868 
1869  if (contrast == UIAccessibilityContrastHigh) {
1870  return @"high";
1871  } else {
1872  return @"normal";
1873  }
1874 }
1875 
1876 #pragma mark - Status bar style
1877 
1878 - (UIStatusBarStyle)preferredStatusBarStyle {
1879  return self.statusBarStyle;
1880 }
1881 
1882 - (void)onPreferredStatusBarStyleUpdated:(NSNotification*)notification {
1883  // Notifications may not be on the iOS UI thread
1884  __weak FlutterViewController* weakSelf = self;
1885  dispatch_async(dispatch_get_main_queue(), ^{
1886  FlutterViewController* strongSelf = weakSelf;
1887  if (!strongSelf) {
1888  return;
1889  }
1890 
1891  NSDictionary* info = notification.userInfo;
1892  NSNumber* update = info[@(flutter::kOverlayStyleUpdateNotificationKey)];
1893  if (update == nil) {
1894  return;
1895  }
1896 
1897  UIStatusBarStyle style = static_cast<UIStatusBarStyle>(update.integerValue);
1898  if (style != strongSelf.statusBarStyle) {
1899  strongSelf.statusBarStyle = style;
1900  [strongSelf setNeedsStatusBarAppearanceUpdate];
1901  }
1902  });
1903 }
1904 
1905 - (void)setPrefersStatusBarHidden:(BOOL)hidden {
1906  if (hidden != self.flutterPrefersStatusBarHidden) {
1907  self.flutterPrefersStatusBarHidden = hidden;
1908  [self setNeedsStatusBarAppearanceUpdate];
1909  }
1910 }
1911 
1912 - (BOOL)prefersStatusBarHidden {
1913  return self.flutterPrefersStatusBarHidden;
1914 }
1915 
1916 #pragma mark - Platform views
1917 
1918 - (FlutterPlatformViewsController*)platformViewsController {
1919  return self.engine.platformViewsController;
1920 }
1921 
1922 - (NSObject<FlutterBinaryMessenger>*)binaryMessenger {
1923  return self.engine.binaryMessenger;
1924 }
1925 
1926 #pragma mark - FlutterBinaryMessenger
1927 
1928 - (void)sendOnChannel:(NSString*)channel message:(NSData*)message {
1929  [self.engine.binaryMessenger sendOnChannel:channel message:message];
1930 }
1931 
1932 - (void)sendOnChannel:(NSString*)channel
1933  message:(NSData*)message
1934  binaryReply:(FlutterBinaryReply)callback {
1935  NSAssert(channel, @"The channel must not be null");
1936  [self.engine.binaryMessenger sendOnChannel:channel message:message binaryReply:callback];
1937 }
1938 
1939 - (NSObject<FlutterTaskQueue>*)makeBackgroundTaskQueue {
1940  return [self.engine.binaryMessenger makeBackgroundTaskQueue];
1941 }
1942 
1943 - (FlutterBinaryMessengerConnection)setMessageHandlerOnChannel:(NSString*)channel
1944  binaryMessageHandler:
1945  (FlutterBinaryMessageHandler)handler {
1946  return [self setMessageHandlerOnChannel:channel binaryMessageHandler:handler taskQueue:nil];
1947 }
1948 
1950  setMessageHandlerOnChannel:(NSString*)channel
1951  binaryMessageHandler:(FlutterBinaryMessageHandler _Nullable)handler
1952  taskQueue:(NSObject<FlutterTaskQueue>* _Nullable)taskQueue {
1953  NSAssert(channel, @"The channel must not be null");
1954  return [self.engine.binaryMessenger setMessageHandlerOnChannel:channel
1955  binaryMessageHandler:handler
1956  taskQueue:taskQueue];
1957 }
1958 
1959 - (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection {
1960  [self.engine.binaryMessenger cleanUpConnection:connection];
1961 }
1962 
1963 #pragma mark - FlutterTextureRegistry
1964 
1965 - (int64_t)registerTexture:(NSObject<FlutterTexture>*)texture {
1966  return [self.engine.textureRegistry registerTexture:texture];
1967 }
1968 
1969 - (void)unregisterTexture:(int64_t)textureId {
1970  [self.engine.textureRegistry unregisterTexture:textureId];
1971 }
1972 
1973 - (void)textureFrameAvailable:(int64_t)textureId {
1974  [self.engine.textureRegistry textureFrameAvailable:textureId];
1975 }
1976 
1977 - (NSString*)lookupKeyForAsset:(NSString*)asset {
1978  return [FlutterDartProject lookupKeyForAsset:asset];
1979 }
1980 
1981 - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
1982  return [FlutterDartProject lookupKeyForAsset:asset fromPackage:package];
1983 }
1984 
1985 - (id<FlutterPluginRegistry>)pluginRegistry {
1986  return self.engine;
1987 }
1988 
1989 + (BOOL)isUIAccessibilityIsVoiceOverRunning {
1990  return UIAccessibilityIsVoiceOverRunning();
1991 }
1992 
1993 #pragma mark - FlutterPluginRegistry
1994 
1995 - (NSObject<FlutterPluginRegistrar>*)registrarForPlugin:(NSString*)pluginKey {
1996  return [self.engine registrarForPlugin:pluginKey];
1997 }
1998 
1999 - (BOOL)hasPlugin:(NSString*)pluginKey {
2000  return [self.engine hasPlugin:pluginKey];
2001 }
2002 
2003 - (NSObject*)valuePublishedByPlugin:(NSString*)pluginKey {
2004  return [self.engine valuePublishedByPlugin:pluginKey];
2005 }
2006 
2007 - (void)presentViewController:(UIViewController*)viewControllerToPresent
2008  animated:(BOOL)flag
2009  completion:(void (^)(void))completion {
2010  self.isPresentingViewControllerAnimating = YES;
2011  __weak FlutterViewController* weakSelf = self;
2012  [super presentViewController:viewControllerToPresent
2013  animated:flag
2014  completion:^{
2015  weakSelf.isPresentingViewControllerAnimating = NO;
2016  if (completion) {
2017  completion();
2018  }
2019  }];
2020 }
2021 
2022 - (BOOL)isPresentingViewController {
2023  return self.presentedViewController != nil || self.isPresentingViewControllerAnimating;
2024 }
2025 
2026 - (flutter::PointerData)updateMousePointerDataFrom:(UIGestureRecognizer*)gestureRecognizer
2027  API_AVAILABLE(ios(13.4)) {
2028  CGPoint location = [gestureRecognizer locationInView:self.view];
2029  CGFloat scale = self.flutterScreenIfViewLoaded.scale;
2030  _mouseState.location = {location.x * scale, location.y * scale};
2031  flutter::PointerData pointer_data;
2032  pointer_data.Clear();
2033  pointer_data.time_stamp = [[NSProcessInfo processInfo] systemUptime] * kMicrosecondsPerSecond;
2034  pointer_data.physical_x = _mouseState.location.x;
2035  pointer_data.physical_y = _mouseState.location.y;
2036  return pointer_data;
2037 }
2038 
2039 - (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer
2040  shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer*)otherGestureRecognizer
2041  API_AVAILABLE(ios(13.4)) {
2042  return YES;
2043 }
2044 
2045 - (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer
2046  shouldReceiveEvent:(UIEvent*)event API_AVAILABLE(ios(13.4)) {
2047  if (gestureRecognizer == _continuousScrollingPanGestureRecognizer &&
2048  event.type == UIEventTypeScroll) {
2049  // Events with type UIEventTypeScroll are only received when running on macOS under emulation.
2050  flutter::PointerData pointer_data = [self updateMousePointerDataFrom:gestureRecognizer];
2051  pointer_data.device = reinterpret_cast<int64_t>(_continuousScrollingPanGestureRecognizer);
2052  pointer_data.kind = flutter::PointerData::DeviceKind::kTrackpad;
2053  pointer_data.signal_kind = flutter::PointerData::SignalKind::kScrollInertiaCancel;
2054  pointer_data.view_id = self.viewIdentifier;
2055 
2056  if (event.timestamp < self.scrollInertiaEventAppKitDeadline) {
2057  // Only send the event if it occured before the expected natural end of gesture momentum.
2058  // If received after the deadline, it's not likely the event is from a user-initiated cancel.
2059  auto packet = std::make_unique<flutter::PointerDataPacket>(1);
2060  packet->SetPointerData(/*i=*/0, pointer_data);
2061  [self.engine dispatchPointerDataPacket:std::move(packet)];
2062  self.scrollInertiaEventAppKitDeadline = 0;
2063  }
2064  }
2065  // This method is also called for UITouches, should return YES to process all touches.
2066  return YES;
2067 }
2068 
2069 - (void)hoverEvent:(UIHoverGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) {
2070  CGPoint oldLocation = _mouseState.location;
2071 
2072  flutter::PointerData pointer_data = [self updateMousePointerDataFrom:recognizer];
2073  pointer_data.device = reinterpret_cast<int64_t>(recognizer);
2074  pointer_data.kind = flutter::PointerData::DeviceKind::kMouse;
2075  pointer_data.view_id = self.viewIdentifier;
2076 
2077  switch (_hoverGestureRecognizer.state) {
2078  case UIGestureRecognizerStateBegan:
2079  pointer_data.change = flutter::PointerData::Change::kAdd;
2080  break;
2081  case UIGestureRecognizerStateChanged:
2082  pointer_data.change = flutter::PointerData::Change::kHover;
2083  break;
2084  case UIGestureRecognizerStateEnded:
2085  case UIGestureRecognizerStateCancelled:
2086  pointer_data.change = flutter::PointerData::Change::kRemove;
2087  break;
2088  default:
2089  // Sending kHover is the least harmful thing to do here
2090  // But this state is not expected to ever be reached.
2091  pointer_data.change = flutter::PointerData::Change::kHover;
2092  break;
2093  }
2094 
2095  NSTimeInterval time = [NSProcessInfo processInfo].systemUptime;
2096  BOOL isRunningOnMac = NO;
2097  // This "stationary pointer" heuristic is not reliable when running within macOS.
2098  // We instead receive a scroll cancel event directly from AppKit.
2099  // See gestureRecognizer:shouldReceiveEvent:
2100  isRunningOnMac = [NSProcessInfo processInfo].iOSAppOnMac;
2101  if (!isRunningOnMac && CGPointEqualToPoint(oldLocation, _mouseState.location) &&
2102  time > self.scrollInertiaEventStartline) {
2103  // iPadOS reports trackpad movements events with high (sub-pixel) precision. When an event
2104  // is received with the same position as the previous one, it can only be from a finger
2105  // making or breaking contact with the trackpad surface.
2106  auto packet = std::make_unique<flutter::PointerDataPacket>(2);
2107  packet->SetPointerData(/*i=*/0, pointer_data);
2108  flutter::PointerData inertia_cancel = pointer_data;
2109  inertia_cancel.device = reinterpret_cast<int64_t>(_continuousScrollingPanGestureRecognizer);
2110  inertia_cancel.kind = flutter::PointerData::DeviceKind::kTrackpad;
2111  inertia_cancel.signal_kind = flutter::PointerData::SignalKind::kScrollInertiaCancel;
2112  inertia_cancel.view_id = self.viewIdentifier;
2113  packet->SetPointerData(/*i=*/1, inertia_cancel);
2114  [self.engine dispatchPointerDataPacket:std::move(packet)];
2115  self.scrollInertiaEventStartline = DBL_MAX;
2116  } else {
2117  auto packet = std::make_unique<flutter::PointerDataPacket>(1);
2118  packet->SetPointerData(/*i=*/0, pointer_data);
2119  [self.engine dispatchPointerDataPacket:std::move(packet)];
2120  }
2121 }
2122 
2123 - (void)discreteScrollEvent:(UIPanGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) {
2124  CGPoint translation = [recognizer translationInView:self.view];
2125  const CGFloat scale = self.flutterScreenIfViewLoaded.scale;
2126 
2127  translation.x *= scale;
2128  translation.y *= scale;
2129 
2130  flutter::PointerData pointer_data = [self updateMousePointerDataFrom:recognizer];
2131  pointer_data.device = reinterpret_cast<int64_t>(recognizer);
2132  pointer_data.kind = flutter::PointerData::DeviceKind::kMouse;
2133  pointer_data.signal_kind = flutter::PointerData::SignalKind::kScroll;
2134  pointer_data.scroll_delta_x = (translation.x - _mouseState.last_translation.x);
2135  pointer_data.scroll_delta_y = -(translation.y - _mouseState.last_translation.y);
2136  pointer_data.view_id = self.viewIdentifier;
2137 
2138  // The translation reported by UIPanGestureRecognizer is the total translation
2139  // generated by the pan gesture since the gesture began. We need to be able
2140  // to keep track of the last translation value in order to generate the deltaX
2141  // and deltaY coordinates for each subsequent scroll event.
2142  if (recognizer.state != UIGestureRecognizerStateEnded) {
2143  _mouseState.last_translation = translation;
2144  } else {
2145  _mouseState.last_translation = CGPointZero;
2146  }
2147 
2148  auto packet = std::make_unique<flutter::PointerDataPacket>(1);
2149  packet->SetPointerData(/*i=*/0, pointer_data);
2150  [self.engine dispatchPointerDataPacket:std::move(packet)];
2151 }
2152 
2153 - (void)continuousScrollEvent:(UIPanGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) {
2154  CGPoint translation = [recognizer translationInView:self.view];
2155  const CGFloat scale = self.flutterScreenIfViewLoaded.scale;
2156 
2157  flutter::PointerData pointer_data = [self updateMousePointerDataFrom:recognizer];
2158  pointer_data.device = reinterpret_cast<int64_t>(recognizer);
2159  pointer_data.kind = flutter::PointerData::DeviceKind::kTrackpad;
2160  pointer_data.view_id = self.viewIdentifier;
2161  switch (recognizer.state) {
2162  case UIGestureRecognizerStateBegan:
2163  pointer_data.change = flutter::PointerData::Change::kPanZoomStart;
2164  break;
2165  case UIGestureRecognizerStateChanged:
2166  pointer_data.change = flutter::PointerData::Change::kPanZoomUpdate;
2167  pointer_data.pan_x = translation.x * scale;
2168  pointer_data.pan_y = translation.y * scale;
2169  pointer_data.pan_delta_x = 0; // Delta will be generated in pointer_data_packet_converter.cc.
2170  pointer_data.pan_delta_y = 0; // Delta will be generated in pointer_data_packet_converter.cc.
2171  pointer_data.scale = 1;
2172  break;
2173  case UIGestureRecognizerStateEnded:
2174  case UIGestureRecognizerStateCancelled:
2175  self.scrollInertiaEventStartline =
2176  [[NSProcessInfo processInfo] systemUptime] +
2177  0.1; // Time to lift fingers off trackpad (experimentally determined)
2178  // When running an iOS app on an Apple Silicon Mac, AppKit will send an event
2179  // of type UIEventTypeScroll when trackpad scroll momentum has ended. This event
2180  // is sent whether the momentum ended normally or was cancelled by a trackpad touch.
2181  // Since Flutter scrolling inertia will likely not match the system inertia, we should
2182  // only send a PointerScrollInertiaCancel event for user-initiated cancellations.
2183  // The following (curve-fitted) calculation provides a cutoff point after which any
2184  // UIEventTypeScroll event will likely be from the system instead of the user.
2185  // See https://github.com/flutter/engine/pull/34929.
2186  self.scrollInertiaEventAppKitDeadline =
2187  [[NSProcessInfo processInfo] systemUptime] +
2188  (0.1821 * log(fmax([recognizer velocityInView:self.view].x,
2189  [recognizer velocityInView:self.view].y))) -
2190  0.4825;
2191  pointer_data.change = flutter::PointerData::Change::kPanZoomEnd;
2192  break;
2193  default:
2194  // continuousScrollEvent: should only ever be triggered with the above phases
2195  NSAssert(NO, @"Trackpad pan event occured with unexpected phase 0x%lx",
2196  (long)recognizer.state);
2197  break;
2198  }
2199 
2200  auto packet = std::make_unique<flutter::PointerDataPacket>(1);
2201  packet->SetPointerData(/*i=*/0, pointer_data);
2202  [self.engine dispatchPointerDataPacket:std::move(packet)];
2203 }
2204 
2205 - (void)pinchEvent:(UIPinchGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) {
2206  flutter::PointerData pointer_data = [self updateMousePointerDataFrom:recognizer];
2207  pointer_data.device = reinterpret_cast<int64_t>(recognizer);
2208  pointer_data.kind = flutter::PointerData::DeviceKind::kTrackpad;
2209  pointer_data.view_id = self.viewIdentifier;
2210  switch (recognizer.state) {
2211  case UIGestureRecognizerStateBegan:
2212  pointer_data.change = flutter::PointerData::Change::kPanZoomStart;
2213  break;
2214  case UIGestureRecognizerStateChanged:
2215  pointer_data.change = flutter::PointerData::Change::kPanZoomUpdate;
2216  pointer_data.scale = recognizer.scale;
2217  pointer_data.rotation = _rotationGestureRecognizer.rotation;
2218  break;
2219  case UIGestureRecognizerStateEnded:
2220  case UIGestureRecognizerStateCancelled:
2221  pointer_data.change = flutter::PointerData::Change::kPanZoomEnd;
2222  break;
2223  default:
2224  // pinchEvent: should only ever be triggered with the above phases
2225  NSAssert(NO, @"Trackpad pinch event occured with unexpected phase 0x%lx",
2226  (long)recognizer.state);
2227  break;
2228  }
2229 
2230  auto packet = std::make_unique<flutter::PointerDataPacket>(1);
2231  packet->SetPointerData(/*i=*/0, pointer_data);
2232  [self.engine dispatchPointerDataPacket:std::move(packet)];
2233 }
2234 
2235 #pragma mark - State Restoration
2236 
2237 - (void)encodeRestorableStateWithCoder:(NSCoder*)coder {
2238  NSData* restorationData = [self.engine.restorationPlugin restorationData];
2239  [coder encodeBytes:(const unsigned char*)restorationData.bytes
2240  length:restorationData.length
2241  forKey:kFlutterRestorationStateAppData];
2242  [super encodeRestorableStateWithCoder:coder];
2243 }
2244 
2245 - (void)decodeRestorableStateWithCoder:(NSCoder*)coder {
2246  NSUInteger restorationDataLength;
2247  const unsigned char* restorationBytes = [coder decodeBytesForKey:kFlutterRestorationStateAppData
2248  returnedLength:&restorationDataLength];
2249  NSData* restorationData = [NSData dataWithBytes:restorationBytes length:restorationDataLength];
2250  [self.engine.restorationPlugin setRestorationData:restorationData];
2251 }
2252 
2253 - (FlutterRestorationPlugin*)restorationPlugin {
2254  return self.engine.restorationPlugin;
2255 }
2256 
2258  return self.engine.textInputPlugin;
2259 }
2260 
2261 #pragma mark - FlutterKeyboardInsetManagerDelegate
2262 
2263 - (void)updateViewportMetricsWithInset:(CGFloat)inset {
2264  _viewportMetrics.physical_view_inset_bottom = inset;
2265  [self updateViewportMetricsIfNeeded];
2266 }
2267 
2268 - (CGFloat)physicalViewInsetBottom {
2269  return _viewportMetrics.physical_view_inset_bottom;
2270 }
2271 
2272 - (FlutterFMLTaskRunner*)uiTaskRunner {
2273  return self.engine.uiTaskRunner;
2274 }
2275 
2276 - (BOOL)isPadInSlideOverOrStageManagerMode {
2277  if (self.view.traitCollection.userInterfaceIdiom == UIUserInterfaceIdiomPad &&
2278  self.view.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact &&
2279  self.view.traitCollection.verticalSizeClass == UIUserInterfaceSizeClassRegular) {
2280  return YES;
2281  }
2282  return NO;
2283 }
2284 
2285 - (CGRect)convertViewRectToScreen:(CGRect)rect {
2286  return [self.view convertRect:rect
2287  toCoordinateSpace:self.flutterScreenIfViewLoaded.coordinateSpace];
2288 }
2289 
2290 @end
NS_ASSUME_NONNULL_BEGIN typedef void(^ FlutterBinaryReply)(NSData *_Nullable reply)
void(^ FlutterBinaryMessageHandler)(NSData *_Nullable message, FlutterBinaryReply reply)
int64_t FlutterBinaryMessengerConnection
void(^ FlutterSendKeyEvent)(const FlutterKeyEvent &, _Nullable FlutterKeyEventCallback, void *_Nullable)
UITextSmartQuotesType smartQuotesType API_AVAILABLE(ios(11.0))
instancetype initWithCoder
FlutterTextInputPlugin * textInputPlugin
NSNotificationName const FlutterViewControllerHideHomeIndicator
FlutterSplashScreenManager * _splashScreenManager
static NSString *const kFlutterRestorationStateAppData
NSNotificationName const FlutterViewControllerShowHomeIndicator
NSNotificationName const FlutterSemanticsUpdateNotification
struct MouseState MouseState
static constexpr CGFloat kScrollViewContentSize
NSNotificationName const FlutterViewControllerWillDealloc
static constexpr FLUTTER_ASSERT_ARC int kMicrosecondsPerSecond
MouseState _mouseState
UIPanGestureRecognizer *continuousScrollingPanGestureRecognizer API_AVAILABLE(ios(13.4))
UIPanGestureRecognizer *discreteScrollingPanGestureRecognizer API_AVAILABLE(ios(13.4))
UIPinchGestureRecognizer *pinchGestureRecognizer API_AVAILABLE(ios(13.4))
UIHoverGestureRecognizer *hoverGestureRecognizer API_AVAILABLE(ios(13.4))
NSString * lookupKeyForAsset:fromPackage:(NSString *asset,[fromPackage] NSString *package)
NSString * lookupKeyForAsset:(NSString *asset)
void setUpIndirectScribbleInteraction:(id< FlutterViewResponder > viewResponder)