Delete deprecated CatalystInstanceImpl and C++ counterparts (#55789)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/55789

Removes the deprecated `CatalystInstanceImpl` class (Java) and its C++ JNI
counterparts (`CatalystInstanceImpl.h` and `CatalystInstanceImpl.cpp`) as part
of the Legacy Architecture cleanup.

`CatalystInstanceImpl` was the bridge implementation for the old architecture.
Its sole consumer, `ReactInstanceManager`, is itself deprecated — its
constructor already throws `UnsupportedOperationException`. The
`createReactContext` method that instantiated `CatalystInstanceImpl` has been
stubbed to throw `UnsupportedOperationException` as well.

Changes:
- Deleted `CatalystInstanceImpl.java` (621 lines)
- Deleted `CatalystInstanceImpl.h` and `CatalystInstanceImpl.cpp` (523 lines)
- Stubbed `ReactInstanceManager.createReactContext` to throw
- Removed from BUCK and CMakeLists.txt build files
- Removed from ReactAndroid.api public API surface
- Removed from ReactNoNewJavaDetector Java allowlist
- Removed from legacy architecture tracking script
- Added direct `#include <cxxreact/MessageQueueThread.h>` to
  `JavaModuleWrapper.cpp` to replace transitive dependency

Changelog: [Android][Removed] - Remove deprecated CatalystInstanceImpl

Reviewed By: javache

Differential Revision: D94548637

fbshipit-source-id: 5c447b85c80605cff17c1555d62ede5e9e2f18a7
This commit is contained in:
David Vacca authored and meta-codesync[bot] committed 2026-02-27 19:47:56 -08:00
1 parent 45de7109fe
commit 0889f7d774
8 files changed
+5 -1296

No files matched your search

@@ -600,59 +600,6 @@ public abstract interface class com/facebook/react/bridge/CatalystInstance : com
public abstract fun setTurboModuleRegistry (Lcom/facebook/react/internal/turbomodule/core/interfaces/TurboModuleRegistry;)V
}
public class com/facebook/react/bridge/CatalystInstanceImpl : com/facebook/react/bridge/CatalystInstance {
public fun callFunction (Lcom/facebook/react/bridge/CatalystInstanceImpl$PendingJSCall;)V
public fun callFunction (Ljava/lang/String;Ljava/lang/String;Lcom/facebook/react/bridge/NativeArray;)V
public fun destroy ()V
public fun extendNativeModules (Lcom/facebook/react/bridge/NativeModuleRegistry;)V
public fun getFabricUIManager ()Lcom/facebook/react/bridge/UIManager;
public fun getJSCallInvokerHolder ()Lcom/facebook/react/turbomodule/core/CallInvokerHolderImpl;
public synthetic fun getJSCallInvokerHolder ()Lcom/facebook/react/turbomodule/core/interfaces/CallInvokerHolder;
public fun getJSModule (Ljava/lang/Class;)Lcom/facebook/react/bridge/JavaScriptModule;
public fun getJavaScriptContextHolder ()Lcom/facebook/react/bridge/JavaScriptContextHolder;
public fun getNativeMethodCallInvokerHolder ()Lcom/facebook/react/turbomodule/core/NativeMethodCallInvokerHolderImpl;
public synthetic fun getNativeMethodCallInvokerHolder ()Lcom/facebook/react/turbomodule/core/interfaces/NativeMethodCallInvokerHolder;
public fun getNativeModule (Ljava/lang/Class;)Lcom/facebook/react/bridge/NativeModule;
public fun getNativeModule (Ljava/lang/String;)Lcom/facebook/react/bridge/NativeModule;
public fun getNativeModules ()Ljava/util/Collection;
public fun getReactQueueConfiguration ()Lcom/facebook/react/bridge/queue/ReactQueueConfiguration;
public fun getRuntimeExecutor ()Lcom/facebook/react/bridge/RuntimeExecutor;
public fun getRuntimeScheduler ()Lcom/facebook/react/bridge/RuntimeScheduler;
public fun getSourceURL ()Ljava/lang/String;
public fun handleMemoryPressure (I)V
public fun hasNativeModule (Ljava/lang/Class;)Z
public fun hasRunJSBundle ()Z
public fun invokeCallback (ILcom/facebook/react/bridge/NativeArrayInterface;)V
public fun isDestroyed ()Z
public fun loadScriptFromAssets (Landroid/content/res/AssetManager;Ljava/lang/String;Z)V
public fun loadScriptFromFile (Ljava/lang/String;Ljava/lang/String;Z)V
public fun loadSplitBundleFromFile (Ljava/lang/String;Ljava/lang/String;)V
public fun registerSegment (ILjava/lang/String;)V
public fun runJSBundle ()V
public fun setFabricUIManager (Lcom/facebook/react/bridge/UIManager;)V
public fun setGlobalVariable (Ljava/lang/String;Ljava/lang/String;)V
public fun setSourceURLs (Ljava/lang/String;Ljava/lang/String;)V
public fun setTurboModuleRegistry (Lcom/facebook/react/internal/turbomodule/core/interfaces/TurboModuleRegistry;)V
}
public class com/facebook/react/bridge/CatalystInstanceImpl$Builder {
public fun <init> ()V
public fun build ()Lcom/facebook/react/bridge/CatalystInstanceImpl;
public fun setJSBundleLoader (Lcom/facebook/react/bridge/JSBundleLoader;)Lcom/facebook/react/bridge/CatalystInstanceImpl$Builder;
public fun setJSExceptionHandler (Lcom/facebook/react/bridge/JSExceptionHandler;)Lcom/facebook/react/bridge/CatalystInstanceImpl$Builder;
public fun setJSExecutor (Lcom/facebook/react/bridge/JavaScriptExecutor;)Lcom/facebook/react/bridge/CatalystInstanceImpl$Builder;
public fun setReactQueueConfigurationSpec (Lcom/facebook/react/bridge/queue/ReactQueueConfigurationSpec;)Lcom/facebook/react/bridge/CatalystInstanceImpl$Builder;
public fun setRegistry (Lcom/facebook/react/bridge/NativeModuleRegistry;)Lcom/facebook/react/bridge/CatalystInstanceImpl$Builder;
}
public class com/facebook/react/bridge/CatalystInstanceImpl$PendingJSCall {
public field mArguments Lcom/facebook/react/bridge/NativeArray;
public field mMethod Ljava/lang/String;
public field mModule Ljava/lang/String;
public fun <init> (Ljava/lang/String;Ljava/lang/String;Lcom/facebook/react/bridge/NativeArray;)V
public fun toString ()Ljava/lang/String;
}
public final class com/facebook/react/bridge/ColorPropConverter {
public static final field INSTANCE Lcom/facebook/react/bridge/ColorPropConverter;
public static final fun getColor (Ljava/lang/Object;Landroid/content/Context;)Ljava/lang/Integer;
@@ -13,9 +13,6 @@ import static com.facebook.react.bridge.ReactMarkerConstants.ATTACH_MEASURED_ROO
import static com.facebook.react.bridge.ReactMarkerConstants.BUILD_NATIVE_MODULE_REGISTRY_END;
import static com.facebook.react.bridge.ReactMarkerConstants.BUILD_NATIVE_MODULE_REGISTRY_START;
import static com.facebook.react.bridge.ReactMarkerConstants.CHANGE_THREAD_PRIORITY;
import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_CATALYST_INSTANCE_END;
import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_CATALYST_INSTANCE_START;
import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_REACT_CONTEXT_START;
import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_VIEW_MANAGERS_END;
import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_VIEW_MANAGERS_START;
import static com.facebook.react.bridge.ReactMarkerConstants.PRE_SETUP_REACT_CONTEXT_END;
@@ -49,9 +46,7 @@ import com.facebook.infer.annotation.Assertions;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.infer.annotation.ThreadSafe;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.BridgeReactContext;
import com.facebook.react.bridge.CatalystInstance;
import com.facebook.react.bridge.CatalystInstanceImpl;
import com.facebook.react.bridge.JSBundleLoader;
import com.facebook.react.bridge.JSExceptionHandler;
import com.facebook.react.bridge.JavaScriptExecutor;
@@ -67,7 +62,6 @@ import com.facebook.react.bridge.UIManager;
import com.facebook.react.bridge.UIManagerProvider;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.bridge.queue.ReactQueueConfigurationSpec;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.common.ReactConstants;
import com.facebook.react.common.SurfaceDelegateFactory;
@@ -86,8 +80,6 @@ import com.facebook.react.interfaces.TaskInterface;
import com.facebook.react.internal.AndroidChoreographerProvider;
import com.facebook.react.internal.ChoreographerProvider;
import com.facebook.react.internal.featureflags.ReactNativeNewArchitectureFeatureFlags;
import com.facebook.react.internal.turbomodule.core.TurboModuleManager;
import com.facebook.react.internal.turbomodule.core.TurboModuleManagerDelegate;
import com.facebook.react.modules.appearance.AppearanceModule;
import com.facebook.react.modules.appregistry.AppRegistry;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
@@ -1395,88 +1387,10 @@ public class ReactInstanceManager {
*/
private ReactApplicationContext createReactContext(
JavaScriptExecutor jsExecutor, JSBundleLoader jsBundleLoader) {
FLog.d(ReactConstants.TAG, "ReactInstanceManager.createReactContext()");
ReactMarker.logMarker(CREATE_REACT_CONTEXT_START, jsExecutor.getName());
final BridgeReactContext reactContext = new BridgeReactContext(mApplicationContext);
JSExceptionHandler exceptionHandler =
mJSExceptionHandler != null ? mJSExceptionHandler : mDevSupportManager;
reactContext.setJSExceptionHandler(exceptionHandler);
NativeModuleRegistry nativeModuleRegistry = processPackages(reactContext, mPackages);
CatalystInstanceImpl.Builder catalystInstanceBuilder =
new CatalystInstanceImpl.Builder()
.setReactQueueConfigurationSpec(ReactQueueConfigurationSpec.createDefault())
.setJSExecutor(jsExecutor)
.setRegistry(nativeModuleRegistry)
.setJSBundleLoader(jsBundleLoader)
.setJSExceptionHandler(exceptionHandler);
ReactMarker.logMarker(CREATE_CATALYST_INSTANCE_START);
// CREATE_CATALYST_INSTANCE_END is in JSCExecutor.cpp
Systrace.beginSection(TRACE_TAG_REACT, "createCatalystInstance");
final CatalystInstance catalystInstance;
try {
catalystInstance = catalystInstanceBuilder.build();
} finally {
Systrace.endSection(TRACE_TAG_REACT);
ReactMarker.logMarker(CREATE_CATALYST_INSTANCE_END);
}
reactContext.initializeWithInstance(catalystInstance);
// On Old Architecture, we need to initialize the Native Runtime Scheduler so that
// the `nativeRuntimeScheduler` object is registered on JS.
// On New Architecture, this is normally triggered by instantiate a TurboModuleManager.
// Here we invoke getRuntimeScheduler() to trigger the creation of it regardless of the
// architecture so it will always be there.
catalystInstance.getRuntimeScheduler();
if (ReactNativeNewArchitectureFeatureFlags.useTurboModules() && mTMMDelegateBuilder != null) {
TurboModuleManagerDelegate tmmDelegate =
mTMMDelegateBuilder
.setPackages(mPackages)
.setReactApplicationContext(reactContext)
.build();
TurboModuleManager turboModuleManager =
new TurboModuleManager(
catalystInstance.getRuntimeExecutor(),
tmmDelegate,
catalystInstance.getJSCallInvokerHolder(),
catalystInstance.getNativeMethodCallInvokerHolder());
catalystInstance.setTurboModuleRegistry(turboModuleManager);
// Eagerly initialize TurboModules
for (String moduleName : turboModuleManager.getEagerInitModuleNames()) {
turboModuleManager.getModule(moduleName);
}
}
if (mUIManagerProvider != null) {
UIManager uiManager = mUIManagerProvider.createUIManager(reactContext);
if (uiManager != null) {
catalystInstance.setFabricUIManager(uiManager);
// Initialize the UIManager
uiManager.initialize();
catalystInstance.setFabricUIManager(uiManager);
}
}
if (BuildConfig.ENABLE_PERFETTO || Systrace.isTracing(TRACE_TAG_REACT)) {
catalystInstance.setGlobalVariable("__RCTProfileIsProfiling", "true");
}
ReactMarker.logMarker(ReactMarkerConstants.PRE_RUN_JS_BUNDLE_START);
Systrace.beginSection(TRACE_TAG_REACT, "runJSBundle");
catalystInstance.runJSBundle();
Systrace.endSection(TRACE_TAG_REACT);
return reactContext;
// CatalystInstanceImpl has been removed as part of the Legacy Architecture cleanup.
throw new UnsupportedOperationException(
"ReactInstanceManager.createReactContext is unsupported. CatalystInstanceImpl has been"
+ " removed.");
}
private NativeModuleRegistry processPackages(
@@ -1,621 +0,0 @@
/*
* 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.bridge;
import static com.facebook.infer.annotation.ThreadConfined.UI;
import static com.facebook.systrace.Systrace.TRACE_TAG_REACT;
import android.annotation.SuppressLint;
import android.content.res.AssetManager;
import androidx.annotation.Nullable;
import com.facebook.common.logging.FLog;
import com.facebook.infer.annotation.Assertions;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.jni.HybridData;
import com.facebook.proguard.annotations.DoNotStrip;
import com.facebook.proguard.annotations.DoNotStripAny;
import com.facebook.react.bridge.queue.MessageQueueThread;
import com.facebook.react.bridge.queue.QueueThreadExceptionHandler;
import com.facebook.react.bridge.queue.ReactQueueConfiguration;
import com.facebook.react.bridge.queue.ReactQueueConfigurationImpl;
import com.facebook.react.bridge.queue.ReactQueueConfigurationSpec;
import com.facebook.react.common.ReactConstants;
import com.facebook.react.common.annotations.VisibleForTesting;
import com.facebook.react.common.annotations.internal.LegacyArchitecture;
import com.facebook.react.common.annotations.internal.LegacyArchitectureLogLevel;
import com.facebook.react.common.annotations.internal.LegacyArchitectureLogger;
import com.facebook.react.internal.featureflags.ReactNativeNewArchitectureFeatureFlags;
import com.facebook.react.internal.turbomodule.core.interfaces.TurboModuleRegistry;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.turbomodule.core.CallInvokerHolderImpl;
import com.facebook.react.turbomodule.core.NativeMethodCallInvokerHolderImpl;
import com.facebook.systrace.Systrace;
import com.facebook.systrace.TraceListener;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicInteger;
/**
* This provides an implementation of the public CatalystInstance instance. It is public because it
* is built by ReactInstanceManager which is in a different package.
*/
@DoNotStrip
@LegacyArchitecture
@Deprecated(
since = "This class is part of Legacy Architecture and will be removed in a future release")
public class CatalystInstanceImpl implements CatalystInstance {
static {
ReactNativeJNISoLoader.staticInit();
LegacyArchitectureLogger.assertLegacyArchitecture(
"CatalystInstanceImpl", LegacyArchitectureLogLevel.WARNING);
}
private static final AtomicInteger sNextInstanceIdForTrace = new AtomicInteger(1);
public static class PendingJSCall {
public String mModule;
public String mMethod;
public @Nullable NativeArray mArguments;
public PendingJSCall(String module, String method, @Nullable NativeArray arguments) {
mModule = module;
mMethod = method;
mArguments = arguments;
}
void call(CatalystInstanceImpl catalystInstance) {
NativeArray arguments = mArguments != null ? mArguments : new WritableNativeArray();
catalystInstance.jniCallJSFunction(mModule, mMethod, arguments);
}
public String toString() {
return mModule
+ "."
+ mMethod
+ "("
+ (mArguments == null ? "" : mArguments.toString())
+ ")";
}
}
// Access from any thread
private final ReactQueueConfigurationImpl mReactQueueConfiguration;
private final AtomicInteger mPendingJSCalls = new AtomicInteger(0);
private final String mJsPendingCallsTitleForTrace =
"pending_js_calls_instance" + sNextInstanceIdForTrace.getAndIncrement();
private volatile boolean mDestroyed = false;
private final TraceListener mTraceListener;
private final JavaScriptModuleRegistry mJSModuleRegistry;
private final JSBundleLoader mJSBundleLoader;
private final ArrayList<PendingJSCall> mJSCallsPendingInit = new ArrayList<>();
private final Object mJSCallsPendingInitLock = new Object();
private final NativeModuleRegistry mNativeModuleRegistry;
private final JSExceptionHandler mJSExceptionHandler;
private final MessageQueueThread mNativeModulesQueueThread;
private boolean mInitialized = false;
private volatile boolean mAcceptCalls = false;
private boolean mJSBundleHasLoaded;
private @Nullable String mSourceURL;
private JavaScriptContextHolder mJavaScriptContextHolder;
private @Nullable TurboModuleRegistry mTurboModuleRegistry;
private @Nullable UIManager mFabricUIManager;
// C++ parts
private final HybridData mHybridData;
private static native HybridData initHybrid();
public native CallInvokerHolderImpl getJSCallInvokerHolder();
public native NativeMethodCallInvokerHolderImpl getNativeMethodCallInvokerHolder();
private CatalystInstanceImpl(
final ReactQueueConfigurationSpec reactQueueConfigurationSpec,
final JavaScriptExecutor jsExecutor,
final NativeModuleRegistry nativeModuleRegistry,
final JSBundleLoader jsBundleLoader,
JSExceptionHandler jSExceptionHandler) {
FLog.d(ReactConstants.TAG, "Initializing React Xplat Bridge.");
Systrace.beginSection(TRACE_TAG_REACT, "createCatalystInstanceImpl");
mHybridData = initHybrid();
mReactQueueConfiguration =
ReactQueueConfigurationImpl.create(
reactQueueConfigurationSpec, new NativeExceptionHandler());
mNativeModuleRegistry = nativeModuleRegistry;
mJSModuleRegistry = new JavaScriptModuleRegistry();
mJSBundleLoader = jsBundleLoader;
mJSExceptionHandler = jSExceptionHandler;
mNativeModulesQueueThread = mReactQueueConfiguration.getNativeModulesQueueThread();
mTraceListener = new JSProfilerTraceListener(this);
Systrace.endSection(TRACE_TAG_REACT);
FLog.d(ReactConstants.TAG, "Initializing React Xplat Bridge before initializeBridge");
Systrace.beginSection(TRACE_TAG_REACT, "initializeCxxBridge");
initializeBridge(
new InstanceCallback(this),
jsExecutor,
mReactQueueConfiguration.getJSQueueThread(),
mNativeModulesQueueThread,
mNativeModuleRegistry.getJavaModules(this));
FLog.d(ReactConstants.TAG, "Initializing React Xplat Bridge after initializeBridge");
Systrace.endSection(TRACE_TAG_REACT);
mJavaScriptContextHolder = new JavaScriptContextHolder(getJavaScriptContext());
}
@DoNotStripAny
private static class InstanceCallback {
// We do this so the callback doesn't keep the CatalystInstanceImpl alive.
// In this case, the callback is held in C++ code, so the GC can't see it
// and determine there's an inaccessible cycle.
private final WeakReference<CatalystInstanceImpl> mOuter;
InstanceCallback(CatalystInstanceImpl outer) {
mOuter = new WeakReference<>(outer);
}
public void incrementPendingJSCalls() {
CatalystInstanceImpl impl = mOuter.get();
if (impl != null) {
impl.incrementPendingJSCalls();
}
}
public void decrementPendingJSCalls() {
CatalystInstanceImpl impl = mOuter.get();
if (impl != null) {
impl.decrementPendingJSCalls();
}
}
}
/**
* This method and the native below permits a CatalystInstance to extend the known Native modules.
* This registry contains only the new modules to load. The registry {@code mNativeModuleRegistry}
* updates internally to contain all the new modules, and generates the new registry for
* extracting just the new collections.
*/
@Override
public void extendNativeModules(NativeModuleRegistry modules) {
// Extend the Java-visible registry of modules
mNativeModuleRegistry.registerModules(modules);
Collection<JavaModuleWrapper> javaModules = modules.getJavaModules(this);
// Extend the Cxx-visible registry of modules wrapped in appropriate interfaces
jniExtendNativeModules(javaModules);
}
private native void jniExtendNativeModules(Collection<JavaModuleWrapper> javaModules);
private native void initializeBridge(
InstanceCallback callback,
JavaScriptExecutor jsExecutor,
MessageQueueThread jsQueue,
MessageQueueThread moduleQueue,
Collection<JavaModuleWrapper> javaModules);
@Override
public void setSourceURLs(String deviceURL, String remoteURL) {
mSourceURL = deviceURL;
jniSetSourceURL(remoteURL);
}
@Override
public void registerSegment(int segmentId, String path) {
jniRegisterSegment(segmentId, path);
}
@Override
public void loadScriptFromAssets(
AssetManager assetManager, String assetURL, boolean loadSynchronously) {
mSourceURL = assetURL;
jniLoadScriptFromAssets(assetManager, assetURL, loadSynchronously);
}
@Override
public void loadScriptFromFile(String fileName, String sourceURL, boolean loadSynchronously) {
mSourceURL = sourceURL;
jniLoadScriptFromFile(fileName, sourceURL, loadSynchronously);
}
@Override
public void loadSplitBundleFromFile(String fileName, String sourceURL) {
jniLoadScriptFromFile(fileName, sourceURL, false);
}
private native void jniSetSourceURL(String sourceURL);
private native void jniRegisterSegment(int segmentId, String path);
private native void jniLoadScriptFromAssets(
AssetManager assetManager, String assetURL, boolean loadSynchronously);
private native void jniLoadScriptFromFile(
String fileName, String sourceURL, boolean loadSynchronously);
@Override
public void runJSBundle() {
FLog.d(ReactConstants.TAG, "CatalystInstanceImpl.runJSBundle()");
Assertions.assertCondition(!mJSBundleHasLoaded, "JS bundle was already loaded!");
// incrementPendingJSCalls();
mJSBundleLoader.loadScript(CatalystInstanceImpl.this);
synchronized (mJSCallsPendingInitLock) {
// Loading the bundle is queued on the JS thread, but may not have
// run yet. It's safe to set this here, though, since any work it
// gates will be queued on the JS thread behind the load.
mAcceptCalls = true;
for (PendingJSCall function : mJSCallsPendingInit) {
function.call(this);
}
mJSCallsPendingInit.clear();
mJSBundleHasLoaded = true;
}
// This is registered after JS starts since it makes a JS call
Systrace.registerListener(mTraceListener);
}
@Override
public boolean hasRunJSBundle() {
synchronized (mJSCallsPendingInitLock) {
return mJSBundleHasLoaded && mAcceptCalls;
}
}
@Override
public @Nullable String getSourceURL() {
return mSourceURL;
}
private native void jniCallJSFunction(String module, String method, NativeArray arguments);
@Override
public void callFunction(final String module, final String method, final NativeArray arguments) {
callFunction(new PendingJSCall(module, method, arguments));
}
public void callFunction(PendingJSCall function) {
if (mDestroyed) {
final String call = function.toString();
FLog.w(ReactConstants.TAG, "Calling JS function after bridge has been destroyed: " + call);
return;
}
if (!mAcceptCalls) {
// Most of the time the instance is initialized and we don't need to acquire the lock
synchronized (mJSCallsPendingInitLock) {
if (!mAcceptCalls) {
mJSCallsPendingInit.add(function);
return;
}
}
}
function.call(this);
}
private native void jniCallJSCallback(int callbackID, NativeArray arguments);
@Override
public void invokeCallback(final int callbackID, final NativeArrayInterface arguments) {
if (mDestroyed) {
FLog.w(ReactConstants.TAG, "Invoking JS callback after bridge has been destroyed.");
return;
}
jniCallJSCallback(callbackID, (NativeArray) arguments);
}
@SuppressLint("NotInvokedPrivateMethod") // Called from C++ via JNI
private native void unregisterFromInspector();
/**
* Destroys this catalyst instance, waiting for any other threads in ReactQueueConfiguration
* (besides the UI thread) to finish running. Must be called from the UI thread so that we can
* fully shut down other threads.
*/
@Override
@ThreadConfined(UI)
public void destroy() {
FLog.d(ReactConstants.TAG, "CatalystInstanceImpl.destroy() start");
UiThreadUtil.assertOnUiThread();
if (mDestroyed) {
return;
}
// TODO: tell all APIs to shut down
ReactMarker.logMarker(ReactMarkerConstants.DESTROY_CATALYST_INSTANCE_START);
mDestroyed = true;
mNativeModulesQueueThread.runOnQueue(
() -> {
mNativeModuleRegistry.notifyJSInstanceDestroy();
if (mFabricUIManager != null) {
mFabricUIManager.invalidate();
}
mPendingJSCalls.getAndSet(0);
getReactQueueConfiguration()
.getJSQueueThread()
.runOnQueue(
() -> {
// We need to destroy the TurboModuleManager on the JS Thread
if (mTurboModuleRegistry != null) {
mTurboModuleRegistry.invalidate();
}
// Kill non-UI threads from neutral third party
// potentially expensive, so don't run on UI thread
new Thread(
() -> {
// contextHolder is used as a lock to guard against
// other users of the JS VM having the VM destroyed
// underneath them, so notify them before we reset
// Native
mJavaScriptContextHolder.clear();
mHybridData.resetNative();
getReactQueueConfiguration().destroy();
FLog.w(ReactConstants.TAG, "CatalystInstanceImpl.destroy() end");
ReactMarker.logMarker(
ReactMarkerConstants.DESTROY_CATALYST_INSTANCE_END);
},
"destroy_react_context")
.start();
});
});
// This is a noop if the listener was not yet registered.
Systrace.unregisterListener(mTraceListener);
}
@Override
public boolean isDestroyed() {
return mDestroyed;
}
/** Initialize all the native modules */
@VisibleForTesting
@Override
public void initialize() {
FLog.d(ReactConstants.TAG, "CatalystInstanceImpl.initialize()");
Assertions.assertCondition(
!mInitialized, "This catalyst instance has already been initialized");
// We assume that the instance manager blocks on running the JS bundle. If
// that changes, then we need to set mAcceptCalls just after posting the
// task that will run the js bundle.
Assertions.assertCondition(mAcceptCalls, "RunJSBundle hasn't completed.");
mInitialized = true;
mNativeModulesQueueThread.runOnQueue(
() -> {
mNativeModuleRegistry.notifyJSInstanceInitialized();
});
}
@Override
public ReactQueueConfiguration getReactQueueConfiguration() {
return mReactQueueConfiguration;
}
@Override
public <T extends JavaScriptModule> T getJSModule(Class<T> jsInterface) {
return mJSModuleRegistry.getJavaScriptModule(this, jsInterface);
}
@Override
public <T extends NativeModule> boolean hasNativeModule(Class<T> nativeModuleInterface) {
String moduleName = getNameFromAnnotation(nativeModuleInterface);
return (getTurboModuleRegistry() != null && getTurboModuleRegistry().hasModule(moduleName))
|| mNativeModuleRegistry.hasModule(moduleName);
}
@Override
@Nullable
public <T extends NativeModule> T getNativeModule(Class<T> nativeModuleInterface) {
return (T) getNativeModule(getNameFromAnnotation(nativeModuleInterface));
}
private TurboModuleRegistry getTurboModuleRegistry() {
if (ReactNativeNewArchitectureFeatureFlags.useTurboModules()) {
return Assertions.assertNotNull(
mTurboModuleRegistry,
"TurboModules are enabled, but mTurboModuleRegistry hasn't been set.");
}
return null;
}
@Override
@Nullable
public NativeModule getNativeModule(String moduleName) {
if (getTurboModuleRegistry() != null) {
NativeModule module = getTurboModuleRegistry().getModule(moduleName);
if (module != null) {
return module;
}
}
return mNativeModuleRegistry.hasModule(moduleName)
? mNativeModuleRegistry.getModule(moduleName)
: null;
}
private <T extends NativeModule> String getNameFromAnnotation(Class<T> nativeModuleInterface) {
ReactModule annotation = nativeModuleInterface.getAnnotation(ReactModule.class);
if (annotation == null) {
throw new IllegalArgumentException(
"Could not find @ReactModule annotation in " + nativeModuleInterface.getCanonicalName());
}
return annotation.name();
}
// This is only used by com.facebook.react.modules.common.ModuleDataCleaner
@Override
public Collection<NativeModule> getNativeModules() {
Collection<NativeModule> nativeModules = new ArrayList<>();
nativeModules.addAll(mNativeModuleRegistry.getAllModules());
if (getTurboModuleRegistry() != null) {
for (NativeModule module : getTurboModuleRegistry().getModules()) {
nativeModules.add(module);
}
}
return nativeModules;
}
private native void jniHandleMemoryPressure(int level);
@Override
public void handleMemoryPressure(int level) {
if (mDestroyed) {
return;
}
jniHandleMemoryPressure(level);
}
@Override
public native void setGlobalVariable(String propName, String jsonValue);
@Override
public JavaScriptContextHolder getJavaScriptContextHolder() {
return mJavaScriptContextHolder;
}
public native RuntimeExecutor getRuntimeExecutor();
public native RuntimeScheduler getRuntimeScheduler();
private native long getJavaScriptContext();
private void incrementPendingJSCalls() {
int oldPendingCalls = mPendingJSCalls.getAndIncrement();
Systrace.traceCounter(TRACE_TAG_REACT, mJsPendingCallsTitleForTrace, oldPendingCalls + 1);
}
@Override
public void setTurboModuleRegistry(TurboModuleRegistry turboModuleRegistry) {
mTurboModuleRegistry = turboModuleRegistry;
}
@Override
public void setFabricUIManager(UIManager fabricUIManager) {
mFabricUIManager = fabricUIManager;
}
@Override
public UIManager getFabricUIManager() {
return mFabricUIManager;
}
private void decrementPendingJSCalls() {
int newPendingCalls = mPendingJSCalls.decrementAndGet();
// TODO(9604406): handle case of web workers injecting messages to main thread
// Assertions.assertCondition(newPendingCalls >= 0);
Systrace.traceCounter(TRACE_TAG_REACT, mJsPendingCallsTitleForTrace, newPendingCalls);
}
private void onNativeException(Exception e) {
mJSExceptionHandler.handleException(e);
mReactQueueConfiguration
.getUIQueueThread()
.runOnQueue(
() -> {
destroy();
});
}
private class NativeExceptionHandler implements QueueThreadExceptionHandler {
@Override
public void handleException(Exception e) {
// Any Exception caught here is because of something in JS. Even if it's a bug in the
// framework/native code, it was triggered by JS and theoretically since we were able
// to set up the bridge, JS could change its logic, reload, and not trigger that crash.
onNativeException(e);
}
}
private static class JSProfilerTraceListener implements TraceListener {
// We do this so the callback doesn't keep the CatalystInstanceImpl alive.
// In this case, Systrace will keep the registered listener around forever
// if the CatalystInstanceImpl is not explicitly destroyed. These instances
// can still leak, but they are at least small.
private final WeakReference<CatalystInstanceImpl> mOuter;
public JSProfilerTraceListener(CatalystInstanceImpl outer) {
mOuter = new WeakReference<CatalystInstanceImpl>(outer);
}
@Override
public void onTraceStarted() {
CatalystInstanceImpl impl = mOuter.get();
if (impl != null) {
impl.getJSModule(com.facebook.react.bridge.Systrace.class).setEnabled(true);
}
}
@Override
public void onTraceStopped() {
CatalystInstanceImpl impl = mOuter.get();
if (impl != null) {
impl.getJSModule(com.facebook.react.bridge.Systrace.class).setEnabled(false);
}
}
}
public static class Builder {
private @Nullable ReactQueueConfigurationSpec mReactQueueConfigurationSpec;
private @Nullable JSBundleLoader mJSBundleLoader;
private @Nullable NativeModuleRegistry mRegistry;
private @Nullable JavaScriptExecutor mJSExecutor;
private @Nullable JSExceptionHandler mJSExceptionHandler;
public Builder setReactQueueConfigurationSpec(
ReactQueueConfigurationSpec ReactQueueConfigurationSpec) {
mReactQueueConfigurationSpec = ReactQueueConfigurationSpec;
return this;
}
public Builder setRegistry(NativeModuleRegistry registry) {
mRegistry = registry;
return this;
}
public Builder setJSBundleLoader(JSBundleLoader jsBundleLoader) {
mJSBundleLoader = jsBundleLoader;
return this;
}
public Builder setJSExecutor(JavaScriptExecutor jsExecutor) {
mJSExecutor = jsExecutor;
return this;
}
public Builder setJSExceptionHandler(JSExceptionHandler handler) {
mJSExceptionHandler = handler;
return this;
}
public CatalystInstanceImpl build() {
return new CatalystInstanceImpl(
Assertions.assertNotNull(mReactQueueConfigurationSpec),
Assertions.assertNotNull(mJSExecutor),
Assertions.assertNotNull(mRegistry),
Assertions.assertNotNull(mJSBundleLoader),
Assertions.assertNotNull(mJSExceptionHandler));
}
}
}
@@ -51,7 +51,6 @@ include(${REACT_ANDROID_DIR}/src/main/jni/first-party/jni-lib-merge/SoMerging-ut
add_library(
reactnativejni
OBJECT
CatalystInstanceImpl.cpp
InspectorNetworkRequestListener.cpp
JExecutor.cpp
JMessageQueueThread.cpp
@@ -1,410 +0,0 @@
/*
* 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.
*/
#include "CatalystInstanceImpl.h"
#include <fstream>
#include <memory>
#include <utility>
#include <ReactCommon/CallInvokerHolder.h>
#include <cxxreact/CxxNativeModule.h>
#include <cxxreact/Instance.h>
#include <cxxreact/JSBigString.h>
#include <cxxreact/JSBundleType.h>
#include <cxxreact/JSIndexedRAMBundle.h>
#include <cxxreact/MethodCall.h>
#include <cxxreact/ModuleRegistry.h>
#include <cxxreact/RAMBundleRegistry.h>
#include <cxxreact/RecoverableError.h>
#include <fbjni/ByteBuffer.h>
#include <folly/dynamic.h>
#include <glog/logging.h>
#include <react/renderer/runtimescheduler/RuntimeScheduler.h>
#include <react/renderer/runtimescheduler/RuntimeSchedulerBinding.h>
#include <react/renderer/runtimescheduler/RuntimeSchedulerCallInvoker.h>
#include <logger/react_native_log.h>
#include "JReactSoftExceptionLogger.h"
#include "JavaScriptExecutorHolder.h"
#include "JniJSModulesUnbundle.h"
#include "NativeArray.h"
#ifndef RCT_REMOVE_LEGACY_ARCH
using namespace facebook::jni;
namespace facebook::react {
namespace {
class [[deprecated(
"This API will be removed along with the legacy architecture.")]]
InstanceCallbackImpl : public InstanceCallback {
public:
explicit InstanceCallbackImpl(alias_ref<JInstanceCallback::javaobject> jobj)
: jobj_(make_global(jobj)) {}
void onBatchComplete() override {
jni::ThreadScope guard;
static auto method =
JInstanceCallback::javaClassStatic()->getMethod<void()>(
"onBatchComplete");
method(jobj_);
}
void incrementPendingJSCalls() override {
// For C++ modules, this can be called from an arbitrary thread
// managed by the module, via callJSCallback or callJSFunction. So,
// we ensure that it is registered with the JVM.
jni::ThreadScope guard;
static auto method =
JInstanceCallback::javaClassStatic()->getMethod<void()>(
"incrementPendingJSCalls");
method(jobj_);
}
void decrementPendingJSCalls() override {
jni::ThreadScope guard;
static auto method =
JInstanceCallback::javaClassStatic()->getMethod<void()>(
"decrementPendingJSCalls");
method(jobj_);
}
private:
global_ref<JInstanceCallback::javaobject> jobj_;
};
} // namespace
jni::local_ref<CatalystInstanceImpl::jhybriddata>
CatalystInstanceImpl::initHybrid(jni::alias_ref<jclass> /*unused*/) {
return makeCxxInstance();
}
CatalystInstanceImpl::CatalystInstanceImpl()
: instance_(std::make_unique<Instance>()) {}
void CatalystInstanceImpl::registerNatives() {
registerHybrid({
makeNativeMethod("initHybrid", CatalystInstanceImpl::initHybrid),
makeNativeMethod(
"initializeBridge", CatalystInstanceImpl::initializeBridge),
makeNativeMethod(
"jniExtendNativeModules", CatalystInstanceImpl::extendNativeModules),
makeNativeMethod(
"jniSetSourceURL", CatalystInstanceImpl::jniSetSourceURL),
makeNativeMethod(
"jniRegisterSegment", CatalystInstanceImpl::jniRegisterSegment),
makeNativeMethod(
"jniLoadScriptFromAssets",
CatalystInstanceImpl::jniLoadScriptFromAssets),
makeNativeMethod(
"jniLoadScriptFromFile", CatalystInstanceImpl::jniLoadScriptFromFile),
makeNativeMethod(
"jniCallJSFunction", CatalystInstanceImpl::jniCallJSFunction),
makeNativeMethod(
"jniCallJSCallback", CatalystInstanceImpl::jniCallJSCallback),
makeNativeMethod(
"setGlobalVariable", CatalystInstanceImpl::setGlobalVariable),
makeNativeMethod(
"getJavaScriptContext", CatalystInstanceImpl::getJavaScriptContext),
makeNativeMethod(
"getJSCallInvokerHolder",
CatalystInstanceImpl::getJSCallInvokerHolder),
makeNativeMethod(
"getNativeMethodCallInvokerHolder",
CatalystInstanceImpl::getNativeMethodCallInvokerHolder),
makeNativeMethod(
"jniHandleMemoryPressure",
CatalystInstanceImpl::handleMemoryPressure),
makeNativeMethod(
"getRuntimeExecutor", CatalystInstanceImpl::getRuntimeExecutor),
makeNativeMethod(
"getRuntimeScheduler", CatalystInstanceImpl::getRuntimeScheduler),
makeNativeMethod(
"unregisterFromInspector",
CatalystInstanceImpl::unregisterFromInspector),
});
}
void log(ReactNativeLogLevel level, const char* message) {
switch (level) {
case ReactNativeLogLevelInfo:
LOG(INFO) << message;
break;
case ReactNativeLogLevelWarning:
LOG(WARNING) << message;
JReactSoftExceptionLogger::logNoThrowSoftExceptionWithMessage(
"react_native_log#warning", message);
break;
case ReactNativeLogLevelError:
LOG(ERROR) << message;
break;
case ReactNativeLogLevelFatal:
LOG(FATAL) << message;
break;
}
}
void CatalystInstanceImpl::initializeBridge(
jni::alias_ref<JInstanceCallback::javaobject> callback,
// This executor is actually a factory holder.
JavaScriptExecutorHolder* jseh,
jni::alias_ref<JavaMessageQueueThread::javaobject> jsQueue,
jni::alias_ref<JavaMessageQueueThread::javaobject> nativeModulesQueue,
jni::alias_ref<jni::JCollection<JavaModuleWrapper::javaobject>::javaobject>
javaModules) {
set_react_native_logfunc(&log);
// TODO mhorowitz: how to assert here?
// Assertions.assertCondition(mBridge == null, "initializeBridge should be
// called once");
moduleMessageQueue_ =
std::make_shared<JMessageQueueThread>(nativeModulesQueue);
// This used to be:
//
// Java CatalystInstanceImpl -> C++ CatalystInstanceImpl -> Bridge ->
// Bridge::Callback
// --weak--> ReactCallback -> Java CatalystInstanceImpl
//
// Now the weak ref is a global ref. So breaking the loop depends on
// CatalystInstanceImpl#destroy() calling mHybridData.resetNative(), which
// should cause all the C++ pointers to be cleaned up (except C++
// CatalystInstanceImpl might be kept alive for a short time by running
// callbacks). This also means that all native calls need to be pre-checked
// to avoid NPE.
// See the comment in callJSFunction. Once js calls switch to strings, we
// don't need jsModuleDescriptions any more, all the way up and down the
// stack.
moduleRegistry_ = std::make_shared<ModuleRegistry>(buildNativeModuleList(
std::weak_ptr<Instance>(instance_), javaModules, moduleMessageQueue_));
instance_->initializeBridge(
std::make_unique<InstanceCallbackImpl>(callback),
jseh->getExecutorFactory(),
std::make_unique<JMessageQueueThread>(jsQueue),
moduleRegistry_);
}
void CatalystInstanceImpl::extendNativeModules(
jni::alias_ref<jni::JCollection<JavaModuleWrapper::javaobject>::javaobject>
javaModules) {
moduleRegistry_->registerModules(buildNativeModuleList(
std::weak_ptr<Instance>(instance_), javaModules, moduleMessageQueue_));
}
void CatalystInstanceImpl::jniSetSourceURL(const std::string& sourceURL) {
instance_->setSourceURL(sourceURL);
}
void CatalystInstanceImpl::jniRegisterSegment(
int segmentId,
const std::string& path) {
instance_->registerBundle((uint32_t)segmentId, path);
}
static ScriptTag getScriptTagFromFile(const char* sourcePath) {
std::ifstream bundle_stream(sourcePath, std::ios_base::in);
BundleHeader header;
if (bundle_stream &&
bundle_stream.read(reinterpret_cast<char*>(&header), sizeof(header))) {
return parseTypeFromHeader(header);
} else {
return ScriptTag::String;
}
}
static bool isIndexedRAMBundle(std::unique_ptr<const JSBigString>* script) {
BundleHeader header;
strncpy(
reinterpret_cast<char*>(&header), script->get()->c_str(), sizeof(header));
return parseTypeFromHeader(header) == ScriptTag::RAMBundle;
}
void CatalystInstanceImpl::jniLoadScriptFromAssets(
jni::alias_ref<JAssetManager::javaobject> assetManager,
const std::string& assetURL,
bool loadSynchronously) {
const int kAssetsLength = 9; // strlen("assets://");
auto sourceURL = assetURL.substr(kAssetsLength);
auto manager = extractAssetManager(assetManager);
auto script = loadScriptFromAssets(manager, sourceURL);
if (JniJSModulesUnbundle::isUnbundle(manager, sourceURL)) {
auto bundle = JniJSModulesUnbundle::fromEntryFile(manager, sourceURL);
auto registry = RAMBundleRegistry::singleBundleRegistry(std::move(bundle));
instance_->loadRAMBundle(
std::move(registry), std::move(script), sourceURL, loadSynchronously);
return;
} else if (isIndexedRAMBundle(&script)) {
instance_->loadRAMBundleFromString(std::move(script), sourceURL);
} else {
instance_->loadScriptFromString(
std::move(script), sourceURL, loadSynchronously);
}
}
void CatalystInstanceImpl::jniLoadScriptFromFile(
const std::string& fileName,
const std::string& sourceURL,
bool loadSynchronously) {
auto reactInstance = instance_;
if (!reactInstance) {
return;
}
switch (getScriptTagFromFile(fileName.c_str())) {
case ScriptTag::RAMBundle:
instance_->loadRAMBundleFromFile(fileName, sourceURL, loadSynchronously);
break;
case ScriptTag::String:
default: {
std::unique_ptr<const JSBigFileString> script;
RecoverableError::runRethrowingAsRecoverable<std::system_error>(
[&fileName, &script]() {
script = JSBigFileString::fromPath(fileName);
});
instance_->loadScriptFromString(
std::move(script), sourceURL, loadSynchronously);
}
}
}
void CatalystInstanceImpl::jniCallJSFunction(
std::string module,
std::string method,
NativeArray* arguments) {
// We want to share the C++ code, and on iOS, modules pass module/method
// names as strings all the way through to JS, and there's no way to do
// string -> id mapping on the objc side. So on Android, we convert the
// number to a string, here which gets passed as-is to JS. There, they they
// used as ids if isFinite(), which handles this case, and looked up as
// strings otherwise. Eventually, we'll probably want to modify the stack
// from the JS proxy through here to use strings, too.
instance_->callJSFunction(
std::move(module), std::move(method), arguments->consume());
}
void CatalystInstanceImpl::jniCallJSCallback(
jint callbackId,
NativeArray* arguments) {
instance_->callJSCallback(callbackId, arguments->consume());
}
void CatalystInstanceImpl::setGlobalVariable(
std::string propName,
std::string&& jsonValue) {
// This is only ever called from Java with short strings, and only
// for testing, so no need to try hard for zero-copy here.
instance_->setGlobalVariable(
std::move(propName),
std::make_unique<JSBigStdString>(std::move(jsonValue)));
}
jlong CatalystInstanceImpl::getJavaScriptContext() {
return (jlong)(intptr_t)instance_->getJavaScriptContext();
}
void CatalystInstanceImpl::handleMemoryPressure(int pressureLevel) {
instance_->handleMemoryPressure(pressureLevel);
}
jni::alias_ref<CallInvokerHolder::javaobject>
CatalystInstanceImpl::getJSCallInvokerHolder() {
if (!jsCallInvokerHolder_) {
auto runtimeScheduler = getRuntimeScheduler();
auto runtimeSchedulerCallInvoker =
std::make_shared<RuntimeSchedulerCallInvoker>(
runtimeScheduler->cthis()->get());
jsCallInvokerHolder_ = jni::make_global(
CallInvokerHolder::newObjectCxxArgs(runtimeSchedulerCallInvoker));
}
return jsCallInvokerHolder_;
}
jni::alias_ref<NativeMethodCallInvokerHolder::javaobject>
CatalystInstanceImpl::getNativeMethodCallInvokerHolder() {
if (!nativeMethodCallInvokerHolder_) {
class NativeMethodCallInvokerImpl : public NativeMethodCallInvoker {
private:
std::shared_ptr<JMessageQueueThread> messageQueueThread_;
public:
NativeMethodCallInvokerImpl(
std::shared_ptr<JMessageQueueThread> messageQueueThread)
: messageQueueThread_(std::move(messageQueueThread)) {}
void invokeAsync(
const std::string& /*methodName*/,
std::function<void()>&& work) noexcept override {
messageQueueThread_->runOnQueue(std::move(work));
}
void invokeSync(
const std::string& /*methodName*/,
std::function<void()>&& work) override {
messageQueueThread_->runOnQueueSync(std::move(work));
}
};
std::shared_ptr<NativeMethodCallInvoker> nativeMethodCallInvoker =
std::make_shared<NativeMethodCallInvokerImpl>(moduleMessageQueue_);
std::shared_ptr<NativeMethodCallInvoker> decoratedNativeMethodCallInvoker =
instance_->getDecoratedNativeMethodCallInvoker(nativeMethodCallInvoker);
nativeMethodCallInvokerHolder_ = jni::make_global(
NativeMethodCallInvokerHolder::newObjectCxxArgs(
decoratedNativeMethodCallInvoker));
}
return nativeMethodCallInvokerHolder_;
}
jni::alias_ref<JRuntimeExecutor::javaobject>
CatalystInstanceImpl::getRuntimeExecutor() {
if (!runtimeExecutor_) {
auto executor = instance_->getRuntimeExecutor();
if (executor) {
runtimeExecutor_ =
jni::make_global(JRuntimeExecutor::newObjectCxxArgs(executor));
}
}
return runtimeExecutor_;
}
jni::alias_ref<JRuntimeScheduler::javaobject>
CatalystInstanceImpl::getRuntimeScheduler() {
if (!runtimeScheduler_) {
auto runtimeExecutor = instance_->getRuntimeExecutor();
if (runtimeExecutor) {
auto runtimeScheduler =
std::make_shared<RuntimeScheduler>(runtimeExecutor);
runtimeScheduler_ = jni::make_global(
JRuntimeScheduler::newObjectCxxArgs(runtimeScheduler));
runtimeExecutor([scheduler =
std::move(runtimeScheduler)](jsi::Runtime& runtime) {
RuntimeSchedulerBinding::createAndInstallIfNeeded(runtime, scheduler);
});
}
}
return runtimeScheduler_;
}
void CatalystInstanceImpl::unregisterFromInspector() {
instance_->unregisterFromInspector();
}
} // namespace facebook::react
#endif
@@ -1,113 +0,0 @@
/*
* 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.
*/
#include <memory>
#include <string>
#include <ReactCommon/CallInvokerHolder.h>
#include <ReactCommon/NativeMethodCallInvokerHolder.h>
#include <ReactCommon/RuntimeExecutor.h>
#include <fbjni/fbjni.h>
#include "JMessageQueueThread.h"
#include "JRuntimeExecutor.h"
#include "JRuntimeScheduler.h"
#include "JSLoader.h"
#include "JavaModuleWrapper.h"
#include "ModuleRegistryBuilder.h"
#ifndef RCT_REMOVE_LEGACY_ARCH
namespace facebook::react {
class Instance;
class JavaScriptExecutorHolder;
class NativeArray;
struct [[deprecated("This API will be removed along with the legacy architecture.")]] JInstanceCallback
: public jni::JavaClass<JInstanceCallback> {
static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/CatalystInstanceImpl$InstanceCallback;";
};
class [[deprecated("This API will be removed along with the legacy architecture.")]] CatalystInstanceImpl
: public jni::HybridClass<CatalystInstanceImpl> {
public:
static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/CatalystInstanceImpl;";
static jni::local_ref<jhybriddata> initHybrid(jni::alias_ref<jclass> /*unused*/);
static void registerNatives();
std::shared_ptr<Instance> getInstance()
{
return instance_;
}
private:
friend HybridBase;
CatalystInstanceImpl();
void initializeBridge(
jni::alias_ref<JInstanceCallback::javaobject> callback,
// This executor is actually a factory holder.
JavaScriptExecutorHolder *jseh,
jni::alias_ref<JavaMessageQueueThread::javaobject> jsQueue,
jni::alias_ref<JavaMessageQueueThread::javaobject> nativeModulesQueue,
jni::alias_ref<jni::JCollection<JavaModuleWrapper::javaobject>::javaobject> javaModules);
void extendNativeModules(jni::alias_ref<jni::JCollection<JavaModuleWrapper::javaobject>::javaobject> javaModules);
/**
* Sets the source URL of the underlying bridge without loading any JS code.
*/
void jniSetSourceURL(const std::string &sourceURL);
/**
* Registers the file path of an additional JS segment by its ID.
*
*/
void jniRegisterSegment(int segmentId, const std::string &path);
void jniLoadScriptFromAssets(
jni::alias_ref<JAssetManager::javaobject> assetManager,
const std::string &assetURL,
bool loadSynchronously);
void jniLoadScriptFromFile(const std::string &fileName, const std::string &sourceURL, bool loadSynchronously);
void jniCallJSFunction(std::string module, std::string method, NativeArray *arguments);
void jniCallJSCallback(jint callbackId, NativeArray *arguments);
jni::alias_ref<CallInvokerHolder::javaobject> getJSCallInvokerHolder();
jni::alias_ref<NativeMethodCallInvokerHolder::javaobject> getNativeMethodCallInvokerHolder();
jni::alias_ref<JRuntimeExecutor::javaobject> getRuntimeExecutor();
jni::alias_ref<JRuntimeScheduler::javaobject> getRuntimeScheduler();
void setGlobalVariable(std::string propName, std::string &&jsonValue);
jlong getJavaScriptContext();
void handleMemoryPressure(int pressureLevel);
void createAndInstallRuntimeSchedulerIfNecessary();
/**
* Unregisters the instance from the inspector. This method must be called
* on the main thread, after initializeBridge has finished executing and
* before the destructor for Instance has started.
*/
void unregisterFromInspector();
// This should be the only long-lived strong reference, but every C++ class
// will have a weak reference.
std::shared_ptr<Instance> instance_;
std::shared_ptr<ModuleRegistry> moduleRegistry_;
std::shared_ptr<JMessageQueueThread> moduleMessageQueue_;
jni::global_ref<CallInvokerHolder::javaobject> jsCallInvokerHolder_;
jni::global_ref<NativeMethodCallInvokerHolder::javaobject> nativeMethodCallInvokerHolder_;
jni::global_ref<JRuntimeExecutor::javaobject> runtimeExecutor_;
jni::global_ref<JRuntimeScheduler::javaobject> runtimeScheduler_;
};
} // namespace facebook::react
#endif
@@ -12,6 +12,7 @@
#include <cxxreact/CxxNativeModule.h>
#include <cxxreact/Instance.h>
#include <cxxreact/JsArgumentHelpers.h>
#include <cxxreact/MessageQueueThread.h>
#include <cxxreact/NativeModule.h>
#include <fbjni/fbjni.h>
@@ -19,7 +20,6 @@
#include <fbsystrace.h>
#endif
#include "CatalystInstanceImpl.h"
#include "ReadableNativeArray.h"
#ifndef RCT_REMOVE_LEGACY_ARCH
@@ -10,7 +10,6 @@
#include <fb/glog_init.h>
#include <fbjni/fbjni.h>
#include "CatalystInstanceImpl.h"
#include "InspectorNetworkRequestListener.h"
#include "JavaScriptExecutorHolder.h"
@@ -33,12 +32,6 @@ extern "C" JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
#if WITH_GLOGINIT
gloginit::initialize();
FLAGS_minloglevel = 0;
#endif
#ifndef RCT_REMOVE_LEGACY_ARCH
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
CatalystInstanceImpl::registerNatives();
#pragma clang diagnostic pop
#endif
InspectorNetworkRequestListener::registerNatives();
});