UnityAppController+ViewHandling.mm 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. #include "UnityAppController+ViewHandling.h"
  2. #include "UnityAppController+Rendering.h"
  3. #include "UI/OrientationSupport.h"
  4. #include "UI/UnityView.h"
  5. #include "UI/UnityViewControllerBase.h"
  6. #include "Unity/DisplayManager.h"
  7. // TEMP: ?
  8. #include "UI/ActivityIndicator.h"
  9. #include "UI/Keyboard.h"
  10. #include <utility>
  11. extern bool _skipPresent;
  12. extern bool _unityAppReady;
  13. static BOOL _shouldUseDefaultViewControllerForFixedOrientations = NO;
  14. @implementation UnityAppController (ViewHandling)
  15. #if UNITY_SUPPORT_ROTATION
  16. // special case for when we DO know the app orientation, but dont get it through normal mechanism (UIViewController orientation handling)
  17. // how can this happen:
  18. // 1. On startup: ios is not sending "change orientation" notifications on startup (but rather we "start" in correct one already)
  19. // 2. When using presentation controller it can override orientation constraints, so on dismissing we need to tweak app orientation;
  20. // pretty much like startup situation UIViewController would have correct orientation, and app will be out-of-sync
  21. - (void)updateAppOrientation:(UIInterfaceOrientation)orientation
  22. {
  23. // update our (AppContoller) view of orientation
  24. _curOrientation = orientation;
  25. // do unity view "orientation magic"
  26. [_unityView willRotateToOrientation: orientation fromOrientation: (UIInterfaceOrientation)UIInterfaceOrientationUnknown];
  27. [_unityView didRotate];
  28. // after we have updated unity view, this will poke unity itself about the changes in orient/extents
  29. [_unityView boundsUpdated];
  30. }
  31. #endif
  32. - (UnityView*)createUnityView
  33. {
  34. return [[UnityView alloc] initFromMainScreen];
  35. }
  36. - (UIViewController*)createUnityViewControllerDefault
  37. {
  38. #if PLATFORM_IOS
  39. UnityViewControllerBase* ret = [[UnityDefaultViewController alloc] initShouldHandleFixedOrientation: _shouldUseDefaultViewControllerForFixedOrientations];
  40. #else
  41. UnityViewControllerBase* ret = [[UnityDefaultViewController alloc] init];
  42. #endif
  43. ret.notificationDelegate = [[UnityViewControllerNotificationsDefaultSender alloc] init];
  44. #if PLATFORM_TVOS
  45. ret.controllerUserInteractionEnabled = YES;
  46. #endif
  47. return ret;
  48. }
  49. #if UNITY_SUPPORT_ROTATION
  50. - (UIViewController*)createUnityViewControllerForOrientation:(UIInterfaceOrientation)orient
  51. {
  52. UnityViewControllerBase* ret = [AllocUnitySingleOrientationViewController(orient) init];
  53. ret.notificationDelegate = [[UnityViewControllerNotificationsDefaultSender alloc] init];
  54. return ret;
  55. }
  56. #endif
  57. - (UIViewController*)createRootViewController
  58. {
  59. UIViewController* ret = nil;
  60. if (!UNITY_SUPPORT_ROTATION || UnityShouldAutorotate() || _shouldUseDefaultViewControllerForFixedOrientations)
  61. ret = [self createUnityViewControllerDefault];
  62. #if UNITY_SUPPORT_ROTATION
  63. if (ret == nil)
  64. ret = [self createRootViewControllerForOrientation: ConvertToIosScreenOrientation((ScreenOrientation)UnityRequestedScreenOrientation())];
  65. #endif
  66. return ret;
  67. }
  68. - (UIViewController*)topMostController
  69. {
  70. UIViewController *topController = self.window.rootViewController;
  71. while (topController.presentedViewController)
  72. topController = topController.presentedViewController;
  73. return topController;
  74. }
  75. - (void)willStartWithViewController:(UIViewController*)controller
  76. {
  77. #if !PLATFORM_VISIONOS
  78. _unityView.contentScaleFactor = UnityScreenScaleFactor([UIScreen mainScreen]);
  79. #else
  80. _unityView.contentScaleFactor = 1.0f;
  81. #endif
  82. _unityView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  83. _rootController.view = _rootView = _unityView;
  84. }
  85. - (void)willTransitionToViewController:(UIViewController*)toController fromViewController:(UIViewController*)fromController
  86. {
  87. }
  88. - (void)didTransitionToViewController:(UIViewController*)toController fromViewController:(UIViewController*)fromController
  89. {
  90. #if UNITY_SUPPORT_ROTATION && !PLATFORM_VISIONOS
  91. // when transitioning between view controllers ios will not send reorient events (because they are bound to controllers, not view)
  92. // so we imitate them here so unity view can update its size/orientation
  93. UIInterfaceOrientation newOrientation = UIViewControllerInterfaceOrientation(toController);
  94. [_unityView willRotateToOrientation: newOrientation fromOrientation: ConvertToIosScreenOrientation(_unityView.contentOrientation)];
  95. [_unityView didRotate];
  96. // NB: this is both important and insane at the same time (that we have several places to keep current orentation and we need to sync them)
  97. _curOrientation = newOrientation;
  98. #endif
  99. }
  100. - (UIView*)createSnapshotView
  101. {
  102. // Note that on iPads with iOS 9 or later (up to iOS 10.2 at least) there's a bug in the iOS compositor: any use of -[UIView snapshotViewAfterScreenUpdates]
  103. // causes black screen being shown temporarily when 4 finger gesture to swipe to another app in the task switcher is being performed slowly
  104. return [_rootView snapshotViewAfterScreenUpdates: YES];
  105. }
  106. - (void)createUI
  107. {
  108. NSAssert(_unityView != nil, @"_unityView should be inited at this point");
  109. NSAssert(_window != nil, @"_window should be inited at this point");
  110. if (@available(iOS 16.0, *)) _shouldUseDefaultViewControllerForFixedOrientations = YES;
  111. else _shouldUseDefaultViewControllerForFixedOrientations = NO;
  112. _rootController = [self createRootViewController];
  113. [self willStartWithViewController: _rootController];
  114. NSAssert(_rootView != nil, @"_rootView should be inited at this point");
  115. NSAssert(_rootController != nil, @"_rootController should be inited at this point");
  116. // CODE ARCHEOLOGY: We used to add _rootView (unityView) to the subviews of _window so that unityView would get its
  117. // initial actual device values (e.g. safeAreaInsets) before initializing graphics. This is not needed anymore after
  118. // we made a change where iOS is handling splash screen. Now unityView will be configured at
  119. // [_window makeKeyAndVisible] call. makeKeyAndVisible will configure _window.rootViewController.view, which is
  120. // _rootController.view, which is unityView (_rootView)
  121. // We should have rootViewController set always, otherwise UIKit might trow exception when doing anything with UI
  122. _window.rootViewController = _rootController;
  123. [UIView setAnimationsEnabled: NO];
  124. // make window visible only after we have set up initial controller we want to show
  125. [_window makeKeyAndVisible];
  126. #if UNITY_SUPPORT_ROTATION
  127. // to be able to query orientation from view controller we should actually show it.
  128. // at this point we can only show splash screen, so update app orientation after we started showing it
  129. // NB: _window.rootViewController = splash view controller (not _rootController)
  130. [self updateAppOrientation: ConvertToIosScreenOrientation(UIViewControllerOrientation(_window.rootViewController))];
  131. #endif
  132. NSNumber* style = [[[NSBundle mainBundle] infoDictionary] objectForKey: @"Unity_LoadingActivityIndicatorStyle"];
  133. ShowActivityIndicator(_rootView, style ? [style intValue] : -1);
  134. NSNumber* vcControlled = [[[NSBundle mainBundle] infoDictionary] objectForKey: @"UIViewControllerBasedStatusBarAppearance"];
  135. if (vcControlled && ![vcControlled boolValue])
  136. printf_console("\nSetting UIViewControllerBasedStatusBarAppearance to NO is no longer supported.\n"
  137. "Apple actively discourages that, and all application-wide methods of changing status bar appearance are deprecated\n\n"
  138. );
  139. }
  140. - (void)showGameUI
  141. {
  142. HideActivityIndicator();
  143. // make sure that we start up with correctly created/inited rendering surface
  144. // NB: recreateRenderingSurface won't go into rendering because _unityAppReady is false
  145. #if UNITY_SUPPORT_ROTATION
  146. [self checkOrientationRequest];
  147. #endif
  148. [_unityView recreateRenderingSurface];
  149. // UI hierarchy
  150. _window.rootViewController = _rootController;
  151. [_window bringSubviewToFront: _rootView];
  152. #if UNITY_SUPPORT_ROTATION
  153. // to be able to query orientation from view controller we should actually show it.
  154. // at this point we finally started to show game view controller. Just in case update orientation again
  155. [self updateAppOrientation: ConvertToIosScreenOrientation(UIViewControllerOrientation(_rootController))];
  156. #endif
  157. // why we set level ready only now:
  158. // surface recreate will try to repaint if this var is set (poking unity to do it)
  159. // but this frame now is actually the first one we want to process/draw
  160. // so all the recreateSurface before now (triggered by reorientation) should simply change extents
  161. _unityAppReady = true;
  162. // why we skip present:
  163. // this will be the first frame to draw, so Start methods will be called
  164. // and we want to properly handle resolution request in Start (which might trigger surface recreate)
  165. // NB: we want to draw right after showing window, to avoid black frame creeping in
  166. _skipPresent = true;
  167. if (!UnityIsPaused())
  168. UnityRepaint();
  169. _skipPresent = false;
  170. [self repaint];
  171. [UIView setAnimationsEnabled: YES];
  172. }
  173. #if UNITY_SUPPORT_ROTATION
  174. - (void)transitionToViewController:(UIViewController*)vc
  175. {
  176. [self willTransitionToViewController: vc fromViewController: _rootController];
  177. // first: remove from view hierarchy.
  178. // if we simply hide the window before assigning the new view controller, it will cause black frame flickering
  179. // on the other hand, hiding the window is important by itself to better signal the intent to iOS
  180. // e.g. unless we hide the window view, safeArea might stop working (due to bug in iOS if we're to speculate)
  181. // due to that we do this hide/unhide sequence: we want to to make it hidden, but still unhide it before changing window view controller.
  182. _window.hidden = YES;
  183. _window.hidden = NO;
  184. _rootController.view = nil;
  185. _window.rootViewController = nil;
  186. // second: assign new root controller (and view hierarchy with that), restore bounds
  187. // this is very important to first set _rootController, and only then window root controller
  188. // as the latter will poke [UIApplicationDelegate application:supportedInterfaceOrientationsForWindow:]
  189. // and unity implementation expects _rootController to be already set
  190. _window.rootViewController = _rootController = vc;
  191. _rootController.view = _rootView;
  192. // CODE ARCHEOLOGY: in here we were tweaking window bounds to agree with screen bounds (and did some iOS8 specific workaround)
  193. // This is no longer needed it seems, and is actually harmful for the "split view" supporting apps
  194. // If you have fullscreen window, it will be automatically resized to take the whole screen
  195. // and otherwise we must not touch it, as it will be controlled by multitasking
  196. // third: restore window as key and layout subviews to finalize size changes
  197. [_window makeKeyAndVisible];
  198. [_window layoutSubviews];
  199. // In iOS16+ after we setup a new contoller and when we have multiple windows visible, iOS not fully prepares
  200. // view controller according it's orientation requirements. And then inside didTransitionToViewController:
  201. // from UIViewControllerInterfaceOrientation we get bad orientation as it uses scree.coordinationSpace which is not
  202. // yet changed. So we want to delay didTransitionToViewController call. And in this case we get a call to view
  203. // controllers -viewWillTransitionToSize: method and at this time the orientation change is already happened and
  204. // then we send didTransitionToViewController. If view controller changes are setup correctly from iOS, then iOS do
  205. // not call -viewWillTransitionToSize:.
  206. UIInterfaceOrientation newOrientation = UIViewControllerInterfaceOrientation(vc);
  207. BOOL orientationChangedToSupported = vc.supportedInterfaceOrientations & (1 << newOrientation);
  208. if (!UnityiOS160orNewer() || orientationChangedToSupported)
  209. {
  210. [self didTransitionToViewController: vc fromViewController: _rootController];
  211. }
  212. }
  213. - (void)interfaceWillChangeOrientationTo:(UIInterfaceOrientation)toInterfaceOrientation
  214. {
  215. UIInterfaceOrientation fromInterfaceOrientation = _curOrientation;
  216. _curOrientation = toInterfaceOrientation;
  217. [_unityView willRotateToOrientation: toInterfaceOrientation fromOrientation: fromInterfaceOrientation];
  218. }
  219. - (void)interfaceDidChangeOrientationFrom:(UIInterfaceOrientation)fromInterfaceOrientation
  220. {
  221. [_unityView didRotate];
  222. }
  223. #endif
  224. - (void)notifyHideHomeButtonChange
  225. {
  226. #if PLATFORM_IOS || PLATFORM_VISIONOS
  227. // setNeedsUpdateOfHomeIndicatorAutoHidden is not implemented on iOS 11.0.
  228. // The bug has been fixed in iOS 11.0.1. See http://www.openradar.me/35127134
  229. if ([_rootController respondsToSelector: @selector(setNeedsUpdateOfHomeIndicatorAutoHidden)])
  230. [_rootController setNeedsUpdateOfHomeIndicatorAutoHidden];
  231. #endif
  232. }
  233. - (void)notifyDeferSystemGesturesChange
  234. {
  235. #if PLATFORM_IOS || PLATFORM_VISIONOS
  236. [_rootController setNeedsUpdateOfScreenEdgesDeferringSystemGestures];
  237. #endif
  238. }
  239. @end
  240. #if UNITY_SUPPORT_ROTATION
  241. @implementation UnityAppController (OrientationSupport)
  242. - (UIViewController*)createRootViewControllerForOrientation:(UIInterfaceOrientation)orientation
  243. {
  244. return [self createUnityViewControllerForOrientation: orientation];
  245. }
  246. - (void)checkOrientationRequest
  247. {
  248. // if no orientation/allowed-orientation change - do nothing
  249. if (!UnityHasOrientationRequest() && !UnityShouldChangeAllowedOrientations())
  250. return;
  251. // if there is a presentation controller, it takes over orientation control
  252. // in this case we should completely ignore all orientation changes
  253. // mind you, we just *delay* them, and they will be satisfied once presentation controller is dismissed
  254. // extra care like this is needed, because below we might recreate ViewController completely breaking
  255. // presentation controller dismissal
  256. if (_rootController.presentedViewController)
  257. return;
  258. // to reiterate: we have different processing on newish iOS where we stick to just one view controller
  259. // in this case we leave all the processing to iOS
  260. if(_shouldUseDefaultViewControllerForFixedOrientations)
  261. {
  262. NSAssert([self.rootViewController isKindOfClass: [UnityDefaultViewController class]],
  263. @"UnityDefaultViewController should be root controller");
  264. [(UnityDefaultViewController*)self.rootViewController updateSupportedOrientations];
  265. [UIViewController attemptRotationToDeviceOrientation];
  266. // note that we could have a big if-else block and call it once at the end of the method
  267. // but it was deemed too ugly
  268. UnityOrientationRequestWasCommitted();
  269. return;
  270. }
  271. // normally we want to call attemptRotationToDeviceOrientation to tell iOS that we changed orientation constraints
  272. // but if the current orientation is disabled we need special processing, as iOS will simply ignore us
  273. // the only good/robust way is to simply recreate "autorotating" view controller and transition to it if needed
  274. // please note that we want to trigger "orientation request" code path if we recreate autorotating view controller
  275. bool changeOrient = UnityHasOrientationRequest();
  276. // if we should recreate autorotating view controller - see below
  277. bool shouldTransferToNewAutorotVC = false;
  278. // first we check if we need to update orientations enabled for autorotation
  279. // this needs to be done *only* if we are to continue autorotating
  280. // otherwise we will transition from this view controller
  281. // and iOS will reread enabled orientations on next ViewController activation
  282. const bool autorot = UnityShouldAutorotate(), autorotChanged = UnityAutorotationStatusChanged();
  283. if (UnityShouldChangeAllowedOrientations() && autorot)
  284. {
  285. NSUInteger rootOrient = 1 << UIViewControllerInterfaceOrientation(self.rootViewController);
  286. if (!autorotChanged && (rootOrient & EnabledAutorotationInterfaceOrientations()))
  287. {
  288. // instead of querying unity for supported orientations, we keep them in the default (autorotating) controller
  289. // this is THE place where we should update those (otherwise, filled on creation)
  290. if ([self.rootViewController isKindOfClass: [UnityDefaultViewController class]])
  291. [(UnityDefaultViewController*)self.rootViewController updateSupportedOrientations];
  292. // if we are currently autorotating AND changed allowed orientations while keeping current interface orientation allowed:
  293. // we can simply trigger attemptRotationToDeviceOrientation and we are done
  294. // please note that this can happen when current *device* orientation is disabled (and we want to enable it)
  295. [UIViewController attemptRotationToDeviceOrientation];
  296. }
  297. else
  298. {
  299. // otherwise we recreate default autorotating view controller
  300. // to spell it out, we recreate if:
  301. // - we continue doing autorotation, but the current orientation is disabled
  302. // - we were not autorotating but start now
  303. shouldTransferToNewAutorotVC = true;
  304. changeOrient = true;
  305. }
  306. }
  307. if (changeOrient)
  308. {
  309. // on some devices like iPhone XS layoutSubview is not called when transitioning from different orientations with the same resolution
  310. // therefore forcing layoutSubview on all orientation changes
  311. [_unityView setNeedsLayout];
  312. if (autorot)
  313. {
  314. // just started autorotating or decided to recreate autorot controller above
  315. if (autorotChanged || shouldTransferToNewAutorotVC)
  316. [self transitionToViewController: [self createUnityViewControllerDefault]];
  317. [UIViewController attemptRotationToDeviceOrientation];
  318. }
  319. else
  320. {
  321. UIInterfaceOrientation requestedOrient = ConvertToIosScreenOrientation((ScreenOrientation)UnityRequestedScreenOrientation());
  322. // on one hand orientInterface: should be perfectly fine "reorienting" to current orientation
  323. // in reality, ios might be confused by transitionToViewController: shenanigans coupled with "nothing have changed actually"
  324. // as an example: prior to ios12 that might result in status bar going "bad" (becoming transparent)
  325. // NOTE: if we have switched from autorotation to fixed orientation, we must do the switch to pick new VC
  326. if (_curOrientation != requestedOrient || autorotChanged)
  327. [self orientInterface: requestedOrient];
  328. }
  329. }
  330. UnityOrientationRequestWasCommitted();
  331. }
  332. - (void)orientInterface:(UIInterfaceOrientation)orient
  333. {
  334. if (_unityAppReady)
  335. UnityFinishRendering();
  336. [KeyboardDelegate StartReorientation];
  337. [CATransaction begin];
  338. {
  339. UIInterfaceOrientation oldOrient = _curOrientation;
  340. UIInterfaceOrientation newOrient = orient;
  341. [self interfaceWillChangeOrientationTo: newOrient];
  342. // TODO: we should handle _shouldUseDefaultViewControllerForFixedOrientations = YES
  343. // TODO: though i am not sure how this should be done
  344. // TODO: currently in normal orientation processing this will not be called when _shouldUseDefaultViewControllerForFixedOrientations is true
  345. // TODO: but native plugins can still call it directly
  346. [self transitionToViewController: [self createRootViewControllerForOrientation: newOrient]];
  347. [self interfaceDidChangeOrientationFrom: oldOrient];
  348. #if !PLATFORM_VISIONOS
  349. [UIApplication sharedApplication].statusBarOrientation = orient;
  350. #endif
  351. }
  352. [CATransaction commit];
  353. [KeyboardDelegate FinishReorientation];
  354. }
  355. - (void)orientUnity:(UIInterfaceOrientation)orient
  356. {
  357. [self orientInterface: orient];
  358. }
  359. @end
  360. #endif
  361. extern "C" void UnityNotifyHideHomeButtonChange()
  362. {
  363. [GetAppController() notifyHideHomeButtonChange];
  364. }
  365. extern "C" void UnityNotifyDeferSystemGesturesChange()
  366. {
  367. [GetAppController() notifyDeferSystemGesturesChange];
  368. }