diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/Binding.cpp b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/Binding.cpp index ed881126d224ba..4e88dda6afdd22 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/Binding.cpp +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/Binding.cpp @@ -16,9 +16,9 @@ #include #include #include -#include #include #include +#include #include #include #include @@ -73,7 +73,6 @@ std::shared_ptr Binding::getScheduler() { return scheduler_; } - void Binding::startSurface( jint surfaceId, jni::alias_ref moduleName, @@ -89,7 +88,11 @@ void Binding::startSurface( LayoutContext context; context.pointScaleFactor = pointScaleFactor_; scheduler->startSurface( - surfaceId, moduleName->toStdString(), initialProps->consume(), {}, context); + surfaceId, + moduleName->toStdString(), + initialProps->consume(), + {}, + context); } void Binding::startSurfaceWithConstraints( @@ -200,10 +203,12 @@ void Binding::installFabricUIManager( LOG(WARNING) << "Binding::installFabricUIManager() was called (address: " << this << ")."; - // Use std::lock and std::adopt_lock to prevent deadlocks by locking mutexes at the same time + // Use std::lock and std::adopt_lock to prevent deadlocks by locking mutexes + // at the same time std::lock(schedulerMutex_, javaUIManagerMutex_); std::lock_guard schedulerLock(schedulerMutex_, std::adopt_lock); - std::lock_guard uiManagerLock(javaUIManagerMutex_, std::adopt_lock); + std::lock_guard uiManagerLock( + javaUIManagerMutex_, std::adopt_lock); javaUIManager_ = make_global(javaUIManager); @@ -226,13 +231,15 @@ void Binding::installFabricUIManager( // TODO: T31905686 Create synchronous Event Beat jni::global_ref localJavaUIManager = javaUIManager_; EventBeat::Factory synchronousBeatFactory = - [eventBeatManager, runtimeExecutor, localJavaUIManager](EventBeat::SharedOwnerBox const &ownerBox) { + [eventBeatManager, runtimeExecutor, localJavaUIManager]( + EventBeat::SharedOwnerBox const &ownerBox) { return std::make_unique( ownerBox, eventBeatManager, runtimeExecutor, localJavaUIManager); }; EventBeat::Factory asynchronousBeatFactory = - [eventBeatManager, runtimeExecutor, localJavaUIManager](EventBeat::SharedOwnerBox const &ownerBox) { + [eventBeatManager, runtimeExecutor, localJavaUIManager]( + EventBeat::SharedOwnerBox const &ownerBox) { return std::make_unique( ownerBox, eventBeatManager, runtimeExecutor, localJavaUIManager); }; @@ -244,12 +251,14 @@ void Binding::installFabricUIManager( // Keep reference to config object and cache some feature flags here reactNativeConfig_ = config; - shouldCollateRemovesAndDeletes_ = reactNativeConfig_->getBool("react_fabric:enable_removedelete_collation_android"); + shouldCollateRemovesAndDeletes_ = reactNativeConfig_->getBool( + "react_fabric:enable_removedelete_collation_android"); collapseDeleteCreateMountingInstructions_ = reactNativeConfig_->getBool( "react_fabric:enabled_collapse_delete_create_mounting_instructions"); ; - disablePreallocateViews_ = reactNativeConfig_->getBool("react_fabric:disabled_view_preallocation_android"); + disablePreallocateViews_ = reactNativeConfig_->getBool( + "react_fabric:disabled_view_preallocation_android"); auto toolbox = SchedulerToolbox{}; toolbox.contextContainer = contextContainer; @@ -263,10 +272,12 @@ void Binding::installFabricUIManager( void Binding::uninstallFabricUIManager() { LOG(WARNING) << "Binding::uninstallFabricUIManager() was called (address: " << this << ")."; - // Use std::lock and std::adopt_lock to prevent deadlocks by locking mutexes at the same time + // Use std::lock and std::adopt_lock to prevent deadlocks by locking mutexes + // at the same time std::lock(schedulerMutex_, javaUIManagerMutex_); std::lock_guard schedulerLock(schedulerMutex_, std::adopt_lock); - std::lock_guard uiManagerLock(javaUIManagerMutex_, std::adopt_lock); + std::lock_guard uiManagerLock( + javaUIManagerMutex_, std::adopt_lock); scheduler_ = nullptr; javaUIManager_ = nullptr; @@ -279,8 +290,9 @@ inline local_ref castReadableMap( } inline local_ref castReadableArray( - local_ref nativeArray) { - return make_local(reinterpret_cast(nativeArray.get())); + local_ref nativeArray) { + return make_local( + reinterpret_cast(nativeArray.get())); } // TODO: this method will be removed when binding for components are code-gen @@ -351,8 +363,8 @@ local_ref createUpdateLayoutMountItem( oldChildShadowView.layoutMetrics != newChildShadowView.layoutMetrics) { static auto updateLayoutInstruction = jni::findClassStatic(UIManagerJavaDescriptor) - ->getMethod(jint, jint, jint, jint, jint, jint)>( - "updateLayoutMountItem"); + ->getMethod( + jint, jint, jint, jint, jint, jint)>("updateLayoutMountItem"); auto layoutMetrics = newChildShadowView.layoutMetrics; auto pointScaleFactor = layoutMetrics.pointScaleFactor; auto frame = layoutMetrics.frame; @@ -361,7 +373,8 @@ local_ref createUpdateLayoutMountItem( int y = round(frame.origin.y * pointScaleFactor); int w = round(frame.size.width * pointScaleFactor); int h = round(frame.size.height * pointScaleFactor); - auto layoutDirection = toInt(newChildShadowView.layoutMetrics.layoutDirection); + auto layoutDirection = + toInt(newChildShadowView.layoutMetrics.layoutDirection); return updateLayoutInstruction( javaUIManager, newChildShadowView.tag, x, y, w, h, layoutDirection); } @@ -370,20 +383,20 @@ local_ref createUpdateLayoutMountItem( } local_ref createUpdatePaddingMountItem( - const jni::global_ref &javaUIManager, - const ShadowViewMutation &mutation) { - + const jni::global_ref &javaUIManager, + const ShadowViewMutation &mutation) { auto oldChildShadowView = mutation.oldChildShadowView; auto newChildShadowView = mutation.newChildShadowView; - if (oldChildShadowView.layoutMetrics.contentInsets == newChildShadowView.layoutMetrics.contentInsets) { + if (oldChildShadowView.layoutMetrics.contentInsets == + newChildShadowView.layoutMetrics.contentInsets) { return nullptr; } static auto updateLayoutInstruction = - jni::findClassStatic(UIManagerJavaDescriptor) - ->getMethod(jint, jint, jint, jint, jint)>( - "updatePaddingMountItem"); + jni::findClassStatic(UIManagerJavaDescriptor) + ->getMethod(jint, jint, jint, jint, jint)>( + "updatePaddingMountItem"); auto layoutMetrics = newChildShadowView.layoutMetrics; auto pointScaleFactor = layoutMetrics.pointScaleFactor; @@ -394,7 +407,8 @@ local_ref createUpdatePaddingMountItem( int right = round(contentInsets.right * pointScaleFactor); int bottom = round(contentInsets.bottom * pointScaleFactor); - return updateLayoutInstruction(javaUIManager, newChildShadowView.tag, left, top, right, bottom); + return updateLayoutInstruction( + javaUIManager, newChildShadowView.tag, left, top, right, bottom); } local_ref createInsertMountItem( @@ -439,9 +453,9 @@ local_ref createUpdateStateMountItem( const jni::global_ref &javaUIManager, const ShadowViewMutation &mutation) { static auto updateStateInstruction = - jni::findClassStatic(UIManagerJavaDescriptor) - ->getMethod(jint, jobject)>( - "updateStateMountItem"); + jni::findClassStatic(UIManagerJavaDescriptor) + ->getMethod(jint, jobject)>( + "updateStateMountItem"); auto state = mutation.newChildShadowView.state; @@ -456,9 +470,9 @@ local_ref createUpdateStateMountItem( } return updateStateInstruction( - javaUIManager, - mutation.newChildShadowView.tag, - (javaStateWrapper != nullptr ? javaStateWrapper.get() : nullptr)); + javaUIManager, + mutation.newChildShadowView.tag, + (javaStateWrapper != nullptr ? javaStateWrapper.get() : nullptr)); } local_ref createRemoveMountItem( @@ -487,14 +501,13 @@ local_ref createDeleteMountItem( } local_ref createRemoveAndDeleteMultiMountItem( - const jni::global_ref &javaUIManager, - const std::vector &metadata) { - + const jni::global_ref &javaUIManager, + const std::vector &metadata) { auto env = Environment::current(); - auto removeAndDeleteArray = env->NewIntArray(metadata.size()*4); + auto removeAndDeleteArray = env->NewIntArray(metadata.size() * 4); int position = 0; jint temp[4]; - for (const auto& x : metadata) { + for (const auto &x : metadata) { temp[0] = x.tag; temp[1] = x.parentTag; temp[2] = x.index; @@ -504,30 +517,34 @@ local_ref createRemoveAndDeleteMultiMountItem( } static auto removeDeleteMultiInstruction = - jni::findClassStatic(UIManagerJavaDescriptor) - ->getMethod(jintArray)>("removeDeleteMultiMountItem"); + jni::findClassStatic(UIManagerJavaDescriptor) + ->getMethod(jintArray)>( + "removeDeleteMultiMountItem"); auto ret = removeDeleteMultiInstruction(javaUIManager, removeAndDeleteArray); - // It is not strictly necessary to manually delete the ref here, in this particular case. - // If JNI memory is being allocated in a loop, it's easy to overload the localref table - // and crash; this is not possible in this case since the JNI would automatically clear this - // ref when it goes out of scope, anyway. However, this is being left here as a reminder of - // good hygiene and to be careful with JNI-allocated memory in general. + // It is not strictly necessary to manually delete the ref here, in this + // particular case. If JNI memory is being allocated in a loop, it's easy to + // overload the localref table and crash; this is not possible in this case + // since the JNI would automatically clear this ref when it goes out of scope, + // anyway. However, this is being left here as a reminder of good hygiene and + // to be careful with JNI-allocated memory in general. env->DeleteLocalRef(removeAndDeleteArray); return ret; } -// TODO T48019320: because we pass initial props and state to the Create (and preallocate) mount instruction, -// we technically don't need to pass the first Update to any components. Dedupe? +// TODO T48019320: because we pass initial props and state to the Create (and +// preallocate) mount instruction, we technically don't need to pass the first +// Update to any components. Dedupe? local_ref createCreateMountItem( const jni::global_ref &javaUIManager, const ShadowViewMutation &mutation, const Tag surfaceId) { static auto createJavaInstruction = jni::findClassStatic(UIManagerJavaDescriptor) - ->getMethod(jstring, ReadableMap::javaobject, jobject, jint, jint, jboolean)>( + ->getMethod( + jstring, ReadableMap::javaobject, jobject, jint, jint, jboolean)>( "createMountItem"); auto newChildShadowView = mutation.newChildShadowView; @@ -539,7 +556,7 @@ local_ref createCreateMountItem( newChildShadowView.layoutMetrics != EmptyLayoutMetrics; local_ref props = castReadableMap( - ReadableNativeMap::newObjectCxxArgs(newChildShadowView.props->rawProps)); + ReadableNativeMap::newObjectCxxArgs(newChildShadowView.props->rawProps)); // Do not hold onto Java object from C // We DO want to hold onto C object from Java, since we don't know the @@ -570,7 +587,8 @@ void Binding::schedulerDidFinishTransaction( jni::global_ref localJavaUIManager = getJavaUIManager(); if (!localJavaUIManager) { - LOG(ERROR) << "Binding::schedulerDidFinishTransaction: JavaUIManager disappeared"; + LOG(ERROR) + << "Binding::schedulerDidFinishTransaction: JavaUIManager disappeared"; return; } @@ -651,16 +669,20 @@ void Binding::schedulerDidFinishTransaction( oldChildShadowView.layoutMetrics == EmptyLayoutMetrics; // Handle accumulated removals/deletions - if (shouldCollateRemovesAndDeletes_ && mutation.type != ShadowViewMutation::Remove && mutation.type != ShadowViewMutation::Delete) { + if (shouldCollateRemovesAndDeletes_ && + mutation.type != ShadowViewMutation::Remove && + mutation.type != ShadowViewMutation::Delete) { if (toRemove.size() > 0) { - mountItems[position++] = createRemoveAndDeleteMultiMountItem(localJavaUIManager, toRemove); + mountItems[position++] = + createRemoveAndDeleteMultiMountItem(localJavaUIManager, toRemove); toRemove.clear(); } } switch (mutation.type) { case ShadowViewMutation::Create: { - if (disablePreallocateViews_ || mutation.newChildShadowView.props->revision > 1 || + if (disablePreallocateViews_ || + mutation.newChildShadowView.props->revision > 1 || deletedViewTags.find(mutation.newChildShadowView.tag) != deletedViewTags.end()) { mountItems[position++] = @@ -671,9 +693,15 @@ void Binding::schedulerDidFinishTransaction( case ShadowViewMutation::Remove: { if (!isVirtual) { if (shouldCollateRemovesAndDeletes_) { - toRemove.push_back(RemoveDeleteMetadata{mutation.oldChildShadowView.tag, mutation.parentShadowView.tag, mutation.index, true, false}); + toRemove.push_back( + RemoveDeleteMetadata{mutation.oldChildShadowView.tag, + mutation.parentShadowView.tag, + mutation.index, + true, + false}); } else { - mountItems[position++] = createRemoveMountItem(localJavaUIManager, mutation); + mountItems[position++] = + createRemoveMountItem(localJavaUIManager, mutation); } } break; @@ -681,15 +709,22 @@ void Binding::schedulerDidFinishTransaction( case ShadowViewMutation::Delete: { if (shouldCollateRemovesAndDeletes_) { // It is impossible to delete without removing node first - const auto& it = std::find_if(std::begin(toRemove), std::end(toRemove), [&mutation](const auto& x) { return x.tag == mutation.oldChildShadowView.tag; }); + const auto &it = std::find_if( + std::begin(toRemove), + std::end(toRemove), + [&mutation](const auto &x) { + return x.tag == mutation.oldChildShadowView.tag; + }); if (it != std::end(toRemove)) { it->shouldDelete = true; } else { - toRemove.push_back(RemoveDeleteMetadata{mutation.oldChildShadowView.tag, -1, -1, false, true}); + toRemove.push_back(RemoveDeleteMetadata{ + mutation.oldChildShadowView.tag, -1, -1, false, true}); } } else { - mountItems[position++] = createDeleteMountItem(localJavaUIManager, mutation); + mountItems[position++] = + createDeleteMountItem(localJavaUIManager, mutation); } deletedViewTags.insert(mutation.oldChildShadowView.tag); @@ -719,7 +754,8 @@ void Binding::schedulerDidFinishTransaction( mountItems[position++] = updateLayoutMountItem; } - auto updatePaddingMountItem = createUpdatePaddingMountItem(localJavaUIManager, mutation); + auto updatePaddingMountItem = + createUpdatePaddingMountItem(localJavaUIManager, mutation); if (updatePaddingMountItem) { mountItems[position++] = updatePaddingMountItem; } @@ -741,7 +777,8 @@ void Binding::schedulerDidFinishTransaction( mountItems[position++] = createInsertMountItem(localJavaUIManager, mutation); - if (disablePreallocateViews_ || mutation.newChildShadowView.props->revision > 1 || + if (disablePreallocateViews_ || + mutation.newChildShadowView.props->revision > 1 || deletedViewTags.find(mutation.newChildShadowView.tag) != deletedViewTags.end()) { mountItems[position++] = @@ -769,7 +806,7 @@ void Binding::schedulerDidFinishTransaction( // Padding auto updatePaddingMountItem = - createUpdatePaddingMountItem(localJavaUIManager, mutation); + createUpdatePaddingMountItem(localJavaUIManager, mutation); if (updatePaddingMountItem) { mountItems[position++] = updatePaddingMountItem; } @@ -792,12 +829,14 @@ void Binding::schedulerDidFinishTransaction( // Handle remaining removals and deletions if (shouldCollateRemovesAndDeletes_ && toRemove.size() > 0) { - mountItems[position++] = createRemoveAndDeleteMultiMountItem(localJavaUIManager, toRemove); + mountItems[position++] = + createRemoveAndDeleteMultiMountItem(localJavaUIManager, toRemove); toRemove.clear(); } if (position <= 0) { - // If there are no mountItems to be sent to the platform, then it is not necessary to even call. + // If there are no mountItems to be sent to the platform, then it is not + // necessary to even call. return; } @@ -810,10 +849,17 @@ void Binding::schedulerDidFinishTransaction( auto batch = createMountItemsBatchContainer( localJavaUIManager, mountItemsArray.get(), position, commitNumber); - static auto scheduleMountItem = - jni::findClassStatic(UIManagerJavaDescriptor) - ->getMethod( - "scheduleMountItem"); + static auto scheduleMountItem = jni::findClassStatic(UIManagerJavaDescriptor) + ->getMethod("scheduleMountItem"); long finishTransactionEndTime = monotonicTimeInMilliseconds(); @@ -837,14 +883,14 @@ void Binding::setPixelDensity(float pointScaleFactor) { void Binding::schedulerDidRequestPreliminaryViewAllocation( const SurfaceId surfaceId, const ShadowView &shadowView) { - if (disablePreallocateViews_) { return; } jni::global_ref localJavaUIManager = getJavaUIManager(); if (!localJavaUIManager) { - LOG(ERROR) << "Binding::schedulerDidRequestPreliminaryViewAllocation: JavaUIManager disappeared"; + LOG(ERROR) + << "Binding::schedulerDidRequestPreliminaryViewAllocation: JavaUIManager disappeared"; return; } @@ -881,28 +927,28 @@ void Binding::schedulerDidRequestPreliminaryViewAllocation( } void Binding::schedulerDidDispatchCommand( - const ShadowView &shadowView, - std::string const &commandName, - folly::dynamic const args) { - + const ShadowView &shadowView, + std::string const &commandName, + folly::dynamic const args) { jni::global_ref localJavaUIManager = getJavaUIManager(); if (!localJavaUIManager) { - LOG(ERROR) << "Binding::schedulerDidDispatchCommand: JavaUIManager disappeared"; + LOG(ERROR) + << "Binding::schedulerDidDispatchCommand: JavaUIManager disappeared"; return; } static auto dispatchCommand = - jni::findClassStatic(UIManagerJavaDescriptor) - ->getMethod( - "dispatchCommand"); + jni::findClassStatic(UIManagerJavaDescriptor) + ->getMethod( + "dispatchCommand"); local_ref command = make_jstring(commandName); - local_ref argsArray = castReadableArray( - ReadableNativeArray::newObjectCxxArgs(args)); + local_ref argsArray = + castReadableArray(ReadableNativeArray::newObjectCxxArgs(args)); - dispatchCommand(localJavaUIManager, shadowView.tag, command.get(), argsArray.get()); + dispatchCommand( + localJavaUIManager, shadowView.tag, command.get(), argsArray.get()); } void Binding::schedulerDidSetJSResponder( @@ -910,7 +956,6 @@ void Binding::schedulerDidSetJSResponder( const ShadowView &shadowView, const ShadowView &initialShadowView, bool blockNativeResponder) { - jni::global_ref localJavaUIManager = getJavaUIManager(); if (!localJavaUIManager) { LOG(ERROR) << "Binding::schedulerSetJSResponder: JavaUIManager disappeared"; @@ -919,23 +964,25 @@ void Binding::schedulerDidSetJSResponder( static auto setJSResponder = jni::findClassStatic(UIManagerJavaDescriptor) - ->getMethod( - "setJSResponder"); + ->getMethod("setJSResponder"); - setJSResponder(localJavaUIManager, shadowView.tag, initialShadowView.tag, (jboolean) blockNativeResponder); + setJSResponder( + localJavaUIManager, + shadowView.tag, + initialShadowView.tag, + (jboolean)blockNativeResponder); } void Binding::schedulerDidClearJSResponder() { jni::global_ref localJavaUIManager = getJavaUIManager(); if (!localJavaUIManager) { - LOG(ERROR) << "Binding::schedulerClearJSResponder: JavaUIManager disappeared"; + LOG(ERROR) + << "Binding::schedulerClearJSResponder: JavaUIManager disappeared"; return; } - static auto clearJSResponder = - jni::findClassStatic(UIManagerJavaDescriptor) - ->getMethod("clearJSResponder"); + static auto clearJSResponder = jni::findClassStatic(UIManagerJavaDescriptor) + ->getMethod("clearJSResponder"); clearJSResponder(localJavaUIManager); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/Binding.h b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/Binding.h index 8c26a3ccb99bfe..a2c1f71a43e2bc 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/Binding.h +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/Binding.h @@ -76,17 +76,17 @@ class Binding : public jni::HybridClass, public SchedulerDelegate { const ShadowView &shadowView); void schedulerDidDispatchCommand( - const ShadowView &shadowView, - std::string const &commandName, - folly::dynamic const args); + const ShadowView &shadowView, + std::string const &commandName, + folly::dynamic const args); void setPixelDensity(float pointScaleFactor); void schedulerDidSetJSResponder( - SurfaceId surfaceId, - const ShadowView &shadowView, - const ShadowView &initialShadowView, - bool blockNativeResponder); + SurfaceId surfaceId, + const ShadowView &shadowView, + const ShadowView &initialShadowView, + bool blockNativeResponder); void schedulerDidClearJSResponder(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/ComponentFactoryDelegate.h b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/ComponentFactoryDelegate.h index 43b4d1b0128230..e9d091df5ad529 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/ComponentFactoryDelegate.h +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/ComponentFactoryDelegate.h @@ -10,8 +10,8 @@ #include #include #include -#include #include +#include #include #include @@ -25,7 +25,7 @@ class Instance; class ComponentFactoryDelegate : public jni::HybridClass { public: - constexpr static const char* const kJavaDescriptor = + constexpr static const char *const kJavaDescriptor = "Lcom/facebook/react/fabric/ComponentFactoryDelegate;"; static void registerNatives(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/EventBeatManager.cpp b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/EventBeatManager.cpp index 4117d5a74d7640..fb825461a43e9c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/EventBeatManager.cpp +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/EventBeatManager.cpp @@ -13,8 +13,8 @@ namespace facebook { namespace react { EventBeatManager::EventBeatManager( - jni::alias_ref jhybridobject) - : jhybridobject_(jhybridobject) {} + jni::alias_ref jhybridobject) + : jhybridobject_(jhybridobject) {} jni::local_ref EventBeatManager::initHybrid( jni::alias_ref jhybridobject) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/EventEmitterWrapper.cpp b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/EventEmitterWrapper.cpp index ecf147aac4f4f5..cdcc13fc306ca2 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/EventEmitterWrapper.cpp +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/EventEmitterWrapper.cpp @@ -20,7 +20,7 @@ EventEmitterWrapper::initHybrid(jni::alias_ref) { void EventEmitterWrapper::invokeEvent( std::string eventName, - NativeMap* payload) { + NativeMap *payload) { eventEmitter->dispatchEvent( eventName, payload->consume(), EventPriority::AsynchronousBatched); } @@ -33,4 +33,4 @@ void EventEmitterWrapper::registerNatives() { } } // namespace react -} // namespace facebook \ No newline at end of file +} // namespace facebook diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/EventEmitterWrapper.h b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/EventEmitterWrapper.h index 28ab46b4e878f1..353aa24171941d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/EventEmitterWrapper.h +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/EventEmitterWrapper.h @@ -18,14 +18,14 @@ class Instance; class EventEmitterWrapper : public jni::HybridClass { public: - constexpr static const char* const kJavaDescriptor = + constexpr static const char *const kJavaDescriptor = "Lcom/facebook/react/fabric/events/EventEmitterWrapper;"; static void registerNatives(); SharedEventEmitter eventEmitter; - void invokeEvent(std::string eventName, NativeMap* params); + void invokeEvent(std::string eventName, NativeMap *params); private: static jni::local_ref initHybrid(jni::alias_ref); diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/NodeStateWrapper.cpp b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/NodeStateWrapper.cpp index 77aaca433a67eb..7101bb7032aaad 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/NodeStateWrapper.cpp +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/NodeStateWrapper.cpp @@ -14,8 +14,8 @@ using namespace facebook::jni; namespace facebook { namespace react { -jni::local_ref -NodeStateWrapper::initHybrid(jni::alias_ref) { +jni::local_ref NodeStateWrapper::initHybrid( + jni::alias_ref) { return makeCxxInstance(); } @@ -26,7 +26,7 @@ jni::local_ref NodeStateWrapper::getState() { return readableNativeMap; } -void NodeStateWrapper::updateState(ReadableNativeMap* map) { +void NodeStateWrapper::updateState(ReadableNativeMap *map) { // Get folly::dynamic from map auto dynamicMap = map->consume(); // Set state diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/NodeStateWrapper.h b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/NodeStateWrapper.h index fa4e6c33880eda..d19cae44ad1199 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/NodeStateWrapper.h +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/NodeStateWrapper.h @@ -16,7 +16,7 @@ namespace react { class NodeStateWrapper : public jni::HybridClass { public: - constexpr static const char* const kJavaDescriptor = + constexpr static const char *const kJavaDescriptor = "Lcom/facebook/react/fabric/NodeStateWrapper;"; NodeStateWrapper() {} @@ -24,9 +24,10 @@ class NodeStateWrapper : public jni::HybridClass { static void registerNatives(); jni::local_ref getState(); - void updateState(ReadableNativeMap* map); + void updateState(ReadableNativeMap *map); + + const State *state_; - const State* state_; private: static jni::local_ref initHybrid(jni::alias_ref); }; diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/OnLoad.cpp b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/OnLoad.cpp index 824d2b9705ef40..f8b87bddd2dae5 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/OnLoad.cpp +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/OnLoad.cpp @@ -13,7 +13,7 @@ #include "EventEmitterWrapper.h" #include "StateWrapperImpl.h" -JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void*) { +JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) { return facebook::xplat::initialize(vm, [] { facebook::react::Binding::registerNatives(); facebook::react::EventBeatManager::registerNatives(); diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/ReactNativeConfigHolder.cpp b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/ReactNativeConfigHolder.cpp index dd567aff94de3b..e35531e9325dba 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/ReactNativeConfigHolder.cpp +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/ReactNativeConfigHolder.cpp @@ -11,14 +11,14 @@ using namespace facebook::react; -bool ReactNativeConfigHolder::getBool(const std::string& param) const { +bool ReactNativeConfigHolder::getBool(const std::string ¶m) const { static const auto method = facebook::jni::findClassStatic( "com/facebook/react/fabric/ReactNativeConfig") ->getMethod("getBool"); return method(reactNativeConfig_, facebook::jni::make_jstring(param).get()); } -std::string ReactNativeConfigHolder::getString(const std::string& param) const { +std::string ReactNativeConfigHolder::getString(const std::string ¶m) const { static const auto method = facebook::jni::findClassStatic( "com/facebook/react/fabric/ReactNativeConfig") ->getMethod("getString"); @@ -26,14 +26,14 @@ std::string ReactNativeConfigHolder::getString(const std::string& param) const { ->toString(); } -int64_t ReactNativeConfigHolder::getInt64(const std::string& param) const { +int64_t ReactNativeConfigHolder::getInt64(const std::string ¶m) const { static const auto method = facebook::jni::findClassStatic( "com/facebook/react/fabric/ReactNativeConfig") ->getMethod("getInt64"); return method(reactNativeConfig_, facebook::jni::make_jstring(param).get()); } -double ReactNativeConfigHolder::getDouble(const std::string& param) const { +double ReactNativeConfigHolder::getDouble(const std::string ¶m) const { static const auto method = facebook::jni::findClassStatic( "com/facebook/react/fabric/ReactNativeConfig") ->getMethod("getDouble"); diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/ReactNativeConfigHolder.h b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/ReactNativeConfigHolder.h index eb2a689a610191..8b28ffb0a953d0 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/ReactNativeConfigHolder.h +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/ReactNativeConfigHolder.h @@ -25,10 +25,10 @@ class ReactNativeConfigHolder : public ReactNativeConfig { ReactNativeConfigHolder(jni::alias_ref reactNativeConfig) : reactNativeConfig_(make_global(reactNativeConfig)){}; - bool getBool(const std::string& param) const override; - std::string getString(const std::string& param) const override; - int64_t getInt64(const std::string& param) const override; - double getDouble(const std::string& param) const override; + bool getBool(const std::string ¶m) const override; + std::string getString(const std::string ¶m) const override; + int64_t getInt64(const std::string ¶m) const override; + double getDouble(const std::string ¶m) const override; private: jni::global_ref reactNativeConfig_; diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/StateWrapperImpl.cpp b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/StateWrapperImpl.cpp index 63d3d2e3c5a23b..73898875e87d93 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/StateWrapperImpl.cpp +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/StateWrapperImpl.cpp @@ -17,8 +17,8 @@ namespace react { /** * Called from Java constructor through the JNI. */ -jni::local_ref -StateWrapperImpl::initHybrid(jni::alias_ref) { +jni::local_ref StateWrapperImpl::initHybrid( + jni::alias_ref) { return makeCxxInstance(); } @@ -29,7 +29,7 @@ jni::local_ref StateWrapperImpl::getState() { return readableNativeMap; } -void StateWrapperImpl::updateStateImpl(NativeMap* map) { +void StateWrapperImpl::updateStateImpl(NativeMap *map) { // Get folly::dynamic from map auto dynamicMap = map->consume(); // Set state @@ -38,8 +38,8 @@ void StateWrapperImpl::updateStateImpl(NativeMap* map) { void StateWrapperImpl::registerNatives() { registerHybrid({ - makeNativeMethod("initHybrid", StateWrapperImpl::initHybrid), - makeNativeMethod("getState", StateWrapperImpl::getState), + makeNativeMethod("initHybrid", StateWrapperImpl::initHybrid), + makeNativeMethod("getState", StateWrapperImpl::getState), makeNativeMethod("updateStateImpl", StateWrapperImpl::updateStateImpl), }); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/StateWrapperImpl.h b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/StateWrapperImpl.h index 4e00fb004b2df9..fc93083c3b534d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/StateWrapperImpl.h +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/jni/StateWrapperImpl.h @@ -18,7 +18,7 @@ class Instance; class StateWrapperImpl : public jni::HybridClass { public: - constexpr static const char* const kJavaDescriptor = + constexpr static const char *const kJavaDescriptor = "Lcom/facebook/react/fabric/StateWrapperImpl;"; static void registerNatives(); @@ -27,6 +27,7 @@ class StateWrapperImpl : public jni::HybridClass { void updateStateImpl(NativeMap *map); State::Shared state_; + private: jni::alias_ref jhybridobject_; diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/blob/jni/BlobCollector.cpp b/ReactAndroid/src/main/java/com/facebook/react/modules/blob/jni/BlobCollector.cpp index 4d95e17c99bf1b..a4ede5d71e3946 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/blob/jni/BlobCollector.cpp +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/blob/jni/BlobCollector.cpp @@ -27,7 +27,7 @@ BlobCollector::BlobCollector( BlobCollector::~BlobCollector() { jni::ThreadScope::WithClassLoader([&] { static auto removeMethod = jni::findClassStatic(kBlobModuleJavaDescriptor) - ->getMethod("remove"); + ->getMethod("remove"); removeMethod(blobModule_, jni::make_jstring(blobId_).get()); }); } @@ -36,7 +36,7 @@ void BlobCollector::nativeInstall( jni::alias_ref jThis, jni::alias_ref blobModule, jlong jsContextNativePointer) { - auto &runtime = *((jsi::Runtime *) jsContextNativePointer); + auto &runtime = *((jsi::Runtime *)jsContextNativePointer); auto blobModuleRef = jni::make_global(blobModule); runtime.global().setProperty( runtime, diff --git a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/CallInvokerHolder.h b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/CallInvokerHolder.h index c982be0f6d5196..148ff2538b4856 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/CallInvokerHolder.h +++ b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/CallInvokerHolder.h @@ -7,15 +7,14 @@ #pragma once -#include #include +#include #include namespace facebook { namespace react { -class CallInvokerHolder - : public jni::HybridClass { +class CallInvokerHolder : public jni::HybridClass { public: static auto constexpr kJavaDescriptor = "Lcom/facebook/react/turbomodule/core/CallInvokerHolderImpl;"; diff --git a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/OnLoad.cpp b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/OnLoad.cpp index 99d2ee106f3221..3a9e269fe32008 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/OnLoad.cpp +++ b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/OnLoad.cpp @@ -12,7 +12,8 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) { return facebook::xplat::initialize(vm, [] { - // TODO: dvacca ramanpreet unify this with the way "ComponentDescriptorFactory" is defined in Fabric + // TODO: dvacca ramanpreet unify this with the way + // "ComponentDescriptorFactory" is defined in Fabric facebook::react::TurboModuleManager::registerNatives(); }); } diff --git a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/TurboModuleManager.cpp b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/TurboModuleManager.cpp index 051ea471653493..eae88b38143e1f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/TurboModuleManager.cpp +++ b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/TurboModuleManager.cpp @@ -11,8 +11,8 @@ #include #include -#include #include +#include #include #include "TurboModuleManager.h" @@ -21,37 +21,40 @@ namespace facebook { namespace react { TurboModuleManager::TurboModuleManager( - jni::alias_ref jThis, - jsi::Runtime* rt, - std::shared_ptr jsCallInvoker, - std::shared_ptr nativeCallInvoker, - jni::alias_ref delegate -): - javaPart_(jni::make_global(jThis)), - runtime_(rt), - jsCallInvoker_(jsCallInvoker), - nativeCallInvoker_(nativeCallInvoker), - delegate_(jni::make_global(delegate)), - turboModuleCache_(std::make_shared()) - {} + jni::alias_ref jThis, + jsi::Runtime *rt, + std::shared_ptr jsCallInvoker, + std::shared_ptr nativeCallInvoker, + jni::alias_ref delegate) + : javaPart_(jni::make_global(jThis)), + runtime_(rt), + jsCallInvoker_(jsCallInvoker), + nativeCallInvoker_(nativeCallInvoker), + delegate_(jni::make_global(delegate)), + turboModuleCache_(std::make_shared()) {} jni::local_ref TurboModuleManager::initHybrid( - jni::alias_ref jThis, - jlong jsContext, - jni::alias_ref jsCallInvokerHolder, - jni::alias_ref nativeCallInvokerHolder, - jni::alias_ref delegate -) { + jni::alias_ref jThis, + jlong jsContext, + jni::alias_ref jsCallInvokerHolder, + jni::alias_ref nativeCallInvokerHolder, + jni::alias_ref delegate) { auto jsCallInvoker = jsCallInvokerHolder->cthis()->getCallInvoker(); auto nativeCallInvoker = nativeCallInvokerHolder->cthis()->getCallInvoker(); - return makeCxxInstance(jThis, (jsi::Runtime *) jsContext, jsCallInvoker, nativeCallInvoker, delegate); + return makeCxxInstance( + jThis, + (jsi::Runtime *)jsContext, + jsCallInvoker, + nativeCallInvoker, + delegate); } void TurboModuleManager::registerNatives() { registerHybrid({ - makeNativeMethod("initHybrid", TurboModuleManager::initHybrid), - makeNativeMethod("installJSIBindings", TurboModuleManager::installJSIBindings), + makeNativeMethod("initHybrid", TurboModuleManager::initHybrid), + makeNativeMethod( + "installJSIBindings", TurboModuleManager::installJSIBindings), }); } @@ -60,57 +63,67 @@ void TurboModuleManager::installJSIBindings() { return; // Runtime doesn't exist when attached to Chrome debugger. } - TurboModuleBinding::install(*runtime_, std::make_shared( - [ - turboModuleCache_ = std::weak_ptr(turboModuleCache_), - jsCallInvoker_ = std::weak_ptr(jsCallInvoker_), - nativeCallInvoker_ = std::weak_ptr(nativeCallInvoker_), - delegate_ = jni::make_weak(delegate_), - javaPart_ = jni::make_weak(javaPart_) - ] - (const std::string &name) -> std::shared_ptr { - auto turboModuleCache = turboModuleCache_.lock(); - auto jsCallInvoker = jsCallInvoker_.lock(); - auto nativeCallInvoker = nativeCallInvoker_.lock(); - auto delegate = delegate_.lockLocal(); - auto javaPart = javaPart_.lockLocal(); - - if (!turboModuleCache || !jsCallInvoker || !nativeCallInvoker || !delegate || !javaPart) { - return nullptr; - } - - auto turboModuleLookup = turboModuleCache->find(name); - if (turboModuleLookup != turboModuleCache->end()) { - return turboModuleLookup->second; - } - - auto cxxModule = delegate->cthis()->getTurboModule(name, jsCallInvoker); - if (cxxModule) { - turboModuleCache->insert({name, cxxModule}); - return cxxModule; - } - - static auto getLegacyCxxModule = delegate->getClass()->getMethod(const std::string&)>("getLegacyCxxModule"); - auto legacyCxxModule = getLegacyCxxModule(delegate.get(), name); - - if (legacyCxxModule) { - auto turboModule = std::make_shared(legacyCxxModule->cthis()->getModule(), jsCallInvoker); - turboModuleCache->insert({name, turboModule}); - return turboModule; - } - - static auto getJavaModule = javaPart->getClass()->getMethod(const std::string&)>("getJavaModule"); - auto moduleInstance = getJavaModule(javaPart.get(), name); - - if (moduleInstance) { - auto turboModule = delegate->cthis()->getTurboModule(name, moduleInstance, jsCallInvoker, nativeCallInvoker); - turboModuleCache->insert({name, turboModule}); - return turboModule; - } - - return nullptr; - }) - ); + TurboModuleBinding::install( + *runtime_, + std::make_shared( + [turboModuleCache_ = + std::weak_ptr(turboModuleCache_), + jsCallInvoker_ = std::weak_ptr(jsCallInvoker_), + nativeCallInvoker_ = std::weak_ptr(nativeCallInvoker_), + delegate_ = jni::make_weak(delegate_), + javaPart_ = jni::make_weak(javaPart_)]( + const std::string &name) -> std::shared_ptr { + auto turboModuleCache = turboModuleCache_.lock(); + auto jsCallInvoker = jsCallInvoker_.lock(); + auto nativeCallInvoker = nativeCallInvoker_.lock(); + auto delegate = delegate_.lockLocal(); + auto javaPart = javaPart_.lockLocal(); + + if (!turboModuleCache || !jsCallInvoker || !nativeCallInvoker || + !delegate || !javaPart) { + return nullptr; + } + + auto turboModuleLookup = turboModuleCache->find(name); + if (turboModuleLookup != turboModuleCache->end()) { + return turboModuleLookup->second; + } + + auto cxxModule = + delegate->cthis()->getTurboModule(name, jsCallInvoker); + if (cxxModule) { + turboModuleCache->insert({name, cxxModule}); + return cxxModule; + } + + static auto getLegacyCxxModule = + delegate->getClass() + ->getMethod( + const std::string &)>("getLegacyCxxModule"); + auto legacyCxxModule = getLegacyCxxModule(delegate.get(), name); + + if (legacyCxxModule) { + auto turboModule = std::make_shared( + legacyCxxModule->cthis()->getModule(), jsCallInvoker); + turboModuleCache->insert({name, turboModule}); + return turboModule; + } + + static auto getJavaModule = + javaPart->getClass() + ->getMethod( + const std::string &)>("getJavaModule"); + auto moduleInstance = getJavaModule(javaPart.get(), name); + + if (moduleInstance) { + auto turboModule = delegate->cthis()->getTurboModule( + name, moduleInstance, jsCallInvoker, nativeCallInvoker); + turboModuleCache->insert({name, turboModule}); + return turboModule; + } + + return nullptr; + })); } } // namespace react diff --git a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/TurboModuleManager.h b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/TurboModuleManager.h index 26be4a311341a1..131d77095be9c1 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/TurboModuleManager.h +++ b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/TurboModuleManager.h @@ -7,40 +7,42 @@ #pragma once -#include -#include +#include +#include +#include +#include #include #include -#include -#include #include #include -#include -#include +#include +#include namespace facebook { namespace react { class TurboModuleManager : public jni::HybridClass { -public: - static auto constexpr kJavaDescriptor = "Lcom/facebook/react/turbomodule/core/TurboModuleManager;"; + public: + static auto constexpr kJavaDescriptor = + "Lcom/facebook/react/turbomodule/core/TurboModuleManager;"; static jni::local_ref initHybrid( - jni::alias_ref jThis, - jlong jsContext, - jni::alias_ref jsCallInvokerHolder, - jni::alias_ref nativeCallInvokerHolder, - jni::alias_ref delegate - ); + jni::alias_ref jThis, + jlong jsContext, + jni::alias_ref jsCallInvokerHolder, + jni::alias_ref nativeCallInvokerHolder, + jni::alias_ref delegate); static void registerNatives(); -private: + + private: friend HybridBase; jni::global_ref javaPart_; - jsi::Runtime* runtime_; + jsi::Runtime *runtime_; std::shared_ptr jsCallInvoker_; std::shared_ptr nativeCallInvoker_; jni::global_ref delegate_; - using TurboModuleCache = std::unordered_map>; + using TurboModuleCache = + std::unordered_map>; /** * TODO(T48018690): @@ -52,12 +54,11 @@ class TurboModuleManager : public jni::HybridClass { void installJSIBindings(); explicit TurboModuleManager( - jni::alias_ref jThis, - jsi::Runtime *rt, - std::shared_ptr jsCallInvoker, - std::shared_ptr nativeCallInvoker, - jni::alias_ref delegate - ); + jni::alias_ref jThis, + jsi::Runtime *rt, + std::shared_ptr jsCallInvoker, + std::shared_ptr nativeCallInvoker, + jni::alias_ref delegate); }; } // namespace react diff --git a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/TurboModuleManagerDelegate.h b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/TurboModuleManagerDelegate.h index 720b54915c7324..6577d915f416a1 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/TurboModuleManagerDelegate.h +++ b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/TurboModuleManagerDelegate.h @@ -7,23 +7,31 @@ #pragma once -#include -#include #include -#include +#include +#include #include +#include namespace facebook { namespace react { -class TurboModuleManagerDelegate : public jni::HybridClass { -public: - static auto constexpr kJavaDescriptor = "Lcom/facebook/react/turbomodule/core/TurboModuleManagerDelegate;"; +class TurboModuleManagerDelegate + : public jni::HybridClass { + public: + static auto constexpr kJavaDescriptor = + "Lcom/facebook/react/turbomodule/core/TurboModuleManagerDelegate;"; - virtual std::shared_ptr getTurboModule(std::string name, jni::alias_ref turboModule, std::shared_ptr jsInvoker, std::shared_ptr nativeInvoker) = 0; - virtual std::shared_ptr getTurboModule(std::string name, std::shared_ptr jsInvoker) = 0; + virtual std::shared_ptr getTurboModule( + std::string name, + jni::alias_ref turboModule, + std::shared_ptr jsInvoker, + std::shared_ptr nativeInvoker) = 0; + virtual std::shared_ptr getTurboModule( + std::string name, + std::shared_ptr jsInvoker) = 0; -private: + private: friend HybridBase; }; diff --git a/ReactAndroid/src/main/jni/react/jni/CatalystInstanceImpl.cpp b/ReactAndroid/src/main/jni/react/jni/CatalystInstanceImpl.cpp index 07ea9e43a92ee3..424e3c57ccc648 100644 --- a/ReactAndroid/src/main/jni/react/jni/CatalystInstanceImpl.cpp +++ b/ReactAndroid/src/main/jni/react/jni/CatalystInstanceImpl.cpp @@ -290,8 +290,8 @@ void CatalystInstanceImpl::handleMemoryPressure(int pressureLevel) { jni::alias_ref CatalystInstanceImpl::getJSCallInvokerHolder() { if (!jsCallInvokerHolder_) { - jsCallInvokerHolder_ = - jni::make_global(CallInvokerHolder::newObjectCxxArgs(std::make_shared(instance_))); + jsCallInvokerHolder_ = jni::make_global(CallInvokerHolder::newObjectCxxArgs( + std::make_shared(instance_))); } return jsCallInvokerHolder_; @@ -301,7 +301,9 @@ jni::alias_ref CatalystInstanceImpl::getNativeCallInvokerHolder() { if (!nativeCallInvokerHolder_) { nativeCallInvokerHolder_ = - jni::make_global(CallInvokerHolder::newObjectCxxArgs(std::make_shared(moduleMessageQueue_))); + jni::make_global(CallInvokerHolder::newObjectCxxArgs( + std::make_shared( + moduleMessageQueue_))); } return nativeCallInvokerHolder_; diff --git a/ReactAndroid/src/main/jni/react/jni/CxxModuleWrapperBase.h b/ReactAndroid/src/main/jni/react/jni/CxxModuleWrapperBase.h index b012b4eb648e4f..107d0ee71a156b 100644 --- a/ReactAndroid/src/main/jni/react/jni/CxxModuleWrapperBase.h +++ b/ReactAndroid/src/main/jni/react/jni/CxxModuleWrapperBase.h @@ -18,7 +18,7 @@ namespace react { struct JNativeModule : jni::JavaClass { constexpr static const char *const kJavaDescriptor = - "Lcom/facebook/react/bridge/NativeModule;"; + "Lcom/facebook/react/bridge/NativeModule;"; }; /** @@ -26,15 +26,14 @@ struct JNativeModule : jni::JavaClass { * must extend this base class. */ class CxxModuleWrapperBase - : public jni::HybridClass { -public: + : public jni::HybridClass { + public: constexpr static const char *const kJavaDescriptor = - "Lcom/facebook/react/bridge/CxxModuleWrapperBase;"; + "Lcom/facebook/react/bridge/CxxModuleWrapperBase;"; static void registerNatives() { - registerHybrid({ - makeNativeMethod("getName", CxxModuleWrapperBase::getName) - }); + registerHybrid( + {makeNativeMethod("getName", CxxModuleWrapperBase::getName)}); } // JNI method @@ -44,5 +43,5 @@ class CxxModuleWrapperBase virtual std::unique_ptr getModule() = 0; }; -} -} +} // namespace react +} // namespace facebook diff --git a/ReactAndroid/src/main/jni/react/jni/JCallback.h b/ReactAndroid/src/main/jni/react/jni/JCallback.h index 994b4161c44006..4e744c4ccb3436 100644 --- a/ReactAndroid/src/main/jni/react/jni/JCallback.h +++ b/ReactAndroid/src/main/jni/react/jni/JCallback.h @@ -20,30 +20,33 @@ namespace react { class Instance; struct JCallback : public jni::JavaClass { - constexpr static auto kJavaDescriptor = "Lcom/facebook/react/bridge/Callback;"; + constexpr static auto kJavaDescriptor = + "Lcom/facebook/react/bridge/Callback;"; }; class JCxxCallbackImpl : public jni::HybridClass { -public: - constexpr static auto kJavaDescriptor = "Lcom/facebook/react/bridge/CxxCallbackImpl;"; + public: + constexpr static auto kJavaDescriptor = + "Lcom/facebook/react/bridge/CxxCallbackImpl;"; static void registerNatives() { javaClassStatic()->registerNatives({ makeNativeMethod("nativeInvoke", JCxxCallbackImpl::invoke), }); } -private: + + private: friend HybridBase; using Callback = std::function; JCxxCallbackImpl(Callback callback) : callback_(std::move(callback)) {} - void invoke(NativeArray* arguments) { + void invoke(NativeArray *arguments) { callback_(arguments->consume()); } Callback callback_; }; -} -} +} // namespace react +} // namespace facebook diff --git a/ReactAndroid/src/main/jni/react/jni/JInspector.h b/ReactAndroid/src/main/jni/react/jni/JInspector.h index 6dca06401aee24..ccb4df91445f3b 100644 --- a/ReactAndroid/src/main/jni/react/jni/JInspector.h +++ b/ReactAndroid/src/main/jni/react/jni/JInspector.h @@ -19,23 +19,27 @@ namespace facebook { namespace react { class JPage : public jni::JavaClass { -public: - static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/Inspector$Page;"; + public: + static constexpr auto kJavaDescriptor = + "Lcom/facebook/react/bridge/Inspector$Page;"; - static jni::local_ref create(int id, const std::string& title, const std::string& vm); + static jni::local_ref + create(int id, const std::string &title, const std::string &vm); }; class JRemoteConnection : public jni::JavaClass { -public: - static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/Inspector$RemoteConnection;"; + public: + static constexpr auto kJavaDescriptor = + "Lcom/facebook/react/bridge/Inspector$RemoteConnection;"; - void onMessage(const std::string& message) const; + void onMessage(const std::string &message) const; void onDisconnect() const; }; class JLocalConnection : public jni::HybridClass { -public: - static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/Inspector$LocalConnection;"; + public: + static constexpr auto kJavaDescriptor = + "Lcom/facebook/react/bridge/Inspector$LocalConnection;"; JLocalConnection(std::unique_ptr connection); @@ -43,29 +47,35 @@ class JLocalConnection : public jni::HybridClass { void disconnect(); static void registerNatives(); -private: + + private: std::unique_ptr connection_; }; class JInspector : public jni::HybridClass { -public: - static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/Inspector;"; + public: + static constexpr auto kJavaDescriptor = + "Lcom/facebook/react/bridge/Inspector;"; - static jni::global_ref instance(jni::alias_ref); + static jni::global_ref instance( + jni::alias_ref); jni::local_ref> getPages(); - jni::local_ref connect(int pageId, jni::alias_ref remote); + jni::local_ref connect( + int pageId, + jni::alias_ref remote); static void registerNatives(); -private: + + private: friend HybridBase; - JInspector(IInspector* inspector) : inspector_(inspector) {} + JInspector(IInspector *inspector) : inspector_(inspector) {} - IInspector* inspector_; + IInspector *inspector_; }; -} -} +} // namespace react +} // namespace facebook #endif diff --git a/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.cpp b/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.cpp index 9c70f668e87346..92ab920aec3b61 100644 --- a/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.cpp +++ b/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.cpp @@ -22,16 +22,17 @@ namespace react { namespace { struct JavaJSException : jni::JavaClass { - static constexpr auto kJavaDescriptor = "Lcom/facebook/react/devsupport/JSException;"; + static constexpr auto kJavaDescriptor = + "Lcom/facebook/react/devsupport/JSException;"; - static local_ref create(const char* message, const char* stack, - const std::exception& ex) { + static local_ref + create(const char *message, const char *stack, const std::exception &ex) { local_ref cause = jni::JCppException::create(ex); return newInstance(make_jstring(message), make_jstring(stack), cause.get()); } }; -std::function wrapRunnable(std::function&& runnable) { +std::function wrapRunnable(std::function &&runnable) { return [runnable = std::move(runnable)]() mutable { if (!runnable) { // Runnable is empty, nothing to run. @@ -46,33 +47,39 @@ std::function wrapRunnable(std::function&& runnable) { try { localRunnable(); - } catch (const jsi::JSError& ex) { + } catch (const jsi::JSError &ex) { throwNewJavaException( - JavaJSException::create(ex.getMessage().c_str(), ex.getStack().c_str(), ex) - .get()); + JavaJSException::create( + ex.getMessage().c_str(), ex.getStack().c_str(), ex) + .get()); } }; } -} +} // namespace -JMessageQueueThread::JMessageQueueThread(alias_ref jobj) : - m_jobj(make_global(jobj)) { -} +JMessageQueueThread::JMessageQueueThread( + alias_ref jobj) + : m_jobj(make_global(jobj)) {} -void JMessageQueueThread::runOnQueue(std::function&& runnable) { +void JMessageQueueThread::runOnQueue(std::function &&runnable) { // 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 = JavaMessageQueueThread::javaClassStatic()-> - getMethod("runOnQueue"); - method(m_jobj, JNativeRunnable::newObjectCxxArgs(wrapRunnable(std::move(runnable))).get()); + static auto method = + JavaMessageQueueThread::javaClassStatic() + ->getMethod("runOnQueue"); + method( + m_jobj, + JNativeRunnable::newObjectCxxArgs(wrapRunnable(std::move(runnable))) + .get()); } -void JMessageQueueThread::runOnQueueSync(std::function&& runnable) { - static auto jIsOnThread = JavaMessageQueueThread::javaClassStatic()-> - getMethod("isOnThread"); +void JMessageQueueThread::runOnQueueSync(std::function &&runnable) { + static auto jIsOnThread = + JavaMessageQueueThread::javaClassStatic()->getMethod( + "isOnThread"); if (jIsOnThread(m_jobj)) { wrapRunnable(std::move(runnable))(); @@ -81,7 +88,7 @@ void JMessageQueueThread::runOnQueueSync(std::function&& runnable) { std::condition_variable signalCv; bool runnableComplete = false; - runOnQueue([&] () mutable { + runOnQueue([&]() mutable { std::lock_guard lock(signalMutex); runnable(); @@ -96,9 +103,11 @@ void JMessageQueueThread::runOnQueueSync(std::function&& runnable) { } void JMessageQueueThread::quitSynchronous() { - static auto method = JavaMessageQueueThread::javaClassStatic()-> - getMethod("quitSynchronous"); + static auto method = + JavaMessageQueueThread::javaClassStatic()->getMethod( + "quitSynchronous"); method(m_jobj); } -} } +} // namespace react +} // namespace facebook diff --git a/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.h b/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.h index d23544903b96ee..e3389ea4e3fc4c 100644 --- a/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.h +++ b/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.h @@ -18,29 +18,30 @@ namespace facebook { namespace react { class JavaMessageQueueThread : public jni::JavaClass { -public: - static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/queue/MessageQueueThread;"; + public: + static constexpr auto kJavaDescriptor = + "Lcom/facebook/react/bridge/queue/MessageQueueThread;"; }; class JMessageQueueThread : public MessageQueueThread { -public: + public: JMessageQueueThread(alias_ref jobj); /** * Enqueues the given function to run on this MessageQueueThread. */ - void runOnQueue(std::function&& runnable) override; + void runOnQueue(std::function &&runnable) override; /** * Synchronously executes the given function to run on this * MessageQueueThread, waiting until it completes. Can be called from any * thread, but will block if not called on this MessageQueueThread. */ - void runOnQueueSync(std::function&& runnable) override; + void runOnQueueSync(std::function &&runnable) override; /** - * Synchronously quits the current MessageQueueThread. Can be called from any thread, but will - * block if not called on this MessageQueueThread. + * Synchronously quits the current MessageQueueThread. Can be called from any + * thread, but will block if not called on this MessageQueueThread. */ void quitSynchronous() override; @@ -48,8 +49,9 @@ class JMessageQueueThread : public MessageQueueThread { return m_jobj.get(); } -private: + private: global_ref m_jobj; }; -} } +} // namespace react +} // namespace facebook diff --git a/ReactAndroid/src/main/jni/react/jni/JReactMarker.cpp b/ReactAndroid/src/main/jni/react/jni/JReactMarker.cpp index 1e3f0093df55c5..4d0505f3401535 100644 --- a/ReactAndroid/src/main/jni/react/jni/JReactMarker.cpp +++ b/ReactAndroid/src/main/jni/react/jni/JReactMarker.cpp @@ -6,33 +6,38 @@ */ #include "JReactMarker.h" -#include #include #include +#include namespace facebook { namespace react { void JReactMarker::setLogPerfMarkerIfNeeded() { - static std::once_flag flag {}; - std::call_once(flag, [](){ + static std::once_flag flag{}; + std::call_once(flag, []() { ReactMarker::logTaggedMarker = JReactMarker::logPerfMarker; }); } -void JReactMarker::logMarker(const std::string& marker) { +void JReactMarker::logMarker(const std::string &marker) { static auto cls = javaClassStatic(); static auto meth = cls->getStaticMethod("logMarker"); meth(cls, marker); } -void JReactMarker::logMarker(const std::string& marker, const std::string& tag) { +void JReactMarker::logMarker( + const std::string &marker, + const std::string &tag) { static auto cls = javaClassStatic(); - static auto meth = cls->getStaticMethod("logMarker"); + static auto meth = + cls->getStaticMethod("logMarker"); meth(cls, marker, tag); } -void JReactMarker::logPerfMarker(const ReactMarker::ReactMarkerId markerId, const char* tag) { +void JReactMarker::logPerfMarker( + const ReactMarker::ReactMarkerId markerId, + const char *tag) { switch (markerId) { case ReactMarker::RUN_JS_BUNDLE_START: JReactMarker::logMarker("RUN_JS_BUNDLE_START", tag); @@ -68,5 +73,5 @@ void JReactMarker::logPerfMarker(const ReactMarker::ReactMarkerId markerId, cons } } -} -} +} // namespace react +} // namespace facebook diff --git a/ReactAndroid/src/main/jni/react/jni/JReactMarker.h b/ReactAndroid/src/main/jni/react/jni/JReactMarker.h index a1327250aa692d..66e6584d3ec3d7 100644 --- a/ReactAndroid/src/main/jni/react/jni/JReactMarker.h +++ b/ReactAndroid/src/main/jni/react/jni/JReactMarker.h @@ -7,8 +7,8 @@ #pragma once -#include #include +#include #include @@ -16,15 +16,18 @@ namespace facebook { namespace react { class JReactMarker : public facebook::jni::JavaClass { -public: - static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/ReactMarker;"; + public: + static constexpr auto kJavaDescriptor = + "Lcom/facebook/react/bridge/ReactMarker;"; static void setLogPerfMarkerIfNeeded(); -private: - static void logMarker(const std::string& marker); - static void logMarker(const std::string& marker, const std::string& tag); - static void logPerfMarker(const ReactMarker::ReactMarkerId markerId, const char* tag); + private: + static void logMarker(const std::string &marker); + static void logMarker(const std::string &marker, const std::string &tag); + static void logPerfMarker( + const ReactMarker::ReactMarkerId markerId, + const char *tag); }; -} -} +} // namespace react +} // namespace facebook diff --git a/ReactAndroid/src/main/jni/react/jni/JSLoader.cpp b/ReactAndroid/src/main/jni/react/jni/JSLoader.cpp index b5e1eccab74cea..41c42214995f95 100644 --- a/ReactAndroid/src/main/jni/react/jni/JSLoader.cpp +++ b/ReactAndroid/src/main/jni/react/jni/JSLoader.cpp @@ -28,30 +28,33 @@ using namespace facebook::jni; namespace facebook { namespace react { -__attribute__((visibility("default"))) -AAssetManager *extractAssetManager(alias_ref assetManager) { +__attribute__((visibility("default"))) AAssetManager *extractAssetManager( + alias_ref assetManager) { auto env = Environment::current(); return AAssetManager_fromJava(env, assetManager.get()); } -__attribute__((visibility("default"))) -std::unique_ptr loadScriptFromAssets( - AAssetManager *manager, - const std::string& assetName) { - #ifdef WITH_FBSYSTRACE - FbSystraceSection s(TRACE_TAG_REACT_CXX_BRIDGE, "reactbridge_jni_loadScriptFromAssets", - "assetName", assetName); - #endif +__attribute__((visibility("default"))) std::unique_ptr +loadScriptFromAssets(AAssetManager *manager, const std::string &assetName) { +#ifdef WITH_FBSYSTRACE + FbSystraceSection s( + TRACE_TAG_REACT_CXX_BRIDGE, + "reactbridge_jni_loadScriptFromAssets", + "assetName", + assetName); +#endif if (manager) { auto asset = AAssetManager_open( - manager, - assetName.c_str(), - AASSET_MODE_STREAMING); // Optimized for sequential read: see AssetManager.java for docs + manager, + assetName.c_str(), + AASSET_MODE_STREAMING); // Optimized for sequential read: see + // AssetManager.java for docs if (asset) { auto buf = std::make_unique(AAsset_getLength(asset)); size_t offset = 0; int readbytes; - while ((readbytes = AAsset_read(asset, buf->data() + offset, buf->size() - offset)) > 0) { + while ((readbytes = AAsset_read( + asset, buf->data() + offset, buf->size() - offset)) > 0) { offset += readbytes; } AAsset_close(asset); @@ -61,9 +64,12 @@ std::unique_ptr loadScriptFromAssets( } } - throw std::runtime_error(folly::to("Unable to load script. Make sure you're " - "either running a Metro server (run 'react-native start') or that your bundle '", assetName, - "' is packaged correctly for release.")); + throw std::runtime_error(folly::to( + "Unable to load script. Make sure you're " + "either running a Metro server (run 'react-native start') or that your bundle '", + assetName, + "' is packaged correctly for release.")); } -}} +} // namespace react +} // namespace facebook diff --git a/ReactAndroid/src/main/jni/react/jni/JSLoader.h b/ReactAndroid/src/main/jni/react/jni/JSLoader.h index aa781a0d0e6316..b808080389e23c 100644 --- a/ReactAndroid/src/main/jni/react/jni/JSLoader.h +++ b/ReactAndroid/src/main/jni/react/jni/JSLoader.h @@ -23,8 +23,12 @@ struct JAssetManager : jni::JavaClass { /** * Helper method for loading JS script from android asset */ -AAssetManager *extractAssetManager(jni::alias_ref assetManager); +AAssetManager *extractAssetManager( + jni::alias_ref assetManager); -std::unique_ptr loadScriptFromAssets(AAssetManager *assetManager, const std::string& assetName); +std::unique_ptr loadScriptFromAssets( + AAssetManager *assetManager, + const std::string &assetName); -} } +} // namespace react +} // namespace facebook diff --git a/ReactAndroid/src/main/jni/react/jni/JavaModuleWrapper.cpp b/ReactAndroid/src/main/jni/react/jni/JavaModuleWrapper.cpp index 8e1c93c533a67f..5ba12675d7cafc 100644 --- a/ReactAndroid/src/main/jni/react/jni/JavaModuleWrapper.cpp +++ b/ReactAndroid/src/main/jni/react/jni/JavaModuleWrapper.cpp @@ -9,13 +9,13 @@ #include -#include -#include #include #include #include #include #include +#include +#include #ifdef WITH_FBSYSTRACE #include @@ -45,7 +45,8 @@ std::string JMethodDescriptor::getType() const { } std::string JavaNativeModule::getName() { - static auto getNameMethod = wrapper_->getClass()->getMethod("getName"); + static auto getNameMethod = + wrapper_->getClass()->getMethod("getName"); return getNameMethod(wrapper_)->toStdString(); } @@ -53,35 +54,34 @@ std::vector JavaNativeModule::getMethods() { std::vector ret; syncMethods_.clear(); auto descs = wrapper_->getMethodDescriptors(); - for (const auto& desc : *descs) { + for (const auto &desc : *descs) { auto methodName = desc->getName(); auto methodType = desc->getType(); if (methodType == "sync") { - // allow for the sync methods vector to have empty values, resize on demand + // allow for the sync methods vector to have empty values, resize on + // demand size_t methodIndex = ret.size(); if (methodIndex >= syncMethods_.size()) { syncMethods_.resize(methodIndex + 1); } - syncMethods_.insert(syncMethods_.begin() + methodIndex, MethodInvoker( - desc->getMethod(), - desc->getSignature(), - getName() + "." + methodName, - true - )); + syncMethods_.insert( + syncMethods_.begin() + methodIndex, + MethodInvoker( + desc->getMethod(), + desc->getSignature(), + getName() + "." + methodName, + true)); } - ret.emplace_back( - std::move(methodName), - std::move(methodType) - ); + ret.emplace_back(std::move(methodName), std::move(methodType)); } return ret; } folly::dynamic JavaNativeModule::getConstants() { static auto constantsMethod = - wrapper_->getClass()->getMethod("getConstants"); + wrapper_->getClass()->getMethod("getConstants"); auto constants = constantsMethod(wrapper_); if (!constants) { return nullptr; @@ -90,46 +90,60 @@ folly::dynamic JavaNativeModule::getConstants() { } } -void JavaNativeModule::invoke(unsigned int reactMethodId, folly::dynamic&& params, int callId) { - messageQueueThread_->runOnQueue([this, reactMethodId, params=std::move(params), callId] { - static auto invokeMethod = wrapper_->getClass()->getMethod("invoke"); - #ifdef WITH_FBSYSTRACE - if (callId != -1) { - fbsystrace_end_async_flow(TRACE_TAG_REACT_APPS, "native", callId); - } - #endif - invokeMethod( - wrapper_, - static_cast(reactMethodId), - ReadableNativeArray::newObjectCxxArgs(std::move(params)).get()); - }); +void JavaNativeModule::invoke( + unsigned int reactMethodId, + folly::dynamic &¶ms, + int callId) { + messageQueueThread_->runOnQueue( + [this, reactMethodId, params = std::move(params), callId] { + static auto invokeMethod = + wrapper_->getClass() + ->getMethod( + "invoke"); +#ifdef WITH_FBSYSTRACE + if (callId != -1) { + fbsystrace_end_async_flow(TRACE_TAG_REACT_APPS, "native", callId); + } +#endif + invokeMethod( + wrapper_, + static_cast(reactMethodId), + ReadableNativeArray::newObjectCxxArgs(std::move(params)).get()); + }); } -MethodCallResult JavaNativeModule::callSerializableNativeHook(unsigned int reactMethodId, folly::dynamic&& params) { +MethodCallResult JavaNativeModule::callSerializableNativeHook( + unsigned int reactMethodId, + folly::dynamic &¶ms) { // TODO: evaluate whether calling through invoke is potentially faster if (reactMethodId >= syncMethods_.size()) { - throw std::invalid_argument( - folly::to("methodId ", reactMethodId, " out of range [0..", syncMethods_.size(), "]")); + throw std::invalid_argument(folly::to( + "methodId ", + reactMethodId, + " out of range [0..", + syncMethods_.size(), + "]")); } - auto& method = syncMethods_[reactMethodId]; - CHECK(method.hasValue() && method->isSyncHook()) << "Trying to invoke a asynchronous method as synchronous hook"; + auto &method = syncMethods_[reactMethodId]; + CHECK(method.hasValue() && method->isSyncHook()) + << "Trying to invoke a asynchronous method as synchronous hook"; return method->invoke(instance_, wrapper_->getModule(), params); } NewJavaNativeModule::NewJavaNativeModule( - std::weak_ptr instance, - jni::alias_ref wrapper, - std::shared_ptr messageQueueThread) -: instance_(std::move(instance)) -, wrapper_(make_global(wrapper)) -, module_(make_global(wrapper->getModule())) -, messageQueueThread_(std::move(messageQueueThread)) { + std::weak_ptr instance, + jni::alias_ref wrapper, + std::shared_ptr messageQueueThread) + : instance_(std::move(instance)), + wrapper_(make_global(wrapper)), + module_(make_global(wrapper->getModule())), + messageQueueThread_(std::move(messageQueueThread)) { auto descs = wrapper_->getMethodDescriptors(); std::string moduleName = getName(); methods_.reserve(descs->size()); - for (const auto& desc : *descs) { + for (const auto &desc : *descs) { auto type = desc->getType(); auto name = desc->getName(); methods_.emplace_back( @@ -143,7 +157,8 @@ NewJavaNativeModule::NewJavaNativeModule( } std::string NewJavaNativeModule::getName() { - static auto getNameMethod = wrapper_->getClass()->getMethod("getName"); + static auto getNameMethod = + wrapper_->getClass()->getMethod("getName"); return getNameMethod(wrapper_)->toStdString(); } @@ -153,7 +168,7 @@ std::vector NewJavaNativeModule::getMethods() { folly::dynamic NewJavaNativeModule::getConstants() { static auto constantsMethod = - wrapper_->getClass()->getMethod("getConstants"); + wrapper_->getClass()->getMethod("getConstants"); auto constants = constantsMethod(wrapper_); if (!constants) { return nullptr; @@ -162,39 +177,59 @@ folly::dynamic NewJavaNativeModule::getConstants() { } } -void NewJavaNativeModule::invoke(unsigned int reactMethodId, folly::dynamic&& params, int callId) { +void NewJavaNativeModule::invoke( + unsigned int reactMethodId, + folly::dynamic &¶ms, + int callId) { if (reactMethodId >= methods_.size()) { - throw std::invalid_argument( - folly::to("methodId ", reactMethodId, " out of range [0..", methods_.size(), "]")); + throw std::invalid_argument(folly::to( + "methodId ", + reactMethodId, + " out of range [0..", + methods_.size(), + "]")); } - CHECK(!methods_[reactMethodId].isSyncHook()) << "Trying to invoke a synchronous hook asynchronously"; - messageQueueThread_->runOnQueue([this, reactMethodId, params=std::move(params), callId] () mutable { - #ifdef WITH_FBSYSTRACE - if (callId != -1) { - fbsystrace_end_async_flow(TRACE_TAG_REACT_APPS, "native", callId); - } - #endif - invokeInner(reactMethodId, std::move(params)); - }); + CHECK(!methods_[reactMethodId].isSyncHook()) + << "Trying to invoke a synchronous hook asynchronously"; + messageQueueThread_->runOnQueue( + [this, reactMethodId, params = std::move(params), callId]() mutable { +#ifdef WITH_FBSYSTRACE + if (callId != -1) { + fbsystrace_end_async_flow(TRACE_TAG_REACT_APPS, "native", callId); + } +#endif + invokeInner(reactMethodId, std::move(params)); + }); } -MethodCallResult NewJavaNativeModule::callSerializableNativeHook(unsigned int reactMethodId, folly::dynamic&& params) { +MethodCallResult NewJavaNativeModule::callSerializableNativeHook( + unsigned int reactMethodId, + folly::dynamic &¶ms) { if (reactMethodId >= methods_.size()) { - throw std::invalid_argument( - folly::to("methodId ", reactMethodId, " out of range [0..", methods_.size(), "]")); + throw std::invalid_argument(folly::to( + "methodId ", + reactMethodId, + " out of range [0..", + methods_.size(), + "]")); } - CHECK(methods_[reactMethodId].isSyncHook()) << "Trying to invoke a asynchronous method as synchronous hook"; + CHECK(methods_[reactMethodId].isSyncHook()) + << "Trying to invoke a asynchronous method as synchronous hook"; return invokeInner(reactMethodId, std::move(params)); } -MethodCallResult NewJavaNativeModule::invokeInner(unsigned int reactMethodId, folly::dynamic&& params) { +MethodCallResult NewJavaNativeModule::invokeInner( + unsigned int reactMethodId, + folly::dynamic &¶ms) { return methods_[reactMethodId].invoke(instance_, module_.get(), params); } -jni::local_ref JMethodDescriptor::getMethod() const { - static auto method = javaClassStatic()->getField("method"); +jni::local_ref JMethodDescriptor::getMethod() + const { + static auto method = + javaClassStatic()->getField("method"); return getFieldValue(method); } -} -} +} // namespace react +} // namespace facebook diff --git a/ReactAndroid/src/main/jni/react/jni/JavaModuleWrapper.h b/ReactAndroid/src/main/jni/react/jni/JavaModuleWrapper.h index 1e8804b56bd0e9..16205d6038ce85 100644 --- a/ReactAndroid/src/main/jni/react/jni/JavaModuleWrapper.h +++ b/ReactAndroid/src/main/jni/react/jni/JavaModuleWrapper.h @@ -21,7 +21,7 @@ class MessageQueueThread; struct JMethodDescriptor : public jni::JavaClass { static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/bridge/JavaModuleWrapper$MethodDescriptor;"; + "Lcom/facebook/react/bridge/JavaModuleWrapper$MethodDescriptor;"; jni::local_ref getMethod() const; std::string getSignature() const; @@ -30,12 +30,15 @@ struct JMethodDescriptor : public jni::JavaClass { }; struct JavaModuleWrapper : jni::JavaClass { - static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/JavaModuleWrapper;"; + static constexpr auto kJavaDescriptor = + "Lcom/facebook/react/bridge/JavaModuleWrapper;"; jni::local_ref getModule() { // This is the call which causes a lazy Java module to actually be // created. - static auto getModule = javaClassStatic()->getMethod("getModule"); + static auto getModule = + javaClassStatic()->getMethod( + "getModule"); return getModule(self()); } @@ -44,9 +47,13 @@ struct JavaModuleWrapper : jni::JavaClass { return getName(self())->toStdString(); } - jni::local_ref::javaobject> getMethodDescriptors() { - static auto getMethods = getClass() - ->getMethod::javaobject()>("getMethodDescriptors"); + jni::local_ref::javaobject> + getMethodDescriptors() { + static auto getMethods = + getClass() + ->getMethod< + jni::JList::javaobject()>( + "getMethodDescriptors"); return getMethods(self()); } }; @@ -54,18 +61,21 @@ struct JavaModuleWrapper : jni::JavaClass { class JavaNativeModule : public NativeModule { public: JavaNativeModule( - std::weak_ptr instance, - jni::alias_ref wrapper, - std::shared_ptr messageQueueThread) - : instance_(std::move(instance)) - , wrapper_(make_global(wrapper)) - , messageQueueThread_(std::move(messageQueueThread)) {} + std::weak_ptr instance, + jni::alias_ref wrapper, + std::shared_ptr messageQueueThread) + : instance_(std::move(instance)), + wrapper_(make_global(wrapper)), + messageQueueThread_(std::move(messageQueueThread)) {} std::string getName() override; folly::dynamic getConstants() override; std::vector getMethods() override; - void invoke(unsigned int reactMethodId, folly::dynamic&& params, int callId) override; - MethodCallResult callSerializableNativeHook(unsigned int reactMethodId, folly::dynamic&& params) override; + void invoke(unsigned int reactMethodId, folly::dynamic &¶ms, int callId) + override; + MethodCallResult callSerializableNativeHook( + unsigned int reactMethodId, + folly::dynamic &¶ms) override; private: std::weak_ptr instance_; @@ -78,15 +88,18 @@ class JavaNativeModule : public NativeModule { class NewJavaNativeModule : public NativeModule { public: NewJavaNativeModule( - std::weak_ptr instance, - jni::alias_ref wrapper, - std::shared_ptr messageQueueThread); + std::weak_ptr instance, + jni::alias_ref wrapper, + std::shared_ptr messageQueueThread); std::string getName() override; std::vector getMethods() override; folly::dynamic getConstants() override; - void invoke(unsigned int reactMethodId, folly::dynamic&& params, int callId) override; - MethodCallResult callSerializableNativeHook(unsigned int reactMethodId, folly::dynamic&& params) override; + void invoke(unsigned int reactMethodId, folly::dynamic &¶ms, int callId) + override; + MethodCallResult callSerializableNativeHook( + unsigned int reactMethodId, + folly::dynamic &¶ms) override; private: std::weak_ptr instance_; @@ -96,7 +109,10 @@ class NewJavaNativeModule : public NativeModule { std::vector methods_; std::vector methodDescriptors_; - MethodCallResult invokeInner(unsigned int reactMethodId, folly::dynamic&& params); + MethodCallResult invokeInner( + unsigned int reactMethodId, + folly::dynamic &¶ms); }; -}} +} // namespace react +} // namespace facebook diff --git a/ReactAndroid/src/main/jni/react/jni/JavaScriptExecutorHolder.h b/ReactAndroid/src/main/jni/react/jni/JavaScriptExecutorHolder.h index e88a842cc8f73d..1474d0671cd917 100644 --- a/ReactAndroid/src/main/jni/react/jni/JavaScriptExecutorHolder.h +++ b/ReactAndroid/src/main/jni/react/jni/JavaScriptExecutorHolder.h @@ -13,10 +13,11 @@ namespace facebook { namespace react { -class JavaScriptExecutorHolder : public jni::HybridClass { +class JavaScriptExecutorHolder + : public jni::HybridClass { public: static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/bridge/JavaScriptExecutor;"; + "Lcom/facebook/react/bridge/JavaScriptExecutor;"; std::shared_ptr getExecutorFactory() { return mExecutorFactory; @@ -30,4 +31,5 @@ class JavaScriptExecutorHolder : public jni::HybridClass mExecutorFactory; }; -}} +} // namespace react +} // namespace facebook diff --git a/ReactAndroid/src/main/jni/react/jni/MethodInvoker.cpp b/ReactAndroid/src/main/jni/react/jni/MethodInvoker.cpp index 6a1e4365a08deb..f82659d3cffc43 100644 --- a/ReactAndroid/src/main/jni/react/jni/MethodInvoker.cpp +++ b/ReactAndroid/src/main/jni/react/jni/MethodInvoker.cpp @@ -32,9 +32,12 @@ namespace { using dynamic_iterator = folly::dynamic::const_iterator; struct JPromiseImpl : public JavaClass { - constexpr static auto kJavaDescriptor = "Lcom/facebook/react/bridge/PromiseImpl;"; + constexpr static auto kJavaDescriptor = + "Lcom/facebook/react/bridge/PromiseImpl;"; - static local_ref create(local_ref resolve, local_ref reject) { + static local_ref create( + local_ref resolve, + local_ref reject) { return newInstance(resolve, reject); } }; @@ -42,10 +45,10 @@ struct JPromiseImpl : public JavaClass { // HACK: Exposes constructor struct ExposedReadableNativeArray : public ReadableNativeArray { explicit ExposedReadableNativeArray(folly::dynamic array) - : ReadableNativeArray(std::move(array)) {} + : ReadableNativeArray(std::move(array)) {} }; -jdouble extractDouble(const folly::dynamic& value) { +jdouble extractDouble(const folly::dynamic &value) { if (value.isInt()) { return static_cast(value.getInt()); } else { @@ -53,7 +56,7 @@ jdouble extractDouble(const folly::dynamic& value) { } } -jint extractInteger(const folly::dynamic& value) { +jint extractInteger(const folly::dynamic &value) { // The logic here is taken from convertDynamicIfIntegral, but the // return type and exception are different. if (value.isInt()) { @@ -62,14 +65,16 @@ jint extractInteger(const folly::dynamic& value) { double dbl = value.getDouble(); jint result = static_cast(dbl); if (dbl != result) { - throw std::invalid_argument( - folly::to( - "Tried to convert jint argument, but got a non-integral double: ", dbl)); + throw std::invalid_argument(folly::to( + "Tried to convert jint argument, but got a non-integral double: ", + dbl)); } return result; } -local_ref extractCallback(std::weak_ptr& instance, const folly::dynamic& value) { +local_ref extractCallback( + std::weak_ptr &instance, + const folly::dynamic &value) { if (value.isNull()) { return local_ref(nullptr); } else { @@ -77,7 +82,10 @@ local_ref extractCallback(std::weak_ptr extractPromise(std::weak_ptr& instance, dynamic_iterator& it, dynamic_iterator& end) { +local_ref extractPromise( + std::weak_ptr &instance, + dynamic_iterator &it, + dynamic_iterator &end) { auto resolve = extractCallback(instance, *it++); CHECK(it != end); auto reject = extractCallback(instance, *it++); @@ -95,11 +103,16 @@ bool isNullable(char type) { case 'X': return true; default: - return false;; + return false; + ; } } -jvalue extract(std::weak_ptr& instance, char type, dynamic_iterator& it, dynamic_iterator& end) { +jvalue extract( + std::weak_ptr &instance, + char type, + dynamic_iterator &it, + dynamic_iterator &end) { CHECK(it != end); jvalue value; if (type == 'P') { @@ -107,7 +120,7 @@ jvalue extract(std::weak_ptr& instance, char type, dynamic_iterator& i return value; } - const auto& arg = *it++; + const auto &arg = *it++; if (isNullable(type) && arg.isNull()) { value.l = nullptr; return value; @@ -118,7 +131,8 @@ jvalue extract(std::weak_ptr& instance, char type, dynamic_iterator& i value.z = static_cast(arg.getBool()); break; case 'Z': - value.l = JBoolean::valueOf(static_cast(arg.getBool())).release(); + value.l = + JBoolean::valueOf(static_cast(arg.getBool())).release(); break; case 'i': value.i = extractInteger(arg); @@ -130,7 +144,8 @@ jvalue extract(std::weak_ptr& instance, char type, dynamic_iterator& i value.f = static_cast(extractDouble(arg)); break; case 'F': - value.l = JFloat::valueOf(static_cast(extractDouble(arg))).release(); + value.l = + JFloat::valueOf(static_cast(extractDouble(arg))).release(); break; case 'd': value.d = extractDouble(arg); @@ -156,7 +171,7 @@ jvalue extract(std::weak_ptr& instance, char type, dynamic_iterator& i return value; } -std::size_t countJsArgs(const std::string& signature) { +std::size_t countJsArgs(const std::string &signature) { std::size_t count = 0; for (char c : signature) { switch (c) { @@ -171,29 +186,38 @@ std::size_t countJsArgs(const std::string& signature) { return count; } +} // namespace + +MethodInvoker::MethodInvoker( + alias_ref method, + std::string signature, + std::string traceName, + bool isSync) + : method_(method->getMethodID()), + signature_(signature), + jsArgCount_(countJsArgs(signature) - 2), + traceName_(std::move(traceName)), + isSync_(isSync) { + CHECK(signature_.at(1) == '.') << "Improper module method signature"; + CHECK(isSync_ || signature_.at(0) == 'v') + << "Non-sync hooks cannot have a non-void return type"; } -MethodInvoker::MethodInvoker(alias_ref method, std::string signature, std::string traceName, bool isSync) - : method_(method->getMethodID()), - signature_(signature), - jsArgCount_(countJsArgs(signature) -2), - traceName_(std::move(traceName)), - isSync_(isSync) { - CHECK(signature_.at(1) == '.') << "Improper module method signature"; - CHECK(isSync_ || signature_.at(0) == 'v') << "Non-sync hooks cannot have a non-void return type"; -} - -MethodCallResult MethodInvoker::invoke(std::weak_ptr& instance, alias_ref module, const folly::dynamic& params) { - #ifdef WITH_FBSYSTRACE +MethodCallResult MethodInvoker::invoke( + std::weak_ptr &instance, + alias_ref module, + const folly::dynamic ¶ms) { +#ifdef WITH_FBSYSTRACE fbsystrace::FbSystraceSection s( TRACE_TAG_REACT_CXX_BRIDGE, isSync_ ? "callJavaSyncHook" : "callJavaModuleMethod", "method", traceName_); - #endif +#endif if (params.size() != jsArgCount_) { - throw std::invalid_argument(folly::to("expected ", jsArgCount_, " arguments, got ", params.size())); + throw std::invalid_argument(folly::to( + "expected ", jsArgCount_, " arguments, got ", params.size())); } auto env = Environment::current(); @@ -201,44 +225,48 @@ MethodCallResult MethodInvoker::invoke(std::weak_ptr& instance, alias_ JniLocalScope scope(env, argCount); jvalue args[argCount]; std::transform( - signature_.begin() + 2, - signature_.end(), - args, - [&instance, it = params.begin(), end = params.end()] (char type) mutable { - return extract(instance, type, it, end); - }); - -#define PRIMITIVE_CASE(METHOD) { \ - auto result = env->Call ## METHOD ## MethodA(module.get(), method_, args); \ - throwPendingJniExceptionAsCppException(); \ - return folly::dynamic(result); \ -} + signature_.begin() + 2, + signature_.end(), + args, + [&instance, it = params.begin(), end = params.end()](char type) mutable { + return extract(instance, type, it, end); + }); + +#define PRIMITIVE_CASE(METHOD) \ + { \ + auto result = env->Call##METHOD##MethodA(module.get(), method_, args); \ + throwPendingJniExceptionAsCppException(); \ + return folly::dynamic(result); \ + } -#define PRIMITIVE_CASE_CASTING(METHOD, RESULT_TYPE) { \ - auto result = env->Call ## METHOD ## MethodA(module.get(), method_, args); \ - throwPendingJniExceptionAsCppException(); \ - return folly::dynamic(static_cast(result)); \ -} +#define PRIMITIVE_CASE_CASTING(METHOD, RESULT_TYPE) \ + { \ + auto result = env->Call##METHOD##MethodA(module.get(), method_, args); \ + throwPendingJniExceptionAsCppException(); \ + return folly::dynamic(static_cast(result)); \ + } -#define OBJECT_CASE(JNI_CLASS, ACTIONS) { \ - auto jobject = env->CallObjectMethodA(module.get(), method_, args); \ - throwPendingJniExceptionAsCppException(); \ - if (!jobject) { \ - return folly::dynamic(nullptr); \ - } \ - auto result = adopt_local(static_cast(jobject)); \ - return folly::dynamic(result->ACTIONS()); \ -} +#define OBJECT_CASE(JNI_CLASS, ACTIONS) \ + { \ + auto jobject = env->CallObjectMethodA(module.get(), method_, args); \ + throwPendingJniExceptionAsCppException(); \ + if (!jobject) { \ + return folly::dynamic(nullptr); \ + } \ + auto result = adopt_local(static_cast(jobject)); \ + return folly::dynamic(result->ACTIONS()); \ + } -#define OBJECT_CASE_CASTING(JNI_CLASS, ACTIONS, RESULT_TYPE) { \ - auto jobject = env->CallObjectMethodA(module.get(), method_, args); \ - throwPendingJniExceptionAsCppException(); \ - if (!jobject) { \ - return folly::dynamic(nullptr); \ - } \ - auto result = adopt_local(static_cast(jobject)); \ - return folly::dynamic(static_cast(result->ACTIONS())); \ -} +#define OBJECT_CASE_CASTING(JNI_CLASS, ACTIONS, RESULT_TYPE) \ + { \ + auto jobject = env->CallObjectMethodA(module.get(), method_, args); \ + throwPendingJniExceptionAsCppException(); \ + if (!jobject) { \ + return folly::dynamic(nullptr); \ + } \ + auto result = adopt_local(static_cast(jobject)); \ + return folly::dynamic(static_cast(result->ACTIONS())); \ + } char returnType = signature_.at(0); switch (returnType) { @@ -277,5 +305,5 @@ MethodCallResult MethodInvoker::invoke(std::weak_ptr& instance, alias_ } } -} -} +} // namespace react +} // namespace facebook diff --git a/ReactAndroid/src/main/jni/react/jni/MethodInvoker.h b/ReactAndroid/src/main/jni/react/jni/MethodInvoker.h index ea67271c03839b..766c599bad3974 100644 --- a/ReactAndroid/src/main/jni/react/jni/MethodInvoker.h +++ b/ReactAndroid/src/main/jni/react/jni/MethodInvoker.h @@ -29,19 +29,28 @@ struct JReflectMethod : public jni::JavaClass { }; struct JBaseJavaModule : public jni::JavaClass { - static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/BaseJavaModule;"; + static constexpr auto kJavaDescriptor = + "Lcom/facebook/react/bridge/BaseJavaModule;"; }; class MethodInvoker { -public: - MethodInvoker(jni::alias_ref method, std::string signature, std::string traceName, bool isSync); - - MethodCallResult invoke(std::weak_ptr& instance, jni::alias_ref module, const folly::dynamic& params); + public: + MethodInvoker( + jni::alias_ref method, + std::string signature, + std::string traceName, + bool isSync); + + MethodCallResult invoke( + std::weak_ptr &instance, + jni::alias_ref module, + const folly::dynamic ¶ms); bool isSyncHook() const { return isSync_; } -private: + + private: jmethodID method_; std::string signature_; std::size_t jsArgCount_; @@ -49,5 +58,5 @@ class MethodInvoker { bool isSync_; }; -} -} +} // namespace react +} // namespace facebook diff --git a/ReactAndroid/src/main/jni/react/jni/ModuleRegistryBuilder.h b/ReactAndroid/src/main/jni/react/jni/ModuleRegistryBuilder.h index 63693918d92c33..5f84e1f93be9fa 100644 --- a/ReactAndroid/src/main/jni/react/jni/ModuleRegistryBuilder.h +++ b/ReactAndroid/src/main/jni/react/jni/ModuleRegistryBuilder.h @@ -22,16 +22,19 @@ class MessageQueueThread; class ModuleHolder : public jni::JavaClass { public: static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/bridge/ModuleHolder;"; + "Lcom/facebook/react/bridge/ModuleHolder;"; std::string getName() const; - xplat::module::CxxModule::Provider getProvider(const std::string& moduleName) const; + xplat::module::CxxModule::Provider getProvider( + const std::string &moduleName) const; }; std::vector> buildNativeModuleList( - std::weak_ptr winstance, - jni::alias_ref::javaobject> javaModules, - jni::alias_ref::javaobject> cxxModules, - std::shared_ptr moduleMessageQueue); -} -} + std::weak_ptr winstance, + jni::alias_ref::javaobject> + javaModules, + jni::alias_ref::javaobject> + cxxModules, + std::shared_ptr moduleMessageQueue); +} // namespace react +} // namespace facebook diff --git a/ReactAndroid/src/main/jni/react/jni/NativeArray.cpp b/ReactAndroid/src/main/jni/react/jni/NativeArray.cpp index 6af3c6b5c957f6..738037b84ea97f 100644 --- a/ReactAndroid/src/main/jni/react/jni/NativeArray.cpp +++ b/ReactAndroid/src/main/jni/react/jni/NativeArray.cpp @@ -18,8 +18,10 @@ namespace react { NativeArray::NativeArray(folly::dynamic array) : isConsumed(false), array_(std::move(array)) { if (!array_.isArray()) { - throwNewJavaException(exceptions::gUnexpectedNativeTypeExceptionClass, - "expected Array, got a %s", array_.typeName()); + throwNewJavaException( + exceptions::gUnexpectedNativeTypeExceptionClass, + "expected Array, got a %s", + array_.typeName()); } } @@ -30,7 +32,7 @@ local_ref NativeArray::toString() { void NativeArray::registerNatives() { registerHybrid({ - makeNativeMethod("toString", NativeArray::toString), + makeNativeMethod("toString", NativeArray::toString), }); } @@ -44,5 +46,5 @@ void NativeArray::throwIfConsumed() { exceptions::throwIfObjectAlreadyConsumed(this, "Array already consumed"); } -} -} +} // namespace react +} // namespace facebook diff --git a/ReactAndroid/src/main/jni/react/jni/NativeArray.h b/ReactAndroid/src/main/jni/react/jni/NativeArray.h index 419e47485587e8..7fd3cf56d08e04 100644 --- a/ReactAndroid/src/main/jni/react/jni/NativeArray.h +++ b/ReactAndroid/src/main/jni/react/jni/NativeArray.h @@ -17,7 +17,8 @@ namespace react { class NativeArray : public jni::HybridClass { public: - static constexpr const char* kJavaDescriptor = "Lcom/facebook/react/bridge/NativeArray;"; + static constexpr const char *kJavaDescriptor = + "Lcom/facebook/react/bridge/NativeArray;"; jni::local_ref toString(); @@ -37,4 +38,5 @@ class NativeArray : public jni::HybridClass { explicit NativeArray(folly::dynamic array); }; -}} +} // namespace react +} // namespace facebook diff --git a/ReactAndroid/src/main/jni/react/jni/NativeCommon.h b/ReactAndroid/src/main/jni/react/jni/NativeCommon.h index 9562ccdbf5a0e7..daed3ad62a6299 100644 --- a/ReactAndroid/src/main/jni/react/jni/NativeCommon.h +++ b/ReactAndroid/src/main/jni/react/jni/NativeCommon.h @@ -18,7 +18,8 @@ namespace facebook { namespace react { struct ReadableType : public jni::JavaClass { - static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/ReadableType;"; + static auto constexpr kJavaDescriptor = + "Lcom/facebook/react/bridge/ReadableType;"; static jni::local_ref getType(folly::dynamic::Type type); }; @@ -28,9 +29,10 @@ namespace exceptions { extern const char *gUnexpectedNativeTypeExceptionClass; template -void throwIfObjectAlreadyConsumed(const T& t, const char* msg) { +void throwIfObjectAlreadyConsumed(const T &t, const char *msg) { if (t->isConsumed) { - jni::throwNewJavaException("com/facebook/react/bridge/ObjectAlreadyConsumedException", msg); + jni::throwNewJavaException( + "com/facebook/react/bridge/ObjectAlreadyConsumedException", msg); } } diff --git a/ReactAndroid/src/main/jni/react/jni/NativeMap.h b/ReactAndroid/src/main/jni/react/jni/NativeMap.h index 4b0ce25a730d35..3b616a16611107 100644 --- a/ReactAndroid/src/main/jni/react/jni/NativeMap.h +++ b/ReactAndroid/src/main/jni/react/jni/NativeMap.h @@ -17,7 +17,8 @@ namespace react { class NativeMap : public jni::HybridClass { public: - static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/NativeMap;"; + static auto constexpr kJavaDescriptor = + "Lcom/facebook/react/bridge/NativeMap;"; std::string toString(); @@ -38,5 +39,5 @@ class NativeMap : public jni::HybridClass { explicit NativeMap(folly::dynamic s) : isConsumed(false), map_(s) {} }; -} // namespace react -} // namespace facebook +} // namespace react +} // namespace facebook diff --git a/ReactAndroid/src/main/jni/react/jni/ProxyExecutor.cpp b/ReactAndroid/src/main/jni/react/jni/ProxyExecutor.cpp index 4c4a369a6bc9af..3c15e7a27cf2bb 100644 --- a/ReactAndroid/src/main/jni/react/jni/ProxyExecutor.cpp +++ b/ReactAndroid/src/main/jni/react/jni/ProxyExecutor.cpp @@ -10,8 +10,8 @@ #include #include #include -#include #include +#include #include #include #include @@ -25,28 +25,29 @@ const auto EXECUTOR_BASECLASS = "com/facebook/react/bridge/JavaJSExecutor"; static std::string executeJSCallWithProxy( jobject executor, - const std::string& methodName, - const folly::dynamic& arguments) { + const std::string &methodName, + const folly::dynamic &arguments) { static auto executeJSCall = - jni::findClassStatic(EXECUTOR_BASECLASS)->getMethod("executeJSCall"); + jni::findClassStatic(EXECUTOR_BASECLASS) + ->getMethod("executeJSCall"); auto result = executeJSCall( - executor, - jni::make_jstring(methodName).get(), - jni::make_jstring(folly::toJson(arguments).c_str()).get()); + executor, + jni::make_jstring(methodName).get(), + jni::make_jstring(folly::toJson(arguments).c_str()).get()); return result->toString(); } std::unique_ptr ProxyExecutorOneTimeFactory::createJSExecutor( - std::shared_ptr delegate, std::shared_ptr) { + std::shared_ptr delegate, + std::shared_ptr) { return std::make_unique(std::move(m_executor), delegate); } -ProxyExecutor::ProxyExecutor(jni::global_ref&& executorInstance, - std::shared_ptr delegate) - : m_executor(std::move(executorInstance)) - , m_delegate(delegate) -{} +ProxyExecutor::ProxyExecutor( + jni::global_ref &&executorInstance, + std::shared_ptr delegate) + : m_executor(std::move(executorInstance)), m_delegate(delegate) {} ProxyExecutor::~ProxyExecutor() { m_executor.reset(); @@ -55,79 +56,88 @@ ProxyExecutor::~ProxyExecutor() { void ProxyExecutor::loadApplicationScript( std::unique_ptr, std::string sourceURL) { - folly::dynamic nativeModuleConfig = folly::dynamic::array; { SystraceSection s("collectNativeModuleDescriptions"); auto moduleRegistry = m_delegate->getModuleRegistry(); - for (const auto& name : moduleRegistry->moduleNames()) { + for (const auto &name : moduleRegistry->moduleNames()) { auto config = moduleRegistry->getConfig(name); nativeModuleConfig.push_back(config ? config->config : nullptr); } } - folly::dynamic config = - folly::dynamic::object - ("remoteModuleConfig", std::move(nativeModuleConfig)); + folly::dynamic config = folly::dynamic::object( + "remoteModuleConfig", std::move(nativeModuleConfig)); { SystraceSection t("setGlobalVariable"); setGlobalVariable( - "__fbBatchedBridgeConfig", - std::make_unique(folly::toJson(config))); + "__fbBatchedBridgeConfig", + std::make_unique(folly::toJson(config))); } static auto loadApplicationScript = - jni::findClassStatic(EXECUTOR_BASECLASS)->getMethod("loadApplicationScript"); + jni::findClassStatic(EXECUTOR_BASECLASS) + ->getMethod("loadApplicationScript"); // The proxy ignores the script data passed in. - loadApplicationScript( - m_executor.get(), - jni::make_jstring(sourceURL).get()); + loadApplicationScript(m_executor.get(), jni::make_jstring(sourceURL).get()); // We can get pending calls here to native but the queue will be drained when // we launch the application. } void ProxyExecutor::setBundleRegistry(std::unique_ptr) { jni::throwNewJavaException( - "java/lang/UnsupportedOperationException", - "Loading application RAM bundles is not supported for proxy executors"); + "java/lang/UnsupportedOperationException", + "Loading application RAM bundles is not supported for proxy executors"); } -void ProxyExecutor::registerBundle(uint32_t bundleId, const std::string& bundlePath) { +void ProxyExecutor::registerBundle( + uint32_t bundleId, + const std::string &bundlePath) { jni::throwNewJavaException( - "java/lang/UnsupportedOperationException", - "Loading application RAM bundles is not supported for proxy executors"); + "java/lang/UnsupportedOperationException", + "Loading application RAM bundles is not supported for proxy executors"); } -void ProxyExecutor::callFunction(const std::string& moduleId, const std::string& methodId, const folly::dynamic& arguments) { +void ProxyExecutor::callFunction( + const std::string &moduleId, + const std::string &methodId, + const folly::dynamic &arguments) { auto call = folly::dynamic::array(moduleId, methodId, std::move(arguments)); - std::string result = executeJSCallWithProxy(m_executor.get(), "callFunctionReturnFlushedQueue", std::move(call)); + std::string result = executeJSCallWithProxy( + m_executor.get(), "callFunctionReturnFlushedQueue", std::move(call)); m_delegate->callNativeModules(*this, folly::parseJson(result), true); } -void ProxyExecutor::invokeCallback(const double callbackId, const folly::dynamic& arguments) { +void ProxyExecutor::invokeCallback( + const double callbackId, + const folly::dynamic &arguments) { auto call = folly::dynamic::array(callbackId, std::move(arguments)); - std::string result = executeJSCallWithProxy(m_executor.get(), "invokeCallbackAndReturnFlushedQueue", std::move(call)); + std::string result = executeJSCallWithProxy( + m_executor.get(), "invokeCallbackAndReturnFlushedQueue", std::move(call)); m_delegate->callNativeModules(*this, folly::parseJson(result), true); } -void ProxyExecutor::setGlobalVariable(std::string propName, - std::unique_ptr jsonValue) { +void ProxyExecutor::setGlobalVariable( + std::string propName, + std::unique_ptr jsonValue) { static auto setGlobalVariable = - jni::findClassStatic(EXECUTOR_BASECLASS)->getMethod("setGlobalVariable"); + jni::findClassStatic(EXECUTOR_BASECLASS) + ->getMethod("setGlobalVariable"); setGlobalVariable( - m_executor.get(), - jni::make_jstring(propName).get(), - jni::make_jstring(jsonValue->c_str()).get()); + m_executor.get(), + jni::make_jstring(propName).get(), + jni::make_jstring(jsonValue->c_str()).get()); } std::string ProxyExecutor::getDescription() { return "Chrome"; } -} } +} // namespace react +} // namespace facebook diff --git a/ReactAndroid/src/main/jni/react/jni/ProxyExecutor.h b/ReactAndroid/src/main/jni/react/jni/ProxyExecutor.h index d81a98c1a3a736..0af379cb47b853 100644 --- a/ReactAndroid/src/main/jni/react/jni/ProxyExecutor.h +++ b/ReactAndroid/src/main/jni/react/jni/ProxyExecutor.h @@ -17,48 +17,50 @@ namespace facebook { namespace react { /** - * This executor factory can only create a single executor instance because it moves - * executorInstance global reference to the executor instance it creates. + * This executor factory can only create a single executor instance because it + * moves executorInstance global reference to the executor instance it creates. */ class ProxyExecutorOneTimeFactory : public JSExecutorFactory { -public: - ProxyExecutorOneTimeFactory(jni::global_ref&& executorInstance) : - m_executor(std::move(executorInstance)) {} + public: + ProxyExecutorOneTimeFactory(jni::global_ref &&executorInstance) + : m_executor(std::move(executorInstance)) {} virtual std::unique_ptr createJSExecutor( - std::shared_ptr delegate, - std::shared_ptr queue) override; + std::shared_ptr delegate, + std::shared_ptr queue) override; -private: + private: jni::global_ref m_executor; }; class ProxyExecutor : public JSExecutor { -public: - ProxyExecutor(jni::global_ref&& executorInstance, - std::shared_ptr delegate); + public: + ProxyExecutor( + jni::global_ref &&executorInstance, + std::shared_ptr delegate); virtual ~ProxyExecutor() override; virtual void loadApplicationScript( - std::unique_ptr script, - std::string sourceURL) override; + std::unique_ptr script, + std::string sourceURL) override; virtual void setBundleRegistry( - std::unique_ptr bundle) override; - virtual void registerBundle( - uint32_t bundleId, const std::string& bundlePath) override; + std::unique_ptr bundle) override; + virtual void registerBundle(uint32_t bundleId, const std::string &bundlePath) + override; virtual void callFunction( - const std::string& moduleId, - const std::string& methodId, - const folly::dynamic& arguments) override; + const std::string &moduleId, + const std::string &methodId, + const folly::dynamic &arguments) override; virtual void invokeCallback( - const double callbackId, - const folly::dynamic& arguments) override; + const double callbackId, + const folly::dynamic &arguments) override; virtual void setGlobalVariable( - std::string propName, - std::unique_ptr jsonValue) override; + std::string propName, + std::unique_ptr jsonValue) override; virtual std::string getDescription() override; -private: + private: jni::global_ref m_executor; std::shared_ptr m_delegate; }; -} } +} // namespace react +} // namespace facebook diff --git a/ReactAndroid/src/main/jni/react/jni/WritableNativeArray.h b/ReactAndroid/src/main/jni/react/jni/WritableNativeArray.h index 3f820f068782ae..79209609f16875 100644 --- a/ReactAndroid/src/main/jni/react/jni/WritableNativeArray.h +++ b/ReactAndroid/src/main/jni/react/jni/WritableNativeArray.h @@ -19,12 +19,14 @@ namespace react { struct WritableNativeMap; struct WritableArray : jni::JavaClass { - static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/WritableArray;"; + static auto constexpr kJavaDescriptor = + "Lcom/facebook/react/bridge/WritableArray;"; }; struct WritableNativeArray : public jni::HybridClass { - static constexpr const char* kJavaDescriptor = "Lcom/facebook/react/bridge/WritableNativeArray;"; + static constexpr const char *kJavaDescriptor = + "Lcom/facebook/react/bridge/WritableNativeArray;"; WritableNativeArray(); static jni::local_ref initHybrid(jni::alias_ref); @@ -34,11 +36,11 @@ struct WritableNativeArray void pushDouble(jdouble value); void pushInt(jint value); void pushString(jstring value); - void pushNativeArray(WritableNativeArray* otherArray); - void pushNativeMap(WritableNativeMap* map); + void pushNativeArray(WritableNativeArray *otherArray); + void pushNativeMap(WritableNativeMap *map); static void registerNatives(); }; -} -} +} // namespace react +} // namespace facebook diff --git a/ReactAndroid/src/main/jni/react/jni/WritableNativeMap.h b/ReactAndroid/src/main/jni/react/jni/WritableNativeMap.h index caacb8795c543c..b6d3bb88a85463 100644 --- a/ReactAndroid/src/main/jni/react/jni/WritableNativeMap.h +++ b/ReactAndroid/src/main/jni/react/jni/WritableNativeMap.h @@ -18,14 +18,17 @@ namespace facebook { namespace react { struct WritableMap : jni::JavaClass { - static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/WritableMap;"; + static auto constexpr kJavaDescriptor = + "Lcom/facebook/react/bridge/WritableMap;"; }; -struct WritableNativeMap : jni::HybridClass { - static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/WritableNativeMap;"; +struct WritableNativeMap + : jni::HybridClass { + static auto constexpr kJavaDescriptor = + "Lcom/facebook/react/bridge/WritableNativeMap;"; WritableNativeMap(); - WritableNativeMap(folly::dynamic&& val); + WritableNativeMap(folly::dynamic &&val); static jni::local_ref initHybrid(jni::alias_ref); @@ -34,9 +37,9 @@ struct WritableNativeMap : jni::HybridClass val); - void putNativeArray(std::string key, WritableNativeArray* val); - void putNativeMap(std::string key, WritableNativeMap* val); - void mergeNativeMap(ReadableNativeMap* other); + void putNativeArray(std::string key, WritableNativeArray *val); + void putNativeMap(std::string key, WritableNativeMap *val); + void mergeNativeMap(ReadableNativeMap *other); static void registerNatives(); diff --git a/ReactAndroid/src/main/jni/react/perftests/OnLoad.cpp b/ReactAndroid/src/main/jni/react/perftests/OnLoad.cpp index 2b7e0b6ec4eeeb..e2c40008838dbd 100644 --- a/ReactAndroid/src/main/jni/react/perftests/OnLoad.cpp +++ b/ReactAndroid/src/main/jni/react/perftests/OnLoad.cpp @@ -5,13 +5,13 @@ * LICENSE file in the root directory of this source tree. */ -#include -#include #include #include +#include +#include -#include #include +#include namespace facebook { namespace react { @@ -27,9 +27,9 @@ namespace { // really desperate, you can fix this by using ToReflectedMethod on the // underlying jmethodid and invoking that. class JavaJSModule : public jni::JavaClass { -public: + public: static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/CatalystBridgeBenchmarks$BridgeBenchmarkModule;"; + "Lcom/facebook/react/CatalystBridgeBenchmarks$BridgeBenchmarkModule;"; static void bounceCxx(alias_ref obj, int iters) { static auto method = javaClassLocal()->getMethod("bounceCxx"); @@ -39,20 +39,35 @@ class JavaJSModule : public jni::JavaClass { static void bounceArgsCxx( alias_ref obj, int iters, - int a, int b, - double x, double y, - const std::string& s, const std::string& t) { + int a, + int b, + double x, + double y, + const std::string &s, + const std::string &t) { static auto method = - javaClassLocal()->getMethod("bounceArgsCxx"); - method(obj, iters, a, b, x, y, jni::make_jstring(s).get(), jni::make_jstring(t).get()); + javaClassLocal() + ->getMethod( + "bounceArgsCxx"); + method( + obj, + iters, + a, + b, + x, + y, + jni::make_jstring(s).get(), + jni::make_jstring(t).get()); } }; // This is just the test instance itself. Used only to countdown the latch. -class CatalystBridgeBenchmarks : public jni::JavaClass { -public: +class CatalystBridgeBenchmarks + : public jni::JavaClass { + public: static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/CatalystBridgeBenchmarks;"; + "Lcom/facebook/react/CatalystBridgeBenchmarks;"; static void countDown(alias_ref obj) { static auto method = javaClassLocal()->getMethod("countDown"); @@ -72,7 +87,7 @@ Data data; void runBounce(jni::alias_ref, bool isLeft, int iters) { for (int i = 0; i < iters; i++) { std::unique_lock lk(data.m); - data.cv.wait(lk, [&]{ return data.leftActive == isLeft; }); + data.cv.wait(lk, [&] { return data.leftActive == isLeft; }); data.leftActive = !isLeft; data.cv.notify_one(); } @@ -82,30 +97,35 @@ static jni::global_ref jsModule; static jni::global_ref javaTestInstance; class CxxBenchmarkModule : public xplat::module::CxxModule { -public: + public: virtual std::string getName() override { return "CxxBenchmarkModule"; } - virtual auto getConstants() -> std::map override { + virtual auto getConstants() + -> std::map override { return std::map(); } virtual auto getMethods() -> std::vector override { return std::vector{ - Method("bounce", [this] (folly::dynamic args) { - this->bounce(xplat::jsArgAsInt(args, 0)); - }), - Method("bounceArgs", [this] (folly::dynamic args) { - this->bounceArgs( - xplat::jsArgAsInt(args, 0), - xplat::jsArgAsInt(args, 1), - xplat::jsArgAsInt(args, 2), - xplat::jsArgAsDouble(args, 3), - xplat::jsArgAsDouble(args, 4), - xplat::jsArgAsString(args, 5), - xplat::jsArgAsString(args, 6)); - }), + Method( + "bounce", + [this](folly::dynamic args) { + this->bounce(xplat::jsArgAsInt(args, 0)); + }), + Method( + "bounceArgs", + [this](folly::dynamic args) { + this->bounceArgs( + xplat::jsArgAsInt(args, 0), + xplat::jsArgAsInt(args, 1), + xplat::jsArgAsInt(args, 2), + xplat::jsArgAsDouble(args, 3), + xplat::jsArgAsDouble(args, 4), + xplat::jsArgAsString(args, 5), + xplat::jsArgAsString(args, 6)); + }), }; } @@ -119,9 +139,12 @@ class CxxBenchmarkModule : public xplat::module::CxxModule { void bounceArgs( int iters, - int a, int b, - double x, double y, - const std::string& s, const std::string& t) { + int a, + int b, + double x, + double y, + const std::string &s, + const std::string &t) { if (iters == 0) { CatalystBridgeBenchmarks::countDown(javaTestInstance); } else { @@ -130,7 +153,6 @@ class CxxBenchmarkModule : public xplat::module::CxxModule { } }; - void setUp( alias_ref obj, alias_ref mod) { @@ -138,8 +160,7 @@ void setUp( jsModule = jni::make_global(mod); } -void tearDown( - alias_ref) { +void tearDown(alias_ref) { javaTestInstance.reset(); jsModule.reset(); } @@ -163,17 +184,21 @@ static void stubLogHandler(int pri, const char *tag, const char *msg) { gHasSeenMessage |= priorityMatches && substringFound; } -static jboolean hasSeenExpectedLogMessage(JNIEnv*, jclass) { +static jboolean hasSeenExpectedLogMessage(JNIEnv *, jclass) { return gHasSeenMessage ? JNI_TRUE : JNI_FALSE; } -static void stopWatchingLogMessages(JNIEnv*, jclass) { +static void stopWatchingLogMessages(JNIEnv *, jclass) { gMessageToLookFor = ""; gHasSeenMessage = false; setLogHandler(NULL); } -static void startWatchingForLogMessage(JNIEnv* env, jclass loggerClass, jstring jmsg, jint priority) { +static void startWatchingForLogMessage( + JNIEnv *env, + jclass loggerClass, + jstring jmsg, + jint priority) { stopWatchingLogMessages(env, loggerClass); gMessageToLookFor = jni::wrap_alias(jmsg)->toStdString(); gMessagePriorityToLookFor = priority; @@ -187,24 +212,34 @@ static void startWatchingForLogMessage(JNIEnv* env, jclass loggerClass, jstring using namespace facebook::react; -extern "C" facebook::xplat::module::CxxModule* CxxBenchmarkModule() { +extern "C" facebook::xplat::module::CxxModule *CxxBenchmarkModule() { return new facebook::react::CxxBenchmarkModule(); } -extern "C" jint JNI_OnLoad(JavaVM* vm, void*) { +extern "C" jint JNI_OnLoad(JavaVM *vm, void *) { return facebook::jni::initialize(vm, [] { - facebook::jni::registerNatives( - "com/facebook/catalyst/testing/LogWatcher", { - makeNativeMethod("startWatchingForLogMessage", "(Ljava/lang/String;I)V", logwatcher::startWatchingForLogMessage), - makeNativeMethod("stopWatchingLogMessages", "()V", logwatcher::stopWatchingLogMessages), - makeNativeMethod("hasSeenExpectedLogMessage", "()Z", logwatcher::hasSeenExpectedLogMessage), - }); - facebook::jni::registerNatives( - "com/facebook/react/CatalystBridgeBenchmarks", { - makeNativeMethod("runNativeBounce", runBounce), - makeNativeMethod("nativeSetUp", setUp), - makeNativeMethod("nativeTearDown", tearDown), + facebook::jni::registerNatives( + "com/facebook/catalyst/testing/LogWatcher", + { + makeNativeMethod( + "startWatchingForLogMessage", + "(Ljava/lang/String;I)V", + logwatcher::startWatchingForLogMessage), + makeNativeMethod( + "stopWatchingLogMessages", + "()V", + logwatcher::stopWatchingLogMessages), + makeNativeMethod( + "hasSeenExpectedLogMessage", + "()Z", + logwatcher::hasSeenExpectedLogMessage), }); - }); + facebook::jni::registerNatives( + "com/facebook/react/CatalystBridgeBenchmarks", + { + makeNativeMethod("runNativeBounce", runBounce), + makeNativeMethod("nativeSetUp", setUp), + makeNativeMethod("nativeTearDown", tearDown), + }); + }); } -