5 #define FML_USED_ON_EMBEDDER
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"
51 @"FlutterViewControllerHideHomeIndicator";
53 @"FlutterViewControllerShowHomeIndicator";
71 @property(nonatomic, readonly) int64_t viewIdentifier;
76 @property(nonatomic, strong)
void (^flutterViewRenderedCallback)(void);
78 @property(nonatomic, assign) UIInterfaceOrientationMask orientationPreferences;
79 @property(nonatomic, assign) UIStatusBarStyle statusBarStyle;
80 @property(nonatomic, assign) BOOL initialized;
81 @property(nonatomic, assign) BOOL engineNeedsLaunch;
82 @property(nonatomic, assign) BOOL awokenFromNib;
85 @property(nonatomic, assign) BOOL isHomeIndicatorHidden;
86 @property(nonatomic, assign) BOOL isPresentingViewControllerAnimating;
89 @property(nonatomic, assign) BOOL flutterPrefersStatusBarHidden;
91 @property(nonatomic, strong) NSMutableSet<NSNumber*>* ongoingTouches;
96 @property(nonatomic, strong) UIScrollView* scrollView;
97 @property(nonatomic, strong) UIView* keyboardAnimationView;
98 @property(nonatomic, strong) SpringAnimation* keyboardSpringAnimation;
103 @property(nonatomic, assign) BOOL shouldIgnoreViewportMetricsUpdatesDuringRotation;
107 @property(nonatomic, assign) CGFloat targetViewInsetBottom;
108 @property(nonatomic, assign) CGFloat originalViewInsetBottom;
109 @property(nonatomic, strong)
VSyncClient* keyboardAnimationVSyncClient;
110 @property(nonatomic, assign) BOOL keyboardAnimationIsShowing;
111 @property(nonatomic, assign) fml::TimePoint keyboardAnimationStartTime;
112 @property(nonatomic, assign) BOOL isKeyboardInOrTransitioningFromBackground;
115 @property(nonatomic, assign) NSTimeInterval scrollInertiaEventStartline;
123 @property(nonatomic, assign) NSTimeInterval scrollInertiaEventAppKitDeadline;
131 @property(nonatomic, strong)
VSyncClient* touchRateCorrectionVSyncClient;
135 @property(nonatomic, assign) CGSize sizeBeforeAutoResized;
141 @property(nonatomic, strong)
144 @property(nonatomic, strong)
145 UIPanGestureRecognizer* discreteScrollingPanGestureRecognizer
API_AVAILABLE(ios(13.4));
147 @property(nonatomic, strong)
148 UIPanGestureRecognizer* continuousScrollingPanGestureRecognizer
API_AVAILABLE(ios(13.4));
150 @property(nonatomic, strong)
153 @property(nonatomic, strong)
154 UIRotationGestureRecognizer* rotationGestureRecognizer
API_AVAILABLE(ios(13.4));
157 - (void)addInternalPlugins;
158 - (void)deregisterNotifications;
161 - (void)onFirstFrameRendered;
164 - (void)handleKeyboardAnimationCallbackWithTargetTime:(
fml::TimePoint)targetTime;
168 flutter::ViewportMetrics _viewportMetrics;
173 @synthesize viewOpaque = _viewOpaque;
174 @synthesize displayingFlutterUI = _displayingFlutterUI;
179 @dynamic viewIdentifier;
181 #pragma mark - Manage and override all designated initializers
184 nibName:(nullable NSString*)nibName
185 bundle:(nullable NSBundle*)nibBundle {
186 FML_CHECK(
engine) <<
"initWithEngine:nibName:bundle: must be called with non-nil engine";
187 self = [
super initWithNibName:nibName bundle:nibBundle];
190 if (
engine.viewController) {
191 NSString* errorMessage =
192 [NSString stringWithFormat:
193 @"The supplied FlutterEngine %@ is already used with FlutterViewController "
194 "instance %@. One instance of the FlutterEngine can only be attached to "
195 "one FlutterViewController at a time. Set FlutterEngine.viewController to "
196 "nil before attaching it to another FlutterViewController.",
197 engine.description, engine.viewController.description];
198 [FlutterLogger logError:errorMessage];
201 _engineNeedsLaunch = NO;
202 _flutterView = [[
FlutterView alloc] initWithDelegate:_engine
203 opaque:self.isViewOpaque
204 enableWideGamut:engine.project.isWideGamutEnabled];
205 _ongoingTouches = [[NSMutableSet alloc] init];
209 [
self performCommonViewControllerInitialization];
210 [engine setViewController:self];
217 nibName:(NSString*)nibName
218 bundle:(NSBundle*)nibBundle {
219 self = [
super initWithNibName:nibName bundle:nibBundle];
223 [
self sharedSetupWithProject:project initialRoute:nil];
230 initialRoute:(NSString*)initialRoute
231 nibName:(NSString*)nibName
232 bundle:(NSBundle*)nibBundle {
233 self = [
super initWithNibName:nibName bundle:nibBundle];
237 [
self sharedSetupWithProject:project initialRoute:initialRoute];
243 - (instancetype)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil {
244 return [
self initWithProject:nil nibName:nil bundle:nil];
248 self = [
super initWithCoder:aDecoder];
252 - (void)awakeFromNib {
253 [
super awakeFromNib];
254 self.awokenFromNib = YES;
256 [
self sharedSetupWithProject:nil initialRoute:nil];
260 - (instancetype)init {
261 return [
self initWithProject:nil nibName:nil bundle:nil];
265 initialRoute:(nullable NSString*)initialRoute {
268 if ([appDelegate respondsToSelector:
@selector(takeLaunchEngine)]) {
273 engine = [appDelegate takeLaunchEngine];
278 [appDelegate takeLaunchEngine];
290 allowHeadlessExecution:self.engineAllowHeadlessExecution
291 restorationEnabled:self.restorationIdentifier != nil];
299 _flutterView = [[
FlutterView alloc] initWithDelegate:_engine
301 enableWideGamut:engine.project.isWideGamutEnabled];
302 [_engine createShell:nil libraryURI:nil initialRoute:initialRoute];
308 BOOL performedCallback = [_engine performImplicitEngineCallback];
312 respondsToSelector:
@selector(pluginRegistrant)]) {
313 NSObject<FlutterPluginRegistrant>* pluginRegistrant =
315 [pluginRegistrant registerWithRegistry:self];
316 performedCallback = YES;
324 id applicationLifeCycleDelegate = ((
FlutterAppDelegate*)appDelegate).lifeCycleDelegate;
325 [applicationLifeCycleDelegate
326 sceneFallbackWillFinishLaunchingApplication:FlutterSharedApplication.application];
327 [applicationLifeCycleDelegate
328 sceneFallbackDidFinishLaunchingApplication:FlutterSharedApplication.application];
331 _engineNeedsLaunch = YES;
332 _ongoingTouches = [[NSMutableSet alloc] init];
336 [
self loadDefaultSplashScreenView];
337 [
self performCommonViewControllerInitialization];
340 - (BOOL)isViewOpaque {
344 - (void)setViewOpaque:(BOOL)value {
346 if (
self.flutterView.layer.opaque != value) {
347 self.flutterView.layer.opaque = value;
348 [
self.flutterView.layer setNeedsLayout];
352 #pragma mark - Common view controller initialization tasks
354 - (void)performCommonViewControllerInitialization {
360 _orientationPreferences = UIInterfaceOrientationMaskAll;
361 _statusBarStyle = UIStatusBarStyleDefault;
365 [
self setUpNotificationCenterObservers];
368 - (void)setUpNotificationCenterObservers {
369 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
370 [center addObserver:self
371 selector:@selector(onOrientationPreferencesUpdated:)
372 name:@(flutter::kOrientationUpdateNotificationName)
375 [center addObserver:self
376 selector:@selector(onPreferredStatusBarStyleUpdated:)
377 name:@(flutter::kOverlayStyleUpdateNotificationName)
381 [
self setUpApplicationLifecycleNotifications:center];
383 [
self setUpSceneLifecycleNotifications:center];
386 [center addObserver:self
387 selector:@selector(keyboardWillChangeFrame:)
388 name:UIKeyboardWillChangeFrameNotification
391 [center addObserver:self
392 selector:@selector(keyboardWillShowNotification:)
393 name:UIKeyboardWillShowNotification
396 [center addObserver:self
397 selector:@selector(keyboardWillBeHidden:)
398 name:UIKeyboardWillHideNotification
401 [center addObserver:self
402 selector:@selector(onAccessibilityStatusChanged:)
403 name:UIAccessibilityVoiceOverStatusDidChangeNotification
406 [center addObserver:self
407 selector:@selector(onAccessibilityStatusChanged:)
408 name:UIAccessibilitySwitchControlStatusDidChangeNotification
411 [center addObserver:self
412 selector:@selector(onAccessibilityStatusChanged:)
413 name:UIAccessibilitySpeakScreenStatusDidChangeNotification
416 [center addObserver:self
417 selector:@selector(onAccessibilityStatusChanged:)
418 name:UIAccessibilityInvertColorsStatusDidChangeNotification
421 [center addObserver:self
422 selector:@selector(onAccessibilityStatusChanged:)
423 name:UIAccessibilityReduceMotionStatusDidChangeNotification
426 [center addObserver:self
427 selector:@selector(onAccessibilityStatusChanged:)
428 name:UIAccessibilityBoldTextStatusDidChangeNotification
431 [center addObserver:self
432 selector:@selector(onAccessibilityStatusChanged:)
433 name:UIAccessibilityDarkerSystemColorsStatusDidChangeNotification
436 [center addObserver:self
437 selector:@selector(onAccessibilityStatusChanged:)
438 name:UIAccessibilityOnOffSwitchLabelsDidChangeNotification
441 [center addObserver:self
442 selector:@selector(onUserSettingsChanged:)
443 name:UIContentSizeCategoryDidChangeNotification
446 [center addObserver:self
447 selector:@selector(onHideHomeIndicatorNotification:)
448 name:FlutterViewControllerHideHomeIndicator
451 [center addObserver:self
452 selector:@selector(onShowHomeIndicatorNotification:)
453 name:FlutterViewControllerShowHomeIndicator
457 - (void)setUpSceneLifecycleNotifications:(NSNotificationCenter*)center API_AVAILABLE(ios(13.0)) {
458 [center addObserver:self
459 selector:@selector(sceneBecameActive:)
460 name:UISceneDidActivateNotification
463 [center addObserver:self
464 selector:@selector(sceneWillResignActive:)
465 name:UISceneWillDeactivateNotification
468 [center addObserver:self
469 selector:@selector(sceneWillDisconnect:)
470 name:UISceneDidDisconnectNotification
473 [center addObserver:self
474 selector:@selector(sceneDidEnterBackground:)
475 name:UISceneDidEnterBackgroundNotification
478 [center addObserver:self
479 selector:@selector(sceneWillEnterForeground:)
480 name:UISceneWillEnterForegroundNotification
484 - (void)setUpApplicationLifecycleNotifications:(NSNotificationCenter*)center {
485 [center addObserver:self
486 selector:@selector(applicationBecameActive:)
487 name:UIApplicationDidBecomeActiveNotification
490 [center addObserver:self
491 selector:@selector(applicationWillResignActive:)
492 name:UIApplicationWillResignActiveNotification
495 [center addObserver:self
496 selector:@selector(applicationWillTerminate:)
497 name:UIApplicationWillTerminateNotification
500 [center addObserver:self
501 selector:@selector(applicationDidEnterBackground:)
502 name:UIApplicationDidEnterBackgroundNotification
505 [center addObserver:self
506 selector:@selector(applicationWillEnterForeground:)
507 name:UIApplicationWillEnterForegroundNotification
511 - (void)setInitialRoute:(NSString*)route {
512 [
self.engine.navigationChannel invokeMethod:@"setInitialRoute" arguments:route];
516 [
self.engine.navigationChannel invokeMethod:@"popRoute" arguments:nil];
519 - (void)pushRoute:(NSString*)route {
520 [
self.engine.navigationChannel invokeMethod:@"pushRoute" arguments:route];
523 #pragma mark - Loading the view
525 static UIView* GetViewOrPlaceholder(UIView* existing_view) {
527 return existing_view;
530 auto placeholder = [[UIView alloc] init];
532 placeholder.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
533 placeholder.backgroundColor = UIColor.systemBackgroundColor;
534 placeholder.autoresizesSubviews = YES;
539 if (flutter::GetTracingResult() == flutter::TracingResult::kDisabled) {
540 auto messageLabel = [[UILabel alloc] init];
541 messageLabel.numberOfLines = 0u;
542 messageLabel.textAlignment = NSTextAlignmentCenter;
543 messageLabel.autoresizingMask =
544 UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
546 @"In iOS 14+, debug mode Flutter apps can only be launched from Flutter tooling, "
547 @"IDEs with Flutter plugins or from Xcode.\n\nAlternatively, build in profile or release "
548 @"modes to enable launching from the home screen.";
549 [placeholder addSubview:messageLabel];
556 self.view = GetViewOrPlaceholder(
self.flutterView);
557 self.view.multipleTouchEnabled = YES;
558 self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
560 [
self installSplashScreenViewIfNecessary];
563 UIScrollView* scrollView = [[UIScrollView alloc] init];
564 scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
566 scrollView.backgroundColor = UIColor.whiteColor;
567 scrollView.delegate =
self;
573 [
self.view addSubview:scrollView];
574 self.scrollView = scrollView;
577 - (
flutter::PointerData)generatePointerDataForFake {
578 flutter::PointerData pointer_data;
579 pointer_data.Clear();
580 pointer_data.kind = flutter::PointerData::DeviceKind::kTouch;
588 - (BOOL)scrollViewShouldScrollToTop:(UIScrollView*)scrollView {
592 if (
self.isViewLoaded) {
594 [
self.engine onStatusBarTap];
599 #pragma mark - Managing launch views
601 - (void)installSplashScreenViewIfNecessary {
604 if (
self.splashScreenView && (
self.isBeingPresented ||
self.isMovingToParentViewController)) {
605 [
self.splashScreenView removeFromSuperview];
606 self.splashScreenView = nil;
611 UIView* splashScreenView =
self.splashScreenView;
612 if (splashScreenView == nil) {
615 splashScreenView.frame =
self.view.bounds;
616 [
self.view addSubview:splashScreenView];
619 + (BOOL)automaticallyNotifiesObserversOfDisplayingFlutterUI {
623 - (void)setDisplayingFlutterUI:(BOOL)displayingFlutterUI {
624 if (_displayingFlutterUI != displayingFlutterUI) {
625 if (displayingFlutterUI == YES) {
626 if (!
self.viewIfLoaded.window) {
630 [
self willChangeValueForKey:@"displayingFlutterUI"];
631 _displayingFlutterUI = displayingFlutterUI;
632 [
self didChangeValueForKey:@"displayingFlutterUI"];
636 - (void)callViewRenderedCallback {
637 self.displayingFlutterUI = YES;
638 if (
self.flutterViewRenderedCallback) {
639 self.flutterViewRenderedCallback();
640 self.flutterViewRenderedCallback = nil;
644 - (void)removeSplashScreenWithCompletion:(dispatch_block_t _Nullable)onComplete {
645 NSAssert(
self.splashScreenView,
@"The splash screen view must not be nil");
646 UIView* splashScreen =
self.splashScreenView;
648 _splashScreenView = nil;
649 [UIView animateWithDuration:0.2
651 splashScreen.alpha = 0;
653 completion:^(BOOL finished) {
654 [splashScreen removeFromSuperview];
661 - (void)onFirstFrameRendered {
662 if (
self.splashScreenView) {
664 [
self removeSplashScreenWithCompletion:^{
665 [weakSelf callViewRenderedCallback];
668 [
self callViewRenderedCallback];
672 - (void)installFirstFrameCallback {
677 [
self.engine installFirstFrameCallback:^{
678 [weakSelf onFirstFrameRendered];
682 #pragma mark - Properties
684 - (int64_t)viewIdentifier {
687 return flutter::kFlutterImplicitViewId;
690 - (BOOL)loadDefaultSplashScreenView {
691 NSString* launchscreenName =
692 [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UILaunchStoryboardName"];
693 if (launchscreenName == nil) {
696 UIView* splashView = [
self splashScreenFromStoryboard:launchscreenName];
698 splashView = [
self splashScreenFromXib:launchscreenName];
707 - (UIView*)splashScreenFromStoryboard:(NSString*)name {
708 UIStoryboard* storyboard = nil;
710 storyboard = [UIStoryboard storyboardWithName:name bundle:nil];
711 }
@catch (NSException* exception) {
715 UIViewController* splashScreenViewController = [storyboard instantiateInitialViewController];
716 return splashScreenViewController.view;
721 - (UIView*)splashScreenFromXib:(NSString*)name {
722 NSArray* objects = nil;
724 objects = [[NSBundle mainBundle] loadNibNamed:name owner:self options:nil];
725 }
@catch (NSException* exception) {
728 if ([objects count] != 0) {
729 UIView* view = [objects objectAtIndex:0];
735 - (void)setSplashScreenView:(UIView*)view {
736 if (view == _splashScreenView) {
742 if (_splashScreenView) {
743 [
self removeSplashScreenWithCompletion:nil];
748 _splashScreenView = view;
749 _splashScreenView.autoresizingMask =
750 UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
753 - (void)setFlutterViewDidRenderCallback:(
void (^)(
void))callback {
754 _flutterViewRenderedCallback = callback;
757 - (UISceneActivationState)activationState {
758 return self.flutterWindowSceneIfViewLoaded.activationState;
761 - (BOOL)stateIsActive {
764 BOOL isActive = flutterApplication
765 ? [
self isApplicationStateMatching:UIApplicationStateActive
766 withApplication:flutterApplication]
767 : [
self isSceneStateMatching:UISceneActivationStateForegroundActive];
771 - (BOOL)stateIsBackground {
774 return flutterApplication ? [
self isApplicationStateMatching:UIApplicationStateBackground
775 withApplication:flutterApplication]
776 : [
self isSceneStateMatching:UISceneActivationStateBackground];
779 - (BOOL)isApplicationStateMatching:(UIApplicationState)match
780 withApplication:(UIApplication*)application {
781 switch (application.applicationState) {
782 case UIApplicationStateActive:
783 case UIApplicationStateInactive:
784 case UIApplicationStateBackground:
785 return application.applicationState == match;
789 - (BOOL)isSceneStateMatching:(UISceneActivationState)match API_AVAILABLE(ios(13.0)) {
790 switch (
self.activationState) {
791 case UISceneActivationStateForegroundActive:
792 case UISceneActivationStateUnattached:
793 case UISceneActivationStateForegroundInactive:
794 case UISceneActivationStateBackground:
795 return self.activationState == match;
799 #pragma mark - Surface creation and teardown updates
801 - (void)surfaceUpdated:(BOOL)appeared {
809 [
self installFirstFrameCallback];
810 self.platformViewsController.flutterView =
self.flutterView;
811 self.platformViewsController.flutterViewController =
self;
812 [
self.engine notifyViewCreated];
814 self.displayingFlutterUI = NO;
815 [
self.engine notifyViewDestroyed];
816 self.platformViewsController.flutterView = nil;
817 self.platformViewsController.flutterViewController = nil;
821 #pragma mark - UIViewController lifecycle notifications
823 - (void)viewDidLoad {
824 TRACE_EVENT0(
"flutter",
"viewDidLoad");
826 if (
self.
engine &&
self.engineNeedsLaunch) {
827 [
self.engine launchEngine:nil libraryURI:nil entrypointArgs:nil];
828 [
self.engine setViewController:self];
829 self.engineNeedsLaunch = NO;
830 }
else if (
self.
engine.viewController ==
self) {
831 [
self.engine attachView];
835 [
self addInternalPlugins];
838 [
self createTouchRateCorrectionVSyncClientIfNeeded];
840 if (@available(iOS 13.4, *)) {
841 _hoverGestureRecognizer =
842 [[UIHoverGestureRecognizer alloc] initWithTarget:self action:@selector(hoverEvent:)];
843 _hoverGestureRecognizer.delegate =
self;
844 [
self.flutterView addGestureRecognizer:_hoverGestureRecognizer];
846 _discreteScrollingPanGestureRecognizer =
847 [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(discreteScrollEvent:)];
848 _discreteScrollingPanGestureRecognizer.allowedScrollTypesMask = UIScrollTypeMaskDiscrete;
853 _discreteScrollingPanGestureRecognizer.allowedTouchTypes = @[];
854 _discreteScrollingPanGestureRecognizer.delegate =
self;
855 [
self.flutterView addGestureRecognizer:_discreteScrollingPanGestureRecognizer];
856 _continuousScrollingPanGestureRecognizer =
857 [[UIPanGestureRecognizer alloc] initWithTarget:self
858 action:@selector(continuousScrollEvent:)];
859 _continuousScrollingPanGestureRecognizer.allowedScrollTypesMask = UIScrollTypeMaskContinuous;
860 _continuousScrollingPanGestureRecognizer.allowedTouchTypes = @[];
861 _continuousScrollingPanGestureRecognizer.delegate =
self;
862 [
self.flutterView addGestureRecognizer:_continuousScrollingPanGestureRecognizer];
863 _pinchGestureRecognizer =
864 [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchEvent:)];
865 _pinchGestureRecognizer.allowedTouchTypes = @[];
866 _pinchGestureRecognizer.delegate =
self;
867 [
self.flutterView addGestureRecognizer:_pinchGestureRecognizer];
868 _rotationGestureRecognizer = [[UIRotationGestureRecognizer alloc] init];
869 _rotationGestureRecognizer.allowedTouchTypes = @[];
870 _rotationGestureRecognizer.delegate =
self;
871 [
self.flutterView addGestureRecognizer:_rotationGestureRecognizer];
877 - (void)addInternalPlugins {
881 ^(
const FlutterKeyEvent& event, FlutterKeyEventCallback callback,
void* userData) {
882 [weakSelf.engine sendKeyEvent:event callback:callback userData:userData];
884 [
self.keyboardManager
888 [
self.keyboardManager addPrimaryResponder:responder];
891 [
self.keyboardManager addSecondaryResponder:textInputPlugin];
893 if (
self.
engine.viewController ==
self) {
898 - (void)removeInternalPlugins {
899 self.keyboardManager = nil;
902 - (void)viewWillAppear:(BOOL)animated {
903 TRACE_EVENT0(
"flutter",
"viewWillAppear");
904 if (
self.
engine.viewController ==
self) {
906 [
self onUserSettingsChanged:nil];
910 if (_viewportMetrics.physical_width) {
911 [
self surfaceUpdated:YES];
913 [
self.engine.lifecycleChannel sendMessage:@"AppLifecycleState.inactive"];
914 [
self.engine.restorationPlugin markRestorationComplete];
917 [
super viewWillAppear:animated];
920 - (void)viewDidAppear:(BOOL)animated {
921 TRACE_EVENT0(
"flutter",
"viewDidAppear");
922 if (
self.
engine.viewController ==
self) {
923 [
self onUserSettingsChanged:nil];
924 [
self onAccessibilityStatusChanged:nil];
926 if (
self.stateIsActive) {
927 [
self.engine.lifecycleChannel sendMessage:@"AppLifecycleState.resumed"];
930 [
super viewDidAppear:animated];
933 - (void)viewWillDisappear:(BOOL)animated {
934 TRACE_EVENT0(
"flutter",
"viewWillDisappear");
935 if (
self.
engine.viewController ==
self) {
936 [
self.engine.lifecycleChannel sendMessage:@"AppLifecycleState.inactive"];
938 [
super viewWillDisappear:animated];
941 - (void)viewDidDisappear:(BOOL)animated {
942 TRACE_EVENT0(
"flutter",
"viewDidDisappear");
943 if (
self.
engine.viewController ==
self) {
944 [
self invalidateKeyboardAnimationVSyncClient];
945 [
self ensureViewportMetricsIsCorrect];
946 [
self surfaceUpdated:NO];
947 [
self.engine.lifecycleChannel sendMessage:@"AppLifecycleState.paused"];
948 [
self flushOngoingTouches];
949 [
self.engine notifyLowMemory];
952 [
super viewDidDisappear:animated];
955 - (void)viewWillTransitionToSize:(CGSize)size
956 withTransitionCoordinator:(
id<UIViewControllerTransitionCoordinator>)coordinator {
957 [
super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
967 NSTimeInterval transitionDuration = coordinator.transitionDuration;
969 if (transitionDuration == 0) {
974 _shouldIgnoreViewportMetricsUpdatesDuringRotation = YES;
975 dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
976 static_cast<int64_t
>(transitionDuration / 2.0 * NSEC_PER_SEC)),
977 dispatch_get_main_queue(), ^{
985 strongSelf.shouldIgnoreViewportMetricsUpdatesDuringRotation = NO;
986 [strongSelf updateViewportMetricsIfNeeded];
990 - (void)flushOngoingTouches {
991 if (
self.
engine &&
self.ongoingTouches.count > 0) {
992 auto packet = std::make_unique<flutter::PointerDataPacket>(
self.ongoingTouches.count);
993 size_t pointer_index = 0;
996 for (NSNumber* device in
self.ongoingTouches) {
998 flutter::PointerData pointer_data = [
self generatePointerDataForFake];
1000 pointer_data.change = flutter::PointerData::Change::kCancel;
1001 pointer_data.device = device.longLongValue;
1002 pointer_data.pointer_identifier = 0;
1003 pointer_data.view_id =
self.viewIdentifier;
1006 pointer_data.physical_x = 0;
1007 pointer_data.physical_y = 0;
1008 pointer_data.physical_delta_x = 0.0;
1009 pointer_data.physical_delta_y = 0.0;
1010 pointer_data.pressure = 1.0;
1011 pointer_data.pressure_max = 1.0;
1013 packet->SetPointerData(pointer_index++, pointer_data);
1016 [
self.ongoingTouches removeAllObjects];
1017 [
self.engine dispatchPointerDataPacket:std::move(packet)];
1021 - (void)deregisterNotifications {
1022 [[NSNotificationCenter defaultCenter] postNotificationName:FlutterViewControllerWillDealloc
1025 [[NSNotificationCenter defaultCenter] removeObserver:self];
1031 [
self removeInternalPlugins];
1032 [
self deregisterNotifications];
1034 [
self invalidateKeyboardAnimationVSyncClient];
1035 [
self invalidateTouchRateCorrectionVSyncClient];
1039 _scrollView.delegate = nil;
1040 _hoverGestureRecognizer.delegate = nil;
1041 _discreteScrollingPanGestureRecognizer.delegate = nil;
1042 _continuousScrollingPanGestureRecognizer.delegate = nil;
1043 _pinchGestureRecognizer.delegate = nil;
1044 _rotationGestureRecognizer.delegate = nil;
1047 #pragma mark - Application lifecycle notifications
1049 - (void)applicationBecameActive:(NSNotification*)notification {
1050 TRACE_EVENT0(
"flutter",
"applicationBecameActive");
1051 [
self appOrSceneBecameActive];
1054 - (void)applicationWillResignActive:(NSNotification*)notification {
1055 TRACE_EVENT0(
"flutter",
"applicationWillResignActive");
1056 [
self appOrSceneWillResignActive];
1059 - (void)applicationWillTerminate:(NSNotification*)notification {
1060 [
self appOrSceneWillTerminate];
1063 - (void)applicationDidEnterBackground:(NSNotification*)notification {
1064 TRACE_EVENT0(
"flutter",
"applicationDidEnterBackground");
1065 [
self appOrSceneDidEnterBackground];
1068 - (void)applicationWillEnterForeground:(NSNotification*)notification {
1069 TRACE_EVENT0(
"flutter",
"applicationWillEnterForeground");
1070 [
self appOrSceneWillEnterForeground];
1073 #pragma mark - Scene lifecycle notifications
1075 - (void)sceneBecameActive:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1076 TRACE_EVENT0(
"flutter",
"sceneBecameActive");
1077 [
self appOrSceneBecameActive];
1080 - (void)sceneWillResignActive:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1081 TRACE_EVENT0(
"flutter",
"sceneWillResignActive");
1082 [
self appOrSceneWillResignActive];
1085 - (void)sceneWillDisconnect:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1086 [
self appOrSceneWillTerminate];
1089 - (void)sceneDidEnterBackground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1090 TRACE_EVENT0(
"flutter",
"sceneDidEnterBackground");
1091 [
self appOrSceneDidEnterBackground];
1094 - (void)sceneWillEnterForeground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1095 TRACE_EVENT0(
"flutter",
"sceneWillEnterForeground");
1096 [
self appOrSceneWillEnterForeground];
1099 #pragma mark - Lifecycle shared
1101 - (void)appOrSceneBecameActive {
1102 self.isKeyboardInOrTransitioningFromBackground = NO;
1103 if (_viewportMetrics.physical_width) {
1104 [
self surfaceUpdated:YES];
1106 [
self performSelector:@selector(goToApplicationLifecycle:)
1107 withObject:@"AppLifecycleState.resumed"
1111 - (void)appOrSceneWillResignActive {
1112 [NSObject cancelPreviousPerformRequestsWithTarget:self
1113 selector:@selector(goToApplicationLifecycle:)
1114 object:@"AppLifecycleState.resumed"];
1115 [
self goToApplicationLifecycle:@"AppLifecycleState.inactive"];
1118 - (void)appOrSceneWillTerminate {
1119 [
self goToApplicationLifecycle:@"AppLifecycleState.detached"];
1120 [
self.engine destroyContext];
1123 - (void)appOrSceneDidEnterBackground {
1124 self.isKeyboardInOrTransitioningFromBackground = YES;
1125 [
self surfaceUpdated:NO];
1126 [
self goToApplicationLifecycle:@"AppLifecycleState.paused"];
1129 - (void)appOrSceneWillEnterForeground {
1130 [
self goToApplicationLifecycle:@"AppLifecycleState.inactive"];
1134 - (void)goToApplicationLifecycle:(nonnull NSString*)state {
1137 if (
self.viewIfLoaded.window) {
1138 [
self.engine.lifecycleChannel sendMessage:state];
1142 #pragma mark - Touch event handling
1144 static flutter::PointerData::Change PointerDataChangeFromUITouchPhase(UITouchPhase phase) {
1146 case UITouchPhaseBegan:
1147 return flutter::PointerData::Change::kDown;
1148 case UITouchPhaseMoved:
1149 case UITouchPhaseStationary:
1152 return flutter::PointerData::Change::kMove;
1153 case UITouchPhaseEnded:
1154 return flutter::PointerData::Change::kUp;
1155 case UITouchPhaseCancelled:
1156 return flutter::PointerData::Change::kCancel;
1159 FML_DLOG(INFO) <<
"Unhandled touch phase: " << phase;
1163 return flutter::PointerData::Change::kCancel;
1166 static flutter::PointerData::DeviceKind DeviceKindFromTouchType(UITouch* touch) {
1167 switch (touch.type) {
1168 case UITouchTypeDirect:
1169 case UITouchTypeIndirect:
1170 return flutter::PointerData::DeviceKind::kTouch;
1171 case UITouchTypeStylus:
1172 return flutter::PointerData::DeviceKind::kStylus;
1173 case UITouchTypeIndirectPointer:
1174 return flutter::PointerData::DeviceKind::kMouse;
1176 FML_DLOG(INFO) <<
"Unhandled touch type: " << touch.type;
1180 return flutter::PointerData::DeviceKind::kTouch;
1187 - (void)dispatchTouches:(NSSet*)touches
1188 pointerDataChangeOverride:(
flutter::PointerData::Change*)overridden_change
1189 event:(UIEvent*)event {
1214 NSUInteger touches_to_remove_count = 0;
1215 for (UITouch* touch in touches) {
1216 if (touch.phase == UITouchPhaseEnded || touch.phase == UITouchPhaseCancelled) {
1217 touches_to_remove_count++;
1222 [
self triggerTouchRateCorrectionIfNeeded:touches];
1224 const CGFloat scale =
self.flutterScreenIfViewLoaded.scale;
1226 std::make_unique<flutter::PointerDataPacket>(touches.count + touches_to_remove_count);
1228 size_t pointer_index = 0;
1230 for (UITouch* touch in touches) {
1231 CGPoint windowCoordinates = [touch locationInView:self.view];
1233 flutter::PointerData pointer_data;
1234 pointer_data.Clear();
1239 pointer_data.change = overridden_change !=
nullptr
1240 ? *overridden_change
1241 : PointerDataChangeFromUITouchPhase(touch.phase);
1243 pointer_data.kind = DeviceKindFromTouchType(touch);
1245 pointer_data.device =
reinterpret_cast<int64_t
>(touch);
1247 pointer_data.view_id =
self.viewIdentifier;
1250 pointer_data.pointer_identifier = 0;
1252 pointer_data.physical_x = windowCoordinates.x * scale;
1253 pointer_data.physical_y = windowCoordinates.y * scale;
1256 pointer_data.physical_delta_x = 0.0;
1257 pointer_data.physical_delta_y = 0.0;
1259 NSNumber* deviceKey = [NSNumber numberWithLongLong:pointer_data.device];
1262 switch (pointer_data.change) {
1263 case flutter::PointerData::Change::kDown:
1264 [
self.ongoingTouches addObject:deviceKey];
1266 case flutter::PointerData::Change::kCancel:
1267 case flutter::PointerData::Change::kUp:
1268 [
self.ongoingTouches removeObject:deviceKey];
1270 case flutter::PointerData::Change::kHover:
1271 case flutter::PointerData::Change::kMove:
1274 case flutter::PointerData::Change::kAdd:
1275 case flutter::PointerData::Change::kRemove:
1278 case flutter::PointerData::Change::kPanZoomStart:
1279 case flutter::PointerData::Change::kPanZoomUpdate:
1280 case flutter::PointerData::Change::kPanZoomEnd:
1286 pointer_data.pressure = touch.force;
1287 pointer_data.pressure_max = touch.maximumPossibleForce;
1288 pointer_data.radius_major = touch.majorRadius;
1289 pointer_data.radius_min = touch.majorRadius - touch.majorRadiusTolerance;
1290 pointer_data.radius_max = touch.majorRadius + touch.majorRadiusTolerance;
1305 pointer_data.tilt = M_PI_2 - touch.altitudeAngle;
1325 pointer_data.orientation = [touch azimuthAngleInView:nil] - M_PI_2;
1327 if (@available(iOS 13.4, *)) {
1328 if (event !=
nullptr) {
1329 pointer_data.buttons = (((
event.buttonMask & UIEventButtonMaskPrimary) > 0)
1330 ? flutter::PointerButtonMouse::kPointerButtonMousePrimary
1332 (((event.buttonMask & UIEventButtonMaskSecondary) > 0)
1333 ? flutter::PointerButtonMouse::kPointerButtonMouseSecondary
1338 packet->SetPointerData(pointer_index++, pointer_data);
1340 if (touch.phase == UITouchPhaseEnded || touch.phase == UITouchPhaseCancelled) {
1341 flutter::PointerData remove_pointer_data = pointer_data;
1342 remove_pointer_data.change = flutter::PointerData::Change::kRemove;
1343 packet->SetPointerData(pointer_index++, remove_pointer_data);
1347 [
self.engine dispatchPointerDataPacket:std::move(packet)];
1350 - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
1351 [
self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event];
1354 - (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
1355 [
self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event];
1358 - (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
1359 [
self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event];
1362 - (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event {
1363 [
self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event];
1366 - (void)forceTouchesCancelled:(NSSet*)touches {
1367 flutter::PointerData::Change cancel = flutter::PointerData::Change::kCancel;
1368 [
self dispatchTouches:touches pointerDataChangeOverride:&cancel event:nullptr];
1371 #pragma mark - Touch events rate correction
1373 - (void)createTouchRateCorrectionVSyncClientIfNeeded {
1374 if (_touchRateCorrectionVSyncClient != nil) {
1379 const double epsilon = 0.1;
1380 if (displayRefreshRate < 60.0 + epsilon) {
1388 auto callback = [](std::unique_ptr<flutter::FrameTimingsRecorder> recorder) {
1391 _touchRateCorrectionVSyncClient =
1392 [[
VSyncClient alloc] initWithTaskRunner:self.engine.platformTaskRunner callback:callback];
1393 _touchRateCorrectionVSyncClient.allowPauseAfterVsync = NO;
1396 - (void)triggerTouchRateCorrectionIfNeeded:(NSSet*)touches {
1397 if (_touchRateCorrectionVSyncClient == nil) {
1405 BOOL isUserInteracting = NO;
1406 for (UITouch* touch in touches) {
1407 if (touch.phase == UITouchPhaseBegan || touch.phase == UITouchPhaseMoved) {
1408 isUserInteracting = YES;
1413 if (isUserInteracting &&
self.
engine.viewController ==
self) {
1414 [_touchRateCorrectionVSyncClient await];
1416 [_touchRateCorrectionVSyncClient pause];
1420 - (void)invalidateTouchRateCorrectionVSyncClient {
1421 [_touchRateCorrectionVSyncClient invalidate];
1422 _touchRateCorrectionVSyncClient = nil;
1425 #pragma mark - Handle view resizing
1427 - (void)updateViewportMetricsIfNeeded {
1428 if (_shouldIgnoreViewportMetricsUpdatesDuringRotation) {
1431 if (
self.
engine.viewController ==
self) {
1432 [
self.engine updateViewportMetrics:_viewportMetrics];
1436 - (void)viewDidLayoutSubviews {
1437 CGRect viewBounds =
self.view.bounds;
1438 CGFloat scale =
self.flutterScreenIfViewLoaded.scale;
1441 self.scrollView.frame = CGRectMake(0.0, 0.0, viewBounds.size.width, 0.0);
1445 bool firstViewBoundsUpdate = !_viewportMetrics.physical_width;
1446 _viewportMetrics.device_pixel_ratio = scale;
1447 [
self setViewportMetricsSize];
1448 [
self checkAndUpdateAutoResizeConstraints];
1449 [
self setViewportMetricsPaddings];
1450 [
self updateViewportMetricsIfNeeded];
1457 if (firstViewBoundsUpdate &&
self.stateIsActive &&
self.
engine) {
1458 [
self surfaceUpdated:YES];
1459 #if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
1460 NSTimeInterval timeout = 0.2;
1462 NSTimeInterval timeout = 0.1;
1465 waitForFirstFrameSync:timeout
1466 callback:^(BOOL didTimeout) {
1468 [FlutterLogger logInfo:@"Timeout waiting for the first frame to render. "
1469 "This may happen in unoptimized builds. If this is"
1470 "a release build, you should load a less complex "
1471 "frame to avoid the timeout."];
1477 - (BOOL)isAutoResizable {
1478 return self.flutterView.autoResizable;
1481 - (void)setAutoResizable:(BOOL)value {
1482 self.flutterView.autoResizable = value;
1483 self.flutterView.contentMode = UIViewContentModeCenter;
1486 - (void)checkAndUpdateAutoResizeConstraints {
1487 if (!
self.isAutoResizable) {
1491 [
self updateAutoResizeConstraints];
1515 - (void)updateAutoResizeConstraints {
1516 BOOL hasBeenAutoResized = NO;
1517 for (NSLayoutConstraint* constraint in
self.view.constraints) {
1519 hasBeenAutoResized = YES;
1523 if (!hasBeenAutoResized) {
1524 self.sizeBeforeAutoResized =
self.view.frame.size;
1527 CGFloat maxWidth =
self.sizeBeforeAutoResized.width;
1528 CGFloat maxHeight =
self.sizeBeforeAutoResized.height;
1529 CGFloat minWidth =
self.sizeBeforeAutoResized.width;
1530 CGFloat minHeight =
self.sizeBeforeAutoResized.height;
1534 if (maxWidth == 0) {
1535 maxWidth = CGFLOAT_MAX;
1538 @"Warning: The outermost widget in the autoresizable Flutter view is unsized or has "
1539 @"ambiguous dimensions, causing the host native view's width to be 0. The autoresizing "
1540 @"logic is setting the viewport constraint to unbounded DBL_MAX to prevent "
1541 @"rendering failure. Please ensure your top-level Flutter widget has explicit "
1542 @"constraints (e.g., using SizedBox or Container)."];
1544 if (maxHeight == 0) {
1545 maxHeight = CGFLOAT_MAX;
1548 @"Warning: The outermost widget in the autoresizable Flutter view is unsized or has "
1549 @"ambiguous dimensions, causing the host native view's width to be 0. The autoresizing "
1550 @"logic is setting the viewport constraint to unbounded DBL_MAX to prevent "
1551 @"rendering failure. Please ensure your top-level Flutter widget has explicit "
1552 @"constraints (e.g., using SizedBox or Container)."];
1554 _viewportMetrics.physical_min_width_constraint = minWidth * _viewportMetrics.device_pixel_ratio;
1555 _viewportMetrics.physical_max_width_constraint = maxWidth * _viewportMetrics.device_pixel_ratio;
1556 _viewportMetrics.physical_min_height_constraint = minHeight * _viewportMetrics.device_pixel_ratio;
1557 _viewportMetrics.physical_max_height_constraint = maxHeight * _viewportMetrics.device_pixel_ratio;
1560 - (void)viewSafeAreaInsetsDidChange {
1561 [
self setViewportMetricsPaddings];
1562 [
self updateViewportMetricsIfNeeded];
1563 [
super viewSafeAreaInsetsDidChange];
1567 - (void)setViewportMetricsSize {
1568 UIScreen* screen =
self.flutterScreenIfViewLoaded;
1573 CGFloat scale = screen.scale;
1574 _viewportMetrics.physical_width =
self.view.bounds.size.width * scale;
1575 _viewportMetrics.physical_height =
self.view.bounds.size.height * scale;
1577 _viewportMetrics.physical_min_width_constraint = _viewportMetrics.physical_width;
1578 _viewportMetrics.physical_max_width_constraint = _viewportMetrics.physical_width;
1579 _viewportMetrics.physical_min_height_constraint = _viewportMetrics.physical_height;
1580 _viewportMetrics.physical_max_height_constraint = _viewportMetrics.physical_height;
1586 - (void)setViewportMetricsPaddings {
1587 UIScreen* screen =
self.flutterScreenIfViewLoaded;
1592 CGFloat scale = screen.scale;
1593 _viewportMetrics.physical_padding_top =
self.view.safeAreaInsets.top * scale;
1594 _viewportMetrics.physical_padding_left =
self.view.safeAreaInsets.left * scale;
1595 _viewportMetrics.physical_padding_right =
self.view.safeAreaInsets.right * scale;
1596 _viewportMetrics.physical_padding_bottom =
self.view.safeAreaInsets.bottom * scale;
1599 #pragma mark - Keyboard events
1601 - (void)keyboardWillShowNotification:(NSNotification*)notification {
1606 [
self handleKeyboardNotification:notification];
1609 - (void)keyboardWillChangeFrame:(NSNotification*)notification {
1614 [
self handleKeyboardNotification:notification];
1617 - (void)keyboardWillBeHidden:(NSNotification*)notification {
1621 [
self handleKeyboardNotification:notification];
1624 - (void)handleKeyboardNotification:(NSNotification*)notification {
1627 if ([
self shouldIgnoreKeyboardNotification:notification]) {
1631 NSDictionary* info = notification.userInfo;
1632 CGRect beginKeyboardFrame = [info[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
1633 CGRect keyboardFrame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];
1634 FlutterKeyboardMode keyboardMode = [
self calculateKeyboardAttachMode:notification];
1635 CGFloat calculatedInset = [
self calculateKeyboardInset:keyboardFrame keyboardMode:keyboardMode];
1636 NSTimeInterval duration = [info[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
1643 if (keyboardMode == FlutterKeyboardModeHidden && calculatedInset == 0.0 && duration == 0.0) {
1644 [
self hideKeyboardImmediately];
1649 if (
self.targetViewInsetBottom == calculatedInset) {
1653 self.targetViewInsetBottom = calculatedInset;
1660 BOOL keyboardWillShow = beginKeyboardFrame.origin.y > keyboardFrame.origin.y;
1661 BOOL keyboardAnimationIsCompounding =
1662 self.keyboardAnimationIsShowing == keyboardWillShow && _keyboardAnimationVSyncClient != nil;
1665 self.keyboardAnimationIsShowing = keyboardWillShow;
1667 if (!keyboardAnimationIsCompounding) {
1668 [
self startKeyBoardAnimation:duration];
1669 }
else if (
self.keyboardSpringAnimation) {
1670 self.keyboardSpringAnimation.toValue =
self.targetViewInsetBottom;
1674 - (BOOL)shouldIgnoreKeyboardNotification:(NSNotification*)notification {
1679 if (notification.name == UIKeyboardWillHideNotification) {
1688 NSDictionary* info = notification.userInfo;
1689 CGRect keyboardFrame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];
1690 if (notification.name == UIKeyboardWillChangeFrameNotification &&
1691 CGRectEqualToRect(keyboardFrame, CGRectZero)) {
1697 if (CGRectIsEmpty(keyboardFrame)) {
1702 if ([
self isKeyboardNotificationForDifferentView:notification]) {
1708 - (BOOL)isKeyboardNotificationForDifferentView:(NSNotification*)notification {
1709 NSDictionary* info = notification.userInfo;
1713 id isLocal = info[UIKeyboardIsLocalUserInfoKey];
1714 if (isLocal && ![isLocal boolValue]) {
1717 return self.engine.viewController !=
self;
1720 - (FlutterKeyboardMode)calculateKeyboardAttachMode:(NSNotification*)notification {
1728 NSDictionary* info = notification.userInfo;
1729 CGRect keyboardFrame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];
1731 if (notification.name == UIKeyboardWillHideNotification) {
1732 return FlutterKeyboardModeHidden;
1737 if (CGRectEqualToRect(keyboardFrame, CGRectZero)) {
1738 return FlutterKeyboardModeFloating;
1741 if (CGRectIsEmpty(keyboardFrame)) {
1742 return FlutterKeyboardModeHidden;
1745 CGRect screenRect =
self.flutterScreenIfViewLoaded.bounds;
1746 CGRect adjustedKeyboardFrame = keyboardFrame;
1747 adjustedKeyboardFrame.origin.y += [
self calculateMultitaskingAdjustment:screenRect
1748 keyboardFrame:keyboardFrame];
1753 CGRect intersection = CGRectIntersection(adjustedKeyboardFrame, screenRect);
1754 CGFloat intersectionHeight = CGRectGetHeight(intersection);
1755 CGFloat intersectionWidth = CGRectGetWidth(intersection);
1756 if (round(intersectionHeight) > 0 && intersectionWidth > 0) {
1758 CGFloat screenHeight = CGRectGetHeight(screenRect);
1759 CGFloat adjustedKeyboardBottom = CGRectGetMaxY(adjustedKeyboardFrame);
1760 if (round(adjustedKeyboardBottom) < screenHeight) {
1761 return FlutterKeyboardModeFloating;
1763 return FlutterKeyboardModeDocked;
1765 return FlutterKeyboardModeHidden;
1768 - (CGFloat)calculateMultitaskingAdjustment:(CGRect)screenRect keyboardFrame:(CGRect)keyboardFrame {
1772 if (
self.viewIfLoaded.traitCollection.userInterfaceIdiom == UIUserInterfaceIdiomPad &&
1773 self.viewIfLoaded.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact &&
1774 self.viewIfLoaded.traitCollection.verticalSizeClass == UIUserInterfaceSizeClassRegular) {
1775 CGFloat screenHeight = CGRectGetHeight(screenRect);
1776 CGFloat keyboardBottom = CGRectGetMaxY(keyboardFrame);
1780 if (screenHeight == keyboardBottom) {
1783 CGRect viewRectRelativeToScreen =
1784 [
self.viewIfLoaded convertRect:self.viewIfLoaded.frame
1785 toCoordinateSpace:self.flutterScreenIfViewLoaded.coordinateSpace];
1786 CGFloat viewBottom = CGRectGetMaxY(viewRectRelativeToScreen);
1787 CGFloat offset = screenHeight - viewBottom;
1795 - (CGFloat)calculateKeyboardInset:(CGRect)keyboardFrame keyboardMode:(NSInteger)keyboardMode {
1797 if (keyboardMode == FlutterKeyboardModeDocked) {
1799 CGRect viewRectRelativeToScreen =
1800 [
self.viewIfLoaded convertRect:self.viewIfLoaded.frame
1801 toCoordinateSpace:self.flutterScreenIfViewLoaded.coordinateSpace];
1802 CGRect intersection = CGRectIntersection(keyboardFrame, viewRectRelativeToScreen);
1803 CGFloat portionOfKeyboardInView = CGRectGetHeight(intersection);
1808 CGFloat scale =
self.flutterScreenIfViewLoaded.scale;
1809 return portionOfKeyboardInView * scale;
1814 - (void)startKeyBoardAnimation:(NSTimeInterval)duration {
1816 if (_viewportMetrics.physical_view_inset_bottom ==
self.targetViewInsetBottom) {
1822 if (!
self.keyboardAnimationView) {
1823 UIView* keyboardAnimationView = [[UIView alloc] init];
1824 keyboardAnimationView.hidden = YES;
1825 self.keyboardAnimationView = keyboardAnimationView;
1828 if (!
self.keyboardAnimationView.superview) {
1829 [
self.view addSubview:self.keyboardAnimationView];
1833 [
self.keyboardAnimationView.layer removeAllAnimations];
1836 self.keyboardAnimationView.frame =
1837 CGRectMake(0, _viewportMetrics.physical_view_inset_bottom, 0, 0);
1838 self.keyboardAnimationStartTime = fml::TimePoint().Now();
1839 self.originalViewInsetBottom = _viewportMetrics.physical_view_inset_bottom;
1842 [
self invalidateKeyboardAnimationVSyncClient];
1845 [
self setUpKeyboardAnimationVsyncClient:^(fml::TimePoint targetTime) {
1846 [weakSelf handleKeyboardAnimationCallbackWithTargetTime:targetTime];
1848 VSyncClient* currentVsyncClient = _keyboardAnimationVSyncClient;
1850 [UIView animateWithDuration:duration
1858 strongSelf.keyboardAnimationView.frame = CGRectMake(0, self.targetViewInsetBottom, 0, 0);
1861 CAAnimation* keyboardAnimation =
1862 [strongSelf.keyboardAnimationView.layer animationForKey:@"position"];
1863 [strongSelf setUpKeyboardSpringAnimationIfNeeded:keyboardAnimation];
1865 completion:^(BOOL finished) {
1866 if (_keyboardAnimationVSyncClient == currentVsyncClient) {
1875 [strongSelf invalidateKeyboardAnimationVSyncClient];
1876 [strongSelf removeKeyboardAnimationView];
1877 [strongSelf ensureViewportMetricsIsCorrect];
1882 - (void)hideKeyboardImmediately {
1883 [
self invalidateKeyboardAnimationVSyncClient];
1884 if (
self.keyboardAnimationView) {
1885 [
self.keyboardAnimationView.layer removeAllAnimations];
1886 [
self removeKeyboardAnimationView];
1887 self.keyboardAnimationView = nil;
1889 if (
self.keyboardSpringAnimation) {
1890 self.keyboardSpringAnimation = nil;
1893 self.targetViewInsetBottom = 0.0;
1894 [
self ensureViewportMetricsIsCorrect];
1897 - (void)setUpKeyboardSpringAnimationIfNeeded:(CAAnimation*)keyboardAnimation {
1899 if (keyboardAnimation == nil || ![keyboardAnimation isKindOfClass:[CASpringAnimation
class]]) {
1900 _keyboardSpringAnimation = nil;
1905 CASpringAnimation* keyboardCASpringAnimation = (CASpringAnimation*)keyboardAnimation;
1906 _keyboardSpringAnimation =
1907 [[SpringAnimation alloc] initWithStiffness:keyboardCASpringAnimation.stiffness
1908 damping:keyboardCASpringAnimation.damping
1909 mass:keyboardCASpringAnimation.mass
1910 initialVelocity:keyboardCASpringAnimation.initialVelocity
1911 fromValue:self.originalViewInsetBottom
1912 toValue:self.targetViewInsetBottom];
1915 - (void)handleKeyboardAnimationCallbackWithTargetTime:(
fml::TimePoint)targetTime {
1917 if (!
self.isViewLoaded) {
1922 if (!
self.keyboardAnimationView) {
1927 if (!
self.keyboardAnimationVSyncClient) {
1931 if (!
self.keyboardAnimationView.superview) {
1933 [
self.view addSubview:self.keyboardAnimationView];
1936 if (!
self.keyboardSpringAnimation) {
1937 if (
self.keyboardAnimationView.layer.presentationLayer) {
1938 self->_viewportMetrics.physical_view_inset_bottom =
1939 self.keyboardAnimationView.layer.presentationLayer.frame.origin.y;
1940 [
self updateViewportMetricsIfNeeded];
1943 fml::TimeDelta timeElapsed = targetTime -
self.keyboardAnimationStartTime;
1944 self->_viewportMetrics.physical_view_inset_bottom =
1945 [
self.keyboardSpringAnimation curveFunction:timeElapsed.ToSecondsF()];
1946 [
self updateViewportMetricsIfNeeded];
1950 - (void)setUpKeyboardAnimationVsyncClient:
1952 if (!keyboardAnimationCallback) {
1955 NSAssert(_keyboardAnimationVSyncClient == nil,
1956 @"_keyboardAnimationVSyncClient must be nil when setting up.");
1960 auto uiCallback = [animationCallback](std::unique_ptr<flutter::FrameTimingsRecorder> recorder) {
1961 fml::TimeDelta frameInterval = recorder->GetVsyncTargetTime() - recorder->GetVsyncStartTime();
1962 fml::TimePoint targetTime = recorder->GetVsyncTargetTime() + frameInterval;
1963 dispatch_async(dispatch_get_main_queue(), ^(
void) {
1964 animationCallback(targetTime);
1968 _keyboardAnimationVSyncClient = [[
VSyncClient alloc] initWithTaskRunner:self.engine.uiTaskRunner
1969 callback:uiCallback];
1970 _keyboardAnimationVSyncClient.allowPauseAfterVsync = NO;
1971 [_keyboardAnimationVSyncClient await];
1974 - (void)invalidateKeyboardAnimationVSyncClient {
1975 [_keyboardAnimationVSyncClient invalidate];
1976 _keyboardAnimationVSyncClient = nil;
1979 - (void)removeKeyboardAnimationView {
1980 if (
self.keyboardAnimationView.superview != nil) {
1981 [
self.keyboardAnimationView removeFromSuperview];
1985 - (void)ensureViewportMetricsIsCorrect {
1986 if (_viewportMetrics.physical_view_inset_bottom !=
self.targetViewInsetBottom) {
1988 _viewportMetrics.physical_view_inset_bottom =
self.targetViewInsetBottom;
1989 [
self updateViewportMetricsIfNeeded];
1993 - (void)handlePressEvent:(FlutterUIPressProxy*)press
1994 nextAction:(
void (^)())next API_AVAILABLE(ios(13.4)) {
1995 if (@available(iOS 13.4, *)) {
2000 [
self.keyboardManager handlePress:press nextAction:next];
2016 - (void)superPressesBegan:(NSSet<UIPress*>*)presses withEvent:(UIPressesEvent*)event {
2017 [
super pressesBegan:presses withEvent:event];
2020 - (void)superPressesChanged:(NSSet<UIPress*>*)presses withEvent:(UIPressesEvent*)event {
2021 [
super pressesChanged:presses withEvent:event];
2024 - (void)superPressesEnded:(NSSet<UIPress*>*)presses withEvent:(UIPressesEvent*)event {
2025 [
super pressesEnded:presses withEvent:event];
2028 - (void)superPressesCancelled:(NSSet<UIPress*>*)presses withEvent:(UIPressesEvent*)event {
2029 [
super pressesCancelled:presses withEvent:event];
2037 - (void)pressesBegan:(NSSet<UIPress*>*)presses
2038 withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
2039 if (@available(iOS 13.4, *)) {
2041 for (UIPress* press in presses) {
2042 [
self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press event:event]
2044 [weakSelf superPressesBegan:[NSSet setWithObject:press] withEvent:event];
2048 [
super pressesBegan:presses withEvent:event];
2052 - (void)pressesChanged:(NSSet<UIPress*>*)presses
2053 withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
2054 if (@available(iOS 13.4, *)) {
2056 for (UIPress* press in presses) {
2057 [
self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press event:event]
2059 [weakSelf superPressesChanged:[NSSet setWithObject:press] withEvent:event];
2063 [
super pressesChanged:presses withEvent:event];
2067 - (void)pressesEnded:(NSSet<UIPress*>*)presses
2068 withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
2069 if (@available(iOS 13.4, *)) {
2071 for (UIPress* press in presses) {
2072 [
self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press event:event]
2074 [weakSelf superPressesEnded:[NSSet setWithObject:press] withEvent:event];
2078 [
super pressesEnded:presses withEvent:event];
2082 - (void)pressesCancelled:(NSSet<UIPress*>*)presses
2083 withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
2084 if (@available(iOS 13.4, *)) {
2086 for (UIPress* press in presses) {
2087 [
self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press event:event]
2089 [weakSelf superPressesCancelled:[NSSet setWithObject:press] withEvent:event];
2093 [
super pressesCancelled:presses withEvent:event];
2097 #pragma mark - Orientation updates
2099 - (void)onOrientationPreferencesUpdated:(NSNotification*)notification {
2102 dispatch_async(dispatch_get_main_queue(), ^{
2103 NSDictionary* info = notification.userInfo;
2104 NSNumber* update = info[@(flutter::kOrientationUpdateNotificationKey)];
2105 if (update == nil) {
2108 [weakSelf performOrientationUpdate:update.unsignedIntegerValue];
2112 - (void)requestGeometryUpdateForWindowScenes:(NSSet<UIScene*>*)windowScenes
2113 API_AVAILABLE(ios(16.0)) {
2114 for (UIScene* windowScene in windowScenes) {
2115 FML_DCHECK([windowScene isKindOfClass:[UIWindowScene
class]]);
2116 UIWindowSceneGeometryPreferencesIOS* preference = [[UIWindowSceneGeometryPreferencesIOS alloc]
2117 initWithInterfaceOrientations:self.orientationPreferences];
2118 [(UIWindowScene*)windowScene
2119 requestGeometryUpdateWithPreferences:preference
2120 errorHandler:^(NSError* error) {
2121 os_log_error(OS_LOG_DEFAULT,
2122 "Failed to change device orientation: %@", error);
2124 [
self setNeedsUpdateOfSupportedInterfaceOrientations];
2128 - (void)performOrientationUpdate:(UIInterfaceOrientationMask)new_preferences {
2129 if (new_preferences !=
self.orientationPreferences) {
2130 self.orientationPreferences = new_preferences;
2132 if (@available(iOS 16.0, *)) {
2134 NSSet<UIScene*>* scenes = [NSSet set];
2135 if (flutterApplication) {
2136 scenes = [flutterApplication.connectedScenes
2137 filteredSetUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(
2138 id scene, NSDictionary* bindings) {
2139 return [scene isKindOfClass:[UIWindowScene class]];
2141 }
else if (
self.flutterWindowSceneIfViewLoaded) {
2142 scenes = [NSSet setWithObject:self.flutterWindowSceneIfViewLoaded];
2144 [
self requestGeometryUpdateForWindowScenes:scenes];
2146 UIInterfaceOrientationMask currentInterfaceOrientation = 0;
2147 UIWindowScene* windowScene =
self.flutterWindowSceneIfViewLoaded;
2151 @"Accessing the interface orientation when the window scene is unavailable."];
2154 currentInterfaceOrientation = 1 << windowScene.interfaceOrientation;
2155 if (!(
self.orientationPreferences & currentInterfaceOrientation)) {
2156 [UIViewController attemptRotationToDeviceOrientation];
2158 if (
self.orientationPreferences & UIInterfaceOrientationMaskPortrait) {
2162 [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationPortrait)
2163 forKey:@"orientation"];
2164 }
else if (
self.orientationPreferences & UIInterfaceOrientationMaskPortraitUpsideDown) {
2165 [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationPortraitUpsideDown)
2166 forKey:@"orientation"];
2167 }
else if (
self.orientationPreferences & UIInterfaceOrientationMaskLandscapeLeft) {
2168 [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeLeft)
2169 forKey:@"orientation"];
2170 }
else if (
self.orientationPreferences & UIInterfaceOrientationMaskLandscapeRight) {
2171 [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeRight)
2172 forKey:@"orientation"];
2179 - (void)onHideHomeIndicatorNotification:(NSNotification*)notification {
2180 self.isHomeIndicatorHidden = YES;
2183 - (void)onShowHomeIndicatorNotification:(NSNotification*)notification {
2184 self.isHomeIndicatorHidden = NO;
2187 - (void)setIsHomeIndicatorHidden:(BOOL)hideHomeIndicator {
2188 if (hideHomeIndicator != _isHomeIndicatorHidden) {
2189 _isHomeIndicatorHidden = hideHomeIndicator;
2190 [
self setNeedsUpdateOfHomeIndicatorAutoHidden];
2194 - (BOOL)prefersHomeIndicatorAutoHidden {
2195 return self.isHomeIndicatorHidden;
2198 - (BOOL)shouldAutorotate {
2202 - (NSUInteger)supportedInterfaceOrientations {
2203 return self.orientationPreferences;
2206 #pragma mark - Accessibility
2208 - (void)onAccessibilityStatusChanged:(NSNotification*)notification {
2213 int32_t flags =
self.accessibilityFlags;
2214 #if TARGET_OS_SIMULATOR
2220 _isVoiceOverRunning = UIAccessibilityIsVoiceOverRunning();
2221 enabled = _isVoiceOverRunning || UIAccessibilityIsSwitchControlRunning();
2223 flags |=
static_cast<int32_t
>(flutter::AccessibilityFeatureFlag::kAccessibleNavigation);
2225 enabled |= UIAccessibilityIsSpeakScreenEnabled();
2227 [
self.engine enableSemantics:enabled withFlags:flags];
2230 - (int32_t)accessibilityFlags {
2232 if (UIAccessibilityIsInvertColorsEnabled()) {
2233 flags |=
static_cast<int32_t
>(flutter::AccessibilityFeatureFlag::kInvertColors);
2235 if (UIAccessibilityIsReduceMotionEnabled()) {
2236 flags |=
static_cast<int32_t
>(flutter::AccessibilityFeatureFlag::kReduceMotion);
2238 if (UIAccessibilityIsBoldTextEnabled()) {
2239 flags |=
static_cast<int32_t
>(flutter::AccessibilityFeatureFlag::kBoldText);
2241 if (UIAccessibilityDarkerSystemColorsEnabled()) {
2242 flags |=
static_cast<int32_t
>(flutter::AccessibilityFeatureFlag::kHighContrast);
2245 flags |=
static_cast<int32_t
>(flutter::AccessibilityFeatureFlag::kOnOffSwitchLabels);
2251 - (BOOL)accessibilityPerformEscape {
2253 if (navigationChannel) {
2260 + (BOOL)accessibilityIsOnOffSwitchLabelsEnabled {
2261 return UIAccessibilityIsOnOffSwitchLabelsEnabled();
2264 #pragma mark - Set user settings
2266 - (void)traitCollectionDidChange:(UITraitCollection*)previousTraitCollection {
2267 [
super traitCollectionDidChange:previousTraitCollection];
2268 [
self onUserSettingsChanged:nil];
2272 if (
self.isAutoResizable) {
2273 [
self.flutterView resetIntrinsicContentSize];
2277 - (void)onUserSettingsChanged:(NSNotification*)notification {
2278 [
self.engine.settingsChannel sendMessage:@{
2279 @"textScaleFactor" : @(
self.textScaleFactor),
2281 @"platformBrightness" :
self.brightnessMode,
2282 @"platformContrast" : self.contrastMode,
2283 @"nativeSpellCheckServiceDefined" : @YES,
2284 @"supportsShowingSystemContextMenu" : @(self.supportsShowingSystemContextMenu)
2288 - (CGFloat)textScaleFactor {
2290 if (flutterApplication == nil) {
2291 [FlutterLogger logWarning:@"Dynamic content size update is not supported in app extension."];
2295 UIContentSizeCategory category = flutterApplication.preferredContentSizeCategory;
2301 const CGFloat xs = 14;
2302 const CGFloat s = 15;
2303 const CGFloat m = 16;
2304 const CGFloat l = 17;
2305 const CGFloat xl = 19;
2306 const CGFloat xxl = 21;
2307 const CGFloat xxxl = 23;
2310 const CGFloat ax1 = 28;
2311 const CGFloat ax2 = 33;
2312 const CGFloat ax3 = 40;
2313 const CGFloat ax4 = 47;
2314 const CGFloat ax5 = 53;
2318 if ([category isEqualToString:UIContentSizeCategoryExtraSmall]) {
2320 }
else if ([category isEqualToString:UIContentSizeCategorySmall]) {
2322 }
else if ([category isEqualToString:UIContentSizeCategoryMedium]) {
2324 }
else if ([category isEqualToString:UIContentSizeCategoryLarge]) {
2326 }
else if ([category isEqualToString:UIContentSizeCategoryExtraLarge]) {
2328 }
else if ([category isEqualToString:UIContentSizeCategoryExtraExtraLarge]) {
2330 }
else if ([category isEqualToString:UIContentSizeCategoryExtraExtraExtraLarge]) {
2332 }
else if ([category isEqualToString:UIContentSizeCategoryAccessibilityMedium]) {
2334 }
else if ([category isEqualToString:UIContentSizeCategoryAccessibilityLarge]) {
2336 }
else if ([category isEqualToString:UIContentSizeCategoryAccessibilityExtraLarge]) {
2338 }
else if ([category isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraLarge]) {
2340 }
else if ([category isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraExtraLarge]) {
2347 - (BOOL)supportsShowingSystemContextMenu {
2348 if (@available(iOS 16.0, *)) {
2358 - (NSString*)brightnessMode {
2359 UIUserInterfaceStyle style =
self.traitCollection.userInterfaceStyle;
2361 if (style == UIUserInterfaceStyleDark) {
2371 - (NSString*)contrastMode {
2372 UIAccessibilityContrast contrast =
self.traitCollection.accessibilityContrast;
2374 if (contrast == UIAccessibilityContrastHigh) {
2381 #pragma mark - Status bar style
2383 - (UIStatusBarStyle)preferredStatusBarStyle {
2384 return self.statusBarStyle;
2387 - (void)onPreferredStatusBarStyleUpdated:(NSNotification*)notification {
2390 dispatch_async(dispatch_get_main_queue(), ^{
2396 NSDictionary* info = notification.userInfo;
2397 NSNumber* update = info[@(flutter::kOverlayStyleUpdateNotificationKey)];
2398 if (update == nil) {
2402 UIStatusBarStyle style =
static_cast<UIStatusBarStyle
>(update.integerValue);
2403 if (style != strongSelf.statusBarStyle) {
2404 strongSelf.statusBarStyle = style;
2405 [strongSelf setNeedsStatusBarAppearanceUpdate];
2410 - (void)setPrefersStatusBarHidden:(BOOL)hidden {
2411 if (hidden !=
self.flutterPrefersStatusBarHidden) {
2412 self.flutterPrefersStatusBarHidden = hidden;
2413 [
self setNeedsStatusBarAppearanceUpdate];
2417 - (BOOL)prefersStatusBarHidden {
2418 return self.flutterPrefersStatusBarHidden;
2421 #pragma mark - Platform views
2424 return self.engine.platformViewsController;
2428 return self.engine.binaryMessenger;
2431 #pragma mark - FlutterBinaryMessenger
2433 - (void)sendOnChannel:(NSString*)channel message:(NSData*)message {
2434 [
self.engine.binaryMessenger sendOnChannel:channel message:message];
2437 - (void)sendOnChannel:(NSString*)channel
2438 message:(NSData*)message
2440 NSAssert(channel,
@"The channel must not be null");
2441 [
self.engine.binaryMessenger sendOnChannel:channel message:message binaryReply:callback];
2445 return [
self.engine.binaryMessenger makeBackgroundTaskQueue];
2449 binaryMessageHandler:
2451 return [
self setMessageHandlerOnChannel:channel binaryMessageHandler:handler taskQueue:nil];
2455 setMessageHandlerOnChannel:(NSString*)channel
2458 NSAssert(channel,
@"The channel must not be null");
2459 return [
self.engine.binaryMessenger setMessageHandlerOnChannel:channel
2460 binaryMessageHandler:handler
2461 taskQueue:taskQueue];
2465 [
self.engine.binaryMessenger cleanUpConnection:connection];
2468 #pragma mark - FlutterTextureRegistry
2471 return [
self.engine.textureRegistry registerTexture:texture];
2474 - (void)unregisterTexture:(int64_t)textureId {
2475 [
self.engine.textureRegistry unregisterTexture:textureId];
2478 - (void)textureFrameAvailable:(int64_t)textureId {
2479 [
self.engine.textureRegistry textureFrameAvailable:textureId];
2482 - (NSString*)lookupKeyForAsset:(NSString*)asset {
2486 - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
2490 - (id<FlutterPluginRegistry>)pluginRegistry {
2494 + (BOOL)isUIAccessibilityIsVoiceOverRunning {
2495 return UIAccessibilityIsVoiceOverRunning();
2498 #pragma mark - FlutterPluginRegistry
2501 return [
self.engine registrarForPlugin:pluginKey];
2504 - (BOOL)hasPlugin:(NSString*)pluginKey {
2505 return [
self.engine hasPlugin:pluginKey];
2508 - (NSObject*)valuePublishedByPlugin:(NSString*)pluginKey {
2509 return [
self.engine valuePublishedByPlugin:pluginKey];
2512 - (void)presentViewController:(UIViewController*)viewControllerToPresent
2514 completion:(
void (^)(
void))completion {
2515 self.isPresentingViewControllerAnimating = YES;
2517 [
super presentViewController:viewControllerToPresent
2520 weakSelf.isPresentingViewControllerAnimating = NO;
2527 - (BOOL)isPresentingViewController {
2528 return self.presentedViewController != nil ||
self.isPresentingViewControllerAnimating;
2531 - (
flutter::PointerData)updateMousePointerDataFrom:(UIGestureRecognizer*)gestureRecognizer
2532 API_AVAILABLE(ios(13.4)) {
2533 CGPoint location = [gestureRecognizer locationInView:self.view];
2534 CGFloat scale =
self.flutterScreenIfViewLoaded.scale;
2536 flutter::PointerData pointer_data;
2537 pointer_data.Clear();
2541 return pointer_data;
2544 - (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer
2545 shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer*)otherGestureRecognizer
2546 API_AVAILABLE(ios(13.4)) {
2550 - (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer
2551 shouldReceiveEvent:(UIEvent*)event API_AVAILABLE(ios(13.4)) {
2552 if (gestureRecognizer == _continuousScrollingPanGestureRecognizer &&
2553 event.type == UIEventTypeScroll) {
2555 flutter::PointerData pointer_data = [
self updateMousePointerDataFrom:gestureRecognizer];
2556 pointer_data.device =
reinterpret_cast<int64_t
>(_continuousScrollingPanGestureRecognizer);
2557 pointer_data.kind = flutter::PointerData::DeviceKind::kTrackpad;
2558 pointer_data.signal_kind = flutter::PointerData::SignalKind::kScrollInertiaCancel;
2559 pointer_data.view_id =
self.viewIdentifier;
2561 if (event.timestamp <
self.scrollInertiaEventAppKitDeadline) {
2564 auto packet = std::make_unique<flutter::PointerDataPacket>(1);
2565 packet->SetPointerData(0, pointer_data);
2566 [
self.engine dispatchPointerDataPacket:std::move(packet)];
2567 self.scrollInertiaEventAppKitDeadline = 0;
2574 - (void)hoverEvent:(UIHoverGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) {
2577 flutter::PointerData pointer_data = [
self updateMousePointerDataFrom:recognizer];
2578 pointer_data.device =
reinterpret_cast<int64_t
>(recognizer);
2579 pointer_data.kind = flutter::PointerData::DeviceKind::kMouse;
2580 pointer_data.view_id =
self.viewIdentifier;
2582 switch (_hoverGestureRecognizer.state) {
2583 case UIGestureRecognizerStateBegan:
2584 pointer_data.change = flutter::PointerData::Change::kAdd;
2586 case UIGestureRecognizerStateChanged:
2587 pointer_data.change = flutter::PointerData::Change::kHover;
2589 case UIGestureRecognizerStateEnded:
2590 case UIGestureRecognizerStateCancelled:
2591 pointer_data.change = flutter::PointerData::Change::kRemove;
2596 pointer_data.change = flutter::PointerData::Change::kHover;
2600 NSTimeInterval time = [NSProcessInfo processInfo].systemUptime;
2601 BOOL isRunningOnMac = NO;
2602 if (@available(iOS 14.0, *)) {
2606 isRunningOnMac = [NSProcessInfo processInfo].iOSAppOnMac;
2609 time >
self.scrollInertiaEventStartline) {
2613 auto packet = std::make_unique<flutter::PointerDataPacket>(2);
2614 packet->SetPointerData(0, pointer_data);
2615 flutter::PointerData inertia_cancel = pointer_data;
2616 inertia_cancel.device =
reinterpret_cast<int64_t
>(_continuousScrollingPanGestureRecognizer);
2617 inertia_cancel.kind = flutter::PointerData::DeviceKind::kTrackpad;
2618 inertia_cancel.signal_kind = flutter::PointerData::SignalKind::kScrollInertiaCancel;
2619 inertia_cancel.view_id =
self.viewIdentifier;
2620 packet->SetPointerData(1, inertia_cancel);
2621 [
self.engine dispatchPointerDataPacket:std::move(packet)];
2622 self.scrollInertiaEventStartline = DBL_MAX;
2624 auto packet = std::make_unique<flutter::PointerDataPacket>(1);
2625 packet->SetPointerData(0, pointer_data);
2626 [
self.engine dispatchPointerDataPacket:std::move(packet)];
2630 - (void)discreteScrollEvent:(UIPanGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) {
2631 CGPoint translation = [recognizer translationInView:self.view];
2632 const CGFloat scale =
self.flutterScreenIfViewLoaded.scale;
2634 translation.x *= scale;
2635 translation.y *= scale;
2637 flutter::PointerData pointer_data = [
self updateMousePointerDataFrom:recognizer];
2638 pointer_data.device =
reinterpret_cast<int64_t
>(recognizer);
2639 pointer_data.kind = flutter::PointerData::DeviceKind::kMouse;
2640 pointer_data.signal_kind = flutter::PointerData::SignalKind::kScroll;
2641 pointer_data.scroll_delta_x = (translation.x -
_mouseState.last_translation.x);
2642 pointer_data.scroll_delta_y = -(translation.y -
_mouseState.last_translation.y);
2643 pointer_data.view_id =
self.viewIdentifier;
2649 if (recognizer.state != UIGestureRecognizerStateEnded) {
2655 auto packet = std::make_unique<flutter::PointerDataPacket>(1);
2656 packet->SetPointerData(0, pointer_data);
2657 [
self.engine dispatchPointerDataPacket:std::move(packet)];
2660 - (void)continuousScrollEvent:(UIPanGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) {
2661 CGPoint translation = [recognizer translationInView:self.view];
2662 const CGFloat scale =
self.flutterScreenIfViewLoaded.scale;
2664 flutter::PointerData pointer_data = [
self updateMousePointerDataFrom:recognizer];
2665 pointer_data.device =
reinterpret_cast<int64_t
>(recognizer);
2666 pointer_data.kind = flutter::PointerData::DeviceKind::kTrackpad;
2667 pointer_data.view_id =
self.viewIdentifier;
2668 switch (recognizer.state) {
2669 case UIGestureRecognizerStateBegan:
2670 pointer_data.change = flutter::PointerData::Change::kPanZoomStart;
2672 case UIGestureRecognizerStateChanged:
2673 pointer_data.change = flutter::PointerData::Change::kPanZoomUpdate;
2674 pointer_data.pan_x = translation.x * scale;
2675 pointer_data.pan_y = translation.y * scale;
2676 pointer_data.pan_delta_x = 0;
2677 pointer_data.pan_delta_y = 0;
2678 pointer_data.scale = 1;
2680 case UIGestureRecognizerStateEnded:
2681 case UIGestureRecognizerStateCancelled:
2682 self.scrollInertiaEventStartline =
2683 [[NSProcessInfo processInfo] systemUptime] +
2693 self.scrollInertiaEventAppKitDeadline =
2694 [[NSProcessInfo processInfo] systemUptime] +
2695 (0.1821 * log(fmax([recognizer velocityInView:self.view].x,
2696 [recognizer velocityInView:self.view].y))) -
2698 pointer_data.change = flutter::PointerData::Change::kPanZoomEnd;
2702 NSAssert(NO,
@"Trackpad pan event occured with unexpected phase 0x%lx",
2703 (
long)recognizer.state);
2707 auto packet = std::make_unique<flutter::PointerDataPacket>(1);
2708 packet->SetPointerData(0, pointer_data);
2709 [
self.engine dispatchPointerDataPacket:std::move(packet)];
2712 - (void)pinchEvent:(UIPinchGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) {
2713 flutter::PointerData pointer_data = [
self updateMousePointerDataFrom:recognizer];
2714 pointer_data.device =
reinterpret_cast<int64_t
>(recognizer);
2715 pointer_data.kind = flutter::PointerData::DeviceKind::kTrackpad;
2716 pointer_data.view_id =
self.viewIdentifier;
2717 switch (recognizer.state) {
2718 case UIGestureRecognizerStateBegan:
2719 pointer_data.change = flutter::PointerData::Change::kPanZoomStart;
2721 case UIGestureRecognizerStateChanged:
2722 pointer_data.change = flutter::PointerData::Change::kPanZoomUpdate;
2723 pointer_data.scale = recognizer.scale;
2724 pointer_data.rotation = _rotationGestureRecognizer.rotation;
2726 case UIGestureRecognizerStateEnded:
2727 case UIGestureRecognizerStateCancelled:
2728 pointer_data.change = flutter::PointerData::Change::kPanZoomEnd;
2732 NSAssert(NO,
@"Trackpad pinch event occured with unexpected phase 0x%lx",
2733 (
long)recognizer.state);
2737 auto packet = std::make_unique<flutter::PointerDataPacket>(1);
2738 packet->SetPointerData(0, pointer_data);
2739 [
self.engine dispatchPointerDataPacket:std::move(packet)];
2742 #pragma mark - State Restoration
2744 - (void)encodeRestorableStateWithCoder:(NSCoder*)coder {
2745 NSData* restorationData = [
self.engine.restorationPlugin restorationData];
2746 [coder encodeBytes:(const unsigned char*)restorationData.bytes
2747 length:restorationData.length
2748 forKey:kFlutterRestorationStateAppData];
2749 [
super encodeRestorableStateWithCoder:coder];
2752 - (void)decodeRestorableStateWithCoder:(NSCoder*)coder {
2753 NSUInteger restorationDataLength;
2754 const unsigned char* restorationBytes = [coder decodeBytesForKey:kFlutterRestorationStateAppData
2755 returnedLength:&restorationDataLength];
2756 NSData* restorationData = [NSData dataWithBytes:restorationBytes length:restorationDataLength];
2757 [
self.engine.restorationPlugin setRestorationData:restorationData];
2761 return self.engine.restorationPlugin;
2765 return self.engine.textInputPlugin;
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
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
void(^ FlutterKeyboardAnimationCallback)(fml::TimePoint)
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)
double displayRefreshRate
The display refresh rate used for reporting purposes. The engine does not care about this for frame s...
UIApplication * application
void setUpIndirectScribbleInteraction:(id< FlutterViewResponder > viewResponder)
UIView * splashScreenView