Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add support for C++ TurboModules Autolinking #2296

Merged
merged 7 commits into from
Feb 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/autolinking.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ The [native_modules.gradle](https://github.com/react-native-community/cli/blob/m
1. A first Gradle plugin (in `settings.gradle`) runs `applyNativeModulesSettingsGradle` method. It uses the package metadata from `react-native config` to add Android projects.
1. A second Gradle plugin (in `app/build.gradle`) runs `applyNativeModulesAppBuildGradle` method. It creates a list of React Native packages to include in the generated `/android/build/generated/rn/src/main/java/com/facebook/react/PackageList.java` file.
1. When the new architecture is turned on, the `generateNewArchitectureFiles` task is fired, generating `/android/build/generated/rn/src/main/jni` directory with the following files:
- `Android-rncli.mk` – creates a list of codegen'd libs. Used by the project's `Android.mk`.
- `Android-rncli.cmake` – creates a list of codegen'd libs. Used by the project's `CMakeLists.txt`.
- `rncli.cpp` – registers codegen'd Turbo Modules and Fabric component providers. Used by `MainApplicationModuleProvider.cpp` and `MainComponentsRegistry.cpp`.
- `rncli.h` - a header file for `rncli.cpp`.
Expand Down Expand Up @@ -117,6 +116,9 @@ module.exports = {
libraryName: null,
componentDescriptors: null,
cmakeListsPath: null,
cxxModuleCMakeListsModuleName: null,
cxxModuleCMakeListsPath: null,
cxxModuleHeaderName: null,
},
},
},
Expand Down
47 changes: 47 additions & 0 deletions docs/dependencies.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ type AndroidDependencyParams = {
libraryName?: string | null;
componentDescriptors?: string[] | null;
cmakeListsPath?: string | null;
cxxModuleCMakeListsModuleName?: string | null;
cxxModuleCMakeListsPath?: string | null;
cxxModuleHeaderName?: string | null;
};
```

Expand Down Expand Up @@ -140,3 +143,47 @@ An array of custom component descriptor strings. By default they're generated ba
> Note: Only applicable when new architecture is turned on.

A relative path to a custom _CMakeLists.txt_ file not registered by codegen. Relative to `sourceDir`.

#### platforms.android.cxxModuleCMakeListsModuleName

> Note: Only applicable when new architecture is turned on and for C++ TurboModules.

The name of the CMake target that is building the C++ Turbo Module. This is generally
different from the codegen target which is called `react_codegen_<yourlibrary>`.
You will need to create a custom `CMakeLists.txt`, which defines a target, depends on `react_codegen_<yourlibrary>` and builds your C++ Turbo Module.
Specify the name of the target here so that it can be properly linked to the rest of the app project.

#### platforms.android.cxxModuleCMakeListsPath

> Note: Only applicable when new architecture is turned on and for C++ TurboModules.

A relative path to a custom _CMakeLists.txt_ file that is used to build a C++ TurboModule. Relative to `sourceDir`.

#### platforms.android.cxxModuleHeaderName

> Note: Only applicable when new architecture is turned on and for C++ TurboModules.

The name of the C++ TurboModule. Your C++ TurboModule generally should implement one of the JSI interface generated by Codegen. You need to specify the name of the class that is implementing the generated interface here, so that it can properly be linked in the rest of the app project.

We expect that your module exposes a field called `kModuleName` which is a string that contains the name of the module. This field is properly populated by codegen, but if you don't use codegen, you will have to make sure that this field is present.

Say your module name is `NativeCxxModuleExample`, it will be included in the autolinking logic as follows:

```cpp
// We will include a header called as your module
#include <NativeCxxModuleExample.h>

...

std::shared_ptr<TurboModule> rncli_cxxModuleProvider(
const std::string& name,
const std::shared_ptr<CallInvoker>& jsInvoker) {

// Here we expect you have a field called kModuleName
if (name == NativeCxxModuleExample::kModuleName) {
// Here we initialize your module
return std::make_shared<NativeCxxModuleExample>(jsInvoker);
}
return nullptr;
}
```
3 changes: 3 additions & 0 deletions docs/platforms.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,5 +125,8 @@ type AndroidDependencyConfig = {
libraryName?: string | null;
componentDescriptors?: string[] | null;
cmakeListsPath?: string | null;
cxxModuleCMakeListsModuleName? : string | null;
cxxModuleCMakeListsPath? : string | null;
cxxModuleHeaderName? : string | null;
};
```
3 changes: 3 additions & 0 deletions packages/cli-config/src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,9 @@ export const dependencyConfig = t
libraryName: t.string().allow(null),
componentDescriptors: t.array().items(t.string()).allow(null),
cmakeListsPath: t.string().allow(null),
cxxModuleCMakeListsModuleName: t.string().allow(null),
cxxModuleCMakeListsPath: t.string().allow(null),
cxxModuleHeaderName: t.string().allow(null),
})
.allow(null),
})
Expand Down
50 changes: 43 additions & 7 deletions packages/cli-platform-android/native_modules.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,12 @@ namespace react {
{{ rncliReactLegacyComponentNames }}

std::shared_ptr<TurboModule> rncli_ModuleProvider(const std::string moduleName, const JavaTurboModule::InitParams &params) {
{{ rncliCppModuleProviders }}
{{ rncliCppTurboModuleJavaProviders }}
return nullptr;
}

std::shared_ptr<TurboModule> rncli_cxxModuleProvider(const std::string moduleName, const std::shared_ptr<CallInvoker>& jsInvoker) {
{{ rncliCppTurboModuleCxxProviders }}
return nullptr;
}

Expand All @@ -121,6 +126,7 @@ def rncliHTemplate = """/**

#pragma once

#include <ReactCommon/CallInvoker.h>
#include <ReactCommon/JavaTurboModule.h>
#include <ReactCommon/TurboModule.h>
#include <jsi/jsi.h>
Expand All @@ -130,6 +136,7 @@ namespace facebook {
namespace react {

std::shared_ptr<TurboModule> rncli_ModuleProvider(const std::string moduleName, const JavaTurboModule::InitParams &params);
std::shared_ptr<TurboModule> rncli_cxxModuleProvider(const std::string moduleName, const std::shared_ptr<CallInvoker>& jsInvoker);
void rncli_registerProviders(std::shared_ptr<ComponentDescriptorProviderRegistry const> providerRegistry);

} // namespace react
Expand Down Expand Up @@ -258,7 +265,7 @@ class ReactNativeModules {
w << generatedFileContents
}
}

cortinico marked this conversation as resolved.
Show resolved Hide resolved
void generateCmakeFile(File outputDir, String generatedFileName, String generatedFileContentsTemplate) {
ArrayList<HashMap<String, String>> packages = this.reactNativeModules
String packageName = this.packageName
Expand All @@ -268,16 +275,29 @@ class ReactNativeModules {

if (packages.size() > 0) {
libraryIncludes = packages.collect {
def addDirectoryString = ""
if (it.libraryName != null && it.cmakeListsPath != null) {
// If user provided a custom cmakeListsPath, let's honor it.
String nativeFolderPath = it.cmakeListsPath.replace("CMakeLists.txt", "")
"add_subdirectory($nativeFolderPath ${it.libraryName}_autolinked_build)"
addDirectoryString += "add_subdirectory($nativeFolderPath ${it.libraryName}_autolinked_build)"
} else {
null
}
if (it.cxxModuleCMakeListsPath != null) {
// If user provided a custom cxxModuleCMakeListsPath, let's honor it.
String nativeFolderPath = it.cxxModuleCMakeListsPath.replace("CMakeLists.txt", "")
addDirectoryString += "\nadd_subdirectory($nativeFolderPath ${it.libraryName}_cxxmodule_autolinked_build)"
}
addDirectoryString
}.minus(null).join('\n')
libraryModules = packages.collect {
it.libraryName ? "${codegenLibPrefix}${it.libraryName}" : null
def autolinkedLibraries = ""
if (it.libraryName != null) {
autolinkedLibraries += "${codegenLibPrefix}${it.libraryName}"
}
if (it.cxxModuleCMakeListsModuleName != null) {
autolinkedLibraries += "\n${it.cxxModuleCMakeListsModuleName}"
}
}.minus(null).join('\n ')
}

Expand All @@ -295,7 +315,8 @@ class ReactNativeModules {
void generateRncliCpp(File outputDir, String generatedFileName, String generatedFileContentsTemplate) {
ArrayList<HashMap<String, String>> packages = this.reactNativeModules
String rncliCppIncludes = ""
String rncliCppModuleProviders = ""
String rncliCppTurboModuleJavaProviders = ""
String rncliCppTurboModuleCxxProviders = ""
String rncliCppComponentDescriptors = ""
String rncliReactLegacyComponentDescriptors = ""
String rncliReactLegacyComponentNames = ""
Expand All @@ -311,14 +332,25 @@ class ReactNativeModules {
if (it.componentDescriptors && it.componentDescriptors.size() > 0) {
result += "\n#include <${codegenReactComponentsDir}/${it.libraryName}/${codegenComponentDescriptorsHeaderFile}>"
}
if (it.cxxModuleHeaderName) {
result += "\n#include <${it.cxxModuleHeaderName}.h>"
}
result
}.minus(null).join('\n')
rncliCppModuleProviders = packages.collect {
rncliCppTurboModuleJavaProviders = packages.collect {
it.libraryName ? """ auto module_${it.libraryName} = ${it.libraryName}_ModuleProvider(moduleName, params);
if (module_${it.libraryName} != nullptr) {
return module_${it.libraryName};
}""" : null
}.minus(null).join("\n")

rncliCppTurboModuleCxxProviders = packages.collect {
it.cxxModuleHeaderName ? """
if (moduleName == ${it.cxxModuleHeaderName}::kModuleName) {
return std::make_shared<${it.cxxModuleHeaderName}>(jsInvoker);
}""" : null
}.minus(null).join("\n")

rncliCppComponentDescriptors = packages.collect {
def result = ""
if (it.componentDescriptors && it.componentDescriptors.size() > 0) {
Expand All @@ -332,7 +364,8 @@ class ReactNativeModules {

String generatedFileContents = generatedFileContentsTemplate
.replace("{{ rncliCppIncludes }}", rncliCppIncludes)
.replace("{{ rncliCppModuleProviders }}", rncliCppModuleProviders)
.replace("{{ rncliCppTurboModuleJavaProviders }}", rncliCppTurboModuleJavaProviders)
.replace("{{ rncliCppTurboModuleCxxProviders }}", rncliCppTurboModuleCxxProviders)
.replace("{{ rncliCppComponentDescriptors }}", rncliCppComponentDescriptors)
.replace("{{ rncliReactLegacyComponentDescriptors }}", rncliReactLegacyComponentDescriptors)
.replace("{{ rncliReactLegacyComponentNames }}", rncliReactLegacyComponentNames)
Expand Down Expand Up @@ -434,6 +467,9 @@ class ReactNativeModules {
reactNativeModuleConfig.put("libraryName", androidConfig["libraryName"])
reactNativeModuleConfig.put("componentDescriptors", androidConfig["componentDescriptors"])
reactNativeModuleConfig.put("cmakeListsPath", androidConfig["cmakeListsPath"])
reactNativeModuleConfig.put("cxxModuleCMakeListsModuleName", androidConfig["cxxModuleCMakeListsModuleName"])
reactNativeModuleConfig.put("cxxModuleCMakeListsPath", androidConfig["cxxModuleCMakeListsPath"])
reactNativeModuleConfig.put("cxxModuleHeaderName", androidConfig["cxxModuleHeaderName"])

if (androidConfig["buildTypes"] && !androidConfig["buildTypes"].isEmpty()) {
reactNativeModulesBuildVariants.put(nameCleansed, androidConfig["buildTypes"])
Expand Down
11 changes: 11 additions & 0 deletions packages/cli-platform-android/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,9 +166,17 @@ export function dependencyConfig(
let cmakeListsPath = userConfig.cmakeListsPath
? path.join(sourceDir, userConfig.cmakeListsPath)
: path.join(sourceDir, 'build/generated/source/codegen/jni/CMakeLists.txt');
const cxxModuleCMakeListsModuleName =
userConfig.cxxModuleCMakeListsModuleName || null;
const cxxModuleHeaderName = userConfig.cxxModuleHeaderName || null;
let cxxModuleCMakeListsPath = userConfig.cxxModuleCMakeListsPath || null;
if (process.platform === 'win32') {
cmakeListsPath = cmakeListsPath.replace(/\\/g, '/');
if (cxxModuleCMakeListsPath) {
cxxModuleCMakeListsPath = cxxModuleCMakeListsPath.replace(/\\/g, '/');
}
}

return {
sourceDir,
packageImportPath,
Expand All @@ -178,5 +186,8 @@ export function dependencyConfig(
libraryName,
componentDescriptors,
cmakeListsPath,
cxxModuleCMakeListsModuleName,
cxxModuleCMakeListsPath,
cxxModuleHeaderName,
};
}
6 changes: 6 additions & 0 deletions packages/cli-types/src/android.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ export type AndroidDependencyConfig = {
libraryName?: string | null;
componentDescriptors?: string[] | null;
cmakeListsPath?: string | null;
cxxModuleCMakeListsModuleName?: string | null;
cxxModuleCMakeListsPath?: string | null;
cxxModuleHeaderName?: string | null;
};

export type AndroidDependencyParams = {
Expand All @@ -43,4 +46,7 @@ export type AndroidDependencyParams = {
libraryName?: string | null;
componentDescriptors?: string[] | null;
cmakeListsPath?: string | null;
cxxModuleCMakeListsModuleName?: string | null;
cxxModuleCMakeListsPath?: string | null;
cxxModuleHeaderName?: string | null;
};
Loading