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;
363 _accessibilityFeatures = [[FlutterAccessibilityFeatures alloc] init];
367 [
self setUpNotificationCenterObservers];
370 - (void)setUpNotificationCenterObservers {
371 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
372 [center addObserver:self
373 selector:@selector(onOrientationPreferencesUpdated:)
374 name:@(flutter::kOrientationUpdateNotificationName)
377 [center addObserver:self
378 selector:@selector(onPreferredStatusBarStyleUpdated:)
379 name:@(flutter::kOverlayStyleUpdateNotificationName)
383 [
self setUpApplicationLifecycleNotifications:center];
385 [
self setUpSceneLifecycleNotifications:center];
388 [center addObserver:self
389 selector:@selector(keyboardWillChangeFrame:)
390 name:UIKeyboardWillChangeFrameNotification
393 [center addObserver:self
394 selector:@selector(keyboardWillShowNotification:)
395 name:UIKeyboardWillShowNotification
398 [center addObserver:self
399 selector:@selector(keyboardWillBeHidden:)
400 name:UIKeyboardWillHideNotification
403 for (NSString* notification in [
self.accessibilityFeatures observedNotificationNames]) {
404 [center addObserver:self
405 selector:@selector(onAccessibilityStatusChanged:)
410 [center addObserver:self
411 selector:@selector(onUserSettingsChanged:)
412 name:UIContentSizeCategoryDidChangeNotification
415 [center addObserver:self
416 selector:@selector(onHideHomeIndicatorNotification:)
417 name:FlutterViewControllerHideHomeIndicator
420 [center addObserver:self
421 selector:@selector(onShowHomeIndicatorNotification:)
422 name:FlutterViewControllerShowHomeIndicator
426 - (void)setUpSceneLifecycleNotifications:(NSNotificationCenter*)center API_AVAILABLE(ios(13.0)) {
427 [center addObserver:self
428 selector:@selector(sceneBecameActive:)
429 name:UISceneDidActivateNotification
432 [center addObserver:self
433 selector:@selector(sceneWillResignActive:)
434 name:UISceneWillDeactivateNotification
437 [center addObserver:self
438 selector:@selector(sceneWillDisconnect:)
439 name:UISceneDidDisconnectNotification
442 [center addObserver:self
443 selector:@selector(sceneDidEnterBackground:)
444 name:UISceneDidEnterBackgroundNotification
447 [center addObserver:self
448 selector:@selector(sceneWillEnterForeground:)
449 name:UISceneWillEnterForegroundNotification
453 - (void)setUpApplicationLifecycleNotifications:(NSNotificationCenter*)center {
454 [center addObserver:self
455 selector:@selector(applicationBecameActive:)
456 name:UIApplicationDidBecomeActiveNotification
459 [center addObserver:self
460 selector:@selector(applicationWillResignActive:)
461 name:UIApplicationWillResignActiveNotification
464 [center addObserver:self
465 selector:@selector(applicationWillTerminate:)
466 name:UIApplicationWillTerminateNotification
469 [center addObserver:self
470 selector:@selector(applicationDidEnterBackground:)
471 name:UIApplicationDidEnterBackgroundNotification
474 [center addObserver:self
475 selector:@selector(applicationWillEnterForeground:)
476 name:UIApplicationWillEnterForegroundNotification
480 - (void)setInitialRoute:(NSString*)route {
481 [
self.engine.navigationChannel invokeMethod:@"setInitialRoute" arguments:route];
485 [
self.engine.navigationChannel invokeMethod:@"popRoute" arguments:nil];
488 - (void)pushRoute:(NSString*)route {
489 [
self.engine.navigationChannel invokeMethod:@"pushRoute" arguments:route];
492 #pragma mark - Loading the view
494 static UIView* GetViewOrPlaceholder(UIView* existing_view) {
496 return existing_view;
499 auto placeholder = [[UIView alloc] init];
501 placeholder.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
502 placeholder.backgroundColor = UIColor.systemBackgroundColor;
503 placeholder.autoresizesSubviews = YES;
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;
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];
525 self.view = GetViewOrPlaceholder(
self.flutterView);
526 self.view.multipleTouchEnabled = YES;
527 self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
529 [
self installSplashScreenViewIfNecessary];
532 UIScrollView* scrollView = [[UIScrollView alloc] init];
533 scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
535 scrollView.backgroundColor = UIColor.whiteColor;
536 scrollView.delegate =
self;
542 [
self.view addSubview:scrollView];
543 self.scrollView = scrollView;
546 - (
flutter::PointerData)generatePointerDataForFake {
547 flutter::PointerData pointer_data;
548 pointer_data.Clear();
549 pointer_data.kind = flutter::PointerData::DeviceKind::kTouch;
557 - (BOOL)scrollViewShouldScrollToTop:(UIScrollView*)scrollView {
561 if (
self.isViewLoaded) {
563 [
self.engine onStatusBarTap];
568 #pragma mark - Managing launch views
570 - (void)installSplashScreenViewIfNecessary {
573 if (
self.splashScreenView && (
self.isBeingPresented ||
self.isMovingToParentViewController)) {
574 [
self.splashScreenView removeFromSuperview];
575 self.splashScreenView = nil;
580 UIView* splashScreenView =
self.splashScreenView;
581 if (splashScreenView == nil) {
584 splashScreenView.frame =
self.view.bounds;
585 [
self.view addSubview:splashScreenView];
588 + (BOOL)automaticallyNotifiesObserversOfDisplayingFlutterUI {
592 - (void)setDisplayingFlutterUI:(BOOL)displayingFlutterUI {
593 if (_displayingFlutterUI != displayingFlutterUI) {
594 if (displayingFlutterUI == YES) {
595 if (!
self.viewIfLoaded.window) {
599 [
self willChangeValueForKey:@"displayingFlutterUI"];
600 _displayingFlutterUI = displayingFlutterUI;
601 [
self didChangeValueForKey:@"displayingFlutterUI"];
605 - (void)callViewRenderedCallback {
606 self.displayingFlutterUI = YES;
607 if (
self.flutterViewRenderedCallback) {
608 self.flutterViewRenderedCallback();
609 self.flutterViewRenderedCallback = nil;
613 - (void)removeSplashScreenWithCompletion:(dispatch_block_t _Nullable)onComplete {
614 NSAssert(
self.splashScreenView,
@"The splash screen view must not be nil");
615 UIView* splashScreen =
self.splashScreenView;
617 _splashScreenView = nil;
618 [UIView animateWithDuration:0.2
620 splashScreen.alpha = 0;
622 completion:^(BOOL finished) {
623 [splashScreen removeFromSuperview];
630 - (void)onFirstFrameRendered {
631 if (
self.splashScreenView) {
633 [
self removeSplashScreenWithCompletion:^{
634 [weakSelf callViewRenderedCallback];
637 [
self callViewRenderedCallback];
641 - (void)installFirstFrameCallback {
646 [
self.engine installFirstFrameCallback:^{
647 [weakSelf onFirstFrameRendered];
651 #pragma mark - Properties
653 - (int64_t)viewIdentifier {
656 return flutter::kFlutterImplicitViewId;
659 - (BOOL)loadDefaultSplashScreenView {
660 NSString* launchscreenName =
661 [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UILaunchStoryboardName"];
662 if (launchscreenName == nil) {
665 UIView* splashView = [
self splashScreenFromStoryboard:launchscreenName];
667 splashView = [
self splashScreenFromXib:launchscreenName];
676 - (UIView*)splashScreenFromStoryboard:(NSString*)name {
677 UIStoryboard* storyboard = nil;
679 storyboard = [UIStoryboard storyboardWithName:name bundle:nil];
680 }
@catch (NSException* exception) {
684 UIViewController* splashScreenViewController = [storyboard instantiateInitialViewController];
685 return splashScreenViewController.view;
690 - (UIView*)splashScreenFromXib:(NSString*)name {
691 NSArray* objects = nil;
693 objects = [[NSBundle mainBundle] loadNibNamed:name owner:self options:nil];
694 }
@catch (NSException* exception) {
697 if ([objects count] != 0) {
698 UIView* view = [objects objectAtIndex:0];
704 - (void)setSplashScreenView:(UIView*)view {
705 if (view == _splashScreenView) {
711 if (_splashScreenView) {
712 [
self removeSplashScreenWithCompletion:nil];
717 _splashScreenView = view;
718 _splashScreenView.autoresizingMask =
719 UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
722 - (void)setFlutterViewDidRenderCallback:(
void (^)(
void))callback {
723 _flutterViewRenderedCallback = callback;
726 - (UISceneActivationState)activationState {
727 return self.flutterWindowSceneIfViewLoaded.activationState;
730 - (BOOL)stateIsActive {
733 BOOL isActive = flutterApplication
734 ? [
self isApplicationStateMatching:UIApplicationStateActive
735 withApplication:flutterApplication]
736 : [
self isSceneStateMatching:UISceneActivationStateForegroundActive];
740 - (BOOL)stateIsBackground {
743 return flutterApplication ? [
self isApplicationStateMatching:UIApplicationStateBackground
744 withApplication:flutterApplication]
745 : [
self isSceneStateMatching:UISceneActivationStateBackground];
748 - (BOOL)isApplicationStateMatching:(UIApplicationState)match
749 withApplication:(UIApplication*)application {
750 switch (application.applicationState) {
751 case UIApplicationStateActive:
752 case UIApplicationStateInactive:
753 case UIApplicationStateBackground:
754 return application.applicationState == match;
758 - (BOOL)isSceneStateMatching:(UISceneActivationState)match API_AVAILABLE(ios(13.0)) {
759 switch (
self.activationState) {
760 case UISceneActivationStateForegroundActive:
761 case UISceneActivationStateUnattached:
762 case UISceneActivationStateForegroundInactive:
763 case UISceneActivationStateBackground:
764 return self.activationState == match;
768 #pragma mark - Surface creation and teardown updates
770 - (void)surfaceUpdated:(BOOL)appeared {
778 [
self installFirstFrameCallback];
779 self.platformViewsController.flutterView =
self.flutterView;
780 self.platformViewsController.flutterViewController =
self;
781 [
self.engine notifyViewCreated];
783 self.displayingFlutterUI = NO;
784 [
self.engine notifyViewDestroyed];
785 self.platformViewsController.flutterView = nil;
786 self.platformViewsController.flutterViewController = nil;
790 #pragma mark - UIViewController lifecycle notifications
792 - (void)viewDidLoad {
793 TRACE_EVENT0(
"flutter",
"viewDidLoad");
795 if (
self.
engine &&
self.engineNeedsLaunch) {
796 [
self.engine launchEngine:nil libraryURI:nil entrypointArgs:nil];
797 [
self.engine setViewController:self];
798 self.engineNeedsLaunch = NO;
799 }
else if (
self.
engine.viewController ==
self) {
800 [
self.engine attachView];
804 [
self addInternalPlugins];
807 [
self createTouchRateCorrectionVSyncClientIfNeeded];
809 if (@available(iOS 13.4, *)) {
810 _hoverGestureRecognizer =
811 [[UIHoverGestureRecognizer alloc] initWithTarget:self action:@selector(hoverEvent:)];
812 _hoverGestureRecognizer.delegate =
self;
813 [
self.flutterView addGestureRecognizer:_hoverGestureRecognizer];
815 _discreteScrollingPanGestureRecognizer =
816 [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(discreteScrollEvent:)];
817 _discreteScrollingPanGestureRecognizer.allowedScrollTypesMask = UIScrollTypeMaskDiscrete;
822 _discreteScrollingPanGestureRecognizer.allowedTouchTypes = @[];
823 _discreteScrollingPanGestureRecognizer.delegate =
self;
824 [
self.flutterView addGestureRecognizer:_discreteScrollingPanGestureRecognizer];
825 _continuousScrollingPanGestureRecognizer =
826 [[UIPanGestureRecognizer alloc] initWithTarget:self
827 action:@selector(continuousScrollEvent:)];
828 _continuousScrollingPanGestureRecognizer.allowedScrollTypesMask = UIScrollTypeMaskContinuous;
829 _continuousScrollingPanGestureRecognizer.allowedTouchTypes = @[];
830 _continuousScrollingPanGestureRecognizer.delegate =
self;
831 [
self.flutterView addGestureRecognizer:_continuousScrollingPanGestureRecognizer];
832 _pinchGestureRecognizer =
833 [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchEvent:)];
834 _pinchGestureRecognizer.allowedTouchTypes = @[];
835 _pinchGestureRecognizer.delegate =
self;
836 [
self.flutterView addGestureRecognizer:_pinchGestureRecognizer];
837 _rotationGestureRecognizer = [[UIRotationGestureRecognizer alloc] init];
838 _rotationGestureRecognizer.allowedTouchTypes = @[];
839 _rotationGestureRecognizer.delegate =
self;
840 [
self.flutterView addGestureRecognizer:_rotationGestureRecognizer];
846 - (void)addInternalPlugins {
850 ^(
const FlutterKeyEvent& event, FlutterKeyEventCallback callback,
void* userData) {
851 [weakSelf.engine sendKeyEvent:event callback:callback userData:userData];
853 [
self.keyboardManager
857 [
self.keyboardManager addPrimaryResponder:responder];
860 [
self.keyboardManager addSecondaryResponder:textInputPlugin];
862 if (
self.
engine.viewController ==
self) {
867 - (void)removeInternalPlugins {
868 self.keyboardManager = nil;
871 - (void)viewWillAppear:(BOOL)animated {
872 TRACE_EVENT0(
"flutter",
"viewWillAppear");
873 if (
self.
engine.viewController ==
self) {
875 [
self onUserSettingsChanged:nil];
879 if (_viewportMetrics.physical_width) {
880 [
self surfaceUpdated:YES];
882 [
self.engine.lifecycleChannel sendMessage:@"AppLifecycleState.inactive"];
883 [
self.engine.restorationPlugin markRestorationComplete];
886 [
super viewWillAppear:animated];
889 - (void)viewDidAppear:(BOOL)animated {
890 TRACE_EVENT0(
"flutter",
"viewDidAppear");
891 if (
self.
engine.viewController ==
self) {
892 [
self onUserSettingsChanged:nil];
893 [
self onAccessibilityStatusChanged:nil];
895 if (
self.stateIsActive) {
896 [
self.engine.lifecycleChannel sendMessage:@"AppLifecycleState.resumed"];
899 [
super viewDidAppear:animated];
902 - (void)viewWillDisappear:(BOOL)animated {
903 TRACE_EVENT0(
"flutter",
"viewWillDisappear");
904 if (
self.
engine.viewController ==
self) {
905 [
self.engine.lifecycleChannel sendMessage:@"AppLifecycleState.inactive"];
907 [
super viewWillDisappear:animated];
910 - (void)viewDidDisappear:(BOOL)animated {
911 TRACE_EVENT0(
"flutter",
"viewDidDisappear");
912 if (
self.
engine.viewController ==
self) {
913 [
self invalidateKeyboardAnimationVSyncClient];
914 [
self ensureViewportMetricsIsCorrect];
915 [
self surfaceUpdated:NO];
916 [
self.engine.lifecycleChannel sendMessage:@"AppLifecycleState.paused"];
917 [
self flushOngoingTouches];
918 [
self.engine notifyLowMemory];
921 [
super viewDidDisappear:animated];
924 - (void)viewWillTransitionToSize:(CGSize)size
925 withTransitionCoordinator:(
id<UIViewControllerTransitionCoordinator>)coordinator {
926 [
super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
936 NSTimeInterval transitionDuration = coordinator.transitionDuration;
938 if (transitionDuration == 0) {
943 _shouldIgnoreViewportMetricsUpdatesDuringRotation = YES;
944 dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
945 static_cast<int64_t
>(transitionDuration / 2.0 * NSEC_PER_SEC)),
946 dispatch_get_main_queue(), ^{
954 strongSelf.shouldIgnoreViewportMetricsUpdatesDuringRotation = NO;
955 [strongSelf updateViewportMetricsIfNeeded];
959 - (void)flushOngoingTouches {
960 if (
self.
engine &&
self.ongoingTouches.count > 0) {
961 auto packet = std::make_unique<flutter::PointerDataPacket>(
self.ongoingTouches.count);
962 size_t pointer_index = 0;
965 for (NSNumber* device in
self.ongoingTouches) {
967 flutter::PointerData pointer_data = [
self generatePointerDataForFake];
969 pointer_data.change = flutter::PointerData::Change::kCancel;
970 pointer_data.device = device.longLongValue;
971 pointer_data.pointer_identifier = 0;
972 pointer_data.view_id =
self.viewIdentifier;
975 pointer_data.physical_x = 0;
976 pointer_data.physical_y = 0;
977 pointer_data.physical_delta_x = 0.0;
978 pointer_data.physical_delta_y = 0.0;
979 pointer_data.pressure = 1.0;
980 pointer_data.pressure_max = 1.0;
982 packet->SetPointerData(pointer_index++, pointer_data);
985 [
self.ongoingTouches removeAllObjects];
986 [
self.engine dispatchPointerDataPacket:std::move(packet)];
990 - (void)deregisterNotifications {
991 [[NSNotificationCenter defaultCenter] postNotificationName:FlutterViewControllerWillDealloc
994 [[NSNotificationCenter defaultCenter] removeObserver:self];
1000 [
self removeInternalPlugins];
1001 [
self deregisterNotifications];
1003 [
self invalidateKeyboardAnimationVSyncClient];
1004 [
self invalidateTouchRateCorrectionVSyncClient];
1008 _scrollView.delegate = nil;
1009 _hoverGestureRecognizer.delegate = nil;
1010 _discreteScrollingPanGestureRecognizer.delegate = nil;
1011 _continuousScrollingPanGestureRecognizer.delegate = nil;
1012 _pinchGestureRecognizer.delegate = nil;
1013 _rotationGestureRecognizer.delegate = nil;
1016 #pragma mark - Application lifecycle notifications
1018 - (void)applicationBecameActive:(NSNotification*)notification {
1019 TRACE_EVENT0(
"flutter",
"applicationBecameActive");
1020 [
self appOrSceneBecameActive];
1023 - (void)applicationWillResignActive:(NSNotification*)notification {
1024 TRACE_EVENT0(
"flutter",
"applicationWillResignActive");
1025 [
self appOrSceneWillResignActive];
1028 - (void)applicationWillTerminate:(NSNotification*)notification {
1029 [
self appOrSceneWillTerminate];
1032 - (void)applicationDidEnterBackground:(NSNotification*)notification {
1033 TRACE_EVENT0(
"flutter",
"applicationDidEnterBackground");
1034 [
self appOrSceneDidEnterBackground];
1037 - (void)applicationWillEnterForeground:(NSNotification*)notification {
1038 TRACE_EVENT0(
"flutter",
"applicationWillEnterForeground");
1039 [
self appOrSceneWillEnterForeground];
1042 #pragma mark - Scene lifecycle notifications
1044 - (void)sceneBecameActive:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1045 TRACE_EVENT0(
"flutter",
"sceneBecameActive");
1046 [
self appOrSceneBecameActive];
1049 - (void)sceneWillResignActive:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1050 TRACE_EVENT0(
"flutter",
"sceneWillResignActive");
1051 [
self appOrSceneWillResignActive];
1054 - (void)sceneWillDisconnect:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1055 [
self appOrSceneWillTerminate];
1058 - (void)sceneDidEnterBackground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1059 TRACE_EVENT0(
"flutter",
"sceneDidEnterBackground");
1060 [
self appOrSceneDidEnterBackground];
1063 - (void)sceneWillEnterForeground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1064 TRACE_EVENT0(
"flutter",
"sceneWillEnterForeground");
1065 [
self appOrSceneWillEnterForeground];
1068 #pragma mark - Lifecycle shared
1070 - (void)appOrSceneBecameActive {
1071 self.isKeyboardInOrTransitioningFromBackground = NO;
1072 if (_viewportMetrics.physical_width) {
1073 [
self surfaceUpdated:YES];
1075 [
self performSelector:@selector(goToApplicationLifecycle:)
1076 withObject:@"AppLifecycleState.resumed"
1080 - (void)appOrSceneWillResignActive {
1081 [NSObject cancelPreviousPerformRequestsWithTarget:self
1082 selector:@selector(goToApplicationLifecycle:)
1083 object:@"AppLifecycleState.resumed"];
1084 [
self goToApplicationLifecycle:@"AppLifecycleState.inactive"];
1087 - (void)appOrSceneWillTerminate {
1088 [
self goToApplicationLifecycle:@"AppLifecycleState.detached"];
1089 [
self.engine destroyContext];
1092 - (void)appOrSceneDidEnterBackground {
1093 self.isKeyboardInOrTransitioningFromBackground = YES;
1094 [
self surfaceUpdated:NO];
1095 [
self goToApplicationLifecycle:@"AppLifecycleState.paused"];
1098 - (void)appOrSceneWillEnterForeground {
1099 [
self goToApplicationLifecycle:@"AppLifecycleState.inactive"];
1103 - (void)goToApplicationLifecycle:(nonnull NSString*)state {
1106 if (
self.viewIfLoaded.window) {
1107 [
self.engine.lifecycleChannel sendMessage:state];
1111 #pragma mark - Touch event handling
1113 static flutter::PointerData::Change PointerDataChangeFromUITouchPhase(UITouchPhase phase) {
1115 case UITouchPhaseBegan:
1116 return flutter::PointerData::Change::kDown;
1117 case UITouchPhaseMoved:
1118 case UITouchPhaseStationary:
1121 return flutter::PointerData::Change::kMove;
1122 case UITouchPhaseEnded:
1123 return flutter::PointerData::Change::kUp;
1124 case UITouchPhaseCancelled:
1125 return flutter::PointerData::Change::kCancel;
1128 FML_DLOG(INFO) <<
"Unhandled touch phase: " << phase;
1132 return flutter::PointerData::Change::kCancel;
1135 static flutter::PointerData::DeviceKind DeviceKindFromTouchType(UITouch* touch) {
1136 switch (touch.type) {
1137 case UITouchTypeDirect:
1138 case UITouchTypeIndirect:
1139 return flutter::PointerData::DeviceKind::kTouch;
1140 case UITouchTypeStylus:
1141 return flutter::PointerData::DeviceKind::kStylus;
1142 case UITouchTypeIndirectPointer:
1143 return flutter::PointerData::DeviceKind::kMouse;
1145 FML_DLOG(INFO) <<
"Unhandled touch type: " << touch.type;
1149 return flutter::PointerData::DeviceKind::kTouch;
1156 - (void)dispatchTouches:(NSSet*)touches
1157 pointerDataChangeOverride:(
flutter::PointerData::Change*)overridden_change
1158 event:(UIEvent*)event {
1183 NSUInteger touches_to_remove_count = 0;
1184 for (UITouch* touch in touches) {
1185 if (touch.phase == UITouchPhaseEnded || touch.phase == UITouchPhaseCancelled) {
1186 touches_to_remove_count++;
1191 [
self triggerTouchRateCorrectionIfNeeded:touches];
1193 const CGFloat scale =
self.flutterScreenIfViewLoaded.scale;
1195 std::make_unique<flutter::PointerDataPacket>(touches.count + touches_to_remove_count);
1197 size_t pointer_index = 0;
1199 for (UITouch* touch in touches) {
1200 CGPoint windowCoordinates = [touch locationInView:self.view];
1202 flutter::PointerData pointer_data;
1203 pointer_data.Clear();
1208 pointer_data.change = overridden_change !=
nullptr
1209 ? *overridden_change
1210 : PointerDataChangeFromUITouchPhase(touch.phase);
1212 pointer_data.kind = DeviceKindFromTouchType(touch);
1214 pointer_data.device =
reinterpret_cast<int64_t
>(touch);
1216 pointer_data.view_id =
self.viewIdentifier;
1219 pointer_data.pointer_identifier = 0;
1221 pointer_data.physical_x = windowCoordinates.x * scale;
1222 pointer_data.physical_y = windowCoordinates.y * scale;
1225 pointer_data.physical_delta_x = 0.0;
1226 pointer_data.physical_delta_y = 0.0;
1228 NSNumber* deviceKey = [NSNumber numberWithLongLong:pointer_data.device];
1231 switch (pointer_data.change) {
1232 case flutter::PointerData::Change::kDown:
1233 [
self.ongoingTouches addObject:deviceKey];
1235 case flutter::PointerData::Change::kCancel:
1236 case flutter::PointerData::Change::kUp:
1237 [
self.ongoingTouches removeObject:deviceKey];
1239 case flutter::PointerData::Change::kHover:
1240 case flutter::PointerData::Change::kMove:
1243 case flutter::PointerData::Change::kAdd:
1244 case flutter::PointerData::Change::kRemove:
1247 case flutter::PointerData::Change::kPanZoomStart:
1248 case flutter::PointerData::Change::kPanZoomUpdate:
1249 case flutter::PointerData::Change::kPanZoomEnd:
1255 pointer_data.pressure = touch.force;
1256 pointer_data.pressure_max = touch.maximumPossibleForce;
1257 pointer_data.radius_major = touch.majorRadius;
1258 pointer_data.radius_min = touch.majorRadius - touch.majorRadiusTolerance;
1259 pointer_data.radius_max = touch.majorRadius + touch.majorRadiusTolerance;
1274 pointer_data.tilt = M_PI_2 - touch.altitudeAngle;
1294 pointer_data.orientation = [touch azimuthAngleInView:nil] - M_PI_2;
1296 if (@available(iOS 13.4, *)) {
1297 if (event !=
nullptr) {
1298 pointer_data.buttons = (((
event.buttonMask & UIEventButtonMaskPrimary) > 0)
1299 ? flutter::PointerButtonMouse::kPointerButtonMousePrimary
1301 (((event.buttonMask & UIEventButtonMaskSecondary) > 0)
1302 ? flutter::PointerButtonMouse::kPointerButtonMouseSecondary
1307 packet->SetPointerData(pointer_index++, pointer_data);
1309 if (touch.phase == UITouchPhaseEnded || touch.phase == UITouchPhaseCancelled) {
1310 flutter::PointerData remove_pointer_data = pointer_data;
1311 remove_pointer_data.change = flutter::PointerData::Change::kRemove;
1312 packet->SetPointerData(pointer_index++, remove_pointer_data);
1316 [
self.engine dispatchPointerDataPacket:std::move(packet)];
1319 - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
1320 [
self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event];
1323 - (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
1324 [
self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event];
1327 - (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
1328 [
self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event];
1331 - (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event {
1332 [
self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event];
1335 - (void)forceTouchesCancelled:(NSSet*)touches {
1336 flutter::PointerData::Change cancel = flutter::PointerData::Change::kCancel;
1337 [
self dispatchTouches:touches pointerDataChangeOverride:&cancel event:nullptr];
1340 #pragma mark - Touch events rate correction
1342 - (void)createTouchRateCorrectionVSyncClientIfNeeded {
1343 if (_touchRateCorrectionVSyncClient != nil) {
1348 const double epsilon = 0.1;
1349 if (displayRefreshRate < 60.0 + epsilon) {
1357 auto callback = [](std::unique_ptr<flutter::FrameTimingsRecorder> recorder) {
1360 _touchRateCorrectionVSyncClient =
1361 [[
VSyncClient alloc] initWithTaskRunner:self.engine.platformTaskRunner callback:callback];
1362 _touchRateCorrectionVSyncClient.allowPauseAfterVsync = NO;
1365 - (void)triggerTouchRateCorrectionIfNeeded:(NSSet*)touches {
1366 if (_touchRateCorrectionVSyncClient == nil) {
1374 BOOL isUserInteracting = NO;
1375 for (UITouch* touch in touches) {
1376 if (touch.phase == UITouchPhaseBegan || touch.phase == UITouchPhaseMoved) {
1377 isUserInteracting = YES;
1382 if (isUserInteracting &&
self.
engine.viewController ==
self) {
1383 [_touchRateCorrectionVSyncClient await];
1385 [_touchRateCorrectionVSyncClient pause];
1389 - (void)invalidateTouchRateCorrectionVSyncClient {
1390 [_touchRateCorrectionVSyncClient invalidate];
1391 _touchRateCorrectionVSyncClient = nil;
1394 #pragma mark - Handle view resizing
1396 - (void)updateViewportMetricsIfNeeded {
1397 if (_shouldIgnoreViewportMetricsUpdatesDuringRotation) {
1400 if (
self.
engine.viewController ==
self) {
1401 [
self.engine updateViewportMetrics:_viewportMetrics];
1405 - (void)viewDidLayoutSubviews {
1406 CGRect viewBounds =
self.view.bounds;
1407 CGFloat scale =
self.flutterScreenIfViewLoaded.scale;
1410 self.scrollView.frame = CGRectMake(0.0, 0.0, viewBounds.size.width, 0.0);
1414 bool firstViewBoundsUpdate = !_viewportMetrics.physical_width;
1415 _viewportMetrics.device_pixel_ratio = scale;
1416 [
self setViewportMetricsSize];
1417 [
self checkAndUpdateAutoResizeConstraints];
1418 [
self setViewportMetricsPaddings];
1419 [
self updateViewportMetricsIfNeeded];
1426 if (firstViewBoundsUpdate &&
self.stateIsActive &&
self.
engine) {
1427 [
self surfaceUpdated:YES];
1428 #if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
1429 NSTimeInterval timeout = 0.2;
1431 NSTimeInterval timeout = 0.1;
1434 waitForFirstFrameSync:timeout
1435 callback:^(BOOL didTimeout) {
1437 [FlutterLogger logInfo:@"Timeout waiting for the first frame to render. "
1438 "This may happen in unoptimized builds. If this is"
1439 "a release build, you should load a less complex "
1440 "frame to avoid the timeout."];
1446 - (BOOL)isAutoResizable {
1447 return self.flutterView.autoResizable;
1450 - (void)setAutoResizable:(BOOL)value {
1451 self.flutterView.autoResizable = value;
1452 self.flutterView.contentMode = UIViewContentModeCenter;
1455 - (void)checkAndUpdateAutoResizeConstraints {
1456 if (!
self.isAutoResizable) {
1460 [
self updateAutoResizeConstraints];
1484 - (void)updateAutoResizeConstraints {
1485 BOOL hasBeenAutoResized = NO;
1486 for (NSLayoutConstraint* constraint in
self.view.constraints) {
1488 hasBeenAutoResized = YES;
1492 if (!hasBeenAutoResized) {
1493 self.sizeBeforeAutoResized =
self.view.frame.size;
1496 CGFloat maxWidth =
self.sizeBeforeAutoResized.width;
1497 CGFloat maxHeight =
self.sizeBeforeAutoResized.height;
1498 CGFloat minWidth =
self.sizeBeforeAutoResized.width;
1499 CGFloat minHeight =
self.sizeBeforeAutoResized.height;
1503 if (maxWidth == 0) {
1504 maxWidth = CGFLOAT_MAX;
1507 @"Warning: The outermost widget in the autoresizable Flutter view is unsized or has "
1508 @"ambiguous dimensions, causing the host native view's width to be 0. The autoresizing "
1509 @"logic is setting the viewport constraint to unbounded DBL_MAX to prevent "
1510 @"rendering failure. Please ensure your top-level Flutter widget has explicit "
1511 @"constraints (e.g., using SizedBox or Container)."];
1513 if (maxHeight == 0) {
1514 maxHeight = CGFLOAT_MAX;
1517 @"Warning: The outermost widget in the autoresizable Flutter view is unsized or has "
1518 @"ambiguous dimensions, causing the host native view's width to be 0. The autoresizing "
1519 @"logic is setting the viewport constraint to unbounded DBL_MAX to prevent "
1520 @"rendering failure. Please ensure your top-level Flutter widget has explicit "
1521 @"constraints (e.g., using SizedBox or Container)."];
1523 _viewportMetrics.physical_min_width_constraint = minWidth * _viewportMetrics.device_pixel_ratio;
1524 _viewportMetrics.physical_max_width_constraint = maxWidth * _viewportMetrics.device_pixel_ratio;
1525 _viewportMetrics.physical_min_height_constraint = minHeight * _viewportMetrics.device_pixel_ratio;
1526 _viewportMetrics.physical_max_height_constraint = maxHeight * _viewportMetrics.device_pixel_ratio;
1529 - (void)viewSafeAreaInsetsDidChange {
1530 [
self setViewportMetricsPaddings];
1531 [
self updateViewportMetricsIfNeeded];
1532 [
super viewSafeAreaInsetsDidChange];
1536 - (void)setViewportMetricsSize {
1537 UIScreen* screen =
self.flutterScreenIfViewLoaded;
1542 CGFloat scale = screen.scale;
1543 _viewportMetrics.physical_width =
self.view.bounds.size.width * scale;
1544 _viewportMetrics.physical_height =
self.view.bounds.size.height * scale;
1546 _viewportMetrics.physical_min_width_constraint = _viewportMetrics.physical_width;
1547 _viewportMetrics.physical_max_width_constraint = _viewportMetrics.physical_width;
1548 _viewportMetrics.physical_min_height_constraint = _viewportMetrics.physical_height;
1549 _viewportMetrics.physical_max_height_constraint = _viewportMetrics.physical_height;
1555 - (void)setViewportMetricsPaddings {
1556 UIScreen* screen =
self.flutterScreenIfViewLoaded;
1561 CGFloat scale = screen.scale;
1562 _viewportMetrics.physical_padding_top =
self.view.safeAreaInsets.top * scale;
1563 _viewportMetrics.physical_padding_left =
self.view.safeAreaInsets.left * scale;
1564 _viewportMetrics.physical_padding_right =
self.view.safeAreaInsets.right * scale;
1565 _viewportMetrics.physical_padding_bottom =
self.view.safeAreaInsets.bottom * scale;
1568 #pragma mark - Keyboard events
1570 - (void)keyboardWillShowNotification:(NSNotification*)notification {
1575 [
self handleKeyboardNotification:notification];
1578 - (void)keyboardWillChangeFrame:(NSNotification*)notification {
1583 [
self handleKeyboardNotification:notification];
1586 - (void)keyboardWillBeHidden:(NSNotification*)notification {
1590 [
self handleKeyboardNotification:notification];
1593 - (void)handleKeyboardNotification:(NSNotification*)notification {
1596 if ([
self shouldIgnoreKeyboardNotification:notification]) {
1600 NSDictionary* info = notification.userInfo;
1601 CGRect beginKeyboardFrame = [info[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
1602 CGRect keyboardFrame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];
1603 FlutterKeyboardMode keyboardMode = [
self calculateKeyboardAttachMode:notification];
1604 CGFloat calculatedInset = [
self calculateKeyboardInset:keyboardFrame keyboardMode:keyboardMode];
1605 NSTimeInterval duration = [info[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
1612 if (keyboardMode == FlutterKeyboardModeHidden && calculatedInset == 0.0 && duration == 0.0) {
1613 [
self hideKeyboardImmediately];
1618 if (
self.targetViewInsetBottom == calculatedInset) {
1622 self.targetViewInsetBottom = calculatedInset;
1629 BOOL keyboardWillShow = beginKeyboardFrame.origin.y > keyboardFrame.origin.y;
1630 BOOL keyboardAnimationIsCompounding =
1631 self.keyboardAnimationIsShowing == keyboardWillShow && _keyboardAnimationVSyncClient != nil;
1634 self.keyboardAnimationIsShowing = keyboardWillShow;
1636 if (!keyboardAnimationIsCompounding) {
1637 [
self startKeyBoardAnimation:duration];
1638 }
else if (
self.keyboardSpringAnimation) {
1639 self.keyboardSpringAnimation.toValue =
self.targetViewInsetBottom;
1643 - (BOOL)shouldIgnoreKeyboardNotification:(NSNotification*)notification {
1648 if (notification.name == UIKeyboardWillHideNotification) {
1657 NSDictionary* info = notification.userInfo;
1658 CGRect keyboardFrame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];
1659 if (notification.name == UIKeyboardWillChangeFrameNotification &&
1660 CGRectEqualToRect(keyboardFrame, CGRectZero)) {
1666 if (CGRectIsEmpty(keyboardFrame)) {
1671 if ([
self isKeyboardNotificationForDifferentView:notification]) {
1677 - (BOOL)isKeyboardNotificationForDifferentView:(NSNotification*)notification {
1678 NSDictionary* info = notification.userInfo;
1682 id isLocal = info[UIKeyboardIsLocalUserInfoKey];
1683 if (isLocal && ![isLocal boolValue]) {
1686 return self.engine.viewController !=
self;
1689 - (FlutterKeyboardMode)calculateKeyboardAttachMode:(NSNotification*)notification {
1697 NSDictionary* info = notification.userInfo;
1698 CGRect keyboardFrame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];
1700 if (notification.name == UIKeyboardWillHideNotification) {
1701 return FlutterKeyboardModeHidden;
1706 if (CGRectEqualToRect(keyboardFrame, CGRectZero)) {
1707 return FlutterKeyboardModeFloating;
1710 if (CGRectIsEmpty(keyboardFrame)) {
1711 return FlutterKeyboardModeHidden;
1714 CGRect screenRect =
self.flutterScreenIfViewLoaded.bounds;
1715 CGRect adjustedKeyboardFrame = keyboardFrame;
1716 adjustedKeyboardFrame.origin.y += [
self calculateMultitaskingAdjustment:screenRect
1717 keyboardFrame:keyboardFrame];
1722 CGRect intersection = CGRectIntersection(adjustedKeyboardFrame, screenRect);
1723 CGFloat intersectionHeight = CGRectGetHeight(intersection);
1724 CGFloat intersectionWidth = CGRectGetWidth(intersection);
1725 if (round(intersectionHeight) > 0 && intersectionWidth > 0) {
1727 CGFloat screenHeight = CGRectGetHeight(screenRect);
1728 CGFloat adjustedKeyboardBottom = CGRectGetMaxY(adjustedKeyboardFrame);
1729 if (round(adjustedKeyboardBottom) < screenHeight) {
1730 return FlutterKeyboardModeFloating;
1732 return FlutterKeyboardModeDocked;
1734 return FlutterKeyboardModeHidden;
1737 - (CGFloat)calculateMultitaskingAdjustment:(CGRect)screenRect keyboardFrame:(CGRect)keyboardFrame {
1741 if (
self.viewIfLoaded.traitCollection.userInterfaceIdiom == UIUserInterfaceIdiomPad &&
1742 self.viewIfLoaded.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact &&
1743 self.viewIfLoaded.traitCollection.verticalSizeClass == UIUserInterfaceSizeClassRegular) {
1744 CGFloat screenHeight = CGRectGetHeight(screenRect);
1745 CGFloat keyboardBottom = CGRectGetMaxY(keyboardFrame);
1749 if (screenHeight == keyboardBottom) {
1752 CGRect viewRectRelativeToScreen =
1753 [
self.viewIfLoaded convertRect:self.viewIfLoaded.frame
1754 toCoordinateSpace:self.flutterScreenIfViewLoaded.coordinateSpace];
1755 CGFloat viewBottom = CGRectGetMaxY(viewRectRelativeToScreen);
1756 CGFloat offset = screenHeight - viewBottom;
1764 - (CGFloat)calculateKeyboardInset:(CGRect)keyboardFrame keyboardMode:(NSInteger)keyboardMode {
1766 if (keyboardMode == FlutterKeyboardModeDocked) {
1768 CGRect viewRectRelativeToScreen =
1769 [
self.viewIfLoaded convertRect:self.viewIfLoaded.frame
1770 toCoordinateSpace:self.flutterScreenIfViewLoaded.coordinateSpace];
1771 CGRect intersection = CGRectIntersection(keyboardFrame, viewRectRelativeToScreen);
1772 CGFloat portionOfKeyboardInView = CGRectGetHeight(intersection);
1777 CGFloat scale =
self.flutterScreenIfViewLoaded.scale;
1778 return portionOfKeyboardInView * scale;
1783 - (void)startKeyBoardAnimation:(NSTimeInterval)duration {
1785 if (_viewportMetrics.physical_view_inset_bottom ==
self.targetViewInsetBottom) {
1791 if (!
self.keyboardAnimationView) {
1792 UIView* keyboardAnimationView = [[UIView alloc] init];
1793 keyboardAnimationView.hidden = YES;
1794 self.keyboardAnimationView = keyboardAnimationView;
1797 if (!
self.keyboardAnimationView.superview) {
1798 [
self.view addSubview:self.keyboardAnimationView];
1802 [
self.keyboardAnimationView.layer removeAllAnimations];
1805 self.keyboardAnimationView.frame =
1806 CGRectMake(0, _viewportMetrics.physical_view_inset_bottom, 0, 0);
1807 self.keyboardAnimationStartTime = fml::TimePoint().Now();
1808 self.originalViewInsetBottom = _viewportMetrics.physical_view_inset_bottom;
1811 [
self invalidateKeyboardAnimationVSyncClient];
1814 [
self setUpKeyboardAnimationVsyncClient:^(fml::TimePoint targetTime) {
1815 [weakSelf handleKeyboardAnimationCallbackWithTargetTime:targetTime];
1817 VSyncClient* currentVsyncClient = _keyboardAnimationVSyncClient;
1819 [UIView animateWithDuration:duration
1827 strongSelf.keyboardAnimationView.frame = CGRectMake(0, self.targetViewInsetBottom, 0, 0);
1830 CAAnimation* keyboardAnimation =
1831 [strongSelf.keyboardAnimationView.layer animationForKey:@"position"];
1832 [strongSelf setUpKeyboardSpringAnimationIfNeeded:keyboardAnimation];
1834 completion:^(BOOL finished) {
1835 if (_keyboardAnimationVSyncClient == currentVsyncClient) {
1844 [strongSelf invalidateKeyboardAnimationVSyncClient];
1845 [strongSelf removeKeyboardAnimationView];
1846 [strongSelf ensureViewportMetricsIsCorrect];
1851 - (void)hideKeyboardImmediately {
1852 [
self invalidateKeyboardAnimationVSyncClient];
1853 if (
self.keyboardAnimationView) {
1854 [
self.keyboardAnimationView.layer removeAllAnimations];
1855 [
self removeKeyboardAnimationView];
1856 self.keyboardAnimationView = nil;
1858 if (
self.keyboardSpringAnimation) {
1859 self.keyboardSpringAnimation = nil;
1862 self.targetViewInsetBottom = 0.0;
1863 [
self ensureViewportMetricsIsCorrect];
1866 - (void)setUpKeyboardSpringAnimationIfNeeded:(CAAnimation*)keyboardAnimation {
1868 if (keyboardAnimation == nil || ![keyboardAnimation isKindOfClass:[CASpringAnimation
class]]) {
1869 _keyboardSpringAnimation = nil;
1874 CASpringAnimation* keyboardCASpringAnimation = (CASpringAnimation*)keyboardAnimation;
1875 _keyboardSpringAnimation =
1876 [[SpringAnimation alloc] initWithStiffness:keyboardCASpringAnimation.stiffness
1877 damping:keyboardCASpringAnimation.damping
1878 mass:keyboardCASpringAnimation.mass
1879 initialVelocity:keyboardCASpringAnimation.initialVelocity
1880 fromValue:self.originalViewInsetBottom
1881 toValue:self.targetViewInsetBottom];
1884 - (void)handleKeyboardAnimationCallbackWithTargetTime:(
fml::TimePoint)targetTime {
1886 if (!
self.isViewLoaded) {
1891 if (!
self.keyboardAnimationView) {
1896 if (!
self.keyboardAnimationVSyncClient) {
1900 if (!
self.keyboardAnimationView.superview) {
1902 [
self.view addSubview:self.keyboardAnimationView];
1905 if (!
self.keyboardSpringAnimation) {
1906 if (
self.keyboardAnimationView.layer.presentationLayer) {
1907 self->_viewportMetrics.physical_view_inset_bottom =
1908 self.keyboardAnimationView.layer.presentationLayer.frame.origin.y;
1909 [
self updateViewportMetricsIfNeeded];
1912 fml::TimeDelta timeElapsed = targetTime -
self.keyboardAnimationStartTime;
1913 self->_viewportMetrics.physical_view_inset_bottom =
1914 [
self.keyboardSpringAnimation curveFunction:timeElapsed.ToSecondsF()];
1915 [
self updateViewportMetricsIfNeeded];
1919 - (void)setUpKeyboardAnimationVsyncClient:
1921 if (!keyboardAnimationCallback) {
1924 NSAssert(_keyboardAnimationVSyncClient == nil,
1925 @"_keyboardAnimationVSyncClient must be nil when setting up.");
1929 auto uiCallback = [animationCallback](std::unique_ptr<flutter::FrameTimingsRecorder> recorder) {
1930 fml::TimeDelta frameInterval = recorder->GetVsyncTargetTime() - recorder->GetVsyncStartTime();
1931 fml::TimePoint targetTime = recorder->GetVsyncTargetTime() + frameInterval;
1932 dispatch_async(dispatch_get_main_queue(), ^(
void) {
1933 animationCallback(targetTime);
1937 _keyboardAnimationVSyncClient = [[
VSyncClient alloc] initWithTaskRunner:self.engine.uiTaskRunner
1938 callback:uiCallback];
1939 _keyboardAnimationVSyncClient.allowPauseAfterVsync = NO;
1940 [_keyboardAnimationVSyncClient await];
1943 - (void)invalidateKeyboardAnimationVSyncClient {
1944 [_keyboardAnimationVSyncClient invalidate];
1945 _keyboardAnimationVSyncClient = nil;
1948 - (void)removeKeyboardAnimationView {
1949 if (
self.keyboardAnimationView.superview != nil) {
1950 [
self.keyboardAnimationView removeFromSuperview];
1954 - (void)ensureViewportMetricsIsCorrect {
1955 if (_viewportMetrics.physical_view_inset_bottom !=
self.targetViewInsetBottom) {
1957 _viewportMetrics.physical_view_inset_bottom =
self.targetViewInsetBottom;
1958 [
self updateViewportMetricsIfNeeded];
1962 - (void)handlePressEvent:(FlutterUIPressProxy*)press
1963 nextAction:(
void (^)())next API_AVAILABLE(ios(13.4)) {
1964 if (@available(iOS 13.4, *)) {
1969 [
self.keyboardManager handlePress:press nextAction:next];
1985 - (void)superPressesBegan:(NSSet<UIPress*>*)presses withEvent:(UIPressesEvent*)event {
1986 [
super pressesBegan:presses withEvent:event];
1989 - (void)superPressesChanged:(NSSet<UIPress*>*)presses withEvent:(UIPressesEvent*)event {
1990 [
super pressesChanged:presses withEvent:event];
1993 - (void)superPressesEnded:(NSSet<UIPress*>*)presses withEvent:(UIPressesEvent*)event {
1994 [
super pressesEnded:presses withEvent:event];
1997 - (void)superPressesCancelled:(NSSet<UIPress*>*)presses withEvent:(UIPressesEvent*)event {
1998 [
super pressesCancelled:presses withEvent:event];
2006 - (void)pressesBegan:(NSSet<UIPress*>*)presses
2007 withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
2008 if (@available(iOS 13.4, *)) {
2010 for (UIPress* press in presses) {
2011 [
self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press event:event]
2013 [weakSelf superPressesBegan:[NSSet setWithObject:press] withEvent:event];
2017 [
super pressesBegan:presses withEvent:event];
2021 - (void)pressesChanged:(NSSet<UIPress*>*)presses
2022 withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
2023 if (@available(iOS 13.4, *)) {
2025 for (UIPress* press in presses) {
2026 [
self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press event:event]
2028 [weakSelf superPressesChanged:[NSSet setWithObject:press] withEvent:event];
2032 [
super pressesChanged:presses withEvent:event];
2036 - (void)pressesEnded:(NSSet<UIPress*>*)presses
2037 withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
2038 if (@available(iOS 13.4, *)) {
2040 for (UIPress* press in presses) {
2041 [
self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press event:event]
2043 [weakSelf superPressesEnded:[NSSet setWithObject:press] withEvent:event];
2047 [
super pressesEnded:presses withEvent:event];
2051 - (void)pressesCancelled:(NSSet<UIPress*>*)presses
2052 withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
2053 if (@available(iOS 13.4, *)) {
2055 for (UIPress* press in presses) {
2056 [
self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press event:event]
2058 [weakSelf superPressesCancelled:[NSSet setWithObject:press] withEvent:event];
2062 [
super pressesCancelled:presses withEvent:event];
2066 #pragma mark - Orientation updates
2068 - (void)onOrientationPreferencesUpdated:(NSNotification*)notification {
2071 dispatch_async(dispatch_get_main_queue(), ^{
2072 NSDictionary* info = notification.userInfo;
2073 NSNumber* update = info[@(flutter::kOrientationUpdateNotificationKey)];
2074 if (update == nil) {
2077 [weakSelf performOrientationUpdate:update.unsignedIntegerValue];
2081 - (void)requestGeometryUpdateForWindowScenes:(NSSet<UIScene*>*)windowScenes
2082 API_AVAILABLE(ios(16.0)) {
2083 for (UIScene* windowScene in windowScenes) {
2084 FML_DCHECK([windowScene isKindOfClass:[UIWindowScene
class]]);
2085 UIWindowSceneGeometryPreferencesIOS* preference = [[UIWindowSceneGeometryPreferencesIOS alloc]
2086 initWithInterfaceOrientations:self.orientationPreferences];
2087 [(UIWindowScene*)windowScene
2088 requestGeometryUpdateWithPreferences:preference
2089 errorHandler:^(NSError* error) {
2090 os_log_error(OS_LOG_DEFAULT,
2091 "Failed to change device orientation: %@", error);
2093 [
self setNeedsUpdateOfSupportedInterfaceOrientations];
2097 - (void)performOrientationUpdate:(UIInterfaceOrientationMask)new_preferences {
2098 if (new_preferences !=
self.orientationPreferences) {
2099 self.orientationPreferences = new_preferences;
2101 if (@available(iOS 16.0, *)) {
2103 NSSet<UIScene*>* scenes = [NSSet set];
2104 if (flutterApplication) {
2105 scenes = [flutterApplication.connectedScenes
2106 filteredSetUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(
2107 id scene, NSDictionary* bindings) {
2108 return [scene isKindOfClass:[UIWindowScene class]];
2110 }
else if (
self.flutterWindowSceneIfViewLoaded) {
2111 scenes = [NSSet setWithObject:self.flutterWindowSceneIfViewLoaded];
2113 [
self requestGeometryUpdateForWindowScenes:scenes];
2115 UIInterfaceOrientationMask currentInterfaceOrientation = 0;
2116 UIWindowScene* windowScene =
self.flutterWindowSceneIfViewLoaded;
2120 @"Accessing the interface orientation when the window scene is unavailable."];
2123 currentInterfaceOrientation = 1 << windowScene.interfaceOrientation;
2124 if (!(
self.orientationPreferences & currentInterfaceOrientation)) {
2125 [UIViewController attemptRotationToDeviceOrientation];
2127 if (
self.orientationPreferences & UIInterfaceOrientationMaskPortrait) {
2131 [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationPortrait)
2132 forKey:@"orientation"];
2133 }
else if (
self.orientationPreferences & UIInterfaceOrientationMaskPortraitUpsideDown) {
2134 [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationPortraitUpsideDown)
2135 forKey:@"orientation"];
2136 }
else if (
self.orientationPreferences & UIInterfaceOrientationMaskLandscapeLeft) {
2137 [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeLeft)
2138 forKey:@"orientation"];
2139 }
else if (
self.orientationPreferences & UIInterfaceOrientationMaskLandscapeRight) {
2140 [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeRight)
2141 forKey:@"orientation"];
2148 - (void)onHideHomeIndicatorNotification:(NSNotification*)notification {
2149 self.isHomeIndicatorHidden = YES;
2152 - (void)onShowHomeIndicatorNotification:(NSNotification*)notification {
2153 self.isHomeIndicatorHidden = NO;
2156 - (void)setIsHomeIndicatorHidden:(BOOL)hideHomeIndicator {
2157 if (hideHomeIndicator != _isHomeIndicatorHidden) {
2158 _isHomeIndicatorHidden = hideHomeIndicator;
2159 [
self setNeedsUpdateOfHomeIndicatorAutoHidden];
2163 - (BOOL)prefersHomeIndicatorAutoHidden {
2164 return self.isHomeIndicatorHidden;
2167 - (BOOL)shouldAutorotate {
2171 - (NSUInteger)supportedInterfaceOrientations {
2172 return self.orientationPreferences;
2175 #pragma mark - Accessibility
2177 - (void)onAccessibilityStatusChanged:(NSNotification*)notification {
2182 int32_t flags = [
self.accessibilityFeatures flags];
2183 #if TARGET_OS_SIMULATOR
2189 _isVoiceOverRunning = [
self.accessibilityFeatures isVoiceOverRunning];
2190 enabled = _isVoiceOverRunning || [
self.accessibilityFeatures isSwitchControlRunning] ||
2191 [
self.accessibilityFeatures isSpeakScreenEnabled];
2193 [
self.engine enableSemantics:enabled withFlags:flags];
2196 - (BOOL)accessibilityPerformEscape {
2198 if (navigationChannel) {
2205 #pragma mark - Set user settings
2207 - (void)traitCollectionDidChange:(UITraitCollection*)previousTraitCollection {
2208 [
super traitCollectionDidChange:previousTraitCollection];
2209 [
self onUserSettingsChanged:nil];
2213 if (
self.isAutoResizable) {
2214 [
self.flutterView resetIntrinsicContentSize];
2218 - (void)onUserSettingsChanged:(NSNotification*)notification {
2219 [
self.engine.settingsChannel sendMessage:@{
2220 @"textScaleFactor" : @(
self.textScaleFactor),
2222 @"platformBrightness" :
self.brightnessMode,
2223 @"platformContrast" : self.contrastMode,
2224 @"nativeSpellCheckServiceDefined" : @YES,
2225 @"supportsShowingSystemContextMenu" : @(self.supportsShowingSystemContextMenu)
2229 - (CGFloat)textScaleFactor {
2231 if (flutterApplication == nil) {
2232 [FlutterLogger logWarning:@"Dynamic content size update is not supported in app extension."];
2236 UIContentSizeCategory category = flutterApplication.preferredContentSizeCategory;
2242 const CGFloat xs = 14;
2243 const CGFloat s = 15;
2244 const CGFloat m = 16;
2245 const CGFloat l = 17;
2246 const CGFloat xl = 19;
2247 const CGFloat xxl = 21;
2248 const CGFloat xxxl = 23;
2251 const CGFloat ax1 = 28;
2252 const CGFloat ax2 = 33;
2253 const CGFloat ax3 = 40;
2254 const CGFloat ax4 = 47;
2255 const CGFloat ax5 = 53;
2259 if ([category isEqualToString:UIContentSizeCategoryExtraSmall]) {
2261 }
else if ([category isEqualToString:UIContentSizeCategorySmall]) {
2263 }
else if ([category isEqualToString:UIContentSizeCategoryMedium]) {
2265 }
else if ([category isEqualToString:UIContentSizeCategoryLarge]) {
2267 }
else if ([category isEqualToString:UIContentSizeCategoryExtraLarge]) {
2269 }
else if ([category isEqualToString:UIContentSizeCategoryExtraExtraLarge]) {
2271 }
else if ([category isEqualToString:UIContentSizeCategoryExtraExtraExtraLarge]) {
2273 }
else if ([category isEqualToString:UIContentSizeCategoryAccessibilityMedium]) {
2275 }
else if ([category isEqualToString:UIContentSizeCategoryAccessibilityLarge]) {
2277 }
else if ([category isEqualToString:UIContentSizeCategoryAccessibilityExtraLarge]) {
2279 }
else if ([category isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraLarge]) {
2281 }
else if ([category isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraExtraLarge]) {
2288 - (BOOL)supportsShowingSystemContextMenu {
2289 if (@available(iOS 16.0, *)) {
2299 - (NSString*)brightnessMode {
2300 UIUserInterfaceStyle style =
self.traitCollection.userInterfaceStyle;
2302 if (style == UIUserInterfaceStyleDark) {
2312 - (NSString*)contrastMode {
2313 UIAccessibilityContrast contrast =
self.traitCollection.accessibilityContrast;
2315 if (contrast == UIAccessibilityContrastHigh) {
2322 #pragma mark - Status bar style
2324 - (UIStatusBarStyle)preferredStatusBarStyle {
2325 return self.statusBarStyle;
2328 - (void)onPreferredStatusBarStyleUpdated:(NSNotification*)notification {
2331 dispatch_async(dispatch_get_main_queue(), ^{
2337 NSDictionary* info = notification.userInfo;
2338 NSNumber* update = info[@(flutter::kOverlayStyleUpdateNotificationKey)];
2339 if (update == nil) {
2343 UIStatusBarStyle style =
static_cast<UIStatusBarStyle
>(update.integerValue);
2344 if (style != strongSelf.statusBarStyle) {
2345 strongSelf.statusBarStyle = style;
2346 [strongSelf setNeedsStatusBarAppearanceUpdate];
2351 - (void)setPrefersStatusBarHidden:(BOOL)hidden {
2352 if (hidden !=
self.flutterPrefersStatusBarHidden) {
2353 self.flutterPrefersStatusBarHidden = hidden;
2354 [
self setNeedsStatusBarAppearanceUpdate];
2358 - (BOOL)prefersStatusBarHidden {
2359 return self.flutterPrefersStatusBarHidden;
2362 #pragma mark - Platform views
2365 return self.engine.platformViewsController;
2369 return self.engine.binaryMessenger;
2372 #pragma mark - FlutterBinaryMessenger
2374 - (void)sendOnChannel:(NSString*)channel message:(NSData*)message {
2375 [
self.engine.binaryMessenger sendOnChannel:channel message:message];
2378 - (void)sendOnChannel:(NSString*)channel
2379 message:(NSData*)message
2381 NSAssert(channel,
@"The channel must not be null");
2382 [
self.engine.binaryMessenger sendOnChannel:channel message:message binaryReply:callback];
2386 return [
self.engine.binaryMessenger makeBackgroundTaskQueue];
2390 binaryMessageHandler:
2392 return [
self setMessageHandlerOnChannel:channel binaryMessageHandler:handler taskQueue:nil];
2396 setMessageHandlerOnChannel:(NSString*)channel
2399 NSAssert(channel,
@"The channel must not be null");
2400 return [
self.engine.binaryMessenger setMessageHandlerOnChannel:channel
2401 binaryMessageHandler:handler
2402 taskQueue:taskQueue];
2406 [
self.engine.binaryMessenger cleanUpConnection:connection];
2409 #pragma mark - FlutterTextureRegistry
2412 return [
self.engine.textureRegistry registerTexture:texture];
2415 - (void)unregisterTexture:(int64_t)textureId {
2416 [
self.engine.textureRegistry unregisterTexture:textureId];
2419 - (void)textureFrameAvailable:(int64_t)textureId {
2420 [
self.engine.textureRegistry textureFrameAvailable:textureId];
2423 - (NSString*)lookupKeyForAsset:(NSString*)asset {
2427 - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
2431 - (id<FlutterPluginRegistry>)pluginRegistry {
2435 + (BOOL)isUIAccessibilityIsVoiceOverRunning {
2436 return UIAccessibilityIsVoiceOverRunning();
2439 #pragma mark - FlutterPluginRegistry
2442 return [
self.engine registrarForPlugin:pluginKey];
2445 - (BOOL)hasPlugin:(NSString*)pluginKey {
2446 return [
self.engine hasPlugin:pluginKey];
2449 - (NSObject*)valuePublishedByPlugin:(NSString*)pluginKey {
2450 return [
self.engine valuePublishedByPlugin:pluginKey];
2453 - (void)presentViewController:(UIViewController*)viewControllerToPresent
2455 completion:(
void (^)(
void))completion {
2456 self.isPresentingViewControllerAnimating = YES;
2458 [
super presentViewController:viewControllerToPresent
2461 weakSelf.isPresentingViewControllerAnimating = NO;
2468 - (BOOL)isPresentingViewController {
2469 return self.presentedViewController != nil ||
self.isPresentingViewControllerAnimating;
2472 - (
flutter::PointerData)updateMousePointerDataFrom:(UIGestureRecognizer*)gestureRecognizer
2473 API_AVAILABLE(ios(13.4)) {
2474 CGPoint location = [gestureRecognizer locationInView:self.view];
2475 CGFloat scale =
self.flutterScreenIfViewLoaded.scale;
2477 flutter::PointerData pointer_data;
2478 pointer_data.Clear();
2482 return pointer_data;
2485 - (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer
2486 shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer*)otherGestureRecognizer
2487 API_AVAILABLE(ios(13.4)) {
2491 - (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer
2492 shouldReceiveEvent:(UIEvent*)event API_AVAILABLE(ios(13.4)) {
2493 if (gestureRecognizer == _continuousScrollingPanGestureRecognizer &&
2494 event.type == UIEventTypeScroll) {
2496 flutter::PointerData pointer_data = [
self updateMousePointerDataFrom:gestureRecognizer];
2497 pointer_data.device =
reinterpret_cast<int64_t
>(_continuousScrollingPanGestureRecognizer);
2498 pointer_data.kind = flutter::PointerData::DeviceKind::kTrackpad;
2499 pointer_data.signal_kind = flutter::PointerData::SignalKind::kScrollInertiaCancel;
2500 pointer_data.view_id =
self.viewIdentifier;
2502 if (event.timestamp <
self.scrollInertiaEventAppKitDeadline) {
2505 auto packet = std::make_unique<flutter::PointerDataPacket>(1);
2506 packet->SetPointerData(0, pointer_data);
2507 [
self.engine dispatchPointerDataPacket:std::move(packet)];
2508 self.scrollInertiaEventAppKitDeadline = 0;
2515 - (void)hoverEvent:(UIHoverGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) {
2518 flutter::PointerData pointer_data = [
self updateMousePointerDataFrom:recognizer];
2519 pointer_data.device =
reinterpret_cast<int64_t
>(recognizer);
2520 pointer_data.kind = flutter::PointerData::DeviceKind::kMouse;
2521 pointer_data.view_id =
self.viewIdentifier;
2523 switch (_hoverGestureRecognizer.state) {
2524 case UIGestureRecognizerStateBegan:
2525 pointer_data.change = flutter::PointerData::Change::kAdd;
2527 case UIGestureRecognizerStateChanged:
2528 pointer_data.change = flutter::PointerData::Change::kHover;
2530 case UIGestureRecognizerStateEnded:
2531 case UIGestureRecognizerStateCancelled:
2532 pointer_data.change = flutter::PointerData::Change::kRemove;
2537 pointer_data.change = flutter::PointerData::Change::kHover;
2541 NSTimeInterval time = [NSProcessInfo processInfo].systemUptime;
2542 BOOL isRunningOnMac = NO;
2543 if (@available(iOS 14.0, *)) {
2547 isRunningOnMac = [NSProcessInfo processInfo].iOSAppOnMac;
2550 time >
self.scrollInertiaEventStartline) {
2554 auto packet = std::make_unique<flutter::PointerDataPacket>(2);
2555 packet->SetPointerData(0, pointer_data);
2556 flutter::PointerData inertia_cancel = pointer_data;
2557 inertia_cancel.device =
reinterpret_cast<int64_t
>(_continuousScrollingPanGestureRecognizer);
2558 inertia_cancel.kind = flutter::PointerData::DeviceKind::kTrackpad;
2559 inertia_cancel.signal_kind = flutter::PointerData::SignalKind::kScrollInertiaCancel;
2560 inertia_cancel.view_id =
self.viewIdentifier;
2561 packet->SetPointerData(1, inertia_cancel);
2562 [
self.engine dispatchPointerDataPacket:std::move(packet)];
2563 self.scrollInertiaEventStartline = DBL_MAX;
2565 auto packet = std::make_unique<flutter::PointerDataPacket>(1);
2566 packet->SetPointerData(0, pointer_data);
2567 [
self.engine dispatchPointerDataPacket:std::move(packet)];
2571 - (void)discreteScrollEvent:(UIPanGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) {
2572 CGPoint translation = [recognizer translationInView:self.view];
2573 const CGFloat scale =
self.flutterScreenIfViewLoaded.scale;
2575 translation.x *= scale;
2576 translation.y *= scale;
2578 flutter::PointerData pointer_data = [
self updateMousePointerDataFrom:recognizer];
2579 pointer_data.device =
reinterpret_cast<int64_t
>(recognizer);
2580 pointer_data.kind = flutter::PointerData::DeviceKind::kMouse;
2581 pointer_data.signal_kind = flutter::PointerData::SignalKind::kScroll;
2582 pointer_data.scroll_delta_x = (translation.x -
_mouseState.last_translation.x);
2583 pointer_data.scroll_delta_y = -(translation.y -
_mouseState.last_translation.y);
2584 pointer_data.view_id =
self.viewIdentifier;
2590 if (recognizer.state != UIGestureRecognizerStateEnded) {
2596 auto packet = std::make_unique<flutter::PointerDataPacket>(1);
2597 packet->SetPointerData(0, pointer_data);
2598 [
self.engine dispatchPointerDataPacket:std::move(packet)];
2601 - (void)continuousScrollEvent:(UIPanGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) {
2602 CGPoint translation = [recognizer translationInView:self.view];
2603 const CGFloat scale =
self.flutterScreenIfViewLoaded.scale;
2605 flutter::PointerData pointer_data = [
self updateMousePointerDataFrom:recognizer];
2606 pointer_data.device =
reinterpret_cast<int64_t
>(recognizer);
2607 pointer_data.kind = flutter::PointerData::DeviceKind::kTrackpad;
2608 pointer_data.view_id =
self.viewIdentifier;
2609 switch (recognizer.state) {
2610 case UIGestureRecognizerStateBegan:
2611 pointer_data.change = flutter::PointerData::Change::kPanZoomStart;
2613 case UIGestureRecognizerStateChanged:
2614 pointer_data.change = flutter::PointerData::Change::kPanZoomUpdate;
2615 pointer_data.pan_x = translation.x * scale;
2616 pointer_data.pan_y = translation.y * scale;
2617 pointer_data.pan_delta_x = 0;
2618 pointer_data.pan_delta_y = 0;
2619 pointer_data.scale = 1;
2621 case UIGestureRecognizerStateEnded:
2622 case UIGestureRecognizerStateCancelled:
2623 self.scrollInertiaEventStartline =
2624 [[NSProcessInfo processInfo] systemUptime] +
2634 self.scrollInertiaEventAppKitDeadline =
2635 [[NSProcessInfo processInfo] systemUptime] +
2636 (0.1821 * log(fmax([recognizer velocityInView:self.view].x,
2637 [recognizer velocityInView:self.view].y))) -
2639 pointer_data.change = flutter::PointerData::Change::kPanZoomEnd;
2643 NSAssert(NO,
@"Trackpad pan event occured with unexpected phase 0x%lx",
2644 (
long)recognizer.state);
2648 auto packet = std::make_unique<flutter::PointerDataPacket>(1);
2649 packet->SetPointerData(0, pointer_data);
2650 [
self.engine dispatchPointerDataPacket:std::move(packet)];
2653 - (void)pinchEvent:(UIPinchGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) {
2654 flutter::PointerData pointer_data = [
self updateMousePointerDataFrom:recognizer];
2655 pointer_data.device =
reinterpret_cast<int64_t
>(recognizer);
2656 pointer_data.kind = flutter::PointerData::DeviceKind::kTrackpad;
2657 pointer_data.view_id =
self.viewIdentifier;
2658 switch (recognizer.state) {
2659 case UIGestureRecognizerStateBegan:
2660 pointer_data.change = flutter::PointerData::Change::kPanZoomStart;
2662 case UIGestureRecognizerStateChanged:
2663 pointer_data.change = flutter::PointerData::Change::kPanZoomUpdate;
2664 pointer_data.scale = recognizer.scale;
2665 pointer_data.rotation = _rotationGestureRecognizer.rotation;
2667 case UIGestureRecognizerStateEnded:
2668 case UIGestureRecognizerStateCancelled:
2669 pointer_data.change = flutter::PointerData::Change::kPanZoomEnd;
2673 NSAssert(NO,
@"Trackpad pinch event occured with unexpected phase 0x%lx",
2674 (
long)recognizer.state);
2678 auto packet = std::make_unique<flutter::PointerDataPacket>(1);
2679 packet->SetPointerData(0, pointer_data);
2680 [
self.engine dispatchPointerDataPacket:std::move(packet)];
2683 #pragma mark - State Restoration
2685 - (void)encodeRestorableStateWithCoder:(NSCoder*)coder {
2686 NSData* restorationData = [
self.engine.restorationPlugin restorationData];
2687 [coder encodeBytes:(const unsigned char*)restorationData.bytes
2688 length:restorationData.length
2689 forKey:kFlutterRestorationStateAppData];
2690 [
super encodeRestorableStateWithCoder:coder];
2693 - (void)decodeRestorableStateWithCoder:(NSCoder*)coder {
2694 NSUInteger restorationDataLength;
2695 const unsigned char* restorationBytes = [coder decodeBytesForKey:kFlutterRestorationStateAppData
2696 returnedLength:&restorationDataLength];
2697 NSData* restorationData = [NSData dataWithBytes:restorationBytes length:restorationDataLength];
2698 [
self.engine.restorationPlugin setRestorationData:restorationData];
2702 return self.engine.restorationPlugin;
2706 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