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