diff --git a/native/android/app/CMakeLists.txt b/native/android/app/CMakeLists.txt index 8de088a6a..97b68340c 100644 --- a/native/android/app/CMakeLists.txt +++ b/native/android/app/CMakeLists.txt @@ -1,246 +1,246 @@ # For more information about using CMake with Android Studio, read the # documentation: https://d.android.com/studio/projects/add-native-code.html project(comm CXX C) set(CMAKE_CXX_STANDARD 14) # C0103 is a naming convention, but the variable names which need to be set # are determined by the upstream project # cmake-lint: disable=C0103 # Disable line length as some paths are hard to reduce without becoming cryptic # cmake-lint: disable=C0301 # Sets the minimum version of CMake required to build the native library. cmake_minimum_required(VERSION 3.18) # Creates and names a library, sets it as either STATIC # or SHARED, and provides the relative paths to its source code. # You can define multiple libraries, and CMake builds them for you. # Gradle automatically packages shared libraries with your APK. set(PACKAGE_NAME "comm_jni_module") find_package(fbjni REQUIRED CONFIG) set(BUILD_TESTING OFF) set(HAVE_SYMBOLIZE OFF) set(WITH_GTEST OFF CACHE BOOL "Use googletest" FORCE) set(WITH_GFLAGS OFF CACHE BOOL "Use gflags" FORCE) # General set(_third_party_dir ${CMAKE_CURRENT_SOURCE_DIR}/build/third-party-ndk) set(_android_build_dir build/${CMAKE_ANDROID_ARCH_ABI}) include(FetchContent) if(CMAKE_ANDROID_ARCH_ABI STREQUAL arm64-v8a) set(Rust_CARGO_TARGET aarch64-linux-android) elseif(CMAKE_ANDROID_ARCH_ABI STREQUAL x86) set(Rust_CARGO_TARGET i686-linux-android) elseif(CMAKE_ANDROID_ARCH_ABI STREQUAL x86_64) set(Rust_CARGO_TARGET x86_64-linux-android) elseif(CMAKE_ANDROID_ARCH_ABI STREQUAL armeabi-v7a) set(Rust_CARGO_TARGET arm-linux-androideabi) endif() string(TOLOWER ${CMAKE_HOST_SYSTEM_NAME} CMAKE_HOST_SYSTEM_NAME_LOWER) set(_toolchain_path "$ENV{ANDROID_HOME}/ndk/${NDK_VERSION}/toolchains/llvm/prebuilt/${CMAKE_HOST_SYSTEM_NAME_LOWER}-x86_64/bin" ) if(EXISTS "${_toolchain_path}/${Rust_CARGO_TARGET}-ar") set(AR "${_toolchain_path}/${Rust_CARGO_TARGET}-ar") else() set(AR "${_toolchain_path}/llvm-ar") endif() FetchContent_Declare( Corrosion GIT_REPOSITORY https://github.com/corrosion-rs/corrosion.git GIT_TAG v0.2.1 ) FetchContent_MakeAvailable(Corrosion) include(../../../shared/cmake/corrosion-cxx.cmake) add_library_rust(PATH ../../native_rust_library NAMESPACE comm) # We're updating parameters below for Cmake's find_OpenSSL() function set(OPENSSL_ROOT_DIR "${_third_party_dir}/openssl/openssl-${OPENSSL_VERSION}/${_android_build_dir}" ) list(APPEND CMAKE_FIND_ROOT_PATH "${OPENSSL_ROOT_DIR}") add_subdirectory(${_third_party_dir}/glog/glog-${GLOG_VERSION}/) add_subdirectory(../../node_modules/olm ./build) set(_node_modules_dir ${CMAKE_CURRENT_SOURCE_DIR}/../../node_modules) set(_react_native_dir ${_node_modules_dir}/react-native) string(TOLOWER ${CMAKE_BUILD_TYPE} CMAKE_BUILD_TYPE_LOWER) include_directories( ${_react_native_dir}/React ${_react_native_dir}/React/Base ${_react_native_dir}/ReactCommon ${_react_native_dir}/ReactCommon/jsi ${_react_native_dir}/ReactCommon/callinvoker ${_react_native_dir}/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon # OpenSSL ${_third_party_dir}/openssl/openssl-${OPENSSL_VERSION}/build/${CMAKE_ANDROID_ARCH_ABI}/include # SQLCipher amalgamation ${_node_modules_dir}/@commapp/sqlcipher-amalgamation/src # SQLite ORM ../../cpp/third-party/sqlite_orm # symlinked React Native headers ../headers # external libs ${_third_party_dir}/folly ${_third_party_dir}/boost/boost ${_third_party_dir}/double-conversion # comm android specific code ./src/cpp # comm native mutual code ../../cpp/CommonCpp/ ../../cpp/CommonCpp/NativeModules ../../cpp/CommonCpp/NativeModules/InternalModules ../../cpp/CommonCpp/NativeModules/PersistentStorageUtilities ../../cpp/CommonCpp/NativeModules/PersistentStorageUtilities/ThreadOperationsUtilities ../../cpp/CommonCpp/NativeModules/PersistentStorageUtilities/MessageOperationsUtilities ../../cpp/CommonCpp/NativeModules/PersistentStorageUtilities/MessageOperationsUtilities/MessageSpecs ../../cpp/CommonCpp/DatabaseManagers ../../cpp/CommonCpp/Tools # native rust library ${native_rust_library_include_dir} ) # search for all cpp files in this directory file(GLOB SQLCIPHER "${_node_modules_dir}/@commapp/sqlcipher-amalgamation/src/*.c" ) file(GLOB_RECURSE COMMON_NATIVE_CODE "../../cpp/CommonCpp/**/*.cpp") file(GLOB ANDROID_NATIVE_CODE "./src/cpp/*.cpp") file(GLOB DOUBLE_CONVERSION_SOURCES "${_third_party_dir}/double-conversion/double-conversion/*.cc" ) add_library( # Sets the name of the library. ${PACKAGE_NAME} # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). ${_react_native_dir}/ReactCommon/jsi/jsi/jsi.cpp ${_react_native_dir}/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/CallInvokerHolder.cpp ${_react_native_dir}/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.cpp - ${_react_native_dir}/ReactCommon/react/nativemodule/core/ReactCommon/LongLivedObject.cpp + ${_react_native_dir}/ReactCommon/react/bridging/LongLivedObject.cpp ${_react_native_dir}/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.cpp # SQLCipher ${SQLCIPHER} # folly ${_third_party_dir}/folly/folly/detail/Futex.cpp ${_third_party_dir}/folly/folly/synchronization/ParkingLot.cpp ${_third_party_dir}/folly/folly/lang/SafeAssert.cpp ${_third_party_dir}/folly/folly/FileUtil.cpp ${_third_party_dir}/folly/folly/Subprocess.cpp ${_third_party_dir}/folly/folly/File.cpp ${_third_party_dir}/folly/folly/Format.cpp ${_third_party_dir}/folly/folly/Conv.cpp ${_third_party_dir}/folly/folly/io/IOBuf.cpp ${_third_party_dir}/folly/folly/memory/detail/MallocImpl.cpp ${_third_party_dir}/folly/folly/ScopeGuard.cpp ${_third_party_dir}/folly/folly/hash/SpookyHashV2.cpp ${_third_party_dir}/folly/folly/io/IOBufQueue.cpp ${_third_party_dir}/folly/folly/lang/Assume.cpp ${_third_party_dir}/folly/folly/String.cpp ${_third_party_dir}/folly/folly/portability/SysUio.cpp ${_third_party_dir}/folly/folly/net/NetOps.cpp ${_third_party_dir}/folly/folly/dynamic.cpp ${_third_party_dir}/folly/folly/json.cpp ${_third_party_dir}/folly/folly/json_pointer.cpp ${_third_party_dir}/folly/folly/Unicode.cpp # double-conversion ${DOUBLE_CONVERSION_SOURCES} # comm code ${ANDROID_NATIVE_CODE} ${COMMON_NATIVE_CODE} ) add_definitions( # Folly -DFOLLY_NO_CONFIG=1 -DFOLLY_HAVE_CLOCK_GETTIME=1 -DFOLLY_HAVE_MEMRCHR=1 -DFOLLY_USE_LIBCPP=1 -DFOLLY_MOBILE=1 # SQLCipher -DSQLITE_THREADSAFE=0 -DSQLITE_HAS_CODEC -DSQLITE_TEMP_STORE=2 -DSQLCIPHER_CRYPTO_OPENSSL ) find_library(log-lib log) add_library( # OpenSSL Crypto lib openssl-crypto STATIC IMPORTED ) set_target_properties( # OpenSSL Crypto lib openssl-crypto PROPERTIES IMPORTED_LOCATION "${_third_party_dir}/openssl/openssl-${OPENSSL_VERSION}/build/${CMAKE_ANDROID_ARCH_ABI}/lib/libcrypto.a" ) add_library( # OpenSSL SSL lib openssl-ssl STATIC IMPORTED ) set_target_properties( # OpenSSL SSL lib openssl-ssl PROPERTIES IMPORTED_LOCATION "${_third_party_dir}/openssl/openssl-${OPENSSL_VERSION}/build/${CMAKE_ANDROID_ARCH_ABI}/lib/libssl.a" ) target_link_libraries( ${PACKAGE_NAME} fbjni::fbjni android ${log-lib} glog::glog olm openssl-crypto openssl-ssl comm::native_rust_library ) # add a dummy library which is required by CallInvokerHolderImpl.java add_library( turbomodulejsijni # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). ./src/cpp/dummy.cpp ) diff --git a/native/android/app/build.gradle b/native/android/app/build.gradle index c6c8f5a92..03b1b12ef 100644 --- a/native/android/app/build.gradle +++ b/native/android/app/build.gradle @@ -1,582 +1,669 @@ apply plugin: "com.android.application" import com.android.build.OutputFile import de.undercouch.gradle.tasks.download.Download import app.comm.gradle.tasks.GitModules /** * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets * and bundleReleaseJsAndAssets). * These basically call `react-native bundle` with the correct arguments during the Android build * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the * bundle directly from the development server. Below you can see all the possible configurations * and their defaults. If you decide to add a configuration block, make sure to add it before the * `apply from: "../../node_modules/react-native/react.gradle"` line. * * project.ext.react = [ * // the name of the generated asset file containing your JS bundle * bundleAssetName: "index.android.bundle", * * // the entry file for bundle generation. If none specified and * // "index.android.js" exists, it will be used. Otherwise "index.js" is * // default. Can be overridden with ENTRY_FILE environment variable. * entryFile: "index.android.js", * * // https://reactnative.dev/docs/performance#enable-the-ram-format * bundleCommand: "ram-bundle", * * // whether to bundle JS and assets in debug mode * bundleInDebug: false, * * // whether to bundle JS and assets in release mode * bundleInRelease: true, * * // whether to bundle JS and assets in another build variant (if configured). * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants * // The configuration property can be in the following formats * // 'bundleIn${productFlavor}${buildType}' * // 'bundleIn${buildType}' * // bundleInFreeDebug: true, * // bundleInPaidRelease: true, * // bundleInBeta: true, * * // whether to disable dev mode in custom build variants (by default only disabled in release) * // for example: to disable dev mode in the staging build type (if configured) * devDisabledInStaging: true, * // The configuration property can be in the following formats * // 'devDisabledIn${productFlavor}${buildType}' * // 'devDisabledIn${buildType}' * * // the root of your project, i.e. where "package.json" lives * root: "../../", * * // where to put the JS bundle asset in debug mode * jsBundleDirDebug: "$buildDir/intermediates/assets/debug", * * // where to put the JS bundle asset in release mode * jsBundleDirRelease: "$buildDir/intermediates/assets/release", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in debug mode * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in release mode * resourcesDirRelease: "$buildDir/intermediates/res/merged/release", * * // by default the gradle tasks are skipped if none of the JS files or assets change; this means * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to * // date; if you have any other folders that you want to ignore for performance reasons (gradle * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ * // for example, you might want to remove it from here. * inputExcludes: ["android/**", "ios/**"], * * // override which node gets called and with what additional arguments * nodeExecutableAndArgs: ["node"], * * // supply additional arguments to the packager * extraPackagerArgs: [] * ] */ project.ext.react = [ enableHermes: true, // clean and rebuild if changing - hermesCommand: new File(["node", "--print", "require.resolve('hermes-engine/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/%OS-BIN%/hermesc", - cliPath: new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/cli.js", - composeSourceMapsPath: new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/scripts/compose-source-maps.js", + cliPath: ["node", "-e", "console.log(require('react-native/cli').bin);"].execute([], projectDir).text.trim(), ] apply from: new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim(), "../react.gradle") /** * Set this to true to create two separate APKs instead of one: * - An APK that only works on ARM devices * - An APK that only works on x86 devices * The advantage is the size of the APK is reduced by about 4MB. * Upload all the APKs to the Play Store and people will download * the correct one based on the CPU architecture of their device. */ def enableSeparateBuildPerCPUArchitecture = false /** * Run Proguard to shrink the Java bytecode in release builds. */ def enableProguardInReleaseBuilds = false /** * The preferred build flavor of JavaScriptCore. * * For example, to use the international variant, you can use: * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` * * The international variant includes ICU i18n library and necessary data * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that * give correct results when using with locales other than en-US. Note that * this variant is about 6MiB larger per architecture than default. */ def jscFlavor = 'org.webkit:android-jsc:+' /** * Whether to enable the Hermes VM. * * This should be set on project.ext.react and that value will be read here. If it is not set * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode * and the benefits of using Hermes will therefore be sharply reduced. */ def enableHermes = project.ext.react.get("enableHermes", false) /** - * Architectures to build native code for in debug. + * Architectures to build native code for. */ -def nativeArchitectures = project.getProperties().get("reactNativeDebugArchitectures") +def reactNativeArchitectures() { + def value = project.getProperties().get("reactNativeArchitectures") + return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"] +} def customDownloadsDir = System.getenv("REACT_NATIVE_DOWNLOADS_DIR") def dependenciesPath = System.getenv("REACT_NATIVE_DEPENDENCIES") def downloadsDir = customDownloadsDir ? new File(customDownloadsDir) : new File("$buildDir/downloads") def thirdPartyNdkDir = new File("$buildDir/third-party-ndk") // The Boost library is a very large download (>100MB). // If Boost is already present on your system, define the REACT_NATIVE_BOOST_PATH env variable // and the build will use that. def boostPath = dependenciesPath ?: System.getenv("REACT_NATIVE_BOOST_PATH") task createNativeDepsDirectories { downloadsDir.mkdirs() thirdPartyNdkDir.mkdirs() } // FOLLY task downloadFolly(dependsOn: createNativeDepsDirectories, type: Download) { src("https://github.com/facebook/folly/archive/v${FOLLY_VERSION}.tar.gz") onlyIfNewer(true) overwrite(false) dest(new File(downloadsDir, "folly-${FOLLY_VERSION}.tar.gz")) } def follyFindWrapNoInt = 'return int\\(wrapNoInt\\(open, name, flags, mode\\)\\);' def follyReplaceWrapNoInt = ''' ssize_t r; do { r = open(name, flags, mode); } while (r == -1 && errno == EINTR); return r; ''' def follyFindTableSize = 'for \\(int fd = getdtablesize\\(\\) - 1' def follyReplaceTableSize = 'for (int fd = sysconf(_SC_OPEN_MAX) - 1' task prepareFolly(dependsOn: dependenciesPath ? [] : [downloadFolly], type: Copy) { inputs.properties([ 'findWrapNoInt': follyFindWrapNoInt, 'replaceWrapNoInt': follyReplaceWrapNoInt, 'findTableSize': follyFindTableSize, 'replaceTableSize': follyReplaceTableSize, ]) from(dependenciesPath ?: tarTree(downloadFolly.dest)) include("folly-${FOLLY_VERSION}/folly/**/*") eachFile { fname -> fname.path = (fname.path - "folly-${FOLLY_VERSION}/") } // Fixes problem with Folly failing to build on certain systems. See // https://github.com/facebook/react-native/issues/28298 filter { line -> line.replaceAll(follyFindWrapNoInt, follyReplaceWrapNoInt) } // fix undeclared identifier 'getdtablesize' in Subprocess.cpp // https://stackoverflow.com/questions/8225186/portable-equivalent-of-open-max/8225235#8225235 filter { line -> line.replaceAll(follyFindTableSize, follyReplaceTableSize) } includeEmptyDirs = false into("$thirdPartyNdkDir/folly") } // GLOG task downloadGlog(dependsOn: createNativeDepsDirectories, type: Download) { src("https://github.com/google/glog/archive/v${GLOG_VERSION}.tar.gz") onlyIfNewer(true) overwrite(false) dest(new File(downloadsDir, "glog-${GLOG_VERSION}.tar.gz")) } task prepareGlog(dependsOn: dependenciesPath ? [] : [downloadGlog], type: Copy) { from(dependenciesPath ?: tarTree(downloadGlog.dest)) include("glog-${GLOG_VERSION}/**/*") includeEmptyDirs = false into("$thirdPartyNdkDir/glog") } // BOOST task downloadBoost(dependsOn: createNativeDepsDirectories, type: Download) { src("https://github.com/react-native-community/boost-for-react-native/releases/download/v${BOOST_VERSION.replace("_", ".")}-0/boost_${BOOST_VERSION}.tar.gz") onlyIfNewer(true) overwrite(false) dest(new File(downloadsDir, "boost_${BOOST_VERSION}.tar.gz")) } task prepareBoost(dependsOn: boostPath ? [] : [downloadBoost]) { inputs.properties([ 'boost.version': BOOST_VERSION ]) outputs.dir("$thirdPartyNdkDir/boost/boost/") .withPropertyName('boost.output') doFirst { copy { from(boostPath ?: tarTree(resources.gzip(downloadBoost.dest))) include("boost_${BOOST_VERSION}/boost/**/*.hpp", "boost/boost/**/*.hpp") include("boost_${BOOST_VERSION}/boost/**/*.ipp", "boost/boost/**/*.ipp") include("boost_${BOOST_VERSION}/boost/**/*.h", "boost/boost/**/*.h") includeEmptyDirs = false into("$thirdPartyNdkDir/boost") } } doLast { file("$thirdPartyNdkDir/boost/boost_${BOOST_VERSION}").renameTo("$thirdPartyNdkDir/boost/boost") } } // DOUBLE-CONVERSION task downloadDoubleConversion(dependsOn: createNativeDepsDirectories, type: Download) { src("https://github.com/google/double-conversion/archive/v${DOUBLE_CONVERSION_VERSION}.tar.gz") onlyIfNewer(true) overwrite(false) dest(new File(downloadsDir, "double-conversion-${DOUBLE_CONVERSION_VERSION}.tar.gz")) } task prepareDoubleConversion(dependsOn: dependenciesPath ? [] : [downloadDoubleConversion], type: Copy) { from(dependenciesPath ?: tarTree(downloadDoubleConversion.dest)) from("src/main/jni/third-party/double-conversion/Android.mk") include("double-conversion-${DOUBLE_CONVERSION_VERSION}/src/**/*", "Android.mk") filesMatching("*/src/**/*", { fname -> fname.path = "double-conversion/${fname.name}" }) includeEmptyDirs = false into("$thirdPartyNdkDir/double-conversion") } // OPENSSL def hostSystem = System.getProperty('os.name').toLowerCase(Locale.ROOT) def hostTag = hostSystem.contains('mac') ? 'darwin-x86_64' : 'linux-x86_64' task downloadOpenSSL(dependsOn: createNativeDepsDirectories, type: Download) { src("https://www.openssl.org/source/openssl-${OPENSSL_VERSION}.tar.gz") onlyIfNewer(true) overwrite(false) dest(new File(downloadsDir, "openssl-${OPENSSL_VERSION}.tar.gz")) } task prepareOpenSSL( dependsOn: dependenciesPath ? [] : [downloadOpenSSL], type: Copy ) { from(dependenciesPath ?: tarTree(downloadOpenSSL.dest)) include("openssl-${OPENSSL_VERSION}/**/*") includeEmptyDirs = false into("${thirdPartyNdkDir}/openssl") } task prebuildOpenSSL(dependsOn: dependenciesPath ? [] : [prepareOpenSSL]) { inputs.properties([ 'openssl.version': OPENSSL_VERSION, - 'openssl.abis': getBuildTypeABIs(nativeArchitectures) + 'openssl.abis': getBuildTypeABIs(reactNativeArchitectures()) ]) outputs.dir("${thirdPartyNdkDir}/openssl/openssl-${OPENSSL_VERSION}/build/") .withPropertyName('openssl.output') doFirst { - getBuildTypeABIs(nativeArchitectures).each { buildABI -> + getBuildTypeABIs(reactNativeArchitectures()).each { buildABI -> logger.info("Building OpenSSL library for the ${buildABI}") exec { commandLine './bash/build_openssl.sh', // OPENSSL_SUBMODULE_PATH "${thirdPartyNdkDir}/openssl/openssl-${OPENSSL_VERSION}/", // HOST_TAG hostTag, // ANDROID_ARCH_ABI "${buildABI}", // MIN_SDK_VERSION rootProject.ext.minSdkVersion, // ANDROID_NDK_HOME android.ndkDirectory.absolutePath, // PARALLEL_THREADS Runtime.getRuntime().availableProcessors() } } } } // EXTERNAL LIBS task prepareExternalLibs { dependsOn prepareFolly dependsOn prepareGlog dependsOn prepareBoost dependsOn prepareDoubleConversion dependsOn prebuildOpenSSL } // Removes the '.cxx' directory to prevent running // ninja clean when the 'clean' command is executed task removeCXX(type: Exec) { commandLine 'rm', '-rf', '.cxx' } // Add cross-compilation targets to Rust toolchain task updateRustToolchain(type: Exec) { commandLine "rustup", "target", "add", "aarch64-linux-android", "armv7-linux-androideabi", "i686-linux-android", "arm-linux-androideabi", "x86_64-linux-android" } // Bind preBuild dependencies only if not 'clean' running if (!isCleanRunning()) { afterEvaluate { preBuild.dependsOn(prepareExternalLibs, updateRustToolchain) } } // Run removing CXX task before the clean execution beforeEvaluate { clean.dependsOn(removeCXX) } // Detects are we running the 'clean' commands def isCleanRunning() { gradle.startParameter.taskRequests.any { !it.args.isEmpty() && it.args.first().startsWith('clean') } } // Release keystore via macOS Keychain Access def getPassword(String keyLabel) { if (System.getenv('ANDROID_SIGNING_PASSWORD')) { return System.getenv('ANDROID_SIGNING_PASSWORD') } def stdout = new ByteArrayOutputStream() exec { commandLine 'security', 'find-generic-password', '-wl', keyLabel, '-a', System.properties['user.name'] standardOutput = stdout ignoreExitValue true } return stdout.toString().strip() } // Returns all ABIs architectures for the 'bundleRelease' // or only from 'adb devices' if running debug release. def getBuildTypeABIs(nativeArchitectures) { if (System.getenv("BUILDKITE") == "true") { return ["arm64-v8a"] } def isBundleRelease = gradle.startParameter.taskRequests.any { !it.args.isEmpty() && it.args.first().contains("bundleRelease") } if (isBundleRelease) { // All of the supported ABIs // https://developer.android.com/ndk/guides/abis.html#sa final allAbis = ["armeabi-v7a", "x86", "arm64-v8a", "x86_64"] logger.info("Using all architectures to build: ${allAbis}") return allAbis } if (nativeArchitectures) { - return nativeArchitectures.split(',') + return nativeArchitectures } // Get current 'adb devices' architectures def commandOutput = new ByteArrayOutputStream() exec { commandLine "./bash/detect_abis.sh" standardOutput = commandOutput } final detectedAbis = commandOutput.toString("UTF-8").trim().tokenize() logger.info("Detected architectures to build: ${detectedAbis}") return detectedAbis } android { buildFeatures { prefab true } configurations { all*.exclude module: 'fbjni-java-only' } dependencies { implementation 'com.facebook.fbjni:fbjni:0.1.0' } ndkVersion rootProject.ext.ndkVersion compileSdkVersion rootProject.ext.compileSdkVersion defaultConfig { applicationId 'app.comm.android' minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 166 versionName '1.0.166' + buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString() + if (isNewArchitectureEnabled()) { + // We configure the CMake build only if you decide to opt-in for the New Architecture. + externalNativeBuild { + cmake { + arguments "-DPROJECT_BUILD_DIR=$buildDir", + "-DREACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid", + "-DREACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build", + "-DNODE_MODULES_DIR=$rootDir/../node_modules", + "-DANDROID_STL=c++_shared" + } + } + if (!enableSeparateBuildPerCPUArchitecture) { + ndk { + abiFilters (*reactNativeArchitectures()) + } + } + } missingDimensionStrategy 'react-native-camera', 'general' multiDexEnabled true } + + if (isNewArchitectureEnabled()) { + // We configure the NDK build only if you decide to opt-in for the New Architecture. + externalNativeBuild { + cmake { + path "$projectDir/src/main/jni/CMakeLists.txt" + } + } + def reactAndroidProjectDir = project(':ReactAndroid').projectDir + def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) { + dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck") + from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib") + into("$buildDir/react-ndk/exported") + } + def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) { + dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck") + from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib") + into("$buildDir/react-ndk/exported") + } + afterEvaluate { + // If you wish to add a custom TurboModule or component locally, + // you should uncomment this line. + // preBuild.dependsOn("generateCodegenArtifactsFromSchema") + preDebugBuild.dependsOn(packageReactNdkDebugLibs) + preReleaseBuild.dependsOn(packageReactNdkReleaseLibs) + // Due to a bug inside AGP, we have to explicitly set a dependency + // between configureCMakeDebug* tasks and the preBuild tasks. + // This can be removed once this is solved: https://issuetracker.google.com/issues/207403732 + configureCMakeRelWithDebInfo.dependsOn(preReleaseBuild) + configureCMakeDebug.dependsOn(preDebugBuild) + reactNativeArchitectures().each { architecture -> + tasks.findByName("configureCMakeDebug[${architecture}]")?.configure { + dependsOn("preDebugBuild") + } + tasks.findByName("configureCMakeRelWithDebInfo[${architecture}]")?.configure { + dependsOn("preReleaseBuild") + } + } + } + } + splits { abi { reset() enable enableSeparateBuildPerCPUArchitecture universalApk false // If true, also generate a universal APK - include "armeabi-v7a", "x86", "arm64-v8a", "x86_64" + include (*reactNativeArchitectures()) } } signingConfigs { debug { storeFile file('debug.keystore') storePassword 'android' keyAlias 'androiddebugkey' keyPassword 'android' } release { if (project.hasProperty('COMM_UPLOAD_STORE_FILE')) { def password = getPassword('CommAndroidKeyPassword') storeFile file(COMM_UPLOAD_STORE_FILE) storePassword password keyAlias COMM_UPLOAD_KEY_ALIAS keyPassword password } } } buildTypes { - final buildABIs = getBuildTypeABIs(nativeArchitectures) + final buildABIs = getBuildTypeABIs(reactNativeArchitectures()) release { if (project.hasProperty('COMM_UPLOAD_STORE_FILE')) { signingConfig signingConfigs.release } else { signingConfig signingConfigs.debug } minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" ndk { abiFilters = [] abiFilters.addAll(buildABIs) } } debug { signingConfig signingConfigs.debug ndk { abiFilters = [] abiFilters.addAll(buildABIs) } } } packagingOptions { pickFirst "**/libc++_shared.so" pickFirst "**/libfbjni.so" } defaultConfig { externalNativeBuild { cmake { arguments "-DANDROID_STL=c++_shared", "-DGLOG_VERSION=" + GLOG_VERSION, "-DOPENSSL_VERSION=" + OPENSSL_VERSION, "-DNDK_VERSION=" + rootProject.ext.ndkVersion targets "comm_jni_module", "turbomodulejsijni" } } } externalNativeBuild { cmake { path "CMakeLists.txt" version "3.18.1" } } // applicationVariants are e.g. debug, release applicationVariants.all { variant -> variant.outputs.each { output -> // For each separate APK per architecture, set a unique version code as described here: // https://developer.android.com/studio/build/configure-apk-splits.html // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc. def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4] def abi = output.getFilter(OutputFile.ABI) if (abi != null) { // null for the universal-debug, universal-release variants output.versionCodeOverride = defaultConfig.versionCode * 1000 + versionCodes.get(abi) } } } } dependencies { implementation fileTree(dir: "libs", include: ["*.jar"]) implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.4.21" //noinspection GradleDynamicVersion implementation("com.facebook.react:react-native:+") def isGifEnabled = (findProperty('expo.gif.enabled') ?: "") == "true"; def isWebpEnabled = (findProperty('expo.webp.enabled') ?: "") == "true"; def isWebpAnimatedEnabled = (findProperty('expo.webp.animated') ?: "") == "true"; // If your app supports Android versions before Ice Cream Sandwich (API level 14) // All fresco packages should use the same version if (isGifEnabled || isWebpEnabled) { implementation 'com.facebook.fresco:fresco:2.0.0' implementation 'com.facebook.fresco:imagepipeline-okhttp3:2.0.0' } if (isGifEnabled) { // For animated gif support implementation 'com.facebook.fresco:animated-gif:2.0.0' } if (isWebpEnabled) { // For webp support implementation 'com.facebook.fresco:webpsupport:2.0.0' if (isWebpAnimatedEnabled) { // Animated webp support implementation 'com.facebook.fresco:animated-webp:2.0.0' } } implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0" debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") { exclude group:'com.facebook.fbjni' } debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") { exclude group:'com.facebook.flipper' } debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") { exclude group:'com.facebook.flipper' exclude group:'com.facebook.fresco', module:'stetho' } implementation "com.google.android.gms:play-services-base:16.1.0" implementation "com.google.firebase:firebase-core:16.0.9" implementation "com.google.firebase:firebase-messaging:18.0.0" implementation "me.leolin:ShortcutBadger:1.1.21@aar" implementation project(':reactnativekeyboardinput') implementation "androidx.multidex:multidex:2.0.1" implementation "androidx.lifecycle:lifecycle-runtime:2.2.0" implementation "androidx.lifecycle:lifecycle-process:2.2.0" implementation 'com.facebook.fresco:fresco:2.2.0' implementation 'com.facebook.fresco:animated-gif:2.2.0' implementation 'com.facebook.fresco:animated-webp:2.2.0' implementation 'com.facebook.fresco:webpsupport:2.2.0' implementation 'org.conscrypt:conscrypt-android:2.0.0' if (enableHermes) { - debugImplementation files(new File(["node", "--print", "require.resolve('hermes-engine/package.json')"].execute(null, rootDir).text.trim(), "../android/hermes-debug.aar")) - releaseImplementation files(new File(["node", "--print", "require.resolve('hermes-engine/package.json')"].execute(null, rootDir).text.trim(), "../android/hermes-release.aar")) + //noinspection GradleDynamicVersion + implementation("com.facebook.react:hermes-engine:+") { // From node_modules + exclude group:'com.facebook.fbjni' + } } else { implementation jscFlavor } } +if (isNewArchitectureEnabled()) { + // If new architecture is enabled, we let you build RN from source + // Otherwise we fallback to a prebuilt .aar bundled in the NPM package. + // This will be applied to all the imported transtitive dependency. + configurations.all { + resolutionStrategy.dependencySubstitution { + substitute(module("com.facebook.react:react-native")) + .using(project(":ReactAndroid")) + .because("On New Architecture we're building React Native from source") + substitute(module("com.facebook.react:hermes-engine")) + .using(project(":ReactAndroid:hermes-engine")) + .because("On New Architecture we're building Hermes from source") + } + } +} + // Run this once to be able to run the application with BUCK // puts all compile dependencies into folder libs for BUCK to use task copyDownloadableDepsToLibs(type: Copy) { from configurations.implementation into 'libs' } apply from: new File(["node", "--print", "require.resolve('@react-native-community/cli-platform-android/package.json')"].execute(null, rootDir).text.trim(), "../native_modules.gradle"); applyNativeModulesAppBuildGradle(project) + +def isNewArchitectureEnabled() { + // To opt-in for the New Architecture, you can either: + // - Set `newArchEnabled` to true inside the `gradle.properties` file + // - Invoke gradle with `-newArchEnabled=true` + // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true` + return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true" +} + apply plugin: 'com.google.gms.google-services' diff --git a/native/android/app/src/debug/AndroidManifest.xml b/native/android/app/src/debug/AndroidManifest.xml index c9bd575e8..71977d943 100644 --- a/native/android/app/src/debug/AndroidManifest.xml +++ b/native/android/app/src/debug/AndroidManifest.xml @@ -1,14 +1,14 @@ - + diff --git a/native/android/app/src/debug/java/app/comm/android/ReactNativeFlipper.java b/native/android/app/src/debug/java/app/comm/android/ReactNativeFlipper.java index c6e735e01..4fcd4cb80 100644 --- a/native/android/app/src/debug/java/app/comm/android/ReactNativeFlipper.java +++ b/native/android/app/src/debug/java/app/comm/android/ReactNativeFlipper.java @@ -1,72 +1,73 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * 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 app.comm.android; import android.content.Context; import com.facebook.flipper.android.AndroidFlipperClient; import com.facebook.flipper.android.utils.FlipperUtils; import com.facebook.flipper.core.FlipperClient; import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin; import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin; import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin; import com.facebook.flipper.plugins.inspector.DescriptorMapping; import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin; import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor; import com.facebook.flipper.plugins.network.NetworkFlipperPlugin; import com.facebook.flipper.plugins.react.ReactFlipperPlugin; import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin; +import com.facebook.react.ReactInstanceEventListener; import com.facebook.react.ReactInstanceManager; import com.facebook.react.bridge.ReactContext; import com.facebook.react.modules.network.NetworkingModule; import okhttp3.OkHttpClient; public class ReactNativeFlipper { public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) { if (FlipperUtils.shouldEnableFlipper(context)) { final FlipperClient client = AndroidFlipperClient.getInstance(context); client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults())); client.addPlugin(new ReactFlipperPlugin()); client.addPlugin(new DatabasesFlipperPlugin(context)); client.addPlugin(new SharedPreferencesFlipperPlugin(context)); client.addPlugin(CrashReporterPlugin.getInstance()); NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin(); NetworkingModule.setCustomClientBuilder( new NetworkingModule.CustomClientBuilder() { @Override public void apply(OkHttpClient.Builder builder) { builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); } }); client.addPlugin(networkFlipperPlugin); client.start(); // Fresco Plugin needs to ensure that ImagePipelineFactory is initialized // Hence we run if after all native modules have been initialized ReactContext reactContext = reactInstanceManager.getCurrentReactContext(); if (reactContext == null) { reactInstanceManager.addReactInstanceEventListener( - new ReactInstanceManager.ReactInstanceEventListener() { + new ReactInstanceEventListener() { @Override public void onReactContextInitialized(ReactContext reactContext) { reactInstanceManager.removeReactInstanceEventListener(this); reactContext.runOnNativeModulesQueueThread( new Runnable() { @Override public void run() { client.addPlugin(new FrescoFlipperPlugin()); } }); } }); } else { client.addPlugin(new FrescoFlipperPlugin()); } } } } diff --git a/native/android/app/src/main/AndroidManifest.xml b/native/android/app/src/main/AndroidManifest.xml index 0d1e9d9af..dff351601 100644 --- a/native/android/app/src/main/AndroidManifest.xml +++ b/native/android/app/src/main/AndroidManifest.xml @@ -1,69 +1,69 @@ diff --git a/native/android/app/src/main/java/app/comm/android/MainActivity.java b/native/android/app/src/main/java/app/comm/android/MainActivity.java index 41ce0b436..ead5e8eeb 100644 --- a/native/android/app/src/main/java/app/comm/android/MainActivity.java +++ b/native/android/app/src/main/java/app/comm/android/MainActivity.java @@ -1,48 +1,75 @@ package app.comm.android; import android.content.Intent; import android.os.Bundle; import com.facebook.react.ReactActivity; import com.facebook.react.ReactActivityDelegate; import com.facebook.react.ReactRootView; import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView; import expo.modules.ReactActivityDelegateWrapper; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "Comm"; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(null); } @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); } + /** + * Returns the instance of the {@link ReactActivityDelegate}. There the + * RootView is created and you can specify the renderer you wish to use - the + * new renderer (Fabric) or the old renderer (Paper). + */ @Override protected ReactActivityDelegate createReactActivityDelegate() { return new ReactActivityDelegateWrapper( - this, new ReactActivityDelegate(this, getMainComponentName()) { + this, new MainActivityDelegate(this, getMainComponentName()) { @Override protected ReactRootView createRootView() { return new RNGestureHandlerEnabledRootView(MainActivity.this); } }); } + public static class MainActivityDelegate extends ReactActivityDelegate { + public MainActivityDelegate( + ReactActivity activity, + String mainComponentName) { + super(activity, mainComponentName); + } + @Override + protected ReactRootView createRootView() { + ReactRootView reactRootView = new ReactRootView(getContext()); + // If you opted-in for the New Architecture, we enable the Fabric + // Renderer. + reactRootView.setIsFabric(BuildConfig.IS_NEW_ARCHITECTURE_ENABLED); + return reactRootView; + } + @Override + protected boolean isConcurrentRootEnabled() { + // If you opted-in for the New Architecture, we enable Concurrent Root + // (i.e. React 18). More on this on + // https://reactjs.org/blog/2022/03/29/react-v18.html + return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED; + } + } @Override public void invokeDefaultOnBackPressed() { moveTaskToBack(true); } } diff --git a/native/android/app/src/main/java/app/comm/android/MainApplication.java b/native/android/app/src/main/java/app/comm/android/MainApplication.java index 2e439fc28..56a0831d1 100644 --- a/native/android/app/src/main/java/app/comm/android/MainApplication.java +++ b/native/android/app/src/main/java/app/comm/android/MainApplication.java @@ -1,120 +1,134 @@ package app.comm.android; import android.content.Context; import android.content.res.Configuration; import android.database.CursorWindow; import androidx.annotation.NonNull; import androidx.multidex.MultiDexApplication; +import app.comm.android.newarchitecture.MainApplicationReactNativeHost; import com.facebook.react.PackageList; import com.facebook.react.ReactApplication; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JSIModulePackage; +import com.facebook.react.config.ReactFeatureFlags; import com.facebook.soloader.SoLoader; import com.wix.reactnativekeyboardinput.KeyboardInputPackage; import expo.modules.ApplicationLifecycleDispatcher; import expo.modules.ReactNativeHostWrapper; import io.invertase.firebase.messaging.RNFirebaseMessagingPackage; import io.invertase.firebase.notifications.RNFirebaseNotificationsPackage; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.security.Security; import java.util.List; public class MainApplication extends MultiDexApplication implements ReactApplication { static { System.loadLibrary("comm_jni_module"); } private final ReactNativeHost mReactNativeHost = new ReactNativeHostWrapper(this, new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List getPackages() { @SuppressWarnings("UnnecessaryLocalVariable") List packages = new PackageList(this).getPackages(); packages.add(new RNFirebaseMessagingPackage()); packages.add(new RNFirebaseNotificationsPackage()); packages.add(new KeyboardInputPackage(this.getApplication())); packages.add(new CommPackage()); return packages; } @Override protected String getJSMainModuleName() { return "index"; } @Override protected JSIModulePackage getJSIModulePackage() { return new CommCoreJSIModulePackage(); } }); + private final ReactNativeHost mNewArchitectureNativeHost = + new MainApplicationReactNativeHost(this); + @Override public ReactNativeHost getReactNativeHost() { - return mReactNativeHost; + if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { + return mNewArchitectureNativeHost; + } else { + return mReactNativeHost; + } } @Override public void onCreate() { super.onCreate(); + // If you opted-in for the New Architecture, we enable the TurboModule + // system + ReactFeatureFlags.useTurboModules = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED; + Security.insertProviderAt(new org.conscrypt.OpenSSLProvider(), 1); + SoLoader.init(this, /* native exopackage */ false); initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); ApplicationLifecycleDispatcher.onApplicationCreate(this); try { Field field = CursorWindow.class.getDeclaredField("sCursorWindowSize"); field.setAccessible(true); field.set(null, 100 * 1024 * 1024); // 100 MiB } catch (Exception e) { if (BuildConfig.DEBUG) { e.printStackTrace(); } } } @Override public void onConfigurationChanged(@NonNull Configuration newConfig) { super.onConfigurationChanged(newConfig); ApplicationLifecycleDispatcher.onConfigurationChanged(this, newConfig); } /** * Loads Flipper in React Native templates. Call this in the onCreate method * with something like * initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); * * @param context * @param reactInstanceManager */ private static void initializeFlipper( Context context, ReactInstanceManager reactInstanceManager) { if (BuildConfig.DEBUG) { try { // We use reflection here to pick up the class that initializes Flipper, // since Flipper library is not available in release mode Class aClass = Class.forName("app.comm.android.ReactNativeFlipper"); aClass .getMethod( "initializeFlipper", Context.class, ReactInstanceManager.class) .invoke(null, context, reactInstanceManager); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } } diff --git a/native/android/app/src/main/java/app/comm/android/newarchitecture/MainApplicationReactNativeHost.java b/native/android/app/src/main/java/app/comm/android/newarchitecture/MainApplicationReactNativeHost.java new file mode 100644 index 000000000..15b8ff91b --- /dev/null +++ b/native/android/app/src/main/java/app/comm/android/newarchitecture/MainApplicationReactNativeHost.java @@ -0,0 +1,118 @@ +package app.comm.android.newarchitecture; + +import android.app.Application; +import androidx.annotation.NonNull; +import app.comm.android.BuildConfig; +import app.comm.android.newarchitecture.components.MainComponentsRegistry; +import app.comm.android.newarchitecture.modules.MainApplicationTurboModuleManagerDelegate; +import com.facebook.react.PackageList; +import com.facebook.react.ReactInstanceManager; +import com.facebook.react.ReactNativeHost; +import com.facebook.react.ReactPackage; +import com.facebook.react.ReactPackageTurboModuleManagerDelegate; +import com.facebook.react.bridge.JSIModulePackage; +import com.facebook.react.bridge.JSIModuleProvider; +import com.facebook.react.bridge.JSIModuleSpec; +import com.facebook.react.bridge.JSIModuleType; +import com.facebook.react.bridge.JavaScriptContextHolder; +import com.facebook.react.bridge.ReactApplicationContext; +import com.facebook.react.bridge.UIManager; +import com.facebook.react.fabric.ComponentFactory; +import com.facebook.react.fabric.CoreComponentsRegistry; +import com.facebook.react.fabric.FabricJSIModuleProvider; +import com.facebook.react.fabric.ReactNativeConfig; +import com.facebook.react.uimanager.ViewManagerRegistry; +import java.util.ArrayList; +import java.util.List; + +/** + * A {@link ReactNativeHost} that helps you load everything needed for the New + * Architecture, both TurboModule delegates and the Fabric Renderer. + * + *

Please note that this class is used ONLY if you opt-in for the New + * Architecture (see the `newArchEnabled` property). Is ignored otherwise. + */ +public class MainApplicationReactNativeHost extends ReactNativeHost { + public MainApplicationReactNativeHost(Application application) { + super(application); + } + + @Override + public boolean getUseDeveloperSupport() { + return BuildConfig.DEBUG; + } + + @Override + protected List getPackages() { + List packages = new PackageList(this).getPackages(); + // Packages that cannot be autolinked yet can be added manually here, for + // example: + // packages.add(new MyReactNativePackage()); + // TurboModules must also be loaded here providing a valid TurboReactPackage + // implementation: + // packages.add(new TurboReactPackage() { ... }); + // If you have custom Fabric Components, their ViewManagers should also be + // loaded here inside a ReactPackage. + return packages; + } + + @Override + protected String getJSMainModuleName() { + return "index"; + } + + @NonNull + @Override + protected ReactPackageTurboModuleManagerDelegate.Builder + getReactPackageTurboModuleManagerDelegateBuilder() { + // Here we provide the ReactPackageTurboModuleManagerDelegate Builder. This + // is necessary for the new architecture and to use TurboModules correctly. + return new MainApplicationTurboModuleManagerDelegate.Builder(); + } + + @Override + protected JSIModulePackage getJSIModulePackage() { + return new JSIModulePackage() { + @Override + public List getJSIModules( + final ReactApplicationContext reactApplicationContext, + final JavaScriptContextHolder jsContext) { + final List specs = new ArrayList<>(); + + // Here we provide a new JSIModuleSpec that will be responsible of + // providing the custom Fabric Components. + specs.add(new JSIModuleSpec() { + @Override + public JSIModuleType getJSIModuleType() { + return JSIModuleType.UIManager; + } + + @Override + public JSIModuleProvider getJSIModuleProvider() { + final ComponentFactory componentFactory = new ComponentFactory(); + CoreComponentsRegistry.register(componentFactory); + + // Here we register a Components Registry. + // The one that is generated with the template contains no + // components and just provides you the one from React Native core. + MainComponentsRegistry.register(componentFactory); + + final ReactInstanceManager reactInstanceManager = + getReactInstanceManager(); + + ViewManagerRegistry viewManagerRegistry = new ViewManagerRegistry( + reactInstanceManager.getOrCreateViewManagers( + reactApplicationContext)); + + return new FabricJSIModuleProvider( + reactApplicationContext, + componentFactory, + ReactNativeConfig.DEFAULT_CONFIG, + viewManagerRegistry); + } + }); + return specs; + } + }; + } +} diff --git a/native/android/app/src/main/java/app/comm/android/newarchitecture/components/MainComponentsRegistry.java b/native/android/app/src/main/java/app/comm/android/newarchitecture/components/MainComponentsRegistry.java new file mode 100644 index 000000000..887d295c3 --- /dev/null +++ b/native/android/app/src/main/java/app/comm/android/newarchitecture/components/MainComponentsRegistry.java @@ -0,0 +1,37 @@ +package app.comm.android.newarchitecture.components; + +import com.facebook.jni.HybridData; +import com.facebook.proguard.annotations.DoNotStrip; +import com.facebook.react.fabric.ComponentFactory; +import com.facebook.soloader.SoLoader; + +/** + * Class responsible to load the custom Fabric Components. This class has native + * methods and needs a corresponding C++ implementation/header file to work + * correctly (already placed inside the jni/ folder for you). + * + *

Please note that this class is used ONLY if you opt-in for the New + * Architecture (see the `newArchEnabled` property). Is ignored otherwise. + */ +@DoNotStrip +public class MainComponentsRegistry { + static { + SoLoader.loadLibrary("fabricjni"); + } + + @DoNotStrip private final HybridData mHybridData; + + @DoNotStrip + private native HybridData initHybrid(ComponentFactory componentFactory); + + @DoNotStrip + private MainComponentsRegistry(ComponentFactory componentFactory) { + mHybridData = initHybrid(componentFactory); + } + + @DoNotStrip + public static MainComponentsRegistry register( + ComponentFactory componentFactory) { + return new MainComponentsRegistry(componentFactory); + } +} diff --git a/native/android/app/src/main/java/app/comm/android/newarchitecture/modules/MainApplicationTurboModuleManagerDelegate.java b/native/android/app/src/main/java/app/comm/android/newarchitecture/modules/MainApplicationTurboModuleManagerDelegate.java new file mode 100644 index 000000000..4266d700e --- /dev/null +++ b/native/android/app/src/main/java/app/comm/android/newarchitecture/modules/MainApplicationTurboModuleManagerDelegate.java @@ -0,0 +1,50 @@ +package app.comm.android.newarchitecture.modules; + +import com.facebook.jni.HybridData; +import com.facebook.react.ReactPackage; +import com.facebook.react.ReactPackageTurboModuleManagerDelegate; +import com.facebook.react.bridge.ReactApplicationContext; +import com.facebook.soloader.SoLoader; +import java.util.List; + +/** + * Class responsible to load the TurboModules. This class has native methods and + * needs a corresponding C++ implementation/header file to work correctly + * (already placed inside the jni/ folder for you). + * + *

Please note that this class is used ONLY if you opt-in for the New + * Architecture (see the `newArchEnabled` property). Is ignored otherwise. + */ +public class MainApplicationTurboModuleManagerDelegate + extends ReactPackageTurboModuleManagerDelegate { + + private static volatile boolean sIsSoLibraryLoaded; + + protected MainApplicationTurboModuleManagerDelegate( + ReactApplicationContext reactApplicationContext, + List packages) { + super(reactApplicationContext, packages); + } + + protected native HybridData initHybrid(); + + native boolean canCreateTurboModule(String moduleName); + + public static class Builder + extends ReactPackageTurboModuleManagerDelegate.Builder { + protected MainApplicationTurboModuleManagerDelegate + build(ReactApplicationContext context, List packages) { + return new MainApplicationTurboModuleManagerDelegate(context, packages); + } + } + + @Override + protected synchronized void maybeLoadOtherSoLibraries() { + if (!sIsSoLibraryLoaded) { + // If you change the name of your application .so file in the Android.mk + // file, make sure you update the name here as well. + SoLoader.loadLibrary("comm_appmodules"); + sIsSoLibraryLoaded = true; + } + } +} diff --git a/native/android/app/src/main/jni/CMakeLists.txt b/native/android/app/src/main/jni/CMakeLists.txt new file mode 100644 index 000000000..e56daef1c --- /dev/null +++ b/native/android/app/src/main/jni/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.13) +# Define the library name here. +project(comm_appmodules) +# This file includes all the necessary to +# let you build your application with the New Architecture. +include(${REACT_ANDROID_DIR}/cmake-utils/ReactNative-application.cmake) diff --git a/native/android/app/src/main/jni/MainApplicationModuleProvider.cpp b/native/android/app/src/main/jni/MainApplicationModuleProvider.cpp new file mode 100644 index 000000000..26162dd87 --- /dev/null +++ b/native/android/app/src/main/jni/MainApplicationModuleProvider.cpp @@ -0,0 +1,32 @@ +#include "MainApplicationModuleProvider.h" + +#include +#include + +namespace facebook { +namespace react { + +std::shared_ptr MainApplicationModuleProvider( + const std::string &moduleName, + const JavaTurboModule::InitParams ¶ms) { + // Here you can provide your own module provider for TurboModules coming from + // either your application or from external libraries. The approach to follow + // is similar to the following (for a library called `samplelibrary`: + // + // auto module = samplelibrary_ModuleProvider(moduleName, params); + // if (module != nullptr) { + // return module; + // } + // return rncore_ModuleProvider(moduleName, params); + + // Module providers autolinked by RN CLI + auto rncli_module = rncli_ModuleProvider(moduleName, params); + if (rncli_module != nullptr) { + return rncli_module; + } + + return rncore_ModuleProvider(moduleName, params); +} + +} // namespace react +} // namespace facebook diff --git a/native/android/app/src/main/jni/MainApplicationModuleProvider.h b/native/android/app/src/main/jni/MainApplicationModuleProvider.h new file mode 100644 index 000000000..b38ccf53f --- /dev/null +++ b/native/android/app/src/main/jni/MainApplicationModuleProvider.h @@ -0,0 +1,16 @@ +#pragma once + +#include +#include + +#include + +namespace facebook { +namespace react { + +std::shared_ptr MainApplicationModuleProvider( + const std::string &moduleName, + const JavaTurboModule::InitParams ¶ms); + +} // namespace react +} // namespace facebook diff --git a/native/android/app/src/main/jni/MainApplicationTurboModuleManagerDelegate.cpp b/native/android/app/src/main/jni/MainApplicationTurboModuleManagerDelegate.cpp new file mode 100644 index 000000000..5fd688c50 --- /dev/null +++ b/native/android/app/src/main/jni/MainApplicationTurboModuleManagerDelegate.cpp @@ -0,0 +1,45 @@ +#include "MainApplicationTurboModuleManagerDelegate.h" +#include "MainApplicationModuleProvider.h" + +namespace facebook { +namespace react { + +jni::local_ref +MainApplicationTurboModuleManagerDelegate::initHybrid( + jni::alias_ref) { + return makeCxxInstance(); +} + +void MainApplicationTurboModuleManagerDelegate::registerNatives() { + registerHybrid({ + makeNativeMethod( + "initHybrid", MainApplicationTurboModuleManagerDelegate::initHybrid), + makeNativeMethod( + "canCreateTurboModule", + MainApplicationTurboModuleManagerDelegate::canCreateTurboModule), + }); +} + +std::shared_ptr +MainApplicationTurboModuleManagerDelegate::getTurboModule( + const std::string &name, + const std::shared_ptr &jsInvoker) { + // Not implemented yet: provide pure-C++ NativeModules here. + return nullptr; +} + +std::shared_ptr +MainApplicationTurboModuleManagerDelegate::getTurboModule( + const std::string &name, + const JavaTurboModule::InitParams ¶ms) { + return MainApplicationModuleProvider(name, params); +} + +bool MainApplicationTurboModuleManagerDelegate::canCreateTurboModule( + const std::string &name) { + return getTurboModule(name, nullptr) != nullptr || + getTurboModule(name, {.moduleName = name}) != nullptr; +} + +} // namespace react +} // namespace facebook diff --git a/native/android/app/src/main/jni/MainApplicationTurboModuleManagerDelegate.h b/native/android/app/src/main/jni/MainApplicationTurboModuleManagerDelegate.h new file mode 100644 index 000000000..932c41a5f --- /dev/null +++ b/native/android/app/src/main/jni/MainApplicationTurboModuleManagerDelegate.h @@ -0,0 +1,38 @@ +#include +#include + +#include +#include + +namespace facebook { +namespace react { + +class MainApplicationTurboModuleManagerDelegate + : public jni::HybridClass< + MainApplicationTurboModuleManagerDelegate, + TurboModuleManagerDelegate> { + public: + // Adapt it to the package you used for your Java class. + static constexpr auto kJavaDescriptor = + "Lapp/comm/android/newarchitecture/modules/MainApplicationTurboModuleManagerDelegate;"; + + static jni::local_ref initHybrid(jni::alias_ref); + + static void registerNatives(); + + std::shared_ptr getTurboModule( + const std::string &name, + const std::shared_ptr &jsInvoker) override; + std::shared_ptr getTurboModule( + const std::string &name, + const JavaTurboModule::InitParams ¶ms) override; + + /** + * Test-only method. Allows user to verify whether a TurboModule can be + * created by instances of this class. + */ + bool canCreateTurboModule(const std::string &name); +}; + +} // namespace react +} // namespace facebook diff --git a/native/android/app/src/main/jni/MainComponentsRegistry.cpp b/native/android/app/src/main/jni/MainComponentsRegistry.cpp new file mode 100644 index 000000000..54f598a48 --- /dev/null +++ b/native/android/app/src/main/jni/MainComponentsRegistry.cpp @@ -0,0 +1,65 @@ +#include "MainComponentsRegistry.h" + +#include +#include +#include +#include +#include + +namespace facebook { +namespace react { + +MainComponentsRegistry::MainComponentsRegistry(ComponentFactory *delegate) {} + +std::shared_ptr +MainComponentsRegistry::sharedProviderRegistry() { + auto providerRegistry = CoreComponentsRegistry::sharedProviderRegistry(); + + // Autolinked providers registered by RN CLI + rncli_registerProviders(providerRegistry); + + // Custom Fabric Components go here. You can register custom + // components coming from your App or from 3rd party libraries here. + // + // providerRegistry->add(concreteComponentDescriptorProvider< + // AocViewerComponentDescriptor>()); + return providerRegistry; +} + +jni::local_ref +MainComponentsRegistry::initHybrid( + jni::alias_ref, + ComponentFactory *delegate) { + auto instance = makeCxxInstance(delegate); + + auto buildRegistryFunction = + [](EventDispatcher::Weak const &eventDispatcher, + ContextContainer::Shared const &contextContainer) + -> ComponentDescriptorRegistry::Shared { + auto registry = MainComponentsRegistry::sharedProviderRegistry() + ->createComponentDescriptorRegistry( + {eventDispatcher, contextContainer}); + + auto mutableRegistry = + std::const_pointer_cast(registry); + + mutableRegistry->setFallbackComponentDescriptor( + std::make_shared( + ComponentDescriptorParameters{ + eventDispatcher, contextContainer, nullptr})); + + return registry; + }; + + delegate->buildRegistryFunction = buildRegistryFunction; + return instance; +} + +void MainComponentsRegistry::registerNatives() { + registerHybrid({ + makeNativeMethod("initHybrid", MainComponentsRegistry::initHybrid), + }); +} + +} // namespace react +} // namespace facebook diff --git a/native/android/app/src/main/jni/MainComponentsRegistry.h b/native/android/app/src/main/jni/MainComponentsRegistry.h new file mode 100644 index 000000000..e06add55c --- /dev/null +++ b/native/android/app/src/main/jni/MainComponentsRegistry.h @@ -0,0 +1,32 @@ +#pragma once + +#include +#include +#include +#include + +namespace facebook { +namespace react { + +class MainComponentsRegistry + : public facebook::jni::HybridClass { + public: + // Adapt it to the package you used for your Java class. + constexpr static auto kJavaDescriptor = + "Lapp/comm/android/newarchitecture/components/MainComponentsRegistry;"; + + static void registerNatives(); + + MainComponentsRegistry(ComponentFactory *delegate); + + private: + static std::shared_ptr + sharedProviderRegistry(); + + static jni::local_ref initHybrid( + jni::alias_ref, + ComponentFactory *delegate); +}; + +} // namespace react +} // namespace facebook diff --git a/native/android/app/src/main/jni/OnLoad.cpp b/native/android/app/src/main/jni/OnLoad.cpp new file mode 100644 index 000000000..c569b6e86 --- /dev/null +++ b/native/android/app/src/main/jni/OnLoad.cpp @@ -0,0 +1,11 @@ +#include +#include "MainApplicationTurboModuleManagerDelegate.h" +#include "MainComponentsRegistry.h" + +JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) { + return facebook::jni::initialize(vm, [] { + facebook::react::MainApplicationTurboModuleManagerDelegate:: + registerNatives(); + facebook::react::MainComponentsRegistry::registerNatives(); + }); +} diff --git a/native/android/build.gradle b/native/android/build.gradle index 236819591..13ecff359 100644 --- a/native/android/build.gradle +++ b/native/android/build.gradle @@ -1,53 +1,62 @@ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext { - buildToolsVersion = "30.0.2" + buildToolsVersion = "31.0.0" minSdkVersion = 21 compileSdkVersion = 31 targetSdkVersion = 31 + // We can't use NDK 24 yet because of Folly build issues + // https://linear.app/comm/issue/ENG-2169/update-folly-on-android + //if (System.properties['os.arch'] == "aarch64") { + // // For M1 Users we need to use the NDK 24 which added support for aarch64 + // ndkVersion = "24.0.8215888" + //} else { + // // Otherwise we default to the side-by-side NDK version from AGP. + // ndkVersion = "21.4.7075529" + //} ndkVersion = "21.4.7075529" } repositories { google() mavenCentral() } dependencies { - classpath("com.android.tools.build:gradle:4.2.2") - classpath("de.undercouch:gradle-download-task:4.0.2") - classpath("com.google.gms:google-services:4.2.0") + classpath("com.android.tools.build:gradle:7.2.1") + classpath("com.facebook.react:react-native-gradle-plugin") + classpath("de.undercouch:gradle-download-task:5.0.1") + classpath("com.google.gms:google-services:4.3.14") classpath('org.ajoberstar:grgit:1.7.2') // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } ext { reactNativeFFmpegPackage = "min-gpl-lts" } allprojects { repositories { - mavenLocal() maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url(new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim(), "../android")) } maven { // Android JSC is installed from npm url(new File(["node", "--print", "require.resolve('jsc-android/package.json')"].execute(null, rootDir).text.trim(), "../dist")) } mavenCentral { // We don't want to fetch react-native from Maven Central as there are // older versions over there. content { excludeGroup "com.facebook.react" } } google() gradlePluginPortal() maven { url 'https://www.jitpack.io' } jcenter() } } diff --git a/native/android/gradle.properties b/native/android/gradle.properties index 94a7ee6ba..58822c94f 100644 --- a/native/android/gradle.properties +++ b/native/android/gradle.properties @@ -1,50 +1,58 @@ # Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. -# Default value: -Xmx1024m -XX:MaxPermSize=256m -org.gradle.jvmargs=-Xmx4096m -XX:MaxPermSize=4096m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 +# Default value: -Xmx512m -XX:MaxMetaspaceSize=256m +org.gradle.jvmargs=-Xmx4096m -XX:MaxMetaspaceSize=1024m -XX:MaxPermSize=4096m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects org.gradle.parallel=true # AndroidX package structure to make it clearer which packages are bundled with the # Android operating system, and which are packaged with your app's APK # https://developer.android.com/topic/libraries/support-library/androidx-rn android.useAndroidX=true # Automatically convert third-party libraries to use AndroidX android.enableJetifier=true expo.jsEngine=hermes # Enable GIF support in React Native images (~200 B increase) expo.gif.enabled=true # Enable webp support in React Native images (~85 KB increase) expo.webp.enabled=true # Enable animated webp support (~3.4 MB increase) # Disabled by default because iOS doesn't support animated webp expo.webp.animated=false # Version of flipper SDK to use with React Native -FLIPPER_VERSION=0.99.0 +FLIPPER_VERSION=0.125.0 + +# Use this property to specify which architecture you want to build. +# You can also override it from the CLI using +# ./gradlew -PreactNativeArchitectures=x86_64 +reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 + +# Use this property to enable support to the new architecture. +# This will allow you to use TurboModules and the Fabric render in +# your application. You should enable this flag either if you want +# to write custom TurboModules/Fabric components OR use libraries that +# are providing them. +newArchEnabled=false FOLLY_VERSION=2020.01.13.00 GLOG_VERSION=0.4.0 BOOST_VERSION=1_63_0 DOUBLE_CONVERSION_VERSION=1.1.6 # Version of OpenSSL library to build and link OPENSSL_VERSION=1.1.1l - -# Set to something like below to build specific architectures: -# reactNativeDebugArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 -reactNativeDebugArchitectures= diff --git a/native/android/gradle/wrapper/gradle-wrapper.jar b/native/android/gradle/wrapper/gradle-wrapper.jar index e708b1c02..41d9927a4 100644 Binary files a/native/android/gradle/wrapper/gradle-wrapper.jar and b/native/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/native/android/gradle/wrapper/gradle-wrapper.properties b/native/android/gradle/wrapper/gradle-wrapper.properties index 7665b0fa9..8fad3f5a9 100644 --- a/native/android/gradle/wrapper/gradle-wrapper.properties +++ b/native/android/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.9-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-all.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/native/android/gradlew b/native/android/gradlew index 4f906e0c8..1b6c78733 100755 --- a/native/android/gradlew +++ b/native/android/gradlew @@ -1,185 +1,234 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` +APP_BASE_NAME=${0##*/} # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" + JAVACMD=java which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=`expr $i + 1` + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/native/android/settings.gradle b/native/android/settings.gradle index f5b48dad1..653dfd05d 100644 --- a/native/android/settings.gradle +++ b/native/android/settings.gradle @@ -1,15 +1,23 @@ rootProject.name = 'Comm' apply from: new File(["node", "--print", "require.resolve('expo/package.json')"].execute(null, rootDir).text.trim(), "../scripts/autolinking.gradle"); useExpoModules() apply from: new File(["node", "--print", "require.resolve('@react-native-community/cli-platform-android/package.json')"].execute(null, rootDir).text.trim(), "../native_modules.gradle"); applyNativeModulesSettingsGradle(settings) include ':reactnativekeyboardinput' project(':reactnativekeyboardinput').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-keyboard-input/lib/android') include ':app' +includeBuild('../../node_modules/react-native-gradle-plugin') + +if (settings.hasProperty("newArchEnabled") && settings.newArchEnabled == "true") { + include(":ReactAndroid") + project(":ReactAndroid").projectDir = file('../node_modules/react-native/ReactAndroid') + include(":ReactAndroid:hermes-engine") + project(":ReactAndroid:hermes-engine").projectDir = file('../node_modules/react-native/ReactAndroid/hermes-engine') +} // We need to include '.gitmodules' for our 'GitModules' custom task org.apache.tools.ant.DirectoryScanner.removeDefaultExclude("**/.gitmodules")