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