-
Notifications
You must be signed in to change notification settings - Fork 24k
/
DevSupportManagerBase.java
1217 lines (1076 loc) · 41.3 KB
/
DevSupportManagerBase.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.devsupport;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.hardware.SensorManager;
import android.util.Pair;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import com.facebook.common.logging.FLog;
import com.facebook.infer.annotation.Assertions;
import com.facebook.react.R;
import com.facebook.react.bridge.DefaultJSExceptionHandler;
import com.facebook.react.bridge.JSBundleLoader;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactMarker;
import com.facebook.react.bridge.ReactMarkerConstants;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.common.DebugServerException;
import com.facebook.react.common.ReactConstants;
import com.facebook.react.common.ShakeDetector;
import com.facebook.react.common.SurfaceDelegate;
import com.facebook.react.common.SurfaceDelegateFactory;
import com.facebook.react.devsupport.DevServerHelper.PackagerCommandListener;
import com.facebook.react.devsupport.interfaces.BundleLoadCallback;
import com.facebook.react.devsupport.interfaces.DevBundleDownloadListener;
import com.facebook.react.devsupport.interfaces.DevOptionHandler;
import com.facebook.react.devsupport.interfaces.DevSupportManager;
import com.facebook.react.devsupport.interfaces.ErrorCustomizer;
import com.facebook.react.devsupport.interfaces.ErrorType;
import com.facebook.react.devsupport.interfaces.PackagerStatusCallback;
import com.facebook.react.devsupport.interfaces.RedBoxHandler;
import com.facebook.react.devsupport.interfaces.StackFrame;
import com.facebook.react.modules.core.RCTNativeAppEventEmitter;
import com.facebook.react.packagerconnection.RequestHandler;
import com.facebook.react.packagerconnection.Responder;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public abstract class DevSupportManagerBase implements DevSupportManager {
public interface CallbackWithBundleLoader {
void onSuccess(JSBundleLoader bundleLoader);
void onError(String url, Throwable cause);
}
private static final int JAVA_ERROR_COOKIE = -1;
private static final int JSEXCEPTION_ERROR_COOKIE = -1;
private static final String RELOAD_APP_ACTION_SUFFIX = ".RELOAD_APP_ACTION";
private static final String FLIPPER_DEBUGGER_URL =
"flipper://null/Hermesdebuggerrn?device=React%20Native";
private static final String FLIPPER_DEVTOOLS_URL = "flipper://null/React?device=React%20Native";
private static final String EXOPACKAGE_LOCATION_FORMAT =
"/data/local/tmp/exopackage/%s//secondary-dex";
public static final String EMOJI_HUNDRED_POINTS_SYMBOL = " \uD83D\uDCAF";
public static final String EMOJI_FACE_WITH_NO_GOOD_GESTURE = " \uD83D\uDE45";
private final Context mApplicationContext;
private final ShakeDetector mShakeDetector;
private final BroadcastReceiver mReloadAppBroadcastReceiver;
private final DevServerHelper mDevServerHelper;
private final LinkedHashMap<String, DevOptionHandler> mCustomDevOptions = new LinkedHashMap<>();
private final ReactInstanceDevHelper mReactInstanceDevHelper;
private final @Nullable String mJSAppBundleName;
private final File mJSBundleDownloadedFile;
private final File mJSSplitBundlesDir;
private final DefaultJSExceptionHandler mDefaultJSExceptionHandler;
private final DevLoadingViewController mDevLoadingViewController;
private @Nullable SurfaceDelegate mRedBoxSurfaceDelegate;
private @Nullable AlertDialog mDevOptionsDialog;
private @Nullable DebugOverlayController mDebugOverlayController;
private boolean mDevLoadingViewVisible = false;
private int mPendingJSSplitBundleRequests = 0;
private @Nullable ReactContext mCurrentContext;
private DevInternalSettings mDevSettings;
private boolean mIsReceiverRegistered = false;
private boolean mIsShakeDetectorStarted = false;
private boolean mIsDevSupportEnabled = false;
private @Nullable RedBoxHandler mRedBoxHandler;
private @Nullable String mLastErrorTitle;
private @Nullable StackFrame[] mLastErrorStack;
private @Nullable ErrorType mLastErrorType;
private int mLastErrorCookie = 0;
private @Nullable DevBundleDownloadListener mBundleDownloadListener;
private @Nullable List<ErrorCustomizer> mErrorCustomizers;
private @Nullable PackagerLocationCustomizer mPackagerLocationCustomizer;
private InspectorPackagerConnection.BundleStatus mBundleStatus;
private @Nullable Map<String, RequestHandler> mCustomPackagerCommandHandlers;
private @Nullable Activity currentActivity;
private @Nullable final SurfaceDelegateFactory mSurfaceDelegateFactory;
public DevSupportManagerBase(
Context applicationContext,
ReactInstanceDevHelper reactInstanceDevHelper,
@Nullable String packagerPathForJSBundleName,
boolean enableOnCreate,
@Nullable RedBoxHandler redBoxHandler,
@Nullable DevBundleDownloadListener devBundleDownloadListener,
int minNumShakes,
@Nullable Map<String, RequestHandler> customPackagerCommandHandlers,
@Nullable SurfaceDelegateFactory surfaceDelegateFactory) {
mReactInstanceDevHelper = reactInstanceDevHelper;
mApplicationContext = applicationContext;
mJSAppBundleName = packagerPathForJSBundleName;
mDevSettings =
new DevInternalSettings(
applicationContext,
new DevInternalSettings.Listener() {
@Override
public void onInternalSettingsChanged() {
reloadSettings();
}
});
mBundleStatus = new InspectorPackagerConnection.BundleStatus();
mDevServerHelper =
new DevServerHelper(
mDevSettings,
mApplicationContext.getPackageName(),
new InspectorPackagerConnection.BundleStatusProvider() {
@Override
public InspectorPackagerConnection.BundleStatus getBundleStatus() {
return mBundleStatus;
}
});
mBundleDownloadListener = devBundleDownloadListener;
// Prepare shake gesture detector (will be started/stopped from #reload)
mShakeDetector =
new ShakeDetector(
new ShakeDetector.ShakeListener() {
@Override
public void onShake() {
showDevOptionsDialog();
}
},
minNumShakes);
mCustomPackagerCommandHandlers = customPackagerCommandHandlers;
// Prepare reload APP broadcast receiver (will be registered/unregistered from #reload)
mReloadAppBroadcastReceiver =
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (getReloadAppAction(context).equals(action)) {
if (intent.getBooleanExtra(DevServerHelper.RELOAD_APP_EXTRA_JS_PROXY, false)) {
mDevSettings.setRemoteJSDebugEnabled(true);
mDevServerHelper.launchJSDevtools();
} else {
mDevSettings.setRemoteJSDebugEnabled(false);
}
handleReloadJS();
}
}
};
// We store JS bundle loaded from dev server in a single destination in app's data dir.
// In case when someone schedule 2 subsequent reloads it may happen that JS thread will
// start reading first reload output while the second reload starts writing to the same
// file. As this should only be the case in dev mode we leave it as it is.
// TODO(6418010): Fix readers-writers problem in debug reload from HTTP server
final String subclassTag = getUniqueTag();
final String bundleFile = subclassTag + "ReactNativeDevBundle.js";
mJSBundleDownloadedFile = new File(applicationContext.getFilesDir(), bundleFile);
final String splitBundlesDir = subclassTag.toLowerCase(Locale.ROOT) + "_dev_js_split_bundles";
mJSSplitBundlesDir = mApplicationContext.getDir(splitBundlesDir, Context.MODE_PRIVATE);
mDefaultJSExceptionHandler = new DefaultJSExceptionHandler();
setDevSupportEnabled(enableOnCreate);
mRedBoxHandler = redBoxHandler;
mDevLoadingViewController = new DevLoadingViewController(reactInstanceDevHelper);
mSurfaceDelegateFactory = surfaceDelegateFactory;
};
protected abstract String getUniqueTag();
@Override
public void handleException(Exception e) {
if (mIsDevSupportEnabled) {
logJSException(e);
} else {
mDefaultJSExceptionHandler.handleException(e);
}
}
private void logJSException(Exception e) {
StringBuilder message =
new StringBuilder(
e.getMessage() == null ? "Exception in native call from JS" : e.getMessage());
Throwable cause = e.getCause();
while (cause != null) {
message.append("\n\n").append(cause.getMessage());
cause = cause.getCause();
}
if (e instanceof JSException) {
FLog.e(ReactConstants.TAG, "Exception in native call from JS", e);
String stack = ((JSException) e).getStack();
message.append("\n\n").append(stack);
// TODO #11638796: convert the stack into something useful
showNewError(message.toString(), new StackFrame[] {}, JSEXCEPTION_ERROR_COOKIE, ErrorType.JS);
} else {
showNewJavaError(message.toString(), e);
}
}
@Override
public void showNewJavaError(@Nullable String message, Throwable e) {
FLog.e(ReactConstants.TAG, "Exception in native call", e);
showNewError(
message, StackTraceHelper.convertJavaStackTrace(e), JAVA_ERROR_COOKIE, ErrorType.NATIVE);
}
/**
* Add option item to dev settings dialog displayed by this manager. In the case user select given
* option from that dialog, the appropriate handler passed as {@param optionHandler} will be
* called.
*/
@Override
public void addCustomDevOption(String optionName, DevOptionHandler optionHandler) {
mCustomDevOptions.put(optionName, optionHandler);
}
@Override
public void showNewJSError(String message, ReadableArray details, int errorCookie) {
showNewError(message, StackTraceHelper.convertJsStackTrace(details), errorCookie, ErrorType.JS);
}
@Override
public void registerErrorCustomizer(ErrorCustomizer errorCustomizer) {
if (mErrorCustomizers == null) {
mErrorCustomizers = new ArrayList<>();
}
mErrorCustomizers.add(errorCustomizer);
}
@Override
public Pair<String, StackFrame[]> processErrorCustomizers(Pair<String, StackFrame[]> errorInfo) {
if (mErrorCustomizers == null) {
return errorInfo;
} else {
for (ErrorCustomizer errorCustomizer : mErrorCustomizers) {
Pair<String, StackFrame[]> result = errorCustomizer.customizeErrorInfo(errorInfo);
if (result != null) {
errorInfo = result;
}
}
return errorInfo;
}
}
@Override
public void updateJSError(
final String message, final ReadableArray details, final int errorCookie) {
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
public void run() {
// Since we only show the first JS error in a succession of JS errors, make sure we only
// update the error message for that error message. This assumes that updateJSError
// belongs to the most recent showNewJSError
if (!mRedBoxSurfaceDelegate.isShowing() || errorCookie != mLastErrorCookie) {
return;
}
// The RedBox surface delegate will always show the latest error
updateLastErrorInfo(
message, StackTraceHelper.convertJsStackTrace(details), errorCookie, ErrorType.JS);
mRedBoxSurfaceDelegate.show();
}
});
}
@Override
public void hideRedboxDialog() {
if (mRedBoxSurfaceDelegate == null) {
return;
}
mRedBoxSurfaceDelegate.hide();
}
public @Nullable View createRootView(String appKey) {
return mReactInstanceDevHelper.createRootView(appKey);
}
public void destroyRootView(View rootView) {
mReactInstanceDevHelper.destroyRootView(rootView);
}
private void hideDevOptionsDialog() {
if (mDevOptionsDialog != null) {
mDevOptionsDialog.dismiss();
mDevOptionsDialog = null;
}
}
private void showNewError(
@Nullable final String message,
final StackFrame[] stack,
final int errorCookie,
final ErrorType errorType) {
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
public void run() {
// Keep a copy of the latest error to be shown by the RedBoxSurface
updateLastErrorInfo(message, stack, errorCookie, errorType);
if (mRedBoxSurfaceDelegate == null) {
@Nullable SurfaceDelegate redBoxSurfaceDelegate = createSurfaceDelegate("RedBox");
if (redBoxSurfaceDelegate != null) {
mRedBoxSurfaceDelegate = redBoxSurfaceDelegate;
} else {
mRedBoxSurfaceDelegate =
new RedBoxDialogSurfaceDelegate(DevSupportManagerBase.this);
}
mRedBoxSurfaceDelegate.createContentView("RedBox");
}
if (mRedBoxSurfaceDelegate.isShowing()) {
// Sometimes errors cause multiple errors to be thrown in JS in quick succession. Only
// show the first and most actionable one.
return;
}
mRedBoxSurfaceDelegate.show();
}
});
}
@Override
public void showDevOptionsDialog() {
if (mDevOptionsDialog != null || !mIsDevSupportEnabled || ActivityManager.isUserAMonkey()) {
return;
}
LinkedHashMap<String, DevOptionHandler> options = new LinkedHashMap<>();
/* register standard options */
options.put(
mApplicationContext.getString(R.string.catalyst_reload),
new DevOptionHandler() {
@Override
public void onOptionSelected() {
if (!mDevSettings.isJSDevModeEnabled()
&& mDevSettings.isHotModuleReplacementEnabled()) {
Toast.makeText(
mApplicationContext,
mApplicationContext.getString(R.string.catalyst_hot_reloading_auto_disable),
Toast.LENGTH_LONG)
.show();
mDevSettings.setHotModuleReplacementEnabled(false);
}
handleReloadJS();
}
});
if (mDevSettings.isDeviceDebugEnabled()) {
// For on-device debugging we link out to Flipper.
// Since we're assuming Flipper is available, also include the DevTools.
// Reset the old debugger setting so no one gets stuck.
// TODO: Remove in a few weeks.
if (mDevSettings.isRemoteJSDebugEnabled()) {
mDevSettings.setRemoteJSDebugEnabled(false);
handleReloadJS();
}
options.put(
mApplicationContext.getString(R.string.catalyst_debug_open),
new DevOptionHandler() {
@Override
public void onOptionSelected() {
mDevServerHelper.openUrl(
mCurrentContext,
FLIPPER_DEBUGGER_URL,
mApplicationContext.getString(R.string.catalyst_open_flipper_error));
}
});
options.put(
mApplicationContext.getString(R.string.catalyst_devtools_open),
new DevOptionHandler() {
@Override
public void onOptionSelected() {
mDevServerHelper.openUrl(
mCurrentContext,
FLIPPER_DEVTOOLS_URL,
mApplicationContext.getString(R.string.catalyst_open_flipper_error));
}
});
}
options.put(
mApplicationContext.getString(R.string.catalyst_change_bundle_location),
new DevOptionHandler() {
@Override
public void onOptionSelected() {
Activity context = mReactInstanceDevHelper.getCurrentActivity();
if (context == null || context.isFinishing()) {
FLog.e(
ReactConstants.TAG,
"Unable to launch change bundle location because react activity is not available");
return;
}
final EditText input = new EditText(context);
input.setHint("localhost:8081");
AlertDialog bundleLocationDialog =
new AlertDialog.Builder(context)
.setTitle(
mApplicationContext.getString(R.string.catalyst_change_bundle_location))
.setView(input)
.setPositiveButton(
android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String host = input.getText().toString();
mDevSettings.getPackagerConnectionSettings().setDebugServerHost(host);
handleReloadJS();
}
})
.create();
bundleLocationDialog.show();
}
});
options.put(
mDevSettings.isElementInspectorEnabled()
? mApplicationContext.getString(R.string.catalyst_inspector_stop)
: mApplicationContext.getString(R.string.catalyst_inspector),
new DevOptionHandler() {
@Override
public void onOptionSelected() {
mDevSettings.setElementInspectorEnabled(!mDevSettings.isElementInspectorEnabled());
mReactInstanceDevHelper.toggleElementInspector();
}
});
options.put(
mDevSettings.isHotModuleReplacementEnabled()
? mApplicationContext.getString(R.string.catalyst_hot_reloading_stop)
: mApplicationContext.getString(R.string.catalyst_hot_reloading),
new DevOptionHandler() {
@Override
public void onOptionSelected() {
boolean nextEnabled = !mDevSettings.isHotModuleReplacementEnabled();
mDevSettings.setHotModuleReplacementEnabled(nextEnabled);
if (mCurrentContext != null) {
if (nextEnabled) {
mCurrentContext.getJSModule(HMRClient.class).enable();
} else {
mCurrentContext.getJSModule(HMRClient.class).disable();
}
}
if (nextEnabled && !mDevSettings.isJSDevModeEnabled()) {
Toast.makeText(
mApplicationContext,
mApplicationContext.getString(R.string.catalyst_hot_reloading_auto_enable),
Toast.LENGTH_LONG)
.show();
mDevSettings.setJSDevModeEnabled(true);
handleReloadJS();
}
}
});
options.put(
mDevSettings.isFpsDebugEnabled()
? mApplicationContext.getString(R.string.catalyst_perf_monitor_stop)
: mApplicationContext.getString(R.string.catalyst_perf_monitor),
new DevOptionHandler() {
@Override
public void onOptionSelected() {
if (!mDevSettings.isFpsDebugEnabled()) {
// Request overlay permission if needed when "Show Perf Monitor" option is selected
Context context = mReactInstanceDevHelper.getCurrentActivity();
if (context == null) {
FLog.e(ReactConstants.TAG, "Unable to get reference to react activity");
} else {
DebugOverlayController.requestPermission(context);
}
}
mDevSettings.setFpsDebugEnabled(!mDevSettings.isFpsDebugEnabled());
}
});
options.put(
mApplicationContext.getString(R.string.catalyst_settings),
new DevOptionHandler() {
@Override
public void onOptionSelected() {
Intent intent = new Intent(mApplicationContext, DevSettingsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mApplicationContext.startActivity(intent);
}
});
if (mCustomDevOptions.size() > 0) {
options.putAll(mCustomDevOptions);
}
final DevOptionHandler[] optionHandlers = options.values().toArray(new DevOptionHandler[0]);
Activity context = mReactInstanceDevHelper.getCurrentActivity();
if (context == null || context.isFinishing()) {
FLog.e(
ReactConstants.TAG,
"Unable to launch dev options menu because react activity " + "isn't available");
return;
}
final TextView textView = new TextView(getApplicationContext());
textView.setText("React Native DevMenu (" + getUniqueTag() + ")");
textView.setPadding(0, 50, 0, 0);
textView.setGravity(Gravity.CENTER);
textView.setTextColor(Color.BLACK);
textView.setTextSize(17);
textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
mDevOptionsDialog =
new AlertDialog.Builder(context)
.setCustomTitle(textView)
.setItems(
options.keySet().toArray(new String[0]),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
optionHandlers[which].onOptionSelected();
mDevOptionsDialog = null;
}
})
.setOnCancelListener(
new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
mDevOptionsDialog = null;
}
})
.create();
mDevOptionsDialog.show();
if (mCurrentContext != null) {
mCurrentContext.getJSModule(RCTNativeAppEventEmitter.class).emit("RCTDevMenuShown", null);
}
}
/**
* {@link ReactInstanceDevCommandsHandler} is responsible for enabling/disabling dev support when
* a React view is attached/detached or when application state changes (e.g. the application is
* backgrounded).
*/
@Override
public void setDevSupportEnabled(boolean isDevSupportEnabled) {
mIsDevSupportEnabled = isDevSupportEnabled;
reloadSettings();
}
@Override
public boolean getDevSupportEnabled() {
return mIsDevSupportEnabled;
}
@Override
public DevInternalSettings getDevSettings() {
return mDevSettings;
}
@Override
public RedBoxHandler getRedBoxHandler() {
return mRedBoxHandler;
}
@Override
public void onNewReactContextCreated(ReactContext reactContext) {
resetCurrentContext(reactContext);
}
@Override
public void onReactInstanceDestroyed(ReactContext reactContext) {
if (reactContext == mCurrentContext) {
// only call reset context when the destroyed context matches the one that is currently set
// for this manager
resetCurrentContext(null);
}
}
@Override
public String getSourceMapUrl() {
if (mJSAppBundleName == null) {
return "";
}
return mDevServerHelper.getSourceMapUrl(Assertions.assertNotNull(mJSAppBundleName));
}
@Override
public String getSourceUrl() {
if (mJSAppBundleName == null) {
return "";
}
return mDevServerHelper.getSourceUrl(Assertions.assertNotNull(mJSAppBundleName));
}
@Override
public String getJSBundleURLForRemoteDebugging() {
return mDevServerHelper.getJSBundleURLForRemoteDebugging(
Assertions.assertNotNull(mJSAppBundleName));
}
@Override
public String getDownloadedJSBundleFile() {
return mJSBundleDownloadedFile.getAbsolutePath();
}
/**
* @return {@code true} if {@link com.facebook.react.ReactInstanceManager} should use downloaded
* JS bundle file instead of using JS file from assets. This may happen when app has not been
* updated since the last time we fetched the bundle.
*/
@Override
public boolean hasUpToDateJSBundleInCache() {
if (mIsDevSupportEnabled && mJSBundleDownloadedFile.exists()) {
try {
String packageName = mApplicationContext.getPackageName();
PackageInfo thisPackage =
mApplicationContext.getPackageManager().getPackageInfo(packageName, 0);
if (mJSBundleDownloadedFile.lastModified() > thisPackage.lastUpdateTime) {
// Base APK has not been updated since we downloaded JS, but if app is using exopackage
// it may only be a single dex that has been updated. We check for exopackage dir update
// time in that case.
File exopackageDir =
new File(String.format(Locale.US, EXOPACKAGE_LOCATION_FORMAT, packageName));
if (exopackageDir.exists()) {
return mJSBundleDownloadedFile.lastModified() > exopackageDir.lastModified();
}
return true;
}
} catch (PackageManager.NameNotFoundException e) {
// Ignore this error and just fallback to loading JS from assets
FLog.e(ReactConstants.TAG, "DevSupport is unable to get current app info");
}
}
return false;
}
private void resetCurrentContext(@Nullable ReactContext reactContext) {
if (mCurrentContext == reactContext) {
// new context is the same as the old one - do nothing
return;
}
mCurrentContext = reactContext;
// Recreate debug overlay controller with new CatalystInstance object
if (mDebugOverlayController != null) {
mDebugOverlayController.setFpsDebugViewVisible(false);
}
if (reactContext != null) {
mDebugOverlayController = new DebugOverlayController(reactContext);
}
if (mCurrentContext != null) {
try {
URL sourceUrl = new URL(getSourceUrl());
String path = sourceUrl.getPath().substring(1); // strip initial slash in path
String host = sourceUrl.getHost();
int port = sourceUrl.getPort() != -1 ? sourceUrl.getPort() : sourceUrl.getDefaultPort();
mCurrentContext
.getJSModule(HMRClient.class)
.setup("android", path, host, port, mDevSettings.isHotModuleReplacementEnabled());
} catch (MalformedURLException e) {
showNewJavaError(e.getMessage(), e);
}
}
reloadSettings();
}
@Override
public void reloadSettings() {
if (UiThreadUtil.isOnUiThread()) {
reload();
} else {
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
public void run() {
reload();
}
});
}
}
protected @Nullable ReactContext getCurrentContext() {
return mCurrentContext;
}
protected @Nullable String getJSAppBundleName() {
return mJSAppBundleName;
}
protected Context getApplicationContext() {
return mApplicationContext;
}
protected DevServerHelper getDevServerHelper() {
return mDevServerHelper;
}
protected ReactInstanceDevHelper getReactInstanceDevHelper() {
return mReactInstanceDevHelper;
}
@UiThread
private void showDevLoadingViewForUrl(String bundleUrl) {
mDevLoadingViewController.showForUrl(bundleUrl);
mDevLoadingViewVisible = true;
}
@UiThread
protected void showDevLoadingViewForRemoteJSEnabled() {
mDevLoadingViewController.showForRemoteJSEnabled();
mDevLoadingViewVisible = true;
}
@UiThread
protected void hideDevLoadingView() {
mDevLoadingViewController.hide();
mDevLoadingViewVisible = false;
}
public void fetchSplitBundleAndCreateBundleLoader(
String bundlePath, final CallbackWithBundleLoader callback) {
final String bundleUrl = mDevServerHelper.getDevServerSplitBundleURL(bundlePath);
// The bundle path may contain the '/' character, which is not allowed in file names.
final File bundleFile =
new File(mJSSplitBundlesDir, bundlePath.replaceAll("/", "_") + ".jsbundle");
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
public void run() {
showSplitBundleDevLoadingView(bundleUrl);
mDevServerHelper.downloadBundleFromURL(
new DevBundleDownloadListener() {
@Override
public void onSuccess() {
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
public void run() {
hideSplitBundleDevLoadingView();
}
});
@Nullable ReactContext context = mCurrentContext;
if (context == null || !context.hasActiveReactInstance()) {
return;
}
JSBundleLoader bundleLoader =
JSBundleLoader.createCachedSplitBundleFromNetworkLoader(
bundleUrl, bundleFile.getAbsolutePath());
callback.onSuccess(bundleLoader);
}
@Override
public void onProgress(
@Nullable String status, @Nullable Integer done, @Nullable Integer total) {
mDevLoadingViewController.updateProgress(status, done, total);
}
@Override
public void onFailure(Exception cause) {
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
public void run() {
hideSplitBundleDevLoadingView();
}
});
callback.onError(bundleUrl, cause);
}
},
bundleFile,
bundleUrl,
null);
}
});
}
@UiThread
private void showSplitBundleDevLoadingView(String bundleUrl) {
showDevLoadingViewForUrl(bundleUrl);
mPendingJSSplitBundleRequests++;
}
@UiThread
private void hideSplitBundleDevLoadingView() {
if (--mPendingJSSplitBundleRequests == 0) {
hideDevLoadingView();
}
}
@Override
public void isPackagerRunning(final PackagerStatusCallback callback) {
Runnable checkPackagerRunning =
new Runnable() {
@Override
public void run() {
mDevServerHelper.isPackagerRunning(callback);
}
};
if (mPackagerLocationCustomizer != null) {
mPackagerLocationCustomizer.run(checkPackagerRunning);
} else {
checkPackagerRunning.run();
}
}
@Override
public @Nullable File downloadBundleResourceFromUrlSync(
final String resourceURL, final File outputFile) {
return mDevServerHelper.downloadBundleResourceFromUrlSync(resourceURL, outputFile);
}
@Override
public @Nullable String getLastErrorTitle() {
return mLastErrorTitle;
}
@Override
public @Nullable StackFrame[] getLastErrorStack() {
return mLastErrorStack;
}
@Override
public int getLastErrorCookie() {
return mLastErrorCookie;
}
@Override
public @Nullable ErrorType getLastErrorType() {
return mLastErrorType;
}
private void handleCaptureHeap(final Responder responder) {
if (mCurrentContext == null) {
return;
}
JSCHeapCapture heapCapture = mCurrentContext.getNativeModule(JSCHeapCapture.class);
if (heapCapture != null) {
heapCapture.captureHeap(
mApplicationContext.getCacheDir().getPath(),
new JSCHeapCapture.CaptureCallback() {
@Override
public void onSuccess(File capture) {
responder.respond(capture.toString());
}
@Override
public void onFailure(JSCHeapCapture.CaptureException error) {
responder.error(error.toString());
}
});
}
}
private void updateLastErrorInfo(
@Nullable final String message,
final StackFrame[] stack,
final int errorCookie,
final ErrorType errorType) {
mLastErrorTitle = message;
mLastErrorStack = stack;
mLastErrorCookie = errorCookie;
mLastErrorType = errorType;
}
public void reloadJSFromServer(final String bundleURL) {
reloadJSFromServer(
bundleURL,
new BundleLoadCallback() {
@Override
public void onSuccess() {
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
public void run() {
mReactInstanceDevHelper.onJSBundleLoadedFromServer();
}
});
}
});
}
public void reloadJSFromServer(final String bundleURL, final BundleLoadCallback callback) {
ReactMarker.logMarker(ReactMarkerConstants.DOWNLOAD_START);
showDevLoadingViewForUrl(bundleURL);
final BundleDownloader.BundleInfo bundleInfo = new BundleDownloader.BundleInfo();
mDevServerHelper.downloadBundleFromURL(
new DevBundleDownloadListener() {
@Override
public void onSuccess() {
hideDevLoadingView();
synchronized (DevSupportManagerBase.this) {
mBundleStatus.isLastDownloadSucess = true;
mBundleStatus.updateTimestamp = System.currentTimeMillis();
}
if (mBundleDownloadListener != null) {
mBundleDownloadListener.onSuccess();
}
ReactMarker.logMarker(ReactMarkerConstants.DOWNLOAD_END, bundleInfo.toJSONString());
callback.onSuccess();
}
@Override
public void onProgress(
@Nullable final String status,
@Nullable final Integer done,
@Nullable final Integer total) {
mDevLoadingViewController.updateProgress(status, done, total);
if (mBundleDownloadListener != null) {
mBundleDownloadListener.onProgress(status, done, total);
}
}
@Override
public void onFailure(final Exception cause) {
hideDevLoadingView();
synchronized (DevSupportManagerBase.this) {
mBundleStatus.isLastDownloadSucess = false;
}
if (mBundleDownloadListener != null) {
mBundleDownloadListener.onFailure(cause);
}
FLog.e(ReactConstants.TAG, "Unable to download JS bundle", cause);
reportBundleLoadingFailure(cause);
}
},
mJSBundleDownloadedFile,
bundleURL,
bundleInfo);
}
private void reportBundleLoadingFailure(final Exception cause) {
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
public void run() {
if (cause instanceof DebugServerException) {
DebugServerException debugServerException = (DebugServerException) cause;
showNewJavaError(debugServerException.getMessage(), cause);
} else {
showNewJavaError(
mApplicationContext.getString(R.string.catalyst_reload_error), cause);
}