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";
69 FlutterKeyboardInsetManagerDelegate>
73 @property(nonatomic, readonly) int64_t viewIdentifier;
78 @property(nonatomic, strong)
void (^flutterViewRenderedCallback)(void);
80 @property(nonatomic, strong) FlutterSplashScreenManager* splashScreenManager;
82 @property(nonatomic, assign) UIInterfaceOrientationMask orientationPreferences;
83 @property(nonatomic, assign) UIStatusBarStyle statusBarStyle;
84 @property(nonatomic, assign) BOOL initialized;
85 @property(nonatomic, assign) BOOL engineNeedsLaunch;
86 @property(nonatomic, assign) BOOL awokenFromNib;
89 @property(nonatomic, assign) BOOL isHomeIndicatorHidden;
90 @property(nonatomic, assign) BOOL isPresentingViewControllerAnimating;
93 @property(nonatomic, assign) BOOL flutterPrefersStatusBarHidden;
95 @property(nonatomic, strong) NSMutableSet<NSNumber*>* ongoingTouches;
100 @property(nonatomic, strong) UIScrollView* scrollView;
105 @property(nonatomic, assign) BOOL shouldIgnoreViewportMetricsUpdatesDuringRotation;
111 @property(nonatomic, assign) NSTimeInterval scrollInertiaEventStartline;
119 @property(nonatomic, assign) NSTimeInterval scrollInertiaEventAppKitDeadline;
123 @property(nonatomic, assign) CGSize sizeBeforeAutoResized;
129 @property(nonatomic, strong)
132 @property(nonatomic, strong)
133 UIPanGestureRecognizer* discreteScrollingPanGestureRecognizer
API_AVAILABLE(ios(13.4));
135 @property(nonatomic, strong)
136 UIPanGestureRecognizer* continuousScrollingPanGestureRecognizer
API_AVAILABLE(ios(13.4));
138 @property(nonatomic, strong)
141 @property(nonatomic, strong)
142 UIRotationGestureRecognizer* rotationGestureRecognizer
API_AVAILABLE(ios(13.4));
145 - (void)addInternalPlugins;
146 - (void)deregisterNotifications;
149 - (void)onFirstFrameRendered;
156 flutter::ViewportMetrics _viewportMetrics;
162 @synthesize viewOpaque = _viewOpaque;
163 @synthesize displayingFlutterUI = _displayingFlutterUI;
165 - (FlutterSplashScreenManager*)splashScreenManager {
175 @dynamic viewIdentifier;
177 #pragma mark - Manage and override all designated initializers
180 nibName:(nullable NSString*)nibName
181 bundle:(nullable NSBundle*)nibBundle {
182 FML_CHECK(
engine) <<
"initWithEngine:nibName:bundle: must be called with non-nil engine";
183 self = [
super initWithNibName:nibName bundle:nibBundle];
186 if (
engine.viewController) {
187 NSString* errorMessage =
188 [NSString stringWithFormat:
189 @"The supplied FlutterEngine %@ is already used with FlutterViewController "
190 "instance %@. One instance of the FlutterEngine can only be attached to "
191 "one FlutterViewController at a time. Set FlutterEngine.viewController to "
192 "nil before attaching it to another FlutterViewController.",
193 engine.description, engine.viewController.description];
194 [FlutterLogger logError:errorMessage];
197 _engineNeedsLaunch = NO;
198 _flutterView = [[
FlutterView alloc] initWithDelegate:_engine
199 opaque:self.isViewOpaque
200 enableWideGamut:engine.project.isWideGamutEnabled];
201 _ongoingTouches = [[NSMutableSet alloc] init];
205 [
self performCommonViewControllerInitialization];
206 [engine setViewController:self];
213 nibName:(NSString*)nibName
214 bundle:(NSBundle*)nibBundle {
215 self = [
super initWithNibName:nibName bundle:nibBundle];
219 [
self sharedSetupWithProject:project initialRoute:nil];
226 initialRoute:(NSString*)initialRoute
227 nibName:(NSString*)nibName
228 bundle:(NSBundle*)nibBundle {
229 self = [
super initWithNibName:nibName bundle:nibBundle];
233 [
self sharedSetupWithProject:project initialRoute:initialRoute];
239 - (instancetype)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil {
240 return [
self initWithProject:nil nibName:nil bundle:nil];
244 self = [
super initWithCoder:aDecoder];
248 - (void)awakeFromNib {
249 [
super awakeFromNib];
250 self.awokenFromNib = YES;
252 [
self sharedSetupWithProject:nil initialRoute:nil];
256 - (instancetype)init {
257 return [
self initWithProject:nil nibName:nil bundle:nil];
261 initialRoute:(nullable NSString*)initialRoute {
264 if ([appDelegate respondsToSelector:
@selector(takeLaunchEngine)]) {
269 engine = [appDelegate takeLaunchEngine];
274 [appDelegate takeLaunchEngine];
286 allowHeadlessExecution:self.engineAllowHeadlessExecution
287 restorationEnabled:self.restorationIdentifier != nil];
295 _flutterView = [[
FlutterView alloc] initWithDelegate:_engine
297 enableWideGamut:engine.project.isWideGamutEnabled];
298 [_engine createShell:nil libraryURI:nil initialRoute:initialRoute];
304 BOOL performedCallback = [_engine performImplicitEngineCallback];
308 respondsToSelector:
@selector(pluginRegistrant)]) {
309 NSObject<FlutterPluginRegistrant>* pluginRegistrant =
311 [pluginRegistrant registerWithRegistry:self];
312 performedCallback = YES;
320 id applicationLifeCycleDelegate = ((
FlutterAppDelegate*)appDelegate).lifeCycleDelegate;
321 [applicationLifeCycleDelegate
322 sceneFallbackWillFinishLaunchingApplication:FlutterSharedApplication.application];
323 [applicationLifeCycleDelegate
324 sceneFallbackDidFinishLaunchingApplication:FlutterSharedApplication.application];
327 _engineNeedsLaunch = YES;
328 _ongoingTouches = [[NSMutableSet alloc] init];
332 [
self.splashScreenManager loadDefaultSplashScreenView];
333 [
self performCommonViewControllerInitialization];
336 - (BOOL)isViewOpaque {
340 - (void)setViewOpaque:(BOOL)value {
342 if (
self.flutterView.layer.opaque != value) {
343 self.flutterView.layer.opaque = value;
344 [
self.flutterView.layer setNeedsLayout];
348 #pragma mark - Common view controller initialization tasks
350 - (void)performCommonViewControllerInitialization {
356 _orientationPreferences = UIInterfaceOrientationMaskAll;
357 _statusBarStyle = UIStatusBarStyleDefault;
359 _accessibilityFeatures = [[FlutterAccessibilityFeatures alloc] init];
360 _displayLinkManager = FlutterDisplayLinkManager.shared;
361 _keyboardInsetManager =
362 [[FlutterKeyboardInsetManager alloc] initWithDelegate:self
363 displayLinkManager:_displayLinkManager];
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 {
576 if (
self.splashScreenView && (
self.isBeingPresented ||
self.isMovingToParentViewController)) {
578 [
self.splashScreenView removeFromSuperview];
579 self.splashScreenView = nil;
584 [
self.splashScreenManager installSplashScreenViewAsSubviewOf:self.view];
587 + (BOOL)automaticallyNotifiesObserversOfDisplayingFlutterUI {
591 - (void)setDisplayingFlutterUI:(BOOL)displayingFlutterUI {
592 if (_displayingFlutterUI != displayingFlutterUI) {
593 if (displayingFlutterUI == YES) {
594 if (!
self.viewIfLoaded.window) {
598 [
self willChangeValueForKey:@"displayingFlutterUI"];
599 _displayingFlutterUI = displayingFlutterUI;
600 [
self didChangeValueForKey:@"displayingFlutterUI"];
604 - (void)callViewRenderedCallback {
605 self.displayingFlutterUI = YES;
606 if (
self.flutterViewRenderedCallback) {
607 self.flutterViewRenderedCallback();
608 self.flutterViewRenderedCallback = nil;
612 - (void)onFirstFrameRendered {
613 if (
self.splashScreenView) {
615 [
self.splashScreenManager removeSplashScreenWithCompletion:^{
616 [weakSelf callViewRenderedCallback];
619 [
self callViewRenderedCallback];
623 - (void)installFirstFrameCallback {
628 [
self.engine installFirstFrameCallback:^{
629 [weakSelf onFirstFrameRendered];
633 #pragma mark - Properties
635 - (int64_t)viewIdentifier {
638 return flutter::kFlutterImplicitViewId;
641 - (BOOL)loadDefaultSplashScreenView {
642 return [
self.splashScreenManager loadDefaultSplashScreenView];
645 - (UIView*)splashScreenView {
649 - (void)setSplashScreenView:(UIView*)view {
650 self.splashScreenManager.splashScreenView = view;
653 - (void)setFlutterViewDidRenderCallback:(
void (^)(
void))callback {
654 _flutterViewRenderedCallback = callback;
657 - (UISceneActivationState)activationState {
658 return self.flutterWindowSceneIfViewLoaded.activationState;
661 - (BOOL)stateIsActive {
665 if (flutterApplication) {
666 return [
self isApplicationStateMatching:UIApplicationStateActive
667 withApplication:flutterApplication];
669 return [
self isSceneStateMatching:UISceneActivationStateForegroundActive];
672 - (BOOL)stateIsForeground {
676 if (flutterApplication) {
677 return [
self isApplicationStateMatching:UIApplicationStateActive
678 withApplication:flutterApplication] ||
679 [
self isApplicationStateMatching:UIApplicationStateInactive
680 withApplication:flutterApplication];
682 return [
self isSceneStateMatching:UISceneActivationStateForegroundActive] ||
683 [
self isSceneStateMatching:UISceneActivationStateForegroundInactive];
686 - (BOOL)stateIsBackground {
690 if (flutterApplication) {
691 return [
self isApplicationStateMatching:UIApplicationStateBackground
692 withApplication:flutterApplication];
694 return [
self isSceneStateMatching:UISceneActivationStateBackground];
697 - (BOOL)shouldHandleSceneNotification:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
698 if (notification.object == nil) {
701 UIWindowScene* scene =
self.flutterWindowSceneIfViewLoaded;
705 return notification.object == scene;
708 - (BOOL)isApplicationStateMatching:(UIApplicationState)match
709 withApplication:(UIApplication*)application {
710 switch (application.applicationState) {
711 case UIApplicationStateActive:
712 case UIApplicationStateInactive:
713 case UIApplicationStateBackground:
714 return application.applicationState == match;
718 - (BOOL)isSceneStateMatching:(UISceneActivationState)match API_AVAILABLE(ios(13.0)) {
719 switch (
self.activationState) {
720 case UISceneActivationStateForegroundActive:
721 case UISceneActivationStateUnattached:
722 case UISceneActivationStateForegroundInactive:
723 case UISceneActivationStateBackground:
724 return self.activationState == match;
728 #pragma mark - Surface creation and teardown updates
730 - (void)surfaceUpdated:(BOOL)appeared {
738 [
self installFirstFrameCallback];
739 self.platformViewsController.flutterView =
self.flutterView;
740 self.platformViewsController.flutterViewController =
self;
741 [
self.engine notifyViewCreated];
743 self.displayingFlutterUI = NO;
744 [
self.engine notifyViewDestroyed];
745 self.platformViewsController.flutterView = nil;
746 self.platformViewsController.flutterViewController = nil;
755 - (void)createSurfaceIfReady {
756 if (!
self.
engine || !_viewportMetrics.physical_width) {
759 [
self surfaceUpdated:YES];
762 #pragma mark - UIViewController lifecycle notifications
764 - (void)viewDidLoad {
765 TRACE_EVENT0(
"flutter",
"viewDidLoad");
767 if (
self.
engine &&
self.engineNeedsLaunch) {
768 [
self.engine launchEngine:nil libraryURI:nil entrypointArgs:nil];
769 [
self.engine setViewController:self];
770 self.engineNeedsLaunch = NO;
771 }
else if (
self.
engine.viewController ==
self) {
772 [
self.engine attachView];
776 [
self addInternalPlugins];
778 if (@available(iOS 13.4, *)) {
779 _hoverGestureRecognizer =
780 [[UIHoverGestureRecognizer alloc] initWithTarget:self action:@selector(hoverEvent:)];
781 _hoverGestureRecognizer.delegate =
self;
782 [
self.flutterView addGestureRecognizer:_hoverGestureRecognizer];
784 _discreteScrollingPanGestureRecognizer =
785 [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(discreteScrollEvent:)];
786 _discreteScrollingPanGestureRecognizer.allowedScrollTypesMask = UIScrollTypeMaskDiscrete;
791 _discreteScrollingPanGestureRecognizer.allowedTouchTypes = @[];
792 _discreteScrollingPanGestureRecognizer.delegate =
self;
793 [
self.flutterView addGestureRecognizer:_discreteScrollingPanGestureRecognizer];
794 _continuousScrollingPanGestureRecognizer =
795 [[UIPanGestureRecognizer alloc] initWithTarget:self
796 action:@selector(continuousScrollEvent:)];
797 _continuousScrollingPanGestureRecognizer.allowedScrollTypesMask = UIScrollTypeMaskContinuous;
798 _continuousScrollingPanGestureRecognizer.allowedTouchTypes = @[];
799 _continuousScrollingPanGestureRecognizer.delegate =
self;
800 [
self.flutterView addGestureRecognizer:_continuousScrollingPanGestureRecognizer];
801 _pinchGestureRecognizer =
802 [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchEvent:)];
803 _pinchGestureRecognizer.allowedTouchTypes = @[];
804 _pinchGestureRecognizer.delegate =
self;
805 [
self.flutterView addGestureRecognizer:_pinchGestureRecognizer];
806 _rotationGestureRecognizer = [[UIRotationGestureRecognizer alloc] init];
807 _rotationGestureRecognizer.allowedTouchTypes = @[];
808 _rotationGestureRecognizer.delegate =
self;
809 [
self.flutterView addGestureRecognizer:_rotationGestureRecognizer];
815 - (void)addInternalPlugins {
819 ^(
const FlutterKeyEvent& event, FlutterKeyEventCallback callback,
void* userData) {
820 [weakSelf.engine sendKeyEvent:event callback:callback userData:userData];
822 [
self.keyboardManager
826 [
self.keyboardManager addPrimaryResponder:responder];
829 [
self.keyboardManager addSecondaryResponder:textInputPlugin];
831 if (
self.
engine.viewController ==
self) {
836 - (void)removeInternalPlugins {
837 self.keyboardManager = nil;
840 - (void)viewWillAppear:(BOOL)animated {
841 TRACE_EVENT0(
"flutter",
"viewWillAppear");
842 if (
self.
engine.viewController ==
self) {
844 [
self onUserSettingsChanged:nil];
848 [
self createSurfaceIfReady];
849 [
self.engine.lifecycleChannel sendMessage:@"AppLifecycleState.inactive"];
850 [
self.engine.restorationPlugin markRestorationComplete];
853 [
super viewWillAppear:animated];
856 - (void)viewDidAppear:(BOOL)animated {
857 TRACE_EVENT0(
"flutter",
"viewDidAppear");
858 if (
self.
engine.viewController ==
self) {
859 [
self onUserSettingsChanged:nil];
860 [
self onAccessibilityStatusChanged:nil];
862 if (
self.stateIsActive) {
863 [
self.engine.lifecycleChannel sendMessage:@"AppLifecycleState.resumed"];
866 [
super viewDidAppear:animated];
869 - (void)viewWillDisappear:(BOOL)animated {
870 TRACE_EVENT0(
"flutter",
"viewWillDisappear");
871 if (
self.
engine.viewController ==
self) {
872 [
self.engine.lifecycleChannel sendMessage:@"AppLifecycleState.inactive"];
874 [
super viewWillDisappear:animated];
877 - (void)viewDidDisappear:(BOOL)animated {
878 TRACE_EVENT0(
"flutter",
"viewDidDisappear");
879 if (
self.
engine.viewController ==
self) {
880 [
self.keyboardInsetManager hideKeyboardImmediately];
881 [
self surfaceUpdated:NO];
882 [
self.engine.lifecycleChannel sendMessage:@"AppLifecycleState.paused"];
883 [
self flushOngoingTouches];
884 [
self.engine notifyLowMemory];
887 [
super viewDidDisappear:animated];
890 - (void)viewWillTransitionToSize:(CGSize)size
891 withTransitionCoordinator:(
id<UIViewControllerTransitionCoordinator>)coordinator {
892 [
super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
902 NSTimeInterval transitionDuration = coordinator.transitionDuration;
904 if (transitionDuration == 0) {
909 _shouldIgnoreViewportMetricsUpdatesDuringRotation = YES;
910 dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
911 static_cast<int64_t
>(transitionDuration / 2.0 * NSEC_PER_SEC)),
912 dispatch_get_main_queue(), ^{
920 strongSelf.shouldIgnoreViewportMetricsUpdatesDuringRotation = NO;
921 [strongSelf updateViewportMetricsIfNeeded];
925 - (void)flushOngoingTouches {
926 if (
self.
engine &&
self.ongoingTouches.count > 0) {
927 auto packet = std::make_unique<flutter::PointerDataPacket>(
self.ongoingTouches.count);
928 size_t pointer_index = 0;
931 for (NSNumber* device in
self.ongoingTouches) {
933 flutter::PointerData pointer_data = [
self generatePointerDataForFake];
935 pointer_data.change = flutter::PointerData::Change::kCancel;
936 pointer_data.device = device.longLongValue;
937 pointer_data.pointer_identifier = 0;
938 pointer_data.view_id =
self.viewIdentifier;
941 pointer_data.physical_x = 0;
942 pointer_data.physical_y = 0;
943 pointer_data.physical_delta_x = 0.0;
944 pointer_data.physical_delta_y = 0.0;
945 pointer_data.pressure = 1.0;
946 pointer_data.pressure_max = 1.0;
948 packet->SetPointerData(pointer_index++, pointer_data);
951 [
self.ongoingTouches removeAllObjects];
952 [
self.engine dispatchPointerDataPacket:std::move(packet)];
956 - (void)deregisterNotifications {
957 [[NSNotificationCenter defaultCenter] postNotificationName:FlutterViewControllerWillDealloc
960 [[NSNotificationCenter defaultCenter] removeObserver:self];
966 [
self removeInternalPlugins];
967 [
self deregisterNotifications];
969 [
self.keyboardInsetManager invalidate];
973 _scrollView.delegate = nil;
974 _hoverGestureRecognizer.delegate = nil;
975 _discreteScrollingPanGestureRecognizer.delegate = nil;
976 _continuousScrollingPanGestureRecognizer.delegate = nil;
977 _pinchGestureRecognizer.delegate = nil;
978 _rotationGestureRecognizer.delegate = nil;
981 #pragma mark - Application lifecycle notifications
983 - (void)applicationBecameActive:(NSNotification*)notification {
984 TRACE_EVENT0(
"flutter",
"applicationBecameActive");
985 [
self appOrSceneBecameActive];
988 - (void)applicationWillResignActive:(NSNotification*)notification {
989 TRACE_EVENT0(
"flutter",
"applicationWillResignActive");
990 [
self appOrSceneWillResignActive];
993 - (void)applicationWillTerminate:(NSNotification*)notification {
994 [
self appOrSceneWillTerminate];
997 - (void)applicationDidEnterBackground:(NSNotification*)notification {
998 TRACE_EVENT0(
"flutter",
"applicationDidEnterBackground");
999 [
self appOrSceneDidEnterBackground];
1002 - (void)applicationWillEnterForeground:(NSNotification*)notification {
1003 TRACE_EVENT0(
"flutter",
"applicationWillEnterForeground");
1004 [
self appOrSceneWillEnterForeground];
1007 #pragma mark - Scene lifecycle notifications
1009 - (void)sceneBecameActive:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1010 if (![
self shouldHandleSceneNotification:notification]) {
1013 TRACE_EVENT0(
"flutter",
"sceneBecameActive");
1014 [
self appOrSceneBecameActive];
1017 - (void)sceneWillResignActive:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1018 if (![
self shouldHandleSceneNotification:notification]) {
1021 TRACE_EVENT0(
"flutter",
"sceneWillResignActive");
1022 [
self appOrSceneWillResignActive];
1025 - (void)sceneWillDisconnect:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1026 if (![
self shouldHandleSceneNotification:notification]) {
1029 [
self appOrSceneWillTerminate];
1032 - (void)sceneDidEnterBackground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1033 if (![
self shouldHandleSceneNotification:notification]) {
1036 TRACE_EVENT0(
"flutter",
"sceneDidEnterBackground");
1037 [
self appOrSceneDidEnterBackground];
1040 - (void)sceneWillEnterForeground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
1041 if (![
self shouldHandleSceneNotification:notification]) {
1044 TRACE_EVENT0(
"flutter",
"sceneWillEnterForeground");
1045 [
self appOrSceneWillEnterForeground];
1048 #pragma mark - Lifecycle shared
1050 - (void)appOrSceneBecameActive {
1051 self.keyboardInsetManager.isKeyboardInOrTransitioningFromBackground = NO;
1052 [
self performSelector:@selector(goToApplicationLifecycle:)
1053 withObject:@"AppLifecycleState.resumed"
1057 - (void)appOrSceneWillResignActive {
1058 [NSObject cancelPreviousPerformRequestsWithTarget:self
1059 selector:@selector(goToApplicationLifecycle:)
1060 object:@"AppLifecycleState.resumed"];
1061 [
self goToApplicationLifecycle:@"AppLifecycleState.inactive"];
1064 - (void)appOrSceneWillTerminate {
1065 [
self goToApplicationLifecycle:@"AppLifecycleState.detached"];
1066 [
self.engine destroyContext];
1069 - (void)appOrSceneDidEnterBackground {
1070 self.keyboardInsetManager.isKeyboardInOrTransitioningFromBackground = YES;
1071 [
self surfaceUpdated:NO];
1072 [
self goToApplicationLifecycle:@"AppLifecycleState.paused"];
1075 - (void)appOrSceneWillEnterForeground {
1076 [
self createSurfaceIfReady];
1077 [
self goToApplicationLifecycle:@"AppLifecycleState.inactive"];
1081 - (void)goToApplicationLifecycle:(nonnull NSString*)state {
1084 if (
self.viewIfLoaded.window) {
1085 [
self.engine.lifecycleChannel sendMessage:state];
1089 #pragma mark - Touch event handling
1091 static flutter::PointerData::Change PointerDataChangeFromUITouchPhase(UITouchPhase phase) {
1093 case UITouchPhaseBegan:
1094 return flutter::PointerData::Change::kDown;
1095 case UITouchPhaseMoved:
1096 case UITouchPhaseStationary:
1099 return flutter::PointerData::Change::kMove;
1100 case UITouchPhaseEnded:
1101 return flutter::PointerData::Change::kUp;
1102 case UITouchPhaseCancelled:
1103 return flutter::PointerData::Change::kCancel;
1106 FML_DLOG(INFO) <<
"Unhandled touch phase: " << phase;
1110 return flutter::PointerData::Change::kCancel;
1113 static flutter::PointerData::DeviceKind DeviceKindFromTouchType(UITouch* touch) {
1114 switch (touch.type) {
1115 case UITouchTypeDirect:
1116 case UITouchTypeIndirect:
1117 return flutter::PointerData::DeviceKind::kTouch;
1118 case UITouchTypeStylus:
1119 return flutter::PointerData::DeviceKind::kStylus;
1120 case UITouchTypeIndirectPointer:
1121 return flutter::PointerData::DeviceKind::kMouse;
1123 FML_DLOG(INFO) <<
"Unhandled touch type: " << touch.type;
1127 return flutter::PointerData::DeviceKind::kTouch;
1134 - (void)dispatchTouches:(NSSet*)touches
1135 pointerDataChangeOverride:(
flutter::PointerData::Change*)overridden_change
1136 event:(UIEvent*)event {
1161 NSUInteger touches_to_remove_count = 0;
1162 for (UITouch* touch in touches) {
1163 if (touch.phase == UITouchPhaseEnded || touch.phase == UITouchPhaseCancelled) {
1164 touches_to_remove_count++;
1168 const CGFloat scale =
self.flutterScreenIfViewLoaded.scale;
1170 std::make_unique<flutter::PointerDataPacket>(touches.count + touches_to_remove_count);
1172 size_t pointer_index = 0;
1174 for (UITouch* touch in touches) {
1175 CGPoint windowCoordinates = [touch locationInView:self.view];
1177 flutter::PointerData pointer_data;
1178 pointer_data.Clear();
1183 pointer_data.change = overridden_change !=
nullptr
1184 ? *overridden_change
1185 : PointerDataChangeFromUITouchPhase(touch.phase);
1187 pointer_data.kind = DeviceKindFromTouchType(touch);
1189 pointer_data.device =
reinterpret_cast<int64_t
>(touch);
1191 pointer_data.view_id =
self.viewIdentifier;
1194 pointer_data.pointer_identifier = 0;
1196 pointer_data.physical_x = windowCoordinates.x * scale;
1197 pointer_data.physical_y = windowCoordinates.y * scale;
1200 pointer_data.physical_delta_x = 0.0;
1201 pointer_data.physical_delta_y = 0.0;
1203 NSNumber* deviceKey = [NSNumber numberWithLongLong:pointer_data.device];
1206 switch (pointer_data.change) {
1207 case flutter::PointerData::Change::kDown:
1208 [
self.ongoingTouches addObject:deviceKey];
1210 case flutter::PointerData::Change::kCancel:
1211 case flutter::PointerData::Change::kUp:
1212 [
self.ongoingTouches removeObject:deviceKey];
1214 case flutter::PointerData::Change::kHover:
1215 case flutter::PointerData::Change::kMove:
1218 case flutter::PointerData::Change::kAdd:
1219 case flutter::PointerData::Change::kRemove:
1222 case flutter::PointerData::Change::kPanZoomStart:
1223 case flutter::PointerData::Change::kPanZoomUpdate:
1224 case flutter::PointerData::Change::kPanZoomEnd:
1230 pointer_data.pressure = touch.force;
1231 pointer_data.pressure_max = touch.maximumPossibleForce;
1232 pointer_data.radius_major = touch.majorRadius;
1233 pointer_data.radius_min = touch.majorRadius - touch.majorRadiusTolerance;
1234 pointer_data.radius_max = touch.majorRadius + touch.majorRadiusTolerance;
1249 pointer_data.tilt = M_PI_2 - touch.altitudeAngle;
1269 pointer_data.orientation = [touch azimuthAngleInView:nil] - M_PI_2;
1271 if (@available(iOS 13.4, *)) {
1272 if (event !=
nullptr) {
1273 pointer_data.buttons = (((
event.buttonMask & UIEventButtonMaskPrimary) > 0)
1274 ? flutter::PointerButtonMouse::kPointerButtonMousePrimary
1276 (((event.buttonMask & UIEventButtonMaskSecondary) > 0)
1277 ? flutter::PointerButtonMouse::kPointerButtonMouseSecondary
1282 packet->SetPointerData(pointer_index++, pointer_data);
1284 if (touch.phase == UITouchPhaseEnded || touch.phase == UITouchPhaseCancelled) {
1285 flutter::PointerData remove_pointer_data = pointer_data;
1286 remove_pointer_data.change = flutter::PointerData::Change::kRemove;
1287 packet->SetPointerData(pointer_index++, remove_pointer_data);
1291 [
self.engine dispatchPointerDataPacket:std::move(packet)];
1294 - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
1295 [
self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event];
1298 - (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
1299 [
self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event];
1302 - (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
1303 [
self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event];
1306 - (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event {
1307 [
self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event];
1310 - (void)forceTouchesCancelled:(NSSet*)touches {
1311 flutter::PointerData::Change cancel = flutter::PointerData::Change::kCancel;
1312 [
self dispatchTouches:touches pointerDataChangeOverride:&cancel event:nullptr];
1315 - (BOOL)platformViewShouldAcceptTouchAtTouchBeganLocation:(CGPoint)location {
1316 flutter::PointData point{location.x, location.y};
1317 return [
self.engine platformViewShouldAcceptTouchAtTouchBeganLocation:point
1318 viewId:self.viewIdentifier];
1321 #pragma mark - Handle view resizing
1323 - (void)updateViewportMetricsIfNeeded {
1324 if (_shouldIgnoreViewportMetricsUpdatesDuringRotation) {
1327 if (
self.
engine.viewController ==
self) {
1328 [
self.engine updateViewportMetrics:_viewportMetrics];
1332 - (void)viewDidLayoutSubviews {
1333 CGRect viewBounds =
self.view.bounds;
1334 CGFloat scale =
self.flutterScreenIfViewLoaded.scale;
1337 self.scrollView.frame = CGRectMake(0.0, 0.0, viewBounds.size.width, 0.0);
1341 bool firstViewBoundsUpdate = !_viewportMetrics.physical_width;
1342 _viewportMetrics.device_pixel_ratio = scale;
1343 [
self setViewportMetricsSize];
1344 [
self checkAndUpdateAutoResizeConstraints];
1345 [
self setViewportMetricsPaddings];
1346 [
self updateViewportMetricsIfNeeded];
1347 [
self updateEngineDisplays];
1354 if (firstViewBoundsUpdate &&
self.stateIsForeground) {
1355 [
self createSurfaceIfReady];
1362 - (void)updateEngineDisplays {
1363 if (
self.
engine.viewController !=
self) {
1366 [
self.engine updateDisplays];
1369 - (BOOL)isAutoResizable {
1370 return self.flutterView.autoResizable;
1373 - (void)setAutoResizable:(BOOL)value {
1374 self.flutterView.autoResizable = value;
1375 self.flutterView.contentMode = UIViewContentModeCenter;
1378 - (void)checkAndUpdateAutoResizeConstraints {
1379 if (!
self.isAutoResizable) {
1383 [
self updateAutoResizeConstraints];
1407 - (void)updateAutoResizeConstraints {
1408 BOOL hasBeenAutoResized = NO;
1409 for (NSLayoutConstraint* constraint in
self.view.constraints) {
1411 hasBeenAutoResized = YES;
1415 if (!hasBeenAutoResized) {
1416 self.sizeBeforeAutoResized =
self.view.frame.size;
1419 CGFloat maxWidth =
self.sizeBeforeAutoResized.width;
1420 CGFloat maxHeight =
self.sizeBeforeAutoResized.height;
1421 CGFloat minWidth =
self.sizeBeforeAutoResized.width;
1422 CGFloat minHeight =
self.sizeBeforeAutoResized.height;
1426 if (maxWidth == 0) {
1427 maxWidth = CGFLOAT_MAX;
1430 @"Warning: The outermost widget in the autoresizable Flutter view is unsized or has "
1431 @"ambiguous dimensions, causing the host native view's width to be 0. The autoresizing "
1432 @"logic is setting the viewport constraint to unbounded DBL_MAX to prevent "
1433 @"rendering failure. Please ensure your top-level Flutter widget has explicit "
1434 @"constraints (e.g., using SizedBox or Container)."];
1436 if (maxHeight == 0) {
1437 maxHeight = CGFLOAT_MAX;
1440 @"Warning: The outermost widget in the autoresizable Flutter view is unsized or has "
1441 @"ambiguous dimensions, causing the host native view's width to be 0. The autoresizing "
1442 @"logic is setting the viewport constraint to unbounded DBL_MAX to prevent "
1443 @"rendering failure. Please ensure your top-level Flutter widget has explicit "
1444 @"constraints (e.g., using SizedBox or Container)."];
1446 _viewportMetrics.physical_min_width_constraint = minWidth * _viewportMetrics.device_pixel_ratio;
1447 _viewportMetrics.physical_max_width_constraint = maxWidth * _viewportMetrics.device_pixel_ratio;
1448 _viewportMetrics.physical_min_height_constraint = minHeight * _viewportMetrics.device_pixel_ratio;
1449 _viewportMetrics.physical_max_height_constraint = maxHeight * _viewportMetrics.device_pixel_ratio;
1452 - (void)viewSafeAreaInsetsDidChange {
1453 [
self setViewportMetricsPaddings];
1454 [
self updateViewportMetricsIfNeeded];
1455 [
super viewSafeAreaInsetsDidChange];
1459 - (void)setViewportMetricsSize {
1460 UIScreen* screen =
self.flutterScreenIfViewLoaded;
1465 CGFloat scale = screen.scale;
1466 _viewportMetrics.physical_width =
self.view.bounds.size.width * scale;
1467 _viewportMetrics.physical_height =
self.view.bounds.size.height * scale;
1469 _viewportMetrics.physical_min_width_constraint = _viewportMetrics.physical_width;
1470 _viewportMetrics.physical_max_width_constraint = _viewportMetrics.physical_width;
1471 _viewportMetrics.physical_min_height_constraint = _viewportMetrics.physical_height;
1472 _viewportMetrics.physical_max_height_constraint = _viewportMetrics.physical_height;
1478 - (void)setViewportMetricsPaddings {
1479 UIScreen* screen =
self.flutterScreenIfViewLoaded;
1484 CGFloat scale = screen.scale;
1485 _viewportMetrics.physical_padding_top =
self.view.safeAreaInsets.top * scale;
1486 _viewportMetrics.physical_padding_left =
self.view.safeAreaInsets.left * scale;
1487 _viewportMetrics.physical_padding_right =
self.view.safeAreaInsets.right * scale;
1488 _viewportMetrics.physical_padding_bottom =
self.view.safeAreaInsets.bottom * scale;
1491 #pragma mark - Keyboard events
1493 - (void)keyboardWillShowNotification:(NSNotification*)notification {
1498 [
self.keyboardInsetManager handleKeyboardNotification:notification];
1501 - (void)keyboardWillChangeFrame:(NSNotification*)notification {
1506 [
self.keyboardInsetManager handleKeyboardNotification:notification];
1509 - (void)keyboardWillBeHidden:(NSNotification*)notification {
1513 [
self.keyboardInsetManager handleKeyboardNotification:notification];
1516 - (void)handlePressEvent:(FlutterUIPressProxy*)press
1517 nextAction:(
void (^)())next API_AVAILABLE(ios(13.4)) {
1518 if (@available(iOS 13.4, *)) {
1523 [
self.keyboardManager handlePress:press nextAction:next];
1539 - (void)superPressesBegan:(NSSet<UIPress*>*)presses withEvent:(UIPressesEvent*)event {
1540 [
super pressesBegan:presses withEvent:event];
1543 - (void)superPressesChanged:(NSSet<UIPress*>*)presses withEvent:(UIPressesEvent*)event {
1544 [
super pressesChanged:presses withEvent:event];
1547 - (void)superPressesEnded:(NSSet<UIPress*>*)presses withEvent:(UIPressesEvent*)event {
1548 [
super pressesEnded:presses withEvent:event];
1551 - (void)superPressesCancelled:(NSSet<UIPress*>*)presses withEvent:(UIPressesEvent*)event {
1552 [
super pressesCancelled:presses withEvent:event];
1560 - (void)pressesBegan:(NSSet<UIPress*>*)presses
1561 withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
1562 if (@available(iOS 13.4, *)) {
1564 for (UIPress* press in presses) {
1565 [
self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press event:event]
1567 [weakSelf superPressesBegan:[NSSet setWithObject:press] withEvent:event];
1571 [
super pressesBegan:presses withEvent:event];
1575 - (void)pressesChanged:(NSSet<UIPress*>*)presses
1576 withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
1577 if (@available(iOS 13.4, *)) {
1579 for (UIPress* press in presses) {
1580 [
self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press event:event]
1582 [weakSelf superPressesChanged:[NSSet setWithObject:press] withEvent:event];
1586 [
super pressesChanged:presses withEvent:event];
1590 - (void)pressesEnded:(NSSet<UIPress*>*)presses
1591 withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
1592 if (@available(iOS 13.4, *)) {
1594 for (UIPress* press in presses) {
1595 [
self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press event:event]
1597 [weakSelf superPressesEnded:[NSSet setWithObject:press] withEvent:event];
1601 [
super pressesEnded:presses withEvent:event];
1605 - (void)pressesCancelled:(NSSet<UIPress*>*)presses
1606 withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
1607 if (@available(iOS 13.4, *)) {
1609 for (UIPress* press in presses) {
1610 [
self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press event:event]
1612 [weakSelf superPressesCancelled:[NSSet setWithObject:press] withEvent:event];
1616 [
super pressesCancelled:presses withEvent:event];
1620 #pragma mark - Orientation updates
1622 - (void)onOrientationPreferencesUpdated:(NSNotification*)notification {
1625 dispatch_async(dispatch_get_main_queue(), ^{
1626 NSDictionary* info = notification.userInfo;
1627 NSNumber* update = info[@(flutter::kOrientationUpdateNotificationKey)];
1628 if (update == nil) {
1631 [weakSelf performOrientationUpdate:update.unsignedIntegerValue];
1635 - (void)requestGeometryUpdateForWindowScenes:(NSSet<UIScene*>*)windowScenes
1636 API_AVAILABLE(ios(16.0)) {
1637 for (UIScene* windowScene in windowScenes) {
1638 FML_DCHECK([windowScene isKindOfClass:[UIWindowScene
class]]);
1639 UIWindowSceneGeometryPreferencesIOS* preference = [[UIWindowSceneGeometryPreferencesIOS alloc]
1640 initWithInterfaceOrientations:self.orientationPreferences];
1641 [(UIWindowScene*)windowScene
1642 requestGeometryUpdateWithPreferences:preference
1643 errorHandler:^(NSError* error) {
1644 os_log_error(OS_LOG_DEFAULT,
1645 "Failed to change device orientation: %@", error);
1647 [
self setNeedsUpdateOfSupportedInterfaceOrientations];
1651 - (void)performOrientationUpdate:(UIInterfaceOrientationMask)new_preferences {
1652 if (new_preferences !=
self.orientationPreferences) {
1653 self.orientationPreferences = new_preferences;
1655 if (@available(iOS 16.0, *)) {
1657 NSSet<UIScene*>* scenes = [NSSet set];
1658 if (flutterApplication) {
1659 scenes = [flutterApplication.connectedScenes
1660 filteredSetUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(
1661 id scene, NSDictionary* bindings) {
1662 return [scene isKindOfClass:[UIWindowScene class]];
1664 }
else if (
self.flutterWindowSceneIfViewLoaded) {
1665 scenes = [NSSet setWithObject:self.flutterWindowSceneIfViewLoaded];
1667 [
self requestGeometryUpdateForWindowScenes:scenes];
1669 UIInterfaceOrientationMask currentInterfaceOrientation = 0;
1670 UIWindowScene* windowScene =
self.flutterWindowSceneIfViewLoaded;
1674 @"Accessing the interface orientation when the window scene is unavailable."];
1677 currentInterfaceOrientation = 1 << windowScene.interfaceOrientation;
1678 if (!(
self.orientationPreferences & currentInterfaceOrientation)) {
1679 [UIViewController attemptRotationToDeviceOrientation];
1681 if (
self.orientationPreferences & UIInterfaceOrientationMaskPortrait) {
1685 [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationPortrait)
1686 forKey:@"orientation"];
1687 }
else if (
self.orientationPreferences & UIInterfaceOrientationMaskPortraitUpsideDown) {
1688 [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationPortraitUpsideDown)
1689 forKey:@"orientation"];
1690 }
else if (
self.orientationPreferences & UIInterfaceOrientationMaskLandscapeLeft) {
1691 [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeLeft)
1692 forKey:@"orientation"];
1693 }
else if (
self.orientationPreferences & UIInterfaceOrientationMaskLandscapeRight) {
1694 [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeRight)
1695 forKey:@"orientation"];
1702 - (void)onHideHomeIndicatorNotification:(NSNotification*)notification {
1703 self.isHomeIndicatorHidden = YES;
1706 - (void)onShowHomeIndicatorNotification:(NSNotification*)notification {
1707 self.isHomeIndicatorHidden = NO;
1710 - (void)setIsHomeIndicatorHidden:(BOOL)hideHomeIndicator {
1711 if (hideHomeIndicator != _isHomeIndicatorHidden) {
1712 _isHomeIndicatorHidden = hideHomeIndicator;
1713 [
self setNeedsUpdateOfHomeIndicatorAutoHidden];
1717 - (BOOL)prefersHomeIndicatorAutoHidden {
1718 return self.isHomeIndicatorHidden;
1721 - (BOOL)shouldAutorotate {
1725 - (NSUInteger)supportedInterfaceOrientations {
1726 return self.orientationPreferences;
1729 #pragma mark - Accessibility
1731 - (void)onAccessibilityStatusChanged:(NSNotification*)notification {
1736 int32_t flags = [
self.accessibilityFeatures flags];
1737 #if TARGET_OS_SIMULATOR
1743 _isVoiceOverRunning = [
self.accessibilityFeatures isVoiceOverRunning];
1744 enabled = _isVoiceOverRunning || [
self.accessibilityFeatures isSwitchControlRunning] ||
1745 [
self.accessibilityFeatures isSpeakScreenEnabled];
1747 [
self.engine enableSemantics:enabled withFlags:flags];
1750 - (BOOL)accessibilityPerformEscape {
1752 if (navigationChannel) {
1759 #pragma mark - Set user settings
1761 - (void)traitCollectionDidChange:(UITraitCollection*)previousTraitCollection {
1762 [
super traitCollectionDidChange:previousTraitCollection];
1763 [
self onUserSettingsChanged:nil];
1767 if (
self.isAutoResizable) {
1768 [
self.flutterView resetIntrinsicContentSize];
1772 - (void)onUserSettingsChanged:(NSNotification*)notification {
1773 [
self.engine.settingsChannel sendMessage:@{
1774 @"textScaleFactor" : @(
self.textScaleFactor),
1776 @"platformBrightness" :
self.brightnessMode,
1777 @"platformContrast" : self.contrastMode,
1778 @"nativeSpellCheckServiceDefined" : @YES,
1779 @"supportsShowingSystemContextMenu" : @(self.supportsShowingSystemContextMenu)
1783 - (CGFloat)textScaleFactor {
1785 if (flutterApplication == nil) {
1786 [FlutterLogger logWarning:@"Dynamic content size update is not supported in app extension."];
1790 UIContentSizeCategory category = flutterApplication.preferredContentSizeCategory;
1796 const CGFloat xs = 14;
1797 const CGFloat s = 15;
1798 const CGFloat m = 16;
1799 const CGFloat l = 17;
1800 const CGFloat xl = 19;
1801 const CGFloat xxl = 21;
1802 const CGFloat xxxl = 23;
1805 const CGFloat ax1 = 28;
1806 const CGFloat ax2 = 33;
1807 const CGFloat ax3 = 40;
1808 const CGFloat ax4 = 47;
1809 const CGFloat ax5 = 53;
1813 if ([category isEqualToString:UIContentSizeCategoryExtraSmall]) {
1815 }
else if ([category isEqualToString:UIContentSizeCategorySmall]) {
1817 }
else if ([category isEqualToString:UIContentSizeCategoryMedium]) {
1819 }
else if ([category isEqualToString:UIContentSizeCategoryLarge]) {
1821 }
else if ([category isEqualToString:UIContentSizeCategoryExtraLarge]) {
1823 }
else if ([category isEqualToString:UIContentSizeCategoryExtraExtraLarge]) {
1825 }
else if ([category isEqualToString:UIContentSizeCategoryExtraExtraExtraLarge]) {
1827 }
else if ([category isEqualToString:UIContentSizeCategoryAccessibilityMedium]) {
1829 }
else if ([category isEqualToString:UIContentSizeCategoryAccessibilityLarge]) {
1831 }
else if ([category isEqualToString:UIContentSizeCategoryAccessibilityExtraLarge]) {
1833 }
else if ([category isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraLarge]) {
1835 }
else if ([category isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraExtraLarge]) {
1842 - (BOOL)supportsShowingSystemContextMenu {
1843 if (@available(iOS 16.0, *)) {
1853 - (NSString*)brightnessMode {
1854 UIUserInterfaceStyle style =
self.traitCollection.userInterfaceStyle;
1856 if (style == UIUserInterfaceStyleDark) {
1866 - (NSString*)contrastMode {
1867 UIAccessibilityContrast contrast =
self.traitCollection.accessibilityContrast;
1869 if (contrast == UIAccessibilityContrastHigh) {
1876 #pragma mark - Status bar style
1878 - (UIStatusBarStyle)preferredStatusBarStyle {
1879 return self.statusBarStyle;
1882 - (void)onPreferredStatusBarStyleUpdated:(NSNotification*)notification {
1885 dispatch_async(dispatch_get_main_queue(), ^{
1891 NSDictionary* info = notification.userInfo;
1892 NSNumber* update = info[@(flutter::kOverlayStyleUpdateNotificationKey)];
1893 if (update == nil) {
1897 UIStatusBarStyle style =
static_cast<UIStatusBarStyle
>(update.integerValue);
1898 if (style != strongSelf.statusBarStyle) {
1899 strongSelf.statusBarStyle = style;
1900 [strongSelf setNeedsStatusBarAppearanceUpdate];
1905 - (void)setPrefersStatusBarHidden:(BOOL)hidden {
1906 if (hidden !=
self.flutterPrefersStatusBarHidden) {
1907 self.flutterPrefersStatusBarHidden = hidden;
1908 [
self setNeedsStatusBarAppearanceUpdate];
1912 - (BOOL)prefersStatusBarHidden {
1913 return self.flutterPrefersStatusBarHidden;
1916 #pragma mark - Platform views
1919 return self.engine.platformViewsController;
1923 return self.engine.binaryMessenger;
1926 #pragma mark - FlutterBinaryMessenger
1928 - (void)sendOnChannel:(NSString*)channel message:(NSData*)message {
1929 [
self.engine.binaryMessenger sendOnChannel:channel message:message];
1932 - (void)sendOnChannel:(NSString*)channel
1933 message:(NSData*)message
1935 NSAssert(channel,
@"The channel must not be null");
1936 [
self.engine.binaryMessenger sendOnChannel:channel message:message binaryReply:callback];
1940 return [
self.engine.binaryMessenger makeBackgroundTaskQueue];
1944 binaryMessageHandler:
1946 return [
self setMessageHandlerOnChannel:channel binaryMessageHandler:handler taskQueue:nil];
1950 setMessageHandlerOnChannel:(NSString*)channel
1953 NSAssert(channel,
@"The channel must not be null");
1954 return [
self.engine.binaryMessenger setMessageHandlerOnChannel:channel
1955 binaryMessageHandler:handler
1956 taskQueue:taskQueue];
1960 [
self.engine.binaryMessenger cleanUpConnection:connection];
1963 #pragma mark - FlutterTextureRegistry
1966 return [
self.engine.textureRegistry registerTexture:texture];
1969 - (void)unregisterTexture:(int64_t)textureId {
1970 [
self.engine.textureRegistry unregisterTexture:textureId];
1973 - (void)textureFrameAvailable:(int64_t)textureId {
1974 [
self.engine.textureRegistry textureFrameAvailable:textureId];
1977 - (NSString*)lookupKeyForAsset:(NSString*)asset {
1981 - (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
1985 - (id<FlutterPluginRegistry>)pluginRegistry {
1989 + (BOOL)isUIAccessibilityIsVoiceOverRunning {
1990 return UIAccessibilityIsVoiceOverRunning();
1993 #pragma mark - FlutterPluginRegistry
1996 return [
self.engine registrarForPlugin:pluginKey];
1999 - (BOOL)hasPlugin:(NSString*)pluginKey {
2000 return [
self.engine hasPlugin:pluginKey];
2003 - (NSObject*)valuePublishedByPlugin:(NSString*)pluginKey {
2004 return [
self.engine valuePublishedByPlugin:pluginKey];
2007 - (void)presentViewController:(UIViewController*)viewControllerToPresent
2009 completion:(
void (^)(
void))completion {
2010 self.isPresentingViewControllerAnimating = YES;
2012 [
super presentViewController:viewControllerToPresent
2015 weakSelf.isPresentingViewControllerAnimating = NO;
2022 - (BOOL)isPresentingViewController {
2023 return self.presentedViewController != nil ||
self.isPresentingViewControllerAnimating;
2026 - (
flutter::PointerData)updateMousePointerDataFrom:(UIGestureRecognizer*)gestureRecognizer
2027 API_AVAILABLE(ios(13.4)) {
2028 CGPoint location = [gestureRecognizer locationInView:self.view];
2029 CGFloat scale =
self.flutterScreenIfViewLoaded.scale;
2031 flutter::PointerData pointer_data;
2032 pointer_data.Clear();
2036 return pointer_data;
2039 - (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer
2040 shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer*)otherGestureRecognizer
2041 API_AVAILABLE(ios(13.4)) {
2045 - (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer
2046 shouldReceiveEvent:(UIEvent*)event API_AVAILABLE(ios(13.4)) {
2047 if (gestureRecognizer == _continuousScrollingPanGestureRecognizer &&
2048 event.type == UIEventTypeScroll) {
2050 flutter::PointerData pointer_data = [
self updateMousePointerDataFrom:gestureRecognizer];
2051 pointer_data.device =
reinterpret_cast<int64_t
>(_continuousScrollingPanGestureRecognizer);
2052 pointer_data.kind = flutter::PointerData::DeviceKind::kTrackpad;
2053 pointer_data.signal_kind = flutter::PointerData::SignalKind::kScrollInertiaCancel;
2054 pointer_data.view_id =
self.viewIdentifier;
2056 if (event.timestamp <
self.scrollInertiaEventAppKitDeadline) {
2059 auto packet = std::make_unique<flutter::PointerDataPacket>(1);
2060 packet->SetPointerData(0, pointer_data);
2061 [
self.engine dispatchPointerDataPacket:std::move(packet)];
2062 self.scrollInertiaEventAppKitDeadline = 0;
2069 - (void)hoverEvent:(UIHoverGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) {
2072 flutter::PointerData pointer_data = [
self updateMousePointerDataFrom:recognizer];
2073 pointer_data.device =
reinterpret_cast<int64_t
>(recognizer);
2074 pointer_data.kind = flutter::PointerData::DeviceKind::kMouse;
2075 pointer_data.view_id =
self.viewIdentifier;
2077 switch (_hoverGestureRecognizer.state) {
2078 case UIGestureRecognizerStateBegan:
2079 pointer_data.change = flutter::PointerData::Change::kAdd;
2081 case UIGestureRecognizerStateChanged:
2082 pointer_data.change = flutter::PointerData::Change::kHover;
2084 case UIGestureRecognizerStateEnded:
2085 case UIGestureRecognizerStateCancelled:
2086 pointer_data.change = flutter::PointerData::Change::kRemove;
2091 pointer_data.change = flutter::PointerData::Change::kHover;
2095 NSTimeInterval time = [NSProcessInfo processInfo].systemUptime;
2096 BOOL isRunningOnMac = NO;
2100 isRunningOnMac = [NSProcessInfo processInfo].iOSAppOnMac;
2102 time >
self.scrollInertiaEventStartline) {
2106 auto packet = std::make_unique<flutter::PointerDataPacket>(2);
2107 packet->SetPointerData(0, pointer_data);
2108 flutter::PointerData inertia_cancel = pointer_data;
2109 inertia_cancel.device =
reinterpret_cast<int64_t
>(_continuousScrollingPanGestureRecognizer);
2110 inertia_cancel.kind = flutter::PointerData::DeviceKind::kTrackpad;
2111 inertia_cancel.signal_kind = flutter::PointerData::SignalKind::kScrollInertiaCancel;
2112 inertia_cancel.view_id =
self.viewIdentifier;
2113 packet->SetPointerData(1, inertia_cancel);
2114 [
self.engine dispatchPointerDataPacket:std::move(packet)];
2115 self.scrollInertiaEventStartline = DBL_MAX;
2117 auto packet = std::make_unique<flutter::PointerDataPacket>(1);
2118 packet->SetPointerData(0, pointer_data);
2119 [
self.engine dispatchPointerDataPacket:std::move(packet)];
2123 - (void)discreteScrollEvent:(UIPanGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) {
2124 CGPoint translation = [recognizer translationInView:self.view];
2125 const CGFloat scale =
self.flutterScreenIfViewLoaded.scale;
2127 translation.x *= scale;
2128 translation.y *= scale;
2130 flutter::PointerData pointer_data = [
self updateMousePointerDataFrom:recognizer];
2131 pointer_data.device =
reinterpret_cast<int64_t
>(recognizer);
2132 pointer_data.kind = flutter::PointerData::DeviceKind::kMouse;
2133 pointer_data.signal_kind = flutter::PointerData::SignalKind::kScroll;
2134 pointer_data.scroll_delta_x = (translation.x -
_mouseState.last_translation.x);
2135 pointer_data.scroll_delta_y = -(translation.y -
_mouseState.last_translation.y);
2136 pointer_data.view_id =
self.viewIdentifier;
2142 if (recognizer.state != UIGestureRecognizerStateEnded) {
2148 auto packet = std::make_unique<flutter::PointerDataPacket>(1);
2149 packet->SetPointerData(0, pointer_data);
2150 [
self.engine dispatchPointerDataPacket:std::move(packet)];
2153 - (void)continuousScrollEvent:(UIPanGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) {
2154 CGPoint translation = [recognizer translationInView:self.view];
2155 const CGFloat scale =
self.flutterScreenIfViewLoaded.scale;
2157 flutter::PointerData pointer_data = [
self updateMousePointerDataFrom:recognizer];
2158 pointer_data.device =
reinterpret_cast<int64_t
>(recognizer);
2159 pointer_data.kind = flutter::PointerData::DeviceKind::kTrackpad;
2160 pointer_data.view_id =
self.viewIdentifier;
2161 switch (recognizer.state) {
2162 case UIGestureRecognizerStateBegan:
2163 pointer_data.change = flutter::PointerData::Change::kPanZoomStart;
2165 case UIGestureRecognizerStateChanged:
2166 pointer_data.change = flutter::PointerData::Change::kPanZoomUpdate;
2167 pointer_data.pan_x = translation.x * scale;
2168 pointer_data.pan_y = translation.y * scale;
2169 pointer_data.pan_delta_x = 0;
2170 pointer_data.pan_delta_y = 0;
2171 pointer_data.scale = 1;
2173 case UIGestureRecognizerStateEnded:
2174 case UIGestureRecognizerStateCancelled:
2175 self.scrollInertiaEventStartline =
2176 [[NSProcessInfo processInfo] systemUptime] +
2186 self.scrollInertiaEventAppKitDeadline =
2187 [[NSProcessInfo processInfo] systemUptime] +
2188 (0.1821 * log(fmax([recognizer velocityInView:self.view].x,
2189 [recognizer velocityInView:self.view].y))) -
2191 pointer_data.change = flutter::PointerData::Change::kPanZoomEnd;
2195 NSAssert(NO,
@"Trackpad pan event occured with unexpected phase 0x%lx",
2196 (
long)recognizer.state);
2200 auto packet = std::make_unique<flutter::PointerDataPacket>(1);
2201 packet->SetPointerData(0, pointer_data);
2202 [
self.engine dispatchPointerDataPacket:std::move(packet)];
2205 - (void)pinchEvent:(UIPinchGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) {
2206 flutter::PointerData pointer_data = [
self updateMousePointerDataFrom:recognizer];
2207 pointer_data.device =
reinterpret_cast<int64_t
>(recognizer);
2208 pointer_data.kind = flutter::PointerData::DeviceKind::kTrackpad;
2209 pointer_data.view_id =
self.viewIdentifier;
2210 switch (recognizer.state) {
2211 case UIGestureRecognizerStateBegan:
2212 pointer_data.change = flutter::PointerData::Change::kPanZoomStart;
2214 case UIGestureRecognizerStateChanged:
2215 pointer_data.change = flutter::PointerData::Change::kPanZoomUpdate;
2216 pointer_data.scale = recognizer.scale;
2217 pointer_data.rotation = _rotationGestureRecognizer.rotation;
2219 case UIGestureRecognizerStateEnded:
2220 case UIGestureRecognizerStateCancelled:
2221 pointer_data.change = flutter::PointerData::Change::kPanZoomEnd;
2225 NSAssert(NO,
@"Trackpad pinch event occured with unexpected phase 0x%lx",
2226 (
long)recognizer.state);
2230 auto packet = std::make_unique<flutter::PointerDataPacket>(1);
2231 packet->SetPointerData(0, pointer_data);
2232 [
self.engine dispatchPointerDataPacket:std::move(packet)];
2235 #pragma mark - State Restoration
2237 - (void)encodeRestorableStateWithCoder:(NSCoder*)coder {
2238 NSData* restorationData = [
self.engine.restorationPlugin restorationData];
2239 [coder encodeBytes:(const unsigned char*)restorationData.bytes
2240 length:restorationData.length
2241 forKey:kFlutterRestorationStateAppData];
2242 [
super encodeRestorableStateWithCoder:coder];
2245 - (void)decodeRestorableStateWithCoder:(NSCoder*)coder {
2246 NSUInteger restorationDataLength;
2247 const unsigned char* restorationBytes = [coder decodeBytesForKey:kFlutterRestorationStateAppData
2248 returnedLength:&restorationDataLength];
2249 NSData* restorationData = [NSData dataWithBytes:restorationBytes length:restorationDataLength];
2250 [
self.engine.restorationPlugin setRestorationData:restorationData];
2254 return self.engine.restorationPlugin;
2258 return self.engine.textInputPlugin;
2261 #pragma mark - FlutterKeyboardInsetManagerDelegate
2263 - (void)updateViewportMetricsWithInset:(CGFloat)inset {
2264 _viewportMetrics.physical_view_inset_bottom = inset;
2265 [
self updateViewportMetricsIfNeeded];
2268 - (CGFloat)physicalViewInsetBottom {
2269 return _viewportMetrics.physical_view_inset_bottom;
2273 return self.engine.uiTaskRunner;
2276 - (BOOL)isPadInSlideOverOrStageManagerMode {
2277 if (
self.view.traitCollection.userInterfaceIdiom == UIUserInterfaceIdiomPad &&
2278 self.view.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact &&
2279 self.view.traitCollection.verticalSizeClass == UIUserInterfaceSizeClassRegular) {
2285 - (CGRect)convertViewRectToScreen:(CGRect)rect {
2286 return [
self.view convertRect:rect
2287 toCoordinateSpace:self.flutterScreenIfViewLoaded.coordinateSpace];
NS_ASSUME_NONNULL_BEGIN typedef void(^ FlutterBinaryReply)(NSData *_Nullable reply)
void(^ FlutterBinaryMessageHandler)(NSData *_Nullable message, FlutterBinaryReply reply)
int64_t FlutterBinaryMessengerConnection
void(^ FlutterSendKeyEvent)(const FlutterKeyEvent &, _Nullable FlutterKeyEventCallback, void *_Nullable)
UITextSmartQuotesType smartQuotesType API_AVAILABLE(ios(11.0))
instancetype initWithCoder
FlutterTextInputPlugin * textInputPlugin
NSNotificationName const FlutterViewControllerHideHomeIndicator
FlutterSplashScreenManager * _splashScreenManager
static NSString *const kFlutterRestorationStateAppData
NSNotificationName const FlutterViewControllerShowHomeIndicator
NSNotificationName const FlutterSemanticsUpdateNotification
struct MouseState MouseState
static constexpr CGFloat kScrollViewContentSize
NSNotificationName const FlutterViewControllerWillDealloc
static constexpr FLUTTER_ASSERT_ARC int kMicrosecondsPerSecond
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)
UIApplication * application
void setUpIndirectScribbleInteraction:(id< FlutterViewResponder > viewResponder)
UIView * splashScreenView