UnityAppController+ViewHandling.mm 21 KB

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