1// Copyright 2015-present 650 Industries. All rights reserved. 2 3@import UIKit; 4 5#import "EXAnalytics.h" 6#import "EXAppLoader.h" 7#import "EXAppViewController.h" 8#import "EXAppLoadingProgressWindowController.h" 9#import "EXAppLoadingCancelView.h" 10#import "EXManagedAppSplashScreenViewProvider.h" 11#import "EXManagedAppSplashScreenConfigurationBuilder.h" 12#import "EXHomeAppSplashScreenViewProvider.h" 13#import "EXEnvironment.h" 14#import "EXErrorRecoveryManager.h" 15#import "EXErrorView.h" 16#import "EXFileDownloader.h" 17#import "EXKernel.h" 18#import "EXKernelUtil.h" 19#import "EXReactAppManager.h" 20#import "EXScreenOrientationManager.h" 21#import "EXVersions.h" 22#import "EXUpdatesManager.h" 23#import "EXUtil.h" 24 25#import <EXSplashScreen/EXSplashScreenService.h> 26#import <React/RCTUtils.h> 27#import <UMCore/UMModuleRegistryProvider.h> 28 29#if __has_include(<EXScreenOrientation/EXScreenOrientationRegistry.h>) 30#import <EXScreenOrientation/EXScreenOrientationRegistry.h> 31#endif 32 33 34#define EX_INTERFACE_ORIENTATION_USE_MANIFEST 0 35 36// when we encounter an error and auto-refresh, we may actually see a series of errors. 37// we only want to trigger refresh once, so we debounce refresh on a timer. 38const CGFloat kEXAutoReloadDebounceSeconds = 0.1; 39 40// in development only, some errors can happen before we even start loading 41// (e.g. certain packager errors, such as an invalid bundle url) 42// and we want to make sure not to cover the error with a loading view or other chrome. 43const CGFloat kEXDevelopmentErrorCoolDownSeconds = 0.1; 44 45NS_ASSUME_NONNULL_BEGIN 46 47@interface EXAppViewController () 48 <EXReactAppManagerUIDelegate, EXAppLoaderDelegate, EXErrorViewDelegate, EXAppLoadingCancelViewDelegate> 49 50@property (nonatomic, assign) BOOL isLoading; 51@property (nonatomic, assign) BOOL isBridgeAlreadyLoading; 52@property (nonatomic, weak) EXKernelAppRecord *appRecord; 53@property (nonatomic, strong) EXErrorView *errorView; 54@property (nonatomic, assign) UIInterfaceOrientationMask supportedInterfaceOrientations; // override super 55@property (nonatomic, strong) NSTimer *tmrAutoReloadDebounce; 56@property (nonatomic, strong) NSDate *dtmLastFatalErrorShown; 57@property (nonatomic, strong) NSMutableArray<UIViewController *> *backgroundedControllers; 58 59@property (nonatomic, assign) BOOL isStandalone; 60@property (nonatomic, assign) BOOL isHomeApp; 61 62/* 63 * Controller for handling all messages from bundler/fetcher. 64 * It shows another UIWindow with text and percentage progress. 65 * Enabled only in managed workflow or home when in development mode. 66 * It should appear once manifest is fetched. 67 */ 68@property (nonatomic, strong, nonnull) EXAppLoadingProgressWindowController *appLoadingProgressWindowController; 69 70/** 71 * SplashScreenViewProvider that is used only in managed workflow app. 72 * Managed app does not need any specific SplashScreenViewProvider as it uses generic one povided by the SplashScreen module. 73 * See also EXHomeAppSplashScreenViewProvider in self.viewDidLoad 74 */ 75@property (nonatomic, strong, nullable) EXManagedAppSplashScreenViewProvider *managedAppSplashScreenViewProvider; 76 77/* 78 * This view is available in managed apps run in Expo Client only. 79 * It is shown only before any managed app manifest is delivered by the app loader. 80 */ 81@property (nonatomic, strong, nullable) EXAppLoadingCancelView *appLoadingCancelView; 82 83@end 84 85@implementation EXAppViewController 86 87@synthesize supportedInterfaceOrientations = _supportedInterfaceOrientations; 88 89#pragma mark - Lifecycle 90 91- (instancetype)initWithAppRecord:(EXKernelAppRecord *)record 92{ 93 if (self = [super init]) { 94 _appRecord = record; 95 _supportedInterfaceOrientations = EX_INTERFACE_ORIENTATION_USE_MANIFEST; 96 _isStandalone = [EXEnvironment sharedEnvironment].isDetached; 97 } 98 return self; 99} 100 101- (void)dealloc 102{ 103 [self _invalidateRecoveryTimer]; 104 [[NSNotificationCenter defaultCenter] removeObserver:self]; 105} 106 107- (void)viewDidLoad 108{ 109 [super viewDidLoad]; 110 111 // EXKernel.appRegistry.homeAppRecord does not contain any homeAppRecord until this point, 112 // therefore we cannot move this property initialization to the constructor/initializer 113 _isHomeApp = _appRecord == [EXKernel sharedInstance].appRegistry.homeAppRecord; 114 115 // show LoadingCancelView in managed apps only 116 if (!self.isStandalone && !self.isHomeApp) { 117 self.appLoadingCancelView = [EXAppLoadingCancelView new]; 118 // if home app is available then LoadingCancelView can show `go to home` button 119 if ([EXKernel sharedInstance].appRegistry.homeAppRecord) { 120 self.appLoadingCancelView.delegate = self; 121 } 122 [self.view addSubview:self.appLoadingCancelView]; 123 [self.view bringSubviewToFront:self.appLoadingCancelView]; 124 } 125 126 // show LoadingProgressWindow in the development client for all apps other than production home 127 BOOL isProductionHomeApp = self.isHomeApp && ![EXEnvironment sharedEnvironment].isDebugXCodeScheme; 128 self.appLoadingProgressWindowController = [[EXAppLoadingProgressWindowController alloc] initWithEnabled:!self.isStandalone && !isProductionHomeApp]; 129 130 // show SplashScreen in standalone apps and home app only 131 // SplashScreen for managed is shown once the manifest is available 132 if (self.isHomeApp) { 133 EXHomeAppSplashScreenViewProvider *homeAppSplashScreenViewProvider = [EXHomeAppSplashScreenViewProvider new]; 134 [self _showSplashScreenWithProvider:homeAppSplashScreenViewProvider]; 135 } else if (self.isStandalone) { 136 [self _showSplashScreenWithProvider:[EXSplashScreenViewNativeProvider new]]; 137 } 138 139 self.view.backgroundColor = [UIColor whiteColor]; 140 _appRecord.appManager.delegate = self; 141 self.isLoading = YES; 142} 143 144- (void)viewDidAppear:(BOOL)animated 145{ 146 [super viewDidAppear:animated]; 147 if (_appRecord && _appRecord.status == kEXKernelAppRecordStatusNew) { 148 _appRecord.appLoader.delegate = self; 149 _appRecord.appLoader.dataSource = _appRecord.appManager; 150 [self refresh]; 151 } 152} 153 154- (BOOL)shouldAutorotate 155{ 156 return YES; 157} 158 159- (void)viewWillLayoutSubviews 160{ 161 [super viewWillLayoutSubviews]; 162 if (_appLoadingCancelView) { 163 _appLoadingCancelView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); 164 } 165 if (_contentView) { 166 _contentView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); 167 } 168} 169 170- (void)viewWillDisappear:(BOOL)animated 171{ 172 [_appLoadingProgressWindowController hide]; 173 [super viewWillDisappear:animated]; 174} 175 176/** 177 * Force presented view controllers to use the same user interface style. 178 */ 179- (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^ __nullable)(void))completion 180{ 181 [super presentViewController:viewControllerToPresent animated:flag completion:completion]; 182 [self _overrideUserInterfaceStyleOf:viewControllerToPresent]; 183} 184 185/** 186 * Force child view controllers to use the same user interface style. 187 */ 188- (void)addChildViewController:(UIViewController *)childController 189{ 190 [super addChildViewController:childController]; 191 [self _overrideUserInterfaceStyleOf:childController]; 192} 193 194#pragma mark - Public 195 196- (void)maybeShowError:(NSError *)error 197{ 198 self.isLoading = NO; 199 if ([self _willAutoRecoverFromError:error]) { 200 return; 201 } 202 if (error && ![error isKindOfClass:[NSError class]]) { 203#if DEBUG 204 NSAssert(NO, @"AppViewController error handler was called on an object that isn't an NSError"); 205#endif 206 return; 207 } 208 209 // we don't ever want to show any Expo UI in a production standalone app, so hard crash 210 if ([EXEnvironment sharedEnvironment].isDetached && ![_appRecord.appManager enablesDeveloperTools]) { 211 NSException *e = [NSException exceptionWithName:@"ExpoFatalError" 212 reason:[NSString stringWithFormat:@"Expo encountered a fatal error: %@", [error localizedDescription]] 213 userInfo:@{NSUnderlyingErrorKey: error}]; 214 @throw e; 215 } 216 217 NSString *domain = (error && error.domain) ? error.domain : @""; 218 BOOL isNetworkError = ([domain isEqualToString:(NSString *)kCFErrorDomainCFNetwork] || [domain isEqualToString:EXNetworkErrorDomain]); 219 220 if (isNetworkError) { 221 // show a human-readable reachability error 222 dispatch_async(dispatch_get_main_queue(), ^{ 223 [self _showErrorWithType:kEXFatalErrorTypeLoading error:error]; 224 }); 225 } else if ([domain isEqualToString:@"JSServer"] && [_appRecord.appManager enablesDeveloperTools]) { 226 // RCTRedBox already handled this 227 } else if ([domain rangeOfString:RCTErrorDomain].length > 0 && [_appRecord.appManager enablesDeveloperTools]) { 228 // RCTRedBox already handled this 229 } else { 230 dispatch_async(dispatch_get_main_queue(), ^{ 231 [self _showErrorWithType:kEXFatalErrorTypeException error:error]; 232 }); 233 } 234} 235 236- (void)refresh 237{ 238 self.isLoading = YES; 239 self.isBridgeAlreadyLoading = NO; 240 [self _invalidateRecoveryTimer]; 241 [_appRecord.appLoader request]; 242} 243 244- (void)reloadFromCache 245{ 246 self.isLoading = YES; 247 self.isBridgeAlreadyLoading = NO; 248 [self _invalidateRecoveryTimer]; 249 [_appRecord.appLoader requestFromCache]; 250} 251 252- (void)appStateDidBecomeActive 253{ 254 dispatch_async(dispatch_get_main_queue(), ^{ 255 [self _enforceDesiredDeviceOrientation]; 256 257 // Reset the root view background color and window color if we switch between Expo home and project 258 [self _setBackgroundColor:self.view]; 259 }); 260 [_appRecord.appManager appStateDidBecomeActive]; 261} 262 263- (void)appStateDidBecomeInactive 264{ 265 [_appRecord.appManager appStateDidBecomeInactive]; 266} 267 268- (void)_rebuildBridge 269{ 270 if (!self.isBridgeAlreadyLoading) { 271 self.isBridgeAlreadyLoading = YES; 272 dispatch_async(dispatch_get_main_queue(), ^{ 273 [self _overrideUserInterfaceStyleOf:self]; 274 [self _enforceDesiredDeviceOrientation]; 275 [self _invalidateRecoveryTimer]; 276 [[EXKernel sharedInstance] logAnalyticsEvent:@"LOAD_EXPERIENCE" forAppRecord:self.appRecord]; 277 [self.appRecord.appManager rebuildBridge]; 278 }); 279 } 280} 281 282- (void)foregroundControllers 283{ 284 if (_backgroundedControllers != nil) { 285 __block UIViewController *parentController = self; 286 287 [_backgroundedControllers enumerateObjectsUsingBlock:^(UIViewController * _Nonnull viewController, NSUInteger idx, BOOL * _Nonnull stop) { 288 [parentController presentViewController:viewController animated:NO completion:nil]; 289 parentController = viewController; 290 }]; 291 292 _backgroundedControllers = nil; 293 } 294} 295 296- (void)backgroundControllers 297{ 298 UIViewController *childController = [self presentedViewController]; 299 300 if (childController != nil) { 301 if (_backgroundedControllers == nil) { 302 _backgroundedControllers = [NSMutableArray new]; 303 } 304 305 while (childController != nil) { 306 [_backgroundedControllers addObject:childController]; 307 childController = childController.presentedViewController; 308 } 309 } 310} 311 312/** 313 * In managed app we expect two kinds of manifest: 314 * - optimistic one (served from cache) 315 * - actual one served when app is fetched. 316 * For each of them we should show SplashScreen, 317 * therefore for any consecutive SplashScreen.show call we just reconfigure what's already visible. 318 * In HomeApp or standalone apps this function is no-op as SplashScreen is managed differently. 319 */ 320- (void)_showOrReconfigureManagedAppSplashScreen:(NSDictionary *)manifest 321{ 322 if (_isStandalone || _isHomeApp) { 323 return; 324 } 325 if (!_managedAppSplashScreenViewProvider) { 326 _managedAppSplashScreenViewProvider = [[EXManagedAppSplashScreenViewProvider alloc] initWithManifest:manifest]; 327 328 [self _showSplashScreenWithProvider:_managedAppSplashScreenViewProvider]; 329 } else { 330 [_managedAppSplashScreenViewProvider updateSplashScreenViewWithManifest:manifest]; 331 } 332} 333 334- (void)_showCachedExperienceAlert 335{ 336 if (self.isStandalone || self.isHomeApp) { 337 return; 338 } 339 340 dispatch_async(dispatch_get_main_queue(), ^{ 341 UIAlertController *alert = [UIAlertController 342 alertControllerWithTitle:@"Using a cached project" 343 message:@"If you did not intend to use a cached project, check your network connection and reload." 344 preferredStyle:UIAlertControllerStyleAlert]; 345 [alert addAction:[UIAlertAction actionWithTitle:@"Reload" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { 346 [self refresh]; 347 }]]; 348 [alert addAction:[UIAlertAction actionWithTitle:@"Use cache" style:UIAlertActionStyleCancel handler:nil]]; 349 [self presentViewController:alert animated:YES completion:nil]; 350 }); 351} 352 353- (void)_setLoadingViewStatusIfEnabledFromAppLoader:(EXAppLoader *)appLoader 354{ 355 if (appLoader.shouldShowRemoteUpdateStatus) { 356 [self.appLoadingProgressWindowController updateStatus:appLoader.remoteUpdateStatus]; 357 } else { 358 [self.appLoadingProgressWindowController hide]; 359 } 360} 361 362- (void)_showSplashScreenWithProvider:(id<EXSplashScreenViewProvider>)provider 363{ 364 EXSplashScreenService *splashScreenService = (EXSplashScreenService *)[UMModuleRegistryProvider getSingletonModuleForClass:[EXSplashScreenService class]]; 365 366 // EXSplashScreenService presents a splash screen on a root view controller 367 // at the start of the app. Since we want the EXAppViewController to manage 368 // the lifecycle of the splash screen we need to: 369 // 1. present the splash screen on EXAppViewController 370 // 2. hide the splash screen of root view controller 371 void (^hideRootViewControllerSplashScreen)(void) = ^void() { 372 UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController; 373 [splashScreenService hideSplashScreenFor:rootViewController 374 successCallback:^(BOOL hasEffect){} 375 failureCallback:^(NSString * _Nonnull message) { 376 UMLogWarn(@"Hiding splash screen from root view controller did not succeed: %@", message); 377 }]; 378 }; 379 380 UM_WEAKIFY(self); 381 dispatch_async(dispatch_get_main_queue(), ^{ 382 UM_ENSURE_STRONGIFY(self); 383 [splashScreenService showSplashScreenFor:self 384 splashScreenViewProvider:provider 385 successCallback:hideRootViewControllerSplashScreen 386 failureCallback:^(NSString *message){ UMLogWarn(@"%@", message); }]; 387 }); 388} 389 390#pragma mark - EXAppLoaderDelegate 391 392- (void)appLoader:(EXAppLoader *)appLoader didLoadOptimisticManifest:(NSDictionary *)manifest 393{ 394 if (_appLoadingCancelView) { 395 UM_WEAKIFY(self); 396 dispatch_async(dispatch_get_main_queue(), ^{ 397 UM_ENSURE_STRONGIFY(self); 398 [self.appLoadingCancelView removeFromSuperview]; 399 self.appLoadingCancelView = nil; 400 }); 401 } 402 [self _showOrReconfigureManagedAppSplashScreen:manifest]; 403 [self _setLoadingViewStatusIfEnabledFromAppLoader:appLoader]; 404 if ([EXKernel sharedInstance].browserController) { 405 [[EXKernel sharedInstance].browserController addHistoryItemWithUrl:appLoader.manifestUrl manifest:manifest]; 406 } 407 [self _rebuildBridge]; 408} 409 410- (void)appLoader:(EXAppLoader *)appLoader didLoadBundleWithProgress:(EXLoadingProgress *)progress 411{ 412 [self.appLoadingProgressWindowController updateStatusWithProgress:progress]; 413} 414 415- (void)appLoader:(EXAppLoader *)appLoader didFinishLoadingManifest:(NSDictionary *)manifest bundle:(NSData *)data 416{ 417 [self _showOrReconfigureManagedAppSplashScreen:manifest]; 418 [self _rebuildBridge]; 419 if (self->_appRecord.appManager.status == kEXReactAppManagerStatusBridgeLoading) { 420 [self->_appRecord.appManager appLoaderFinished]; 421 } 422 423 if (!appLoader.isUpToDate && appLoader.shouldShowRemoteUpdateStatus) { 424 [self _showCachedExperienceAlert]; 425 } 426} 427 428- (void)appLoader:(EXAppLoader *)appLoader didFailWithError:(NSError *)error 429{ 430 if (_appRecord.appManager.status == kEXReactAppManagerStatusBridgeLoading) { 431 [_appRecord.appManager appLoaderFailedWithError:error]; 432 } 433 [self maybeShowError:error]; 434} 435 436- (void)appLoader:(EXAppLoader *)appLoader didResolveUpdatedBundleWithManifest:(NSDictionary * _Nullable)manifest isFromCache:(BOOL)isFromCache error:(NSError * _Nullable)error 437{ 438 [[EXKernel sharedInstance].serviceRegistry.updatesManager notifyApp:_appRecord ofDownloadWithManifest:manifest isNew:!isFromCache error:error]; 439} 440 441#pragma mark - EXReactAppManagerDelegate 442 443- (void)reactAppManagerIsReadyForLoad:(EXReactAppManager *)appManager 444{ 445 UIView *reactView = appManager.rootView; 446 reactView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); 447 reactView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 448 449 450 [_contentView removeFromSuperview]; 451 _contentView = reactView; 452 [self.view addSubview:_contentView]; 453 [self.view sendSubviewToBack:_contentView]; 454 [reactView becomeFirstResponder]; 455 456 // Set root view background color after adding as subview so we can access window 457 [self _setBackgroundColor:reactView]; 458} 459 460- (void)reactAppManagerStartedLoadingJavaScript:(EXReactAppManager *)appManager 461{ 462 EXAssertMainThread(); 463 self.isLoading = YES; 464} 465 466- (void)reactAppManagerFinishedLoadingJavaScript:(EXReactAppManager *)appManager 467{ 468 EXAssertMainThread(); 469 self.isLoading = NO; 470 if ([EXKernel sharedInstance].browserController) { 471 [[EXKernel sharedInstance].browserController appDidFinishLoadingSuccessfully:_appRecord]; 472 } 473} 474 475- (void)reactAppManagerAppContentDidAppear:(EXReactAppManager *)appManager 476{ 477 EXSplashScreenService *splashScreenService = (EXSplashScreenService *)[UMModuleRegistryProvider getSingletonModuleForClass:[EXSplashScreenService class]]; 478 [splashScreenService onAppContentDidAppear:self]; 479} 480 481- (void)reactAppManagerAppContentWillReload:(EXReactAppManager *)appManager { 482 EXSplashScreenService *splashScreenService = (EXSplashScreenService *)[UMModuleRegistryProvider getSingletonModuleForClass:[EXSplashScreenService class]]; 483 [splashScreenService onAppContentWillReload:self]; 484} 485 486- (void)reactAppManager:(EXReactAppManager *)appManager failedToLoadJavaScriptWithError:(NSError *)error 487{ 488 EXAssertMainThread(); 489 [self maybeShowError:error]; 490} 491 492- (void)reactAppManagerDidInvalidate:(EXReactAppManager *)appManager 493{ 494} 495 496- (void)errorViewDidSelectRetry:(EXErrorView *)errorView 497{ 498 [self refresh]; 499} 500 501#pragma mark - orientation 502 503- (UIInterfaceOrientationMask)supportedInterfaceOrientations 504{ 505#if __has_include(<EXScreenOrientation/EXScreenOrientationRegistry.h>) 506 EXScreenOrientationRegistry *screenOrientationRegistry = (EXScreenOrientationRegistry *)[UMModuleRegistryProvider getSingletonModuleForClass:[EXScreenOrientationRegistry class]]; 507 if (screenOrientationRegistry && [screenOrientationRegistry requiredOrientationMask] > 0) { 508 return [screenOrientationRegistry requiredOrientationMask]; 509 } 510#endif 511 512 // TODO: Remove once sdk 37 is phased out 513 if (_supportedInterfaceOrientations != EX_INTERFACE_ORIENTATION_USE_MANIFEST) { 514 return _supportedInterfaceOrientations; 515 } 516 517 return [self orientationMaskFromManifestOrDefault]; 518} 519 520- (UIInterfaceOrientationMask)orientationMaskFromManifestOrDefault { 521 if (_appRecord.appLoader.manifest) { 522 NSString *orientationConfig = _appRecord.appLoader.manifest[@"orientation"]; 523 if ([orientationConfig isEqualToString:@"portrait"]) { 524 // lock to portrait 525 return UIInterfaceOrientationMaskPortrait; 526 } else if ([orientationConfig isEqualToString:@"landscape"]) { 527 // lock to landscape 528 return UIInterfaceOrientationMaskLandscape; 529 } 530 } 531 // no config or default value: allow autorotation 532 return UIInterfaceOrientationMaskAllButUpsideDown; 533} 534 535// TODO: Remove once sdk 37 is phased out 536- (void)setSupportedInterfaceOrientations:(UIInterfaceOrientationMask)supportedInterfaceOrientations 537{ 538 _supportedInterfaceOrientations = supportedInterfaceOrientations; 539 [self _enforceDesiredDeviceOrientation]; 540} 541 542- (void)traitCollectionDidChange:(nullable UITraitCollection *)previousTraitCollection { 543 [super traitCollectionDidChange:previousTraitCollection]; 544 if ((self.traitCollection.verticalSizeClass != previousTraitCollection.verticalSizeClass) 545 || (self.traitCollection.horizontalSizeClass != previousTraitCollection.horizontalSizeClass)) { 546 547 #if __has_include(<EXScreenOrientation/EXScreenOrientationRegistry.h>) 548 EXScreenOrientationRegistry *screenOrientationRegistryController = (EXScreenOrientationRegistry *)[UMModuleRegistryProvider getSingletonModuleForClass:[EXScreenOrientationRegistry class]]; 549 [screenOrientationRegistryController traitCollectionDidChangeTo:self.traitCollection]; 550 #endif 551 552 // TODO: Remove once sdk 37 is phased out 553 [[EXKernel sharedInstance].serviceRegistry.screenOrientationManager handleScreenOrientationChange:self.traitCollection]; 554 } 555} 556 557// TODO: Remove once sdk 37 is phased out 558- (void)_enforceDesiredDeviceOrientation 559{ 560 RCTAssertMainQueue(); 561 UIInterfaceOrientationMask mask = [self supportedInterfaceOrientations]; 562 UIDeviceOrientation currentOrientation = [[UIDevice currentDevice] orientation]; 563 UIInterfaceOrientation newOrientation = UIInterfaceOrientationUnknown; 564 switch (mask) { 565 case UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown: 566 if (!UIDeviceOrientationIsPortrait(currentOrientation)) { 567 newOrientation = UIInterfaceOrientationPortrait; 568 } 569 break; 570 case UIInterfaceOrientationMaskPortrait: 571 newOrientation = UIInterfaceOrientationPortrait; 572 break; 573 case UIInterfaceOrientationMaskPortraitUpsideDown: 574 newOrientation = UIInterfaceOrientationPortraitUpsideDown; 575 break; 576 case UIInterfaceOrientationMaskLandscape: 577 if (!UIDeviceOrientationIsLandscape(currentOrientation)) { 578 newOrientation = UIInterfaceOrientationLandscapeLeft; 579 } 580 break; 581 case UIInterfaceOrientationMaskLandscapeLeft: 582 newOrientation = UIInterfaceOrientationLandscapeLeft; 583 break; 584 case UIInterfaceOrientationMaskLandscapeRight: 585 newOrientation = UIInterfaceOrientationLandscapeRight; 586 break; 587 case UIInterfaceOrientationMaskAllButUpsideDown: 588 if (currentOrientation == UIDeviceOrientationFaceDown) { 589 newOrientation = UIInterfaceOrientationPortrait; 590 } 591 break; 592 default: 593 break; 594 } 595 if (newOrientation != UIInterfaceOrientationUnknown) { 596 [[UIDevice currentDevice] setValue:@(newOrientation) forKey:@"orientation"]; 597 } 598 [UIViewController attemptRotationToDeviceOrientation]; 599} 600 601#pragma mark - user interface style 602 603- (void)_overrideUserInterfaceStyleOf:(UIViewController *)viewController 604{ 605 if (@available(iOS 13.0, *)) { 606 NSString *userInterfaceStyle = [self _readUserInterfaceStyleFromManifest:_appRecord.appLoader.manifest]; 607 viewController.overrideUserInterfaceStyle = [self _userInterfaceStyleForString:userInterfaceStyle]; 608 } 609} 610 611- (NSString * _Nullable)_readUserInterfaceStyleFromManifest:(NSDictionary *)manifest 612{ 613 if (manifest[@"ios"] && manifest[@"ios"][@"userInterfaceStyle"]) { 614 return manifest[@"ios"][@"userInterfaceStyle"]; 615 } 616 return manifest[@"userInterfaceStyle"]; 617} 618 619- (UIUserInterfaceStyle)_userInterfaceStyleForString:(NSString *)userInterfaceStyleString API_AVAILABLE(ios(12.0)) { 620 if ([userInterfaceStyleString isEqualToString:@"dark"]) { 621 return UIUserInterfaceStyleDark; 622 } 623 if ([userInterfaceStyleString isEqualToString:@"automatic"]) { 624 return UIUserInterfaceStyleUnspecified; 625 } 626 return UIUserInterfaceStyleLight; 627} 628 629#pragma mark - root view and window background color 630 631- (void)_setBackgroundColor:(UIView *)view 632{ 633 NSString *backgroundColorString = [self _readBackgroundColorFromManifest:_appRecord.appLoader.manifest]; 634 UIColor *backgroundColor = [EXUtil colorWithHexString:backgroundColorString]; 635 636 if (backgroundColor) { 637 view.backgroundColor = backgroundColor; 638 // NOTE(brentvatne): it may be desirable at some point to split the window backgroundColor out from the 639 // root view, we can do if use case is presented to us. 640 view.window.backgroundColor = backgroundColor; 641 } else { 642 view.backgroundColor = [UIColor whiteColor]; 643 644 // NOTE(brentvatne): we used to use white as a default background color for window but this caused 645 // problems when using form sheet presentation style with vcs eg: <Modal /> and native-stack. Most 646 // users expect the background behind these to be black, which is the default if backgroundColor is nil. 647 view.window.backgroundColor = nil; 648 649 // NOTE(brentvatne): we may want to default to respecting the default system background color 650 // on iOS13 and higher, but if we do make this choice then we will have to implement it on Android 651 // as well. This would also be a breaking change. Leaaving this here as a placeholder for the future. 652 // if (@available(iOS 13.0, *)) { 653 // view.backgroundColor = [UIColor systemBackgroundColor]; 654 // } else { 655 // view.backgroundColor = [UIColor whiteColor]; 656 // } 657 } 658} 659 660- (NSString * _Nullable)_readBackgroundColorFromManifest:(NSDictionary *)manifest 661{ 662 if (manifest[@"ios"] && manifest[@"ios"][@"backgroundColor"]) { 663 return manifest[@"ios"][@"backgroundColor"]; 664 } 665 return manifest[@"backgroundColor"]; 666} 667 668 669#pragma mark - Internal 670 671- (void)_showErrorWithType:(EXFatalErrorType)type error:(nullable NSError *)error 672{ 673 EXAssertMainThread(); 674 _dtmLastFatalErrorShown = [NSDate date]; 675 if (_errorView && _contentView == _errorView) { 676 // already showing, just update 677 _errorView.type = type; 678 _errorView.error = error; 679 } { 680 [_contentView removeFromSuperview]; 681 if (!_errorView) { 682 _errorView = [[EXErrorView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; 683 _errorView.delegate = self; 684 _errorView.appRecord = _appRecord; 685 } 686 _errorView.type = type; 687 _errorView.error = error; 688 _contentView = _errorView; 689 [self.view addSubview:_contentView]; 690 [[EXAnalytics sharedInstance] logErrorVisibleEvent]; 691 } 692} 693 694- (void)setIsLoading:(BOOL)isLoading 695{ 696 if ([_appRecord.appManager enablesDeveloperTools] && _dtmLastFatalErrorShown) { 697 if ([_dtmLastFatalErrorShown timeIntervalSinceNow] >= -kEXDevelopmentErrorCoolDownSeconds) { 698 // we just showed a fatal error very recently, do not begin loading. 699 // this can happen in some cases where react native sends the 'started loading' notif 700 // in spite of a packager error. 701 return; 702 } 703 } 704 _isLoading = isLoading; 705 UM_WEAKIFY(self); 706 dispatch_async(dispatch_get_main_queue(), ^{ 707 UM_ENSURE_STRONGIFY(self); 708 if (!isLoading) { 709 [self.appLoadingProgressWindowController hide]; 710 } 711 }); 712} 713 714#pragma mark - error recovery 715 716- (BOOL)_willAutoRecoverFromError:(NSError *)error 717{ 718 if (![_appRecord.appManager enablesDeveloperTools]) { 719 BOOL shouldRecover = [[EXKernel sharedInstance].serviceRegistry.errorRecoveryManager experienceIdShouldReloadOnError:_appRecord.experienceId]; 720 if (shouldRecover) { 721 [self _invalidateRecoveryTimer]; 722 _tmrAutoReloadDebounce = [NSTimer scheduledTimerWithTimeInterval:kEXAutoReloadDebounceSeconds 723 target:self 724 selector:@selector(refresh) 725 userInfo:nil 726 repeats:NO]; 727 } 728 return shouldRecover; 729 } 730 return NO; 731} 732 733- (void)_invalidateRecoveryTimer 734{ 735 if (_tmrAutoReloadDebounce) { 736 [_tmrAutoReloadDebounce invalidate]; 737 _tmrAutoReloadDebounce = nil; 738 } 739} 740 741#pragma mark - EXAppLoadingCancelViewDelegate 742 743- (void)appLoadingCancelViewDidCancel:(EXAppLoadingCancelView *)view { 744 if ([EXKernel sharedInstance].browserController) { 745 [[EXKernel sharedInstance].browserController moveHomeToVisible]; 746 } 747} 748 749@end 750 751NS_ASSUME_NONNULL_END 752