-
Notifications
You must be signed in to change notification settings - Fork 24k
/
ReactHostImpl.java
1595 lines (1390 loc) · 58.7 KB
/
ReactHostImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.runtime;
import static com.facebook.infer.annotation.Assertions.assertNotNull;
import static com.facebook.infer.annotation.Assertions.nullsafeFIXME;
import static com.facebook.infer.annotation.ThreadConfined.UI;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.facebook.common.logging.FLog;
import com.facebook.infer.annotation.Assertions;
import com.facebook.infer.annotation.Nullsafe;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.infer.annotation.ThreadSafe;
import com.facebook.react.JSEngineResolutionAlgorithm;
import com.facebook.react.MemoryPressureRouter;
import com.facebook.react.ReactHost;
import com.facebook.react.ReactInstanceEventListener;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.JSBundleLoader;
import com.facebook.react.bridge.JavaScriptContextHolder;
import com.facebook.react.bridge.MemoryPressureListener;
import com.facebook.react.bridge.NativeArray;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactMarker;
import com.facebook.react.bridge.ReactMarkerConstants;
import com.facebook.react.bridge.ReactNoCrashBridgeNotAllowedSoftException;
import com.facebook.react.bridge.ReactNoCrashSoftException;
import com.facebook.react.bridge.ReactSoftExceptionLogger;
import com.facebook.react.bridge.RuntimeExecutor;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.bridge.queue.QueueThreadExceptionHandler;
import com.facebook.react.bridge.queue.ReactQueueConfiguration;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.common.build.ReactBuildConfig;
import com.facebook.react.config.ReactFeatureFlags;
import com.facebook.react.devsupport.DevSupportManagerBase;
import com.facebook.react.devsupport.DisabledDevSupportManager;
import com.facebook.react.devsupport.InspectorFlags;
import com.facebook.react.devsupport.interfaces.DevSupportManager;
import com.facebook.react.fabric.ComponentFactory;
import com.facebook.react.fabric.FabricUIManager;
import com.facebook.react.interfaces.TaskInterface;
import com.facebook.react.interfaces.exceptionmanager.ReactJsExceptionHandler;
import com.facebook.react.interfaces.fabric.ReactSurface;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.runtime.internal.bolts.Continuation;
import com.facebook.react.runtime.internal.bolts.Task;
import com.facebook.react.runtime.internal.bolts.TaskCompletionSource;
import com.facebook.react.turbomodule.core.interfaces.CallInvokerHolder;
import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.uimanager.events.BlackHoleEventDispatcher;
import com.facebook.react.uimanager.events.EventDispatcher;
import com.facebook.react.views.imagehelper.ResourceDrawableIdHelper;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
/**
* A ReactHost is an object that manages a single {@link ReactInstance}. A ReactHost can be
* constructed without initializing the ReactInstance, and it will continue to exist after the
* instance is destroyed. This class ensures safe access to the ReactInstance and the JS runtime;
* methods that operate on the instance use Bolts Tasks to defer the operation until the instance
* has been initialized. They also return a Task so the caller can be notified of completion.
*
* @see <a href="https://github.com/BoltsFramework/Bolts-Android#tasks">Bolts Android</a>
*/
@ThreadSafe
@Nullsafe(Nullsafe.Mode.LOCAL)
public class ReactHostImpl implements ReactHost {
// TODO T61403233 Make this configurable by product code
private static final boolean DEV = ReactBuildConfig.DEBUG;
private static final String TAG = "ReactHost";
private static final int BRIDGELESS_MARKER_INSTANCE_KEY = 1;
private static final AtomicInteger mCounter = new AtomicInteger(0);
private final Context mContext;
private final ReactHostDelegate mReactHostDelegate;
private final ComponentFactory mComponentFactory;
private final ReactJsExceptionHandler mReactJsExceptionHandler;
private final DevSupportManager mDevSupportManager;
private final Executor mBGExecutor;
private final Executor mUIExecutor;
private final QueueThreadExceptionHandler mQueueThreadExceptionHandler;
private final Set<ReactSurfaceImpl> mAttachedSurfaces =
Collections.synchronizedSet(new HashSet<>());
private final MemoryPressureRouter mMemoryPressureRouter;
private final boolean mAllowPackagerServerAccess;
private final boolean mUseDevSupport;
private final Collection<ReactInstanceEventListener> mReactInstanceEventListeners =
Collections.synchronizedList(new ArrayList<>());
private final BridgelessAtomicRef<Task<ReactInstance>> mReactInstanceTaskRef =
new BridgelessAtomicRef<>(
Task.forResult(
nullsafeFIXME(
null, "forResult parameter supports null, but is not annotated as @Nullable")));
private final BridgelessAtomicRef<BridgelessReactContext> mBridgelessReactContextRef =
new BridgelessAtomicRef<>();
private final AtomicReference<Activity> mActivity = new AtomicReference<>();
private final AtomicReference<WeakReference<Activity>> mLastUsedActivity =
new AtomicReference<>(new WeakReference<>(null));
private final BridgelessReactStateTracker mBridgelessReactStateTracker =
new BridgelessReactStateTracker(DEV);
private final ReactLifecycleStateManager mReactLifecycleStateManager =
new ReactLifecycleStateManager(mBridgelessReactStateTracker);
private final int mId = mCounter.getAndIncrement();
private @Nullable JSEngineResolutionAlgorithm mJSEngineResolutionAlgorithm = null;
private MemoryPressureListener mMemoryPressureListener;
private @Nullable DefaultHardwareBackBtnHandler mDefaultHardwareBackBtnHandler;
private final Set<Function0<Unit>> mBeforeDestroyListeners =
Collections.synchronizedSet(new HashSet<>());
private @Nullable ReactHostInspectorTarget mReactHostInspectorTarget;
public ReactHostImpl(
Context context,
ReactHostDelegate delegate,
ComponentFactory componentFactory,
boolean allowPackagerServerAccess,
ReactJsExceptionHandler reactJsExceptionHandler,
boolean useDevSupport) {
this(
context,
delegate,
componentFactory,
Executors.newSingleThreadExecutor(),
Task.UI_THREAD_EXECUTOR,
reactJsExceptionHandler,
allowPackagerServerAccess,
useDevSupport);
}
public ReactHostImpl(
Context context,
ReactHostDelegate delegate,
ComponentFactory componentFactory,
Executor bgExecutor,
Executor uiExecutor,
ReactJsExceptionHandler reactJsExceptionHandler,
boolean allowPackagerServerAccess,
boolean useDevSupport) {
mContext = context;
mReactHostDelegate = delegate;
mComponentFactory = componentFactory;
mBGExecutor = bgExecutor;
mUIExecutor = uiExecutor;
mReactJsExceptionHandler = reactJsExceptionHandler;
mQueueThreadExceptionHandler = ReactHostImpl.this::handleHostException;
mMemoryPressureRouter = new MemoryPressureRouter(context);
mMemoryPressureListener =
level ->
callWithExistingReactInstance(
"handleMemoryPressure(" + level + ")",
reactInstance -> reactInstance.handleMemoryPressure(level));
mAllowPackagerServerAccess = allowPackagerServerAccess;
if (DEV) {
mDevSupportManager =
new BridgelessDevSupportManager(
ReactHostImpl.this, mContext, mReactHostDelegate.getJsMainModulePath());
} else {
mDevSupportManager = new DisabledDevSupportManager();
}
mUseDevSupport = useDevSupport;
}
@Override
public LifecycleState getLifecycleState() {
return mReactLifecycleStateManager.getLifecycleState();
}
/**
* This function can be used to initialize the ReactInstance in a background thread before a
* surface needs to be rendered. It is not necessary to call this function; startSurface() will
* initialize the ReactInstance if it hasn't been preloaded.
*
* @return A Task that completes when the instance is initialized. The task will be faulted if any
* errors occur during initialization, and will be cancelled if ReactHost.destroy() is called
* before it completes.
*/
@Override
public TaskInterface<Void> start() {
return Task.call(this::getOrCreateStartTask, mBGExecutor).continueWithTask(Task::getResult);
}
/** Initialize and run a React Native surface in a background without mounting real views. */
/* package */
TaskInterface<Void> prerenderSurface(final ReactSurfaceImpl surface) {
final String method = "prerenderSurface(surfaceId = " + surface.getSurfaceID() + ")";
log(method, "Schedule");
attachSurface(surface);
return callAfterGetOrCreateReactInstance(
method,
reactInstance -> {
log(method, "Execute");
reactInstance.prerenderSurface(surface);
});
}
/**
* Start rendering a React Native surface on screen.
*
* @param surface The ReactSurface to render
* @return A Task that will complete when startSurface has been called.
*/
/** package */
TaskInterface<Void> startSurface(final ReactSurfaceImpl surface) {
final String method = "startSurface(surfaceId = " + surface.getSurfaceID() + ")";
log(method, "Schedule");
attachSurface(surface);
return callAfterGetOrCreateReactInstance(
method,
reactInstance -> {
log(method, "Execute");
reactInstance.startSurface(surface);
});
}
/**
* Stop rendering a React Native surface.
*
* @param surface The surface to stop
* @return A Task that will complete when stopSurface has been called.
*/
/** package */
TaskInterface<Void> stopSurface(final ReactSurfaceImpl surface) {
final String method = "stopSurface(surfaceId = " + surface.getSurfaceID() + ")";
log(method, "Schedule");
detachSurface(surface);
return callWithExistingReactInstance(
method,
reactInstance -> {
log(method, "Execute");
reactInstance.stopSurface(surface);
})
.makeVoid();
}
/**
* To be called when the host activity is resumed.
*
* @param activity The host activity
*/
@ThreadConfined(UI)
@Override
public void onHostResume(
final @Nullable Activity activity,
@Nullable DefaultHardwareBackBtnHandler defaultBackButtonImpl) {
mDefaultHardwareBackBtnHandler = defaultBackButtonImpl;
onHostResume(activity);
}
@ThreadConfined(UI)
@Override
public void onHostResume(final @Nullable Activity activity) {
final String method = "onHostResume(activity)";
log(method);
setCurrentActivity(activity);
ReactContext currentContext = getCurrentReactContext();
// TODO(T137233065): Enable DevSupportManager here
mReactLifecycleStateManager.moveToOnHostResume(currentContext, getCurrentActivity());
}
@ThreadConfined(UI)
@Override
public void onHostPause(final @Nullable Activity activity) {
final String method = "onHostPause(activity)";
log(method);
ReactContext currentContext = getCurrentReactContext();
Activity currentActivity = getCurrentActivity();
if (currentActivity != null) {
String currentActivityClass = currentActivity.getClass().getSimpleName();
String activityClass = activity == null ? "null" : activity.getClass().getSimpleName();
Assertions.assertCondition(
activity == currentActivity,
"Pausing an activity that is not the current activity, this is incorrect! "
+ "Current activity: "
+ currentActivityClass
+ " "
+ "Paused activity: "
+ activityClass);
}
// TODO(T137233065): Disable DevSupportManager here
mDefaultHardwareBackBtnHandler = null;
mReactLifecycleStateManager.moveToOnHostPause(currentContext, currentActivity);
}
/** To be called when the host activity is paused. */
@ThreadConfined(UI)
@Override
public void onHostPause() {
final String method = "onHostPause()";
log(method);
ReactContext currentContext = getCurrentReactContext();
// TODO(T137233065): Disable DevSupportManager here
mDefaultHardwareBackBtnHandler = null;
mReactLifecycleStateManager.moveToOnHostPause(currentContext, getCurrentActivity());
}
/** To be called when the host activity is destroyed. */
@ThreadConfined(UI)
@Override
public void onHostDestroy() {
final String method = "onHostDestroy()";
log(method);
// TODO(T137233065): Disable DevSupportManager here
moveToHostDestroy(getCurrentReactContext());
}
@ThreadConfined(UI)
@Override
public void onHostDestroy(@Nullable Activity activity) {
final String method = "onHostDestroy(activity)";
log(method);
Activity currentActivity = getCurrentActivity();
// TODO(T137233065): Disable DevSupportManager here
if (currentActivity == activity) {
moveToHostDestroy(getCurrentReactContext());
}
}
/**
* Returns current ReactContext which could be nullable if ReactInstance hasn't been created.
*
* @return The {@link BridgelessReactContext} associated with ReactInstance.
*/
@Override
public @Nullable ReactContext getCurrentReactContext() {
return mBridgelessReactContextRef.getNullable();
}
@Override
public DevSupportManager getDevSupportManager() {
return assertNotNull(mDevSupportManager);
}
@Override
public ReactSurface createSurface(
Context context, String moduleName, @Nullable Bundle initialProps) {
ReactSurfaceImpl surface = new ReactSurfaceImpl(context, moduleName, initialProps);
surface.attachView(new ReactSurfaceView(context, surface));
surface.attach(this);
return surface;
}
public MemoryPressureRouter getMemoryPressureRouter() {
return mMemoryPressureRouter;
}
/* package */ boolean isInstanceInitialized() {
final ReactInstance reactInstance = mReactInstanceTaskRef.get().getResult();
return reactInstance != null;
}
@ThreadConfined(UI)
@Override
public boolean onBackPressed() {
UiThreadUtil.assertOnUiThread();
final ReactInstance reactInstance = mReactInstanceTaskRef.get().getResult();
if (reactInstance == null) {
return false;
}
DeviceEventManagerModule deviceEventManagerModule =
reactInstance.getNativeModule(DeviceEventManagerModule.class);
if (deviceEventManagerModule == null) {
return false;
}
deviceEventManagerModule.emitHardwareBackPressed();
return true;
}
public @Nullable ReactQueueConfiguration getReactQueueConfiguration() {
synchronized (mReactInstanceTaskRef) {
Task<ReactInstance> task = mReactInstanceTaskRef.get();
if (!task.isFaulted() && !task.isCancelled() && task.getResult() != null) {
return task.getResult().getReactQueueConfiguration();
}
}
return null;
}
/** Add a listener to be notified of ReactInstance events. */
public void addReactInstanceEventListener(ReactInstanceEventListener listener) {
mReactInstanceEventListeners.add(listener);
}
/** Remove a listener previously added with {@link #addReactInstanceEventListener}. */
public void removeReactInstanceEventListener(ReactInstanceEventListener listener) {
mReactInstanceEventListeners.remove(listener);
}
/**
* Entrypoint to reload the ReactInstance. If the ReactInstance is destroying, will wait until
* destroy is finished, before reloading.
*
* @param reason {@link String} describing why ReactHost is being reloaded (e.g. js error, user
* tap on reload button)
* @return A task that completes when React Native reloads
*/
@Override
public TaskInterface<Void> reload(String reason) {
final String method = "reload()";
return Task.call(
() -> {
Task<Void> reloadTask = null;
if (mDestroyTask != null) {
log(method, "Waiting for destroy to finish, before reloading React Native.");
reloadTask =
mDestroyTask
.continueWithTask(task -> getOrCreateReloadTask(reason), mBGExecutor)
.makeVoid();
} else {
reloadTask = getOrCreateReloadTask(reason).makeVoid();
}
return reloadTask.continueWithTask(
task -> {
if (task.isFaulted()) {
mReactHostDelegate.handleInstanceException(task.getError());
return getOrCreateDestroyTask("Reload failed", task.getError());
}
return task;
},
mBGExecutor);
},
mBGExecutor)
.continueWithTask(Task::getResult);
}
/**
* Entrypoint to destroy the ReactInstance. If the ReactInstance is reloading, will wait until
* reload is finished, before destroying.
*
* @param reason {@link String} describing why ReactHost is being destroyed (e.g. memmory
* pressure)
* @param ex {@link Exception} exception that caused the trigger to destroy ReactHost (or null)
* This exception will be used to log properly the cause of destroy operation.
* @return A task that completes when React Native gets destroyed.
*/
@Override
public TaskInterface<Void> destroy(String reason, @Nullable Exception ex) {
final String method = "destroy()";
return Task.call(
() -> {
if (mReloadTask != null) {
log(
method,
"Reloading React Native. Waiting for reload to finish before destroying React Native.");
return mReloadTask.continueWithTask(
task -> getOrCreateDestroyTask(reason, ex), mBGExecutor);
}
return getOrCreateDestroyTask(reason, ex);
},
mBGExecutor)
.continueWithTask(Task::getResult);
}
private MemoryPressureListener createMemoryPressureListener(ReactInstance reactInstance) {
WeakReference<ReactInstance> weakReactInstance = new WeakReference<>(reactInstance);
return (level) -> {
mBGExecutor.execute(
() -> {
@Nullable ReactInstance strongReactInstance = weakReactInstance.get();
if (strongReactInstance != null) {
strongReactInstance.handleMemoryPressure(level);
}
});
};
}
@Nullable
/* package */ Activity getCurrentActivity() {
return mActivity.get();
}
@Nullable
/* package */ Activity getLastUsedActivity() {
@Nullable WeakReference<Activity> lastUsedActivityWeakRef = mLastUsedActivity.get();
if (lastUsedActivityWeakRef != null) {
return lastUsedActivityWeakRef.get();
}
return null;
}
private void setCurrentActivity(@Nullable Activity activity) {
mActivity.set(activity);
if (activity != null) {
mLastUsedActivity.set(new WeakReference<>(activity));
}
}
/**
* Get the {@link EventDispatcher} from the {@link FabricUIManager}. This always returns an
* EventDispatcher, even if the instance isn't alive; in that case, it returns a {@link
* BlackHoleEventDispatcher} which no-ops.
*
* @return The real {@link EventDispatcher} if the instance is alive; otherwise, a {@link
* BlackHoleEventDispatcher}.
*/
/* package */ EventDispatcher getEventDispatcher() {
final ReactInstance reactInstance = mReactInstanceTaskRef.get().getResult();
if (reactInstance == null) {
return BlackHoleEventDispatcher.get();
}
return reactInstance.getEventDispatcher();
}
/* package */
@Nullable
FabricUIManager getUIManager() {
final ReactInstance reactInstance = mReactInstanceTaskRef.get().getResult();
if (reactInstance == null) {
return null;
}
return reactInstance.getUIManager();
}
/* package */ <T extends NativeModule> boolean hasNativeModule(Class<T> nativeModuleInterface) {
final ReactInstance reactInstance = mReactInstanceTaskRef.get().getResult();
if (reactInstance != null) {
return reactInstance.hasNativeModule(nativeModuleInterface);
}
return false;
}
/* package */ Collection<NativeModule> getNativeModules() {
final ReactInstance reactInstance = mReactInstanceTaskRef.get().getResult();
if (reactInstance != null) {
return reactInstance.getNativeModules();
}
return new ArrayList<>();
}
/* package */
@Nullable
<T extends NativeModule> T getNativeModule(Class<T> nativeModuleInterface) {
if (nativeModuleInterface == UIManagerModule.class) {
ReactSoftExceptionLogger.logSoftExceptionVerbose(
TAG,
new ReactNoCrashBridgeNotAllowedSoftException(
"getNativeModule(UIManagerModule.class) cannot be called when the bridge is disabled"));
}
final ReactInstance reactInstance = mReactInstanceTaskRef.get().getResult();
if (reactInstance != null) {
return reactInstance.getNativeModule(nativeModuleInterface);
}
return null;
}
/* package */
@Nullable
RuntimeExecutor getRuntimeExecutor() {
final ReactInstance reactInstance = mReactInstanceTaskRef.get().getResult();
if (reactInstance != null) {
return reactInstance.getBufferedRuntimeExecutor();
}
ReactSoftExceptionLogger.logSoftException(
TAG,
new ReactNoCrashSoftException("Tried to get runtime executor while instance is not ready"));
return null;
}
/* package */
@Nullable
CallInvokerHolder getJSCallInvokerHolder() {
final ReactInstance reactInstance = mReactInstanceTaskRef.get().getResult();
if (reactInstance != null) {
return reactInstance.getJSCallInvokerHolder();
}
ReactSoftExceptionLogger.logSoftException(
TAG,
new ReactNoCrashSoftException(
"Tried to get JSCallInvokerHolder while instance is not ready"));
return null;
}
/**
* To be called when the host activity receives an activity result.
*
* @param activity The host activity
*/
@ThreadConfined(UI)
@Override
public void onActivityResult(
Activity activity, int requestCode, int resultCode, @Nullable Intent data) {
final String method =
"onActivityResult(activity = \""
+ activity
+ "\", requestCode = \""
+ requestCode
+ "\", resultCode = \""
+ resultCode
+ "\", data = \""
+ data
+ "\")";
log(method);
ReactContext currentContext = getCurrentReactContext();
if (currentContext != null) {
currentContext.onActivityResult(activity, requestCode, resultCode, data);
}
ReactSoftExceptionLogger.logSoftException(
TAG,
new ReactNoCrashSoftException(
"Tried to access onActivityResult while context is not ready"));
}
@Nullable
JavaScriptContextHolder getJavaScriptContextHolder() {
final ReactInstance reactInstance = mReactInstanceTaskRef.get().getResult();
if (reactInstance != null) {
return reactInstance.getJavaScriptContextHolder();
}
return null;
}
/* package */
DefaultHardwareBackBtnHandler getDefaultBackButtonHandler() {
return () -> {
UiThreadUtil.assertOnUiThread();
if (mDefaultHardwareBackBtnHandler != null) {
mDefaultHardwareBackBtnHandler.invokeDefaultOnBackPressed();
}
};
}
/* package */ Task<Boolean> loadBundle(final JSBundleLoader bundleLoader) {
final String method = "loadBundle()";
log(method, "Schedule");
return callWithExistingReactInstance(
method,
reactInstance -> {
log(method, "Execute");
reactInstance.loadJSBundle(bundleLoader);
});
}
/* package */ Task<Boolean> registerSegment(
final int segmentId, final String path, final Callback callback) {
final String method =
"registerSegment(segmentId = \"" + segmentId + "\", path = \"" + path + "\")";
log(method, "Schedule");
return callWithExistingReactInstance(
method,
reactInstance -> {
log(method, "Execute");
reactInstance.registerSegment(segmentId, path);
assertNotNull(callback).invoke();
});
}
/* package */ void handleHostException(Exception e) {
final String method = "handleHostException(message = \"" + e.getMessage() + "\")";
log(method);
if (DEV) {
mDevSupportManager.handleException(e);
}
destroy(method, e);
mReactHostDelegate.handleInstanceException(e);
}
/**
* Call a function on a JS module that has been registered as callable.
*
* @param moduleName The name of the JS module
* @param methodName The function to call
* @param args Arguments to be passed to the function
* @return A Task that will complete when the function call has been enqueued on the JS thread.
*/
/* package */ Task<Boolean> callFunctionOnModule(
final String moduleName, final String methodName, final NativeArray args) {
final String method = "callFunctionOnModule(\"" + moduleName + "\", \"" + methodName + "\")";
return callWithExistingReactInstance(
method,
reactInstance -> {
reactInstance.callFunctionOnModule(moduleName, methodName, args);
});
}
/* package */ void attachSurface(ReactSurfaceImpl surface) {
final String method = "attachSurface(surfaceId = " + surface.getSurfaceID() + ")";
log(method);
synchronized (mAttachedSurfaces) {
mAttachedSurfaces.add(surface);
}
}
/* package */ void detachSurface(ReactSurfaceImpl surface) {
final String method = "detachSurface(surfaceId = " + surface.getSurfaceID() + ")";
log(method);
synchronized (mAttachedSurfaces) {
mAttachedSurfaces.remove(surface);
}
}
/* package */ boolean isSurfaceAttached(ReactSurfaceImpl surface) {
synchronized (mAttachedSurfaces) {
return mAttachedSurfaces.contains(surface);
}
}
/* package */ boolean isSurfaceWithModuleNameAttached(String moduleName) {
synchronized (mAttachedSurfaces) {
for (ReactSurfaceImpl surface : mAttachedSurfaces) {
if (surface.getModuleName().equals(moduleName)) {
return true;
}
}
return false;
}
}
@Override
public void addBeforeDestroyListener(@NonNull Function0<Unit> onBeforeDestroy) {
synchronized (mBeforeDestroyListeners) {
mBeforeDestroyListeners.add(onBeforeDestroy);
}
}
@Override
public void removeBeforeDestroyListener(@NonNull Function0<Unit> onBeforeDestroy) {
synchronized (mBeforeDestroyListeners) {
mBeforeDestroyListeners.remove(onBeforeDestroy);
}
}
/* package */ interface VeniceThenable<T> {
void then(T t);
}
@ThreadConfined("ReactHost")
private @Nullable Task<Void> mStartTask = null;
@ThreadConfined("ReactHost")
private Task<Void> getOrCreateStartTask() {
final String method = "getOrCreateStartTask()";
if (mStartTask == null) {
log(method, "Schedule");
mStartTask =
waitThenCallGetOrCreateReactInstanceTask()
.continueWithTask(
(task) -> {
if (task.isFaulted()) {
mReactHostDelegate.handleInstanceException(task.getError());
// Wait for destroy to finish
return getOrCreateDestroyTask(
"getOrCreateStartTask() failure: " + task.getError().getMessage(),
task.getError())
.continueWithTask(destroyTask -> Task.forError(task.getError()))
.makeVoid();
}
return task.makeVoid();
},
mBGExecutor);
}
return mStartTask;
}
@ThreadConfined(UI)
private void moveToHostDestroy(@Nullable ReactContext currentContext) {
mReactLifecycleStateManager.moveToOnHostDestroy(currentContext);
destroyReactHostInspectorTarget();
setCurrentActivity(null);
}
private void raiseSoftException(String method, String message) {
raiseSoftException(method, message, null);
}
private void raiseSoftException(String method, String message, @Nullable Throwable throwable) {
log(method, message);
if (ReactFeatureFlags.enableBridgelessArchitectureSoftExceptions) {
if (throwable != null) {
ReactSoftExceptionLogger.logSoftException(
TAG, new ReactNoCrashSoftException(method + ": " + message, throwable));
return;
}
ReactSoftExceptionLogger.logSoftException(
TAG, new ReactNoCrashSoftException(method + ": " + message));
}
}
private Task<Boolean> callWithExistingReactInstance(
final String callingMethod, final VeniceThenable<ReactInstance> continuation) {
final String method = "callWithExistingReactInstance(" + callingMethod + ")";
return mReactInstanceTaskRef
.get()
.onSuccess(
task -> {
final ReactInstance reactInstance = task.getResult();
if (reactInstance == null) {
raiseSoftException(method, "Execute: ReactInstance null. Dropping work.");
return FALSE;
}
continuation.then(reactInstance);
return TRUE;
},
mBGExecutor);
}
private Task<Void> callAfterGetOrCreateReactInstance(
final String callingMethod, final VeniceThenable<ReactInstance> runnable) {
final String method = "callAfterGetOrCreateReactInstance(" + callingMethod + ")";
return getOrCreateReactInstance()
.onSuccess(
(Continuation<ReactInstance, Void>)
task -> {
final ReactInstance reactInstance = task.getResult();
if (reactInstance == null) {
raiseSoftException(method, "Execute: ReactInstance is null");
return null;
}
runnable.then(reactInstance);
return null;
},
mBGExecutor)
.continueWith(
task -> {
if (task.isFaulted()) {
handleHostException(task.getError());
}
return null;
},
mBGExecutor);
}
private BridgelessReactContext getOrCreateReactContext() {
final String method = "getOrCreateReactContext()";
return mBridgelessReactContextRef.getOrCreate(
() -> {
log(method, "Creating BridgelessReactContext");
return new BridgelessReactContext(mContext, ReactHostImpl.this);
});
}
/**
* Entrypoint to create the ReactInstance.
*
* <p>If the ReactInstance is reloading, will return the reload task. If the ReactInstance is
* destroying, will wait until destroy is finished, before creating.
*/
private Task<ReactInstance> getOrCreateReactInstance() {
return Task.call(this::waitThenCallGetOrCreateReactInstanceTask, mBGExecutor)
.continueWithTask(Task::getResult);
}
@ThreadConfined("ReactHost")
private Task<ReactInstance> waitThenCallGetOrCreateReactInstanceTask() {
return waitThenCallGetOrCreateReactInstanceTaskWithRetries(0, 4);
}
@ThreadConfined("ReactHost")
private Task<ReactInstance> waitThenCallGetOrCreateReactInstanceTaskWithRetries(
int tryNum, int maxTries) {
final String method = "waitThenCallGetOrCreateReactInstanceTaskWithRetries";
if (mReloadTask != null) {
log(method, "React Native is reloading. Return reload task.");
return mReloadTask;
}
if (mDestroyTask != null) {
boolean shouldTryAgain = tryNum < maxTries;
if (shouldTryAgain) {
log(
method,
"React Native is tearing down."
+ "Wait for teardown to finish, before trying again (try count = "
+ tryNum
+ ").");
return mDestroyTask.onSuccessTask(
(task) -> waitThenCallGetOrCreateReactInstanceTaskWithRetries(tryNum + 1, maxTries),
mBGExecutor);
}
raiseSoftException(
method,
"React Native is tearing down. Not wait for teardown to finish: reached max retries.");
}
return getOrCreateReactInstanceTask();
}
@ThreadConfined("ReactHost")
private Task<ReactInstance> getOrCreateReactInstanceTask() {
final String method = "getOrCreateReactInstanceTask()";
log(method);
return mReactInstanceTaskRef.getOrCreate(
() -> {
log(method, "Start");
ReactMarker.logMarker(
ReactMarkerConstants.REACT_BRIDGELESS_LOADING_START, BRIDGELESS_MARKER_INSTANCE_KEY);
return getJsBundleLoader()
.onSuccess(
task -> {
final JSBundleLoader bundleLoader = task.getResult();
final BridgelessReactContext reactContext = getOrCreateReactContext();
final DevSupportManager devSupportManager = getDevSupportManager();
reactContext.setJSExceptionHandler(devSupportManager);
log(method, "Creating ReactInstance");
final ReactInstance instance =
new ReactInstance(
reactContext,
mReactHostDelegate,
mComponentFactory,
devSupportManager,
mQueueThreadExceptionHandler,
mReactJsExceptionHandler,
mUseDevSupport,
getOrCreateReactHostInspectorTarget());
if (ReactFeatureFlags
.unstable_bridgelessArchitectureMemoryPressureHackyBoltsFix) {
mMemoryPressureListener = createMemoryPressureListener(instance);
}
mMemoryPressureRouter.addMemoryPressureListener(mMemoryPressureListener);
log(method, "Loading JS Bundle");
instance.loadJSBundle(bundleLoader);
log(
method,
"Calling DevSupportManagerBase.onNewReactContextCreated(reactContext)");
devSupportManager.onNewReactContextCreated(reactContext);
reactContext.runOnJSQueueThread(
() -> {
// Executing on the JS thread to ensurethat we're done
// loading the JS bundle.
// TODO T76081936 Move this if we switch to a sync RTE
ReactMarker.logMarker(
ReactMarkerConstants.REACT_BRIDGELESS_LOADING_END,
BRIDGELESS_MARKER_INSTANCE_KEY);
});
class Result {
final ReactInstance mInstance = instance;
final ReactContext mContext = reactContext;
final boolean mIsReloading = mReloadTask != null;
}
return new Result();
},