UnityAppController.mm 25 KB

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