UnityAppController.mm 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. #import "UnityAppController.h"
  2. #import "UnityAppController+ViewHandling.h"
  3. #import "UnityAppController+Rendering.h"
  4. #import "iPhone_Sensors.h"
  5. #import <CoreGraphics/CoreGraphics.h>
  6. #import <QuartzCore/QuartzCore.h>
  7. #import <QuartzCore/CADisplayLink.h>
  8. #import <Availability.h>
  9. #import <AVFoundation/AVFoundation.h>
  10. #import <SPChannelSDK/SPChannelSDK.h>
  11. #include <mach/mach_time.h>
  12. // MSAA_DEFAULT_SAMPLE_COUNT was removed
  13. // ENABLE_INTERNAL_PROFILER and related defines were moved to iPhone_Profiler.h
  14. // kFPS define for removed: you can use Application.targetFrameRate (30 fps by default)
  15. // DisplayLink is the only run loop mode now - all others were removed
  16. #include "CrashReporter.h"
  17. #include "UI/OrientationSupport.h"
  18. #include "UI/UnityView.h"
  19. #include "UI/Keyboard.h"
  20. #include "UI/UnityViewControllerBase.h"
  21. #include "Unity/InternalProfiler.h"
  22. #include "Unity/DisplayManager.h"
  23. #include "Unity/ObjCRuntime.h"
  24. #include "PluginBase/AppDelegateListener.h"
  25. #include <assert.h>
  26. #include <stdbool.h>
  27. #include <sys/types.h>
  28. #include <unistd.h>
  29. #include <sys/sysctl.h>
  30. // we assume that app delegate is never changed and we can cache it, instead of re-query UIApplication every time
  31. UnityAppController* _UnityAppController = nil;
  32. UnityAppController* GetAppController()
  33. {
  34. return _UnityAppController;
  35. }
  36. // we keep old bools around to support "old" code that might have used them
  37. bool _ios81orNewer = false, _ios82orNewer = false, _ios83orNewer = false, _ios90orNewer = false, _ios91orNewer = false;
  38. bool _ios100orNewer = false, _ios101orNewer = false, _ios102orNewer = false, _ios103orNewer = false;
  39. bool _ios110orNewer = false, _ios111orNewer = false, _ios112orNewer = false;
  40. bool _ios130orNewer = false, _ios140orNewer = false, _ios150orNewer = false, _ios160orNewer = false;
  41. // minimal Unity initialization done, enough to do calls to provide data like URL launch
  42. bool _unityEngineLoaded = false;
  43. // was core of Unity loaded (non-graphics part prior to loading first scene)
  44. bool _unityEngineInitialized = false;
  45. // was unity rendering already inited: we should not touch rendering while this is false
  46. bool _renderingInited = false;
  47. // was unity inited: we should not touch unity api while this is false
  48. bool _unityAppReady = false;
  49. // see if there's a need to do internal player pause/resume handling
  50. //
  51. // Typically the trampoline code should manage this internally, but
  52. // there are use cases, videoplayer, plugin code, etc where the player
  53. // is paused before the internal handling comes relevant. Avoid
  54. // overriding externally managed player pause/resume handling by
  55. // caching the state
  56. bool _wasPausedExternal = false;
  57. // should we skip present on next draw: used in corner cases (like rotation) to fill both draw-buffers with some content
  58. bool _skipPresent = false;
  59. // was app "resigned active": some operations do not make sense while app is in background
  60. bool _didResignActive = false;
  61. #if UNITY_SUPPORT_ROTATION
  62. // Required to enable specific orientation for some presentation controllers: see supportedInterfaceOrientationsForWindow below for details
  63. NSInteger _forceInterfaceOrientationMask = 0;
  64. #endif
  65. @implementation UnityAppController
  66. @synthesize unityView = _unityView;
  67. @synthesize unityDisplayLink = _displayLink;
  68. @synthesize rootView = _rootView;
  69. @synthesize rootViewController = _rootController;
  70. @synthesize mainDisplay = _mainDisplay;
  71. @synthesize renderDelegate = _renderDelegate;
  72. @synthesize quitHandler = _quitHandler;
  73. #if UNITY_SUPPORT_ROTATION
  74. @synthesize interfaceOrientation = _curOrientation;
  75. #endif
  76. - (id)init
  77. {
  78. if ((self = _UnityAppController = [super init]))
  79. {
  80. // due to clang issues with generating warning for overriding deprecated methods
  81. // we will simply assert if deprecated methods are present
  82. // NB: methods table is initied at load (before this call), so it is ok to check for override
  83. NSAssert(![self respondsToSelector: @selector(createUnityViewImpl)],
  84. @"createUnityViewImpl is deprecated and will not be called. Override createUnityView"
  85. );
  86. NSAssert(![self respondsToSelector: @selector(createViewHierarchyImpl)],
  87. @"createViewHierarchyImpl is deprecated and will not be called. Override willStartWithViewController"
  88. );
  89. NSAssert(![self respondsToSelector: @selector(createViewHierarchy)],
  90. @"createViewHierarchy is deprecated and will not be implemented. Use createUI"
  91. );
  92. }
  93. return self;
  94. }
  95. - (void)setWindow:(id)object {}
  96. - (UIWindow*)window { return _window; }
  97. - (void)shouldAttachRenderDelegate {}
  98. - (void)preStartUnity {}
  99. - (void)startUnity:(UIApplication*)application
  100. {
  101. NSAssert(_unityAppReady == NO, @"[UnityAppController startUnity:] called after Unity has been initialized");
  102. UnityInitApplicationGraphics();
  103. // we make sure that first level gets correct display list and orientation
  104. [[DisplayManager Instance] updateDisplayListCacheInUnity];
  105. UnityLoadApplication();
  106. Profiler_InitProfiler();
  107. [self showGameUI];
  108. [self createDisplayLink];
  109. UnitySetPlayerFocus(1);
  110. AVAudioSession* audioSession = [AVAudioSession sharedInstance];
  111. // If Unity audio is disabled, we set the category to ambient to make sure we don't mute other app's audio. We set the audio session
  112. // to active so we can get outputVolume callbacks. If Unity audio is enabled, FMOD should have already handled all of this AVAudioSession init.
  113. if (!UnityIsAudioManagerAvailableAndEnabled())
  114. {
  115. [audioSession setCategory: AVAudioSessionCategoryAmbient error: nil];
  116. [audioSession setActive: YES error: nil];
  117. }
  118. [audioSession addObserver: self forKeyPath: @"outputVolume" options: 0 context: nil];
  119. UnityUpdateMuteState([audioSession outputVolume] < 0.01f ? 1 : 0);
  120. #if UNITY_REPLAY_KIT_AVAILABLE
  121. void InitUnityReplayKit(); // Classes/Unity/UnityReplayKit.mm
  122. InitUnityReplayKit();
  123. #endif
  124. }
  125. extern "C" void UnityDestroyDisplayLink()
  126. {
  127. [GetAppController() destroyDisplayLink];
  128. }
  129. extern "C" void UnityRequestQuit()
  130. {
  131. _didResignActive = true;
  132. if (GetAppController().quitHandler)
  133. GetAppController().quitHandler();
  134. else
  135. exit(0);
  136. }
  137. extern void SensorsCleanup();
  138. extern "C" void UnityCleanupTrampoline()
  139. {
  140. // Unity view and viewController will not necessary be destroyed right after this function execution.
  141. // We need to ensure that these objects will not receive any callbacks from system during that time.
  142. [_UnityAppController window].rootViewController = nil;
  143. [[_UnityAppController unityView] removeFromSuperview];
  144. // Prevent multiple cleanups
  145. if (_UnityAppController == nil)
  146. return;
  147. [KeyboardDelegate Destroy];
  148. SensorsCleanup();
  149. Profiler_UninitProfiler();
  150. [DisplayManager Destroy];
  151. UnityDestroyDisplayLink();
  152. _UnityAppController = nil;
  153. }
  154. #if UNITY_SUPPORT_ROTATION
  155. - (NSUInteger)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window
  156. {
  157. // No rootViewController is set because we are switching from one view controller to another, all orientations should be enabled
  158. if ([window rootViewController] == nil)
  159. return UIInterfaceOrientationMaskAll;
  160. // During splash screen show phase no forced orientations should be allowed.
  161. // This will prevent unwanted rotation while splash screen is on and application is not yet ready to present (Ex. Fogbugz cases: 1190428, 1269547).
  162. if (!_unityAppReady)
  163. return [_rootController supportedInterfaceOrientations];
  164. // Some presentation controllers (e.g. UIImagePickerController) require portrait orientation and will throw exception if it is not supported.
  165. // At the same time enabling all orientations by returning UIInterfaceOrientationMaskAll might cause unwanted orientation change
  166. // (e.g. when using UIActivityViewController to "share to" another application, iOS will use supportedInterfaceOrientations to possibly reorient).
  167. // So to avoid exception we are returning combination of constraints for root view controller and orientation requested by iOS.
  168. // _forceInterfaceOrientationMask is updated in willChangeStatusBarOrientation, which is called if some presentation controller insists on orientation change.
  169. return [[window rootViewController] supportedInterfaceOrientations] | _forceInterfaceOrientationMask;
  170. }
  171. - (void)application:(UIApplication*)application willChangeStatusBarOrientation:(UIInterfaceOrientation)newStatusBarOrientation duration:(NSTimeInterval)duration
  172. {
  173. // Setting orientation mask which is requested by iOS: see supportedInterfaceOrientationsForWindow above for details
  174. _forceInterfaceOrientationMask = 1 << newStatusBarOrientation;
  175. }
  176. #endif
  177. #if !PLATFORM_TVOS
  178. #pragma clang diagnostic push
  179. #pragma clang diagnostic ignored "-Wdeprecated-implementations"
  180. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  181. - (void)application:(UIApplication*)application didReceiveLocalNotification:(UILocalNotification*)notification
  182. {
  183. AppController_SendNotificationWithArg(kUnityDidReceiveLocalNotification, notification);
  184. UnitySendLocalNotification(notification);
  185. }
  186. #pragma clang diagnostic pop
  187. #endif
  188. #if UNITY_USES_REMOTE_NOTIFICATIONS
  189. - (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo
  190. {
  191. AppController_SendNotificationWithArg(kUnityDidReceiveRemoteNotification, userInfo);
  192. UnitySendRemoteNotification(userInfo);
  193. }
  194. - (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
  195. {
  196. AppController_SendNotificationWithArg(kUnityDidRegisterForRemoteNotificationsWithDeviceToken, deviceToken);
  197. UnitySendDeviceToken(deviceToken);
  198. }
  199. #if !PLATFORM_TVOS
  200. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler
  201. {
  202. AppController_SendNotificationWithArg(kUnityDidReceiveRemoteNotification, userInfo);
  203. UnitySendRemoteNotification(userInfo);
  204. if (handler)
  205. {
  206. handler(UIBackgroundFetchResultNoData);
  207. }
  208. }
  209. #endif
  210. - (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
  211. {
  212. AppController_SendNotificationWithArg(kUnityDidFailToRegisterForRemoteNotificationsWithError, error);
  213. UnitySendRemoteNotificationError(error);
  214. // alas people do not check remote notification error through api (which is clunky, i agree) so log here to have at least some visibility
  215. ::printf("\nFailed to register for remote notifications:\n%s\n\n", [[error localizedDescription] UTF8String]);
  216. }
  217. #endif
  218. // UIApplicationOpenURLOptionsKey was added only in ios10 sdk, while we still support ios9 sdk
  219. - (BOOL)application:(UIApplication*)app openURL:(NSURL*)url options:(NSDictionary<NSString*, id>*)options
  220. {
  221. id sourceApplication = options[UIApplicationOpenURLOptionsSourceApplicationKey], annotation = options[UIApplicationOpenURLOptionsAnnotationKey];
  222. NSMutableDictionary<NSString*, id>* notifData = [NSMutableDictionary dictionaryWithCapacity: 3];
  223. if (url)
  224. {
  225. notifData[@"url"] = url;
  226. UnitySetAbsoluteURL(url.absoluteString.UTF8String);
  227. }
  228. if (sourceApplication) notifData[@"sourceApplication"] = sourceApplication;
  229. if (annotation) notifData[@"annotation"] = annotation;
  230. AppController_SendNotificationWithArg(kUnityOnOpenURL, notifData);
  231. return [SPSDKInstance application:app openURL:url options:options];
  232. }
  233. - (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity
  234. #if defined(__IPHONE_12_0) || defined(__TVOS_12_0)
  235. restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring> > * _Nullable restorableObjects))restorationHandler
  236. #else
  237. restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler
  238. #endif
  239. {
  240. NSURL* url = userActivity.webpageURL;
  241. if (url)
  242. UnitySetAbsoluteURL(url.absoluteString.UTF8String);
  243. return [SPSDKInstance application:application continueUserActivity:userActivity restorationHandler:restorationHandler];
  244. }
  245. - (BOOL)application:(UIApplication*)application willFinishLaunchingWithOptions:(NSDictionary*)launchOptions
  246. {
  247. AppController_SendNotificationWithArg(kUnityWillFinishLaunchingWithOptions, launchOptions);
  248. NSURL* url = launchOptions[UIApplicationLaunchOptionsURLKey];
  249. if (url != nil)
  250. {
  251. [self initUnityApplicationNoGraphics];
  252. UnitySetAbsoluteURL(url.absoluteString.UTF8String);
  253. }
  254. return YES;
  255. }
  256. #if (PLATFORM_IOS && defined(__IPHONE_13_0)) || (PLATFORM_TVOS && defined(__TVOS_13_0))
  257. - (UIWindowScene*)pickStartupWindowScene:(NSSet<UIScene*>*)scenes API_AVAILABLE(ios(13.0), tvos(13.0))
  258. {
  259. // if we have scene with UISceneActivationStateForegroundActive - pick it
  260. // otherwise UISceneActivationStateForegroundInactive will work
  261. // it will be the scene going into active state
  262. // if there were no active/inactive scenes (only background) we should allow background scene
  263. // this might happen in some cases with native plugins doing "things"
  264. UIWindowScene *foregroundScene = nil, *backgroundScene = nil;
  265. for (UIScene* scene in scenes)
  266. {
  267. if (![scene isKindOfClass: [UIWindowScene class]])
  268. continue;
  269. UIWindowScene* windowScene = (UIWindowScene*)scene;
  270. if (scene.activationState == UISceneActivationStateForegroundActive)
  271. return windowScene;
  272. if (scene.activationState == UISceneActivationStateForegroundInactive)
  273. foregroundScene = windowScene;
  274. else if (scene.activationState == UISceneActivationStateBackground)
  275. backgroundScene = windowScene;
  276. }
  277. return foregroundScene ? foregroundScene : backgroundScene;
  278. }
  279. #endif
  280. - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
  281. {
  282. ::printf("-> applicationDidFinishLaunching()\n");
  283. [SPSDKInstance application:application didFinishLaunchingWithOptions:launchOptions];
  284. // send notfications
  285. #if !PLATFORM_TVOS
  286. #pragma clang diagnostic push
  287. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  288. if (UILocalNotification* notification = [launchOptions objectForKey: UIApplicationLaunchOptionsLocalNotificationKey])
  289. UnitySendLocalNotification(notification);
  290. if ([UIDevice currentDevice].generatesDeviceOrientationNotifications == NO)
  291. [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
  292. #pragma clang diagnostic pop
  293. #endif
  294. if ([self isBackgroundLaunchOptions: launchOptions])
  295. return YES;
  296. [self initUnityWithApplication: application];
  297. return YES;
  298. }
  299. - (BOOL)isBackgroundLaunchOptions:(NSDictionary*)launchOptions
  300. {
  301. if (launchOptions.count == 0)
  302. return NO;
  303. // launch due to location event, the app likely will stay in background
  304. BOOL locationLaunch = [[launchOptions valueForKey: UIApplicationLaunchOptionsLocationKey] boolValue];
  305. if (locationLaunch)
  306. return YES;
  307. return NO;
  308. }
  309. - (void)initUnityApplicationNoGraphics
  310. {
  311. if (_unityEngineLoaded)
  312. return;
  313. _unityEngineLoaded = true;
  314. UnityInitApplicationNoGraphics(UnityDataBundleDir());
  315. }
  316. - (void)initUnityWithApplication:(UIApplication*)application
  317. {
  318. if (_unityEngineInitialized)
  319. return;
  320. _unityEngineInitialized = true;
  321. // basic unity init
  322. [self initUnityApplicationNoGraphics];
  323. [self selectRenderingAPI];
  324. [UnityRenderingView InitializeForAPI: self.renderingAPI];
  325. #if (PLATFORM_IOS && defined(__IPHONE_13_0)) || (PLATFORM_TVOS && defined(__TVOS_13_0))
  326. if (@available(iOS 13, tvOS 13, *))
  327. _window = [[UIWindow alloc] initWithWindowScene: [self pickStartupWindowScene: application.connectedScenes]];
  328. else
  329. #endif
  330. _window = [[UIWindow alloc] initWithFrame: [UIScreen mainScreen].bounds];
  331. _unityView = [self createUnityView];
  332. [DisplayManager Initialize];
  333. _mainDisplay = [DisplayManager Instance].mainDisplay;
  334. [_mainDisplay createWithWindow: _window andView: _unityView];
  335. [self createUI];
  336. [self preStartUnity];
  337. // if you wont use keyboard you may comment it out at save some memory
  338. [KeyboardDelegate Initialize];
  339. #if UNITY_DEVELOPER_BUILD
  340. // Causes a black screen after splash screen, but would deadlock if waiting for manged debugger otherwise
  341. [self performSelector: @selector(startUnity:) withObject: application afterDelay: 0];
  342. #else
  343. [self startUnity: application];
  344. #endif
  345. }
  346. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey, id> *)change context:(void *)context
  347. {
  348. if ([keyPath isEqual: @"outputVolume"])
  349. {
  350. UnityUpdateMuteState([[AVAudioSession sharedInstance] outputVolume] < 0.01f ? 1 : 0);
  351. }
  352. }
  353. - (void)applicationDidEnterBackground:(UIApplication*)application
  354. {
  355. ::printf("-> applicationDidEnterBackground()\n");
  356. [SPSDKInstance applicationDidEnterBackground:application];
  357. }
  358. - (void)applicationWillEnterForeground:(UIApplication*)application
  359. {
  360. ::printf("-> applicationWillEnterForeground()\n");
  361. [SPSDKInstance applicationWillEnterForeground:application];
  362. // applicationWillEnterForeground: might sometimes arrive *before* actually initing unity (e.g. locking on startup)
  363. if (_unityAppReady)
  364. {
  365. // if we were showing video before going to background - the view size may be changed while we are in background
  366. [GetAppController().unityView recreateRenderingSurfaceIfNeeded];
  367. }
  368. }
  369. - (void)applicationDidBecomeActive:(UIApplication*)application
  370. {
  371. ::printf("-> applicationDidBecomeActive()\n");
  372. [SPSDKInstance applicationDidBecomeActive:application];
  373. [self removeSnapshotViewController];
  374. if (_unityAppReady)
  375. {
  376. if (UnityIsPaused() && _wasPausedExternal == false)
  377. {
  378. UnityWillResume();
  379. UnityPause(0);
  380. }
  381. if (_wasPausedExternal)
  382. {
  383. if (UnityIsFullScreenPlaying())
  384. TryResumeFullScreenVideo();
  385. }
  386. // need to do this with delay because FMOD restarts audio in AVAudioSessionInterruptionNotification handler
  387. [self performSelector: @selector(updateUnityAudioOutput) withObject: nil afterDelay: 0.1];
  388. UnitySetPlayerFocus(1);
  389. }
  390. else
  391. {
  392. [self initUnityWithApplication: application];
  393. }
  394. _didResignActive = false;
  395. }
  396. - (void)updateUnityAudioOutput
  397. {
  398. UnityUpdateMuteState([[AVAudioSession sharedInstance] outputVolume] < 0.01f ? 1 : 0);
  399. }
  400. - (void)addSnapshotViewController
  401. {
  402. if (!_didResignActive || self->_snapshotViewController)
  403. {
  404. return;
  405. }
  406. UIView* snapshotView = [self createSnapshotView];
  407. if (snapshotView != nil)
  408. {
  409. UIViewController* snapshotViewController = [AllocUnityViewController() init];
  410. snapshotViewController.modalPresentationStyle = UIModalPresentationFullScreen;
  411. snapshotViewController.view = snapshotView;
  412. [self->_rootController presentViewController: snapshotViewController animated: false completion: nil];
  413. self->_snapshotViewController = snapshotViewController;
  414. }
  415. }
  416. - (void)removeSnapshotViewController
  417. {
  418. // do this on the main queue async so that if we try to create one
  419. // and remove in the same frame, this always happens after in the same queue
  420. dispatch_async(dispatch_get_main_queue(), ^{
  421. if (self->_snapshotViewController)
  422. {
  423. // we've got a view on top of the snapshot view (3rd party plugin/social media login etc).
  424. if (self->_snapshotViewController.presentedViewController)
  425. {
  426. [self performSelector: @selector(removeSnapshotViewController) withObject: nil afterDelay: 0.05];
  427. return;
  428. }
  429. [self->_snapshotViewController dismissViewControllerAnimated: NO completion: nil];
  430. self->_snapshotViewController = nil;
  431. // Make sure that the keyboard input field regains focus after the application becomes active.
  432. [[KeyboardDelegate Instance] becomeFirstResponder];
  433. }
  434. });
  435. }
  436. - (void)applicationWillResignActive:(UIApplication*)application
  437. {
  438. ::printf("-> applicationWillResignActive()\n");
  439. [SPSDKInstance applicationWillResignActive:application];
  440. if (_unityAppReady)
  441. {
  442. UnitySetPlayerFocus(0);
  443. // signal unity that the frame rendering have ended
  444. // as we will not get the callback from the display link current frame
  445. UnityDisplayLinkCallback(0);
  446. _wasPausedExternal = UnityIsPaused();
  447. if (_wasPausedExternal == false)
  448. {
  449. // Pause Unity only if we don't need special background processing
  450. // otherwise batched player loop can be called to run user scripts.
  451. if (!UnityGetUseCustomAppBackgroundBehavior())
  452. {
  453. #if UNITY_SNAPSHOT_VIEW_ON_APPLICATION_PAUSE
  454. // Force player to do one more frame, so scripts get a chance to render custom screen for minimized app in task manager.
  455. // NB: UnityWillPause will schedule OnApplicationPause message, which will be sent normally inside repaint (unity player loop)
  456. // NB: We will actually pause after the loop (when calling UnityPause).
  457. UnityWillPause();
  458. [self repaint];
  459. UnityWaitForFrame();
  460. [self addSnapshotViewController];
  461. #endif
  462. UnityPause(1);
  463. }
  464. }
  465. }
  466. _didResignActive = true;
  467. }
  468. - (void)applicationDidReceiveMemoryWarning:(UIApplication*)application
  469. {
  470. // We handle it by subscribing for notification, this one is only a placeholder for stuff like forwarding in UaaL setups
  471. }
  472. - (void)applicationWillTerminate:(UIApplication*)application
  473. {
  474. ::printf("-> applicationWillTerminate()\n");
  475. [SPSDKInstance applicationWillTerminate:application];
  476. // Only clean up if Unity has finished initializing, else the clean up process will crash,
  477. // this happens if the app is force closed immediately after opening it.
  478. if (_unityAppReady)
  479. {
  480. UnityCleanup();
  481. UnityCleanupTrampoline();
  482. }
  483. }
  484. - (void)application:(UIApplication*)application handleEventsForBackgroundURLSession:(nonnull NSString *)identifier completionHandler:(nonnull void (^)())completionHandler
  485. {
  486. NSDictionary* arg = @{identifier: completionHandler};
  487. AppController_SendNotificationWithArg(kUnityHandleEventsForBackgroundURLSession, arg);
  488. }
  489. @end
  490. void AppController_SendNotification(NSString* name)
  491. {
  492. [[NSNotificationCenter defaultCenter] postNotificationName: name object: GetAppController()];
  493. }
  494. void AppController_SendNotificationWithArg(NSString* name, id arg)
  495. {
  496. [[NSNotificationCenter defaultCenter] postNotificationName: name object: GetAppController() userInfo: arg];
  497. }
  498. void AppController_SendUnityViewControllerNotification(NSString* name)
  499. {
  500. [[NSNotificationCenter defaultCenter] postNotificationName: name object: UnityGetGLViewController()];
  501. }
  502. extern "C" UIWindow* UnityGetMainWindow()
  503. {
  504. return GetAppController().mainDisplay.window;
  505. }
  506. extern "C" UIViewController* UnityGetGLViewController()
  507. {
  508. return GetAppController().rootViewController;
  509. }
  510. extern "C" UIView* UnityGetGLView()
  511. {
  512. return GetAppController().unityView;
  513. }
  514. extern "C" ScreenOrientation UnityCurrentOrientation() { return GetAppController().unityView.contentOrientation; }
  515. bool LogToNSLogHandler(LogType logType, const char* log, va_list list)
  516. {
  517. NSLogv([NSString stringWithUTF8String: log], list);
  518. return true;
  519. }
  520. static void AddNewAPIImplIfNeeded();
  521. // From https://stackoverflow.com/questions/4744826/detecting-if-ios-app-is-run-in-debugger
  522. static bool isDebuggerAttachedToConsole(void)
  523. // Returns true if the current process is being debugged (either
  524. // running under the debugger or has a debugger attached post facto).
  525. {
  526. int junk;
  527. int mib[4];
  528. struct kinfo_proc info;
  529. size_t size;
  530. // Initialize the flags so that, if sysctl fails for some bizarre
  531. // reason, we get a predictable result.
  532. info.kp_proc.p_flag = 0;
  533. // Initialize mib, which tells sysctl the info we want, in this case
  534. // we're looking for information about a specific process ID.
  535. mib[0] = CTL_KERN;
  536. mib[1] = KERN_PROC;
  537. mib[2] = KERN_PROC_PID;
  538. mib[3] = getpid();
  539. // Call sysctl.
  540. size = sizeof(info);
  541. junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);
  542. assert(junk == 0);
  543. // We're being debugged if the P_TRACED flag is set.
  544. return ((info.kp_proc.p_flag & P_TRACED) != 0);
  545. }
  546. void UnityInitTrampoline()
  547. {
  548. InitCrashHandling();
  549. NSString* version = [[UIDevice currentDevice] systemVersion];
  550. #define CHECK_VER(s) [version compare: s options: NSNumericSearch] != NSOrderedAscending
  551. _ios81orNewer = CHECK_VER(@"8.1"); _ios82orNewer = CHECK_VER(@"8.2"); _ios83orNewer = CHECK_VER(@"8.3");
  552. _ios90orNewer = CHECK_VER(@"9.0"); _ios91orNewer = CHECK_VER(@"9.1");
  553. _ios100orNewer = CHECK_VER(@"10.0"); _ios101orNewer = CHECK_VER(@"10.1"); _ios102orNewer = CHECK_VER(@"10.2"); _ios103orNewer = CHECK_VER(@"10.3");
  554. _ios110orNewer = CHECK_VER(@"11.0"); _ios111orNewer = CHECK_VER(@"11.1"); _ios112orNewer = CHECK_VER(@"11.2");
  555. _ios130orNewer = CHECK_VER(@"13.0"); _ios140orNewer = CHECK_VER(@"14.0"); _ios150orNewer = CHECK_VER(@"15.0");
  556. _ios160orNewer = CHECK_VER(@"16.0");
  557. #undef CHECK_VER
  558. AddNewAPIImplIfNeeded();
  559. #if !TARGET_IPHONE_SIMULATOR
  560. // Use NSLog logging if a debugger is not attached, otherwise we write to stdout.
  561. if (!isDebuggerAttachedToConsole())
  562. UnitySetLogEntryHandler(LogToNSLogHandler);
  563. #endif
  564. }
  565. extern "C" bool UnityiOS81orNewer() { return _ios81orNewer; }
  566. extern "C" bool UnityiOS82orNewer() { return _ios82orNewer; }
  567. extern "C" bool UnityiOS90orNewer() { return _ios90orNewer; }
  568. extern "C" bool UnityiOS91orNewer() { return _ios91orNewer; }
  569. extern "C" bool UnityiOS100orNewer() { return _ios100orNewer; }
  570. extern "C" bool UnityiOS101orNewer() { return _ios101orNewer; }
  571. extern "C" bool UnityiOS102orNewer() { return _ios102orNewer; }
  572. extern "C" bool UnityiOS103orNewer() { return _ios103orNewer; }
  573. extern "C" bool UnityiOS110orNewer() { return _ios110orNewer; }
  574. extern "C" bool UnityiOS111orNewer() { return _ios111orNewer; }
  575. extern "C" bool UnityiOS112orNewer() { return _ios112orNewer; }
  576. extern "C" bool UnityiOS130orNewer() { return _ios130orNewer; }
  577. extern "C" bool UnityiOS140orNewer() { return _ios140orNewer; }
  578. extern "C" bool UnityiOS150orNewer() { return _ios150orNewer; }
  579. extern "C" bool UnityiOS160orNewer() { return _ios160orNewer; }
  580. // sometimes apple adds new api with obvious fallback on older ios.
  581. // in that case we simply add these functions ourselves to simplify code
  582. static void AddNewAPIImplIfNeeded()
  583. {
  584. if (![[UIScreen class] instancesRespondToSelector: @selector(maximumFramesPerSecond)])
  585. {
  586. IMP UIScreen_MaximumFramesPerSecond_IMP = imp_implementationWithBlock(^NSInteger(id _self) {
  587. return 60;
  588. });
  589. class_replaceMethod([UIScreen class], @selector(maximumFramesPerSecond), UIScreen_MaximumFramesPerSecond_IMP, UIScreen_maximumFramesPerSecond_Enc);
  590. }
  591. if (![[UIView class] instancesRespondToSelector: @selector(safeAreaInsets)])
  592. {
  593. IMP UIView_SafeAreaInsets_IMP = imp_implementationWithBlock(^UIEdgeInsets(id _self) {
  594. return UIEdgeInsetsZero;
  595. });
  596. class_replaceMethod([UIView class], @selector(safeAreaInsets), UIView_SafeAreaInsets_IMP, UIView_safeAreaInsets_Enc);
  597. }
  598. }
  599. // xcode11 uses new compiler-rt lib
  600. // if we build unity player lib with xcode11 and then user links final project with older xcode
  601. // the link fails with Undefined Symbol ___isPlatformVersionAtLeast
  602. // hence we add this as a temporary hack until we start requiring xcode11
  603. #if __clang_major__ < 11
  604. extern "C" int32_t __isOSVersionAtLeast(int32_t Major, int32_t Minor, int32_t Subminor);
  605. extern "C" int32_t __isPlatformVersionAtLeast(uint32_t Platform, uint32_t Major, uint32_t Minor, uint32_t Subminor)
  606. {
  607. return __isOSVersionAtLeast(Major, Minor, Subminor);
  608. }
  609. #endif
  610. // starting with xcode 11.4 apple changed FD_SET and related macro to use weakly imported __darwin_check_fd_set_overflow
  611. // alas if we build xcode project with OLDER xcode this function is missing
  612. // and we build unity lib with xcode11+, thus producing linker error
  613. // we mimic the logic of apple sdk itself (this part is open sourced):
  614. // if __darwin_check_fd_set_overflow is not present the caller returns 1, so do we
  615. #ifndef __IPHONE_13_4
  616. extern "C" int __darwin_check_fd_set_overflow(int, const void *, int)
  617. {
  618. return 1;
  619. }
  620. #endif