Summary:
Ran `arc f` against some CPP files to be modified with the next diff
to reduce the churn on it.

## Changelog

[Android] [Changed] - Formatted cpp/h code with clang-format

Reviewed By: javache

Differential Revision: D19371785

fbshipit-source-id: b7f7b92c4cb9ec7f8da728bb577db29cf11fbb39
This commit is contained in:
Pascal Hartig 2020-01-14 01:02:22 -08:00 коммит произвёл Facebook Github Bot
Родитель 8d57691a60
Коммит d5ba113bb2
44 изменённых файлов: 914 добавлений и 648 удалений

Просмотреть файл

@ -16,9 +16,9 @@
#include <jsi/JSIDynamic.h>
#include <jsi/jsi.h>
#include <react/components/scrollview/ScrollViewProps.h>
#include <react/core/conversions.h>
#include <react/core/EventBeat.h>
#include <react/core/EventEmitter.h>
#include <react/core/conversions.h>
#include <react/debug/SystraceSection.h>
#include <react/uimanager/ComponentDescriptorFactory.h>
#include <react/uimanager/Scheduler.h>
@ -73,7 +73,6 @@ std::shared_ptr<Scheduler> Binding::getScheduler() {
return scheduler_;
}
void Binding::startSurface(
jint surfaceId,
jni::alias_ref<jstring> 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<std::mutex> schedulerLock(schedulerMutex_, std::adopt_lock);
std::lock_guard<std::mutex> uiManagerLock(javaUIManagerMutex_, std::adopt_lock);
std::lock_guard<std::mutex> 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<jobject> localJavaUIManager = javaUIManager_;
EventBeat::Factory synchronousBeatFactory =
[eventBeatManager, runtimeExecutor, localJavaUIManager](EventBeat::SharedOwnerBox const &ownerBox) {
[eventBeatManager, runtimeExecutor, localJavaUIManager](
EventBeat::SharedOwnerBox const &ownerBox) {
return std::make_unique<AsyncEventBeat>(
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<AsyncEventBeat>(
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<std::mutex> schedulerLock(schedulerMutex_, std::adopt_lock);
std::lock_guard<std::mutex> uiManagerLock(javaUIManagerMutex_, std::adopt_lock);
std::lock_guard<std::mutex> uiManagerLock(
javaUIManagerMutex_, std::adopt_lock);
scheduler_ = nullptr;
javaUIManager_ = nullptr;
@ -280,7 +291,8 @@ inline local_ref<ReadableMap::javaobject> castReadableMap(
inline local_ref<ReadableArray::javaobject> castReadableArray(
local_ref<ReadableNativeArray::javaobject> nativeArray) {
return make_local(reinterpret_cast<ReadableArray::javaobject>(nativeArray.get()));
return make_local(
reinterpret_cast<ReadableArray::javaobject>(nativeArray.get()));
}
// TODO: this method will be removed when binding for components are code-gen
@ -351,8 +363,8 @@ local_ref<JMountItem::javaobject> createUpdateLayoutMountItem(
oldChildShadowView.layoutMetrics != newChildShadowView.layoutMetrics) {
static auto updateLayoutInstruction =
jni::findClassStatic(UIManagerJavaDescriptor)
->getMethod<alias_ref<JMountItem>(jint, jint, jint, jint, jint, jint)>(
"updateLayoutMountItem");
->getMethod<alias_ref<JMountItem>(
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<JMountItem::javaobject> 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);
}
@ -372,11 +385,11 @@ local_ref<JMountItem::javaobject> createUpdateLayoutMountItem(
local_ref<JMountItem::javaobject> createUpdatePaddingMountItem(
const jni::global_ref<jobject> &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;
}
@ -394,7 +407,8 @@ local_ref<JMountItem::javaobject> 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<JMountItem::javaobject> createInsertMountItem(
@ -489,7 +503,6 @@ local_ref<JMountItem::javaobject> createDeleteMountItem(
local_ref<JMountItem::javaobject> createRemoveAndDeleteMultiMountItem(
const jni::global_ref<jobject> &javaUIManager,
const std::vector<RemoveDeleteMetadata> &metadata) {
auto env = Environment::current();
auto removeAndDeleteArray = env->NewIntArray(metadata.size() * 4);
int position = 0;
@ -505,29 +518,33 @@ local_ref<JMountItem::javaobject> createRemoveAndDeleteMultiMountItem(
static auto removeDeleteMultiInstruction =
jni::findClassStatic(UIManagerJavaDescriptor)
->getMethod<alias_ref<JMountItem>(jintArray)>("removeDeleteMultiMountItem");
->getMethod<alias_ref<JMountItem>(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<JMountItem::javaobject> createCreateMountItem(
const jni::global_ref<jobject> &javaUIManager,
const ShadowViewMutation &mutation,
const Tag surfaceId) {
static auto createJavaInstruction =
jni::findClassStatic(UIManagerJavaDescriptor)
->getMethod<alias_ref<JMountItem>(jstring, ReadableMap::javaobject, jobject, jint, jint, jboolean)>(
->getMethod<alias_ref<JMountItem>(
jstring, ReadableMap::javaobject, jobject, jint, jint, jboolean)>(
"createMountItem");
auto newChildShadowView = mutation.newChildShadowView;
@ -570,7 +587,8 @@ void Binding::schedulerDidFinishTransaction(
jni::global_ref<jobject> 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++] =
@ -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<void(JMountItem::javaobject, jint, jlong, jlong, jlong, jlong, jlong, jlong, jlong)>(
"scheduleMountItem");
static auto scheduleMountItem = jni::findClassStatic(UIManagerJavaDescriptor)
->getMethod<void(
JMountItem::javaobject,
jint,
jlong,
jlong,
jlong,
jlong,
jlong,
jlong,
jlong)>("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<jobject> localJavaUIManager = getJavaUIManager();
if (!localJavaUIManager) {
LOG(ERROR) << "Binding::schedulerDidRequestPreliminaryViewAllocation: JavaUIManager disappeared";
LOG(ERROR)
<< "Binding::schedulerDidRequestPreliminaryViewAllocation: JavaUIManager disappeared";
return;
}
@ -884,25 +930,25 @@ void Binding::schedulerDidDispatchCommand(
const ShadowView &shadowView,
std::string const &commandName,
folly::dynamic const args) {
jni::global_ref<jobject> localJavaUIManager = getJavaUIManager();
if (!localJavaUIManager) {
LOG(ERROR) << "Binding::schedulerDidDispatchCommand: JavaUIManager disappeared";
LOG(ERROR)
<< "Binding::schedulerDidDispatchCommand: JavaUIManager disappeared";
return;
}
static auto dispatchCommand =
jni::findClassStatic(UIManagerJavaDescriptor)
->getMethod<void(
jint, jstring, ReadableArray::javaobject)>(
->getMethod<void(jint, jstring, ReadableArray::javaobject)>(
"dispatchCommand");
local_ref<JString> command = make_jstring(commandName);
local_ref<ReadableArray::javaobject> argsArray = castReadableArray(
ReadableNativeArray::newObjectCxxArgs(args));
local_ref<ReadableArray::javaobject> 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<jobject> localJavaUIManager = getJavaUIManager();
if (!localJavaUIManager) {
LOG(ERROR) << "Binding::schedulerSetJSResponder: JavaUIManager disappeared";
@ -919,22 +964,24 @@ void Binding::schedulerDidSetJSResponder(
static auto setJSResponder =
jni::findClassStatic(UIManagerJavaDescriptor)
->getMethod<void(
jint, jint, jboolean)>(
"setJSResponder");
->getMethod<void(jint, jint, jboolean)>("setJSResponder");
setJSResponder(localJavaUIManager, shadowView.tag, initialShadowView.tag, (jboolean) blockNativeResponder);
setJSResponder(
localJavaUIManager,
shadowView.tag,
initialShadowView.tag,
(jboolean)blockNativeResponder);
}
void Binding::schedulerDidClearJSResponder() {
jni::global_ref<jobject> localJavaUIManager = getJavaUIManager();
if (!localJavaUIManager) {
LOG(ERROR) << "Binding::schedulerClearJSResponder: JavaUIManager disappeared";
LOG(ERROR)
<< "Binding::schedulerClearJSResponder: JavaUIManager disappeared";
return;
}
static auto clearJSResponder =
jni::findClassStatic(UIManagerJavaDescriptor)
static auto clearJSResponder = jni::findClassStatic(UIManagerJavaDescriptor)
->getMethod<void()>("clearJSResponder");
clearJSResponder(localJavaUIManager);

Просмотреть файл

@ -10,8 +10,8 @@
#include <fb/fbjni.h>
#include <jsi/jsi.h>
#include <react/uimanager/ComponentDescriptorRegistry.h>
#include <react/utils/ContextContainer.h>
#include <react/uimanager/Scheduler.h>
#include <react/utils/ContextContainer.h>
#include <mutex>
#include <unordered_set>

Просмотреть файл

@ -14,8 +14,8 @@ using namespace facebook::jni;
namespace facebook {
namespace react {
jni::local_ref<NodeStateWrapper::jhybriddata>
NodeStateWrapper::initHybrid(jni::alias_ref<jclass>) {
jni::local_ref<NodeStateWrapper::jhybriddata> NodeStateWrapper::initHybrid(
jni::alias_ref<jclass>) {
return makeCxxInstance();
}

Просмотреть файл

@ -27,6 +27,7 @@ class NodeStateWrapper : public jni::HybridClass<NodeStateWrapper> {
void updateState(ReadableNativeMap *map);
const State *state_;
private:
static jni::local_ref<jhybriddata> initHybrid(jni::alias_ref<jclass>);
};

Просмотреть файл

@ -17,8 +17,8 @@ namespace react {
/**
* Called from Java constructor through the JNI.
*/
jni::local_ref<StateWrapperImpl::jhybriddata>
StateWrapperImpl::initHybrid(jni::alias_ref<jclass>) {
jni::local_ref<StateWrapperImpl::jhybriddata> StateWrapperImpl::initHybrid(
jni::alias_ref<jclass>) {
return makeCxxInstance();
}

Просмотреть файл

@ -27,6 +27,7 @@ class StateWrapperImpl : public jni::HybridClass<StateWrapperImpl> {
void updateStateImpl(NativeMap *map);
State::Shared state_;
private:
jni::alias_ref<StateWrapperImpl::jhybriddata> jhybridobject_;

Просмотреть файл

@ -7,15 +7,14 @@
#pragma once
#include <fb/fbjni.h>
#include <ReactCommon/CallInvoker.h>
#include <fb/fbjni.h>
#include <memory>
namespace facebook {
namespace react {
class CallInvokerHolder
: public jni::HybridClass<CallInvokerHolder> {
class CallInvokerHolder : public jni::HybridClass<CallInvokerHolder> {
public:
static auto constexpr kJavaDescriptor =
"Lcom/facebook/react/turbomodule/core/CallInvokerHolderImpl;";

Просмотреть файл

@ -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();
});
}

Просмотреть файл

@ -11,8 +11,8 @@
#include <fb/fbjni.h>
#include <jsi/jsi.h>
#include <ReactCommon/TurboModuleBinding.h>
#include <ReactCommon/TurboCxxModule.h>
#include <ReactCommon/TurboModuleBinding.h>
#include <react/jni/JMessageQueueThread.h>
#include "TurboModuleManager.h"
@ -25,33 +25,36 @@ TurboModuleManager::TurboModuleManager(
jsi::Runtime *rt,
std::shared_ptr<CallInvoker> jsCallInvoker,
std::shared_ptr<CallInvoker> nativeCallInvoker,
jni::alias_ref<TurboModuleManagerDelegate::javaobject> delegate
):
javaPart_(jni::make_global(jThis)),
jni::alias_ref<TurboModuleManagerDelegate::javaobject> delegate)
: javaPart_(jni::make_global(jThis)),
runtime_(rt),
jsCallInvoker_(jsCallInvoker),
nativeCallInvoker_(nativeCallInvoker),
delegate_(jni::make_global(delegate)),
turboModuleCache_(std::make_shared<TurboModuleCache>())
{}
turboModuleCache_(std::make_shared<TurboModuleCache>()) {}
jni::local_ref<TurboModuleManager::jhybriddata> TurboModuleManager::initHybrid(
jni::alias_ref<jhybridobject> jThis,
jlong jsContext,
jni::alias_ref<CallInvokerHolder::javaobject> jsCallInvokerHolder,
jni::alias_ref<CallInvokerHolder::javaobject> nativeCallInvokerHolder,
jni::alias_ref<TurboModuleManagerDelegate::javaobject> delegate
) {
jni::alias_ref<TurboModuleManagerDelegate::javaobject> 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(
"installJSIBindings", TurboModuleManager::installJSIBindings),
});
}
@ -60,22 +63,24 @@ void TurboModuleManager::installJSIBindings() {
return; // Runtime doesn't exist when attached to Chrome debugger.
}
TurboModuleBinding::install(*runtime_, std::make_shared<TurboModuleBinding>(
[
turboModuleCache_ = std::weak_ptr<TurboModuleCache>(turboModuleCache_),
TurboModuleBinding::install(
*runtime_,
std::make_shared<TurboModuleBinding>(
[turboModuleCache_ =
std::weak_ptr<TurboModuleCache>(turboModuleCache_),
jsCallInvoker_ = std::weak_ptr<CallInvoker>(jsCallInvoker_),
nativeCallInvoker_ = std::weak_ptr<CallInvoker>(nativeCallInvoker_),
delegate_ = jni::make_weak(delegate_),
javaPart_ = jni::make_weak(javaPart_)
]
(const std::string &name) -> std::shared_ptr<TurboModule> {
javaPart_ = jni::make_weak(javaPart_)](
const std::string &name) -> std::shared_ptr<TurboModule> {
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) {
if (!turboModuleCache || !jsCallInvoker || !nativeCallInvoker ||
!delegate || !javaPart) {
return nullptr;
}
@ -84,33 +89,41 @@ void TurboModuleManager::installJSIBindings() {
return turboModuleLookup->second;
}
auto cxxModule = delegate->cthis()->getTurboModule(name, jsCallInvoker);
auto cxxModule =
delegate->cthis()->getTurboModule(name, jsCallInvoker);
if (cxxModule) {
turboModuleCache->insert({name, cxxModule});
return cxxModule;
}
static auto getLegacyCxxModule = delegate->getClass()->getMethod<jni::alias_ref<CxxModuleWrapper::javaobject>(const std::string&)>("getLegacyCxxModule");
static auto getLegacyCxxModule =
delegate->getClass()
->getMethod<jni::alias_ref<CxxModuleWrapper::javaobject>(
const std::string &)>("getLegacyCxxModule");
auto legacyCxxModule = getLegacyCxxModule(delegate.get(), name);
if (legacyCxxModule) {
auto turboModule = std::make_shared<react::TurboCxxModule>(legacyCxxModule->cthis()->getModule(), jsCallInvoker);
auto turboModule = std::make_shared<react::TurboCxxModule>(
legacyCxxModule->cthis()->getModule(), jsCallInvoker);
turboModuleCache->insert({name, turboModule});
return turboModule;
}
static auto getJavaModule = javaPart->getClass()->getMethod<jni::alias_ref<JTurboModule>(const std::string&)>("getJavaModule");
static auto getJavaModule =
javaPart->getClass()
->getMethod<jni::alias_ref<JTurboModule>(
const std::string &)>("getJavaModule");
auto moduleInstance = getJavaModule(javaPart.get(), name);
if (moduleInstance) {
auto turboModule = delegate->cthis()->getTurboModule(name, moduleInstance, jsCallInvoker, nativeCallInvoker);
auto turboModule = delegate->cthis()->getTurboModule(
name, moduleInstance, jsCallInvoker, nativeCallInvoker);
turboModuleCache->insert({name, turboModule});
return turboModule;
}
return nullptr;
})
);
}));
}
} // namespace react

Просмотреть файл

@ -7,31 +7,32 @@
#pragma once
#include <memory>
#include <unordered_map>
#include <ReactCommon/CallInvokerHolder.h>
#include <ReactCommon/JavaTurboModule.h>
#include <ReactCommon/TurboModule.h>
#include <ReactCommon/TurboModuleManagerDelegate.h>
#include <fb/fbjni.h>
#include <jsi/jsi.h>
#include <ReactCommon/TurboModule.h>
#include <ReactCommon/JavaTurboModule.h>
#include <react/jni/CxxModuleWrapper.h>
#include <react/jni/JMessageQueueThread.h>
#include <ReactCommon/CallInvokerHolder.h>
#include <ReactCommon/TurboModuleManagerDelegate.h>
#include <memory>
#include <unordered_map>
namespace facebook {
namespace react {
class TurboModuleManager : public jni::HybridClass<TurboModuleManager> {
public:
static auto constexpr kJavaDescriptor = "Lcom/facebook/react/turbomodule/core/TurboModuleManager;";
static auto constexpr kJavaDescriptor =
"Lcom/facebook/react/turbomodule/core/TurboModuleManager;";
static jni::local_ref<jhybriddata> initHybrid(
jni::alias_ref<jhybridobject> jThis,
jlong jsContext,
jni::alias_ref<CallInvokerHolder::javaobject> jsCallInvokerHolder,
jni::alias_ref<CallInvokerHolder::javaobject> nativeCallInvokerHolder,
jni::alias_ref<TurboModuleManagerDelegate::javaobject> delegate
);
jni::alias_ref<TurboModuleManagerDelegate::javaobject> delegate);
static void registerNatives();
private:
friend HybridBase;
jni::global_ref<TurboModuleManager::javaobject> javaPart_;
@ -40,7 +41,8 @@ private:
std::shared_ptr<CallInvoker> nativeCallInvoker_;
jni::global_ref<TurboModuleManagerDelegate::javaobject> delegate_;
using TurboModuleCache = std::unordered_map<std::string, std::shared_ptr<react::TurboModule>>;
using TurboModuleCache =
std::unordered_map<std::string, std::shared_ptr<react::TurboModule>>;
/**
* TODO(T48018690):
@ -56,8 +58,7 @@ private:
jsi::Runtime *rt,
std::shared_ptr<CallInvoker> jsCallInvoker,
std::shared_ptr<CallInvoker> nativeCallInvoker,
jni::alias_ref<TurboModuleManagerDelegate::javaobject> delegate
);
jni::alias_ref<TurboModuleManagerDelegate::javaobject> delegate);
};
} // namespace react

Просмотреть файл

@ -7,21 +7,29 @@
#pragma once
#include <fb/fbjni.h>
#include <ReactCommon/JavaTurboModule.h>
#include <ReactCommon/CallInvoker.h>
#include <string>
#include <ReactCommon/JavaTurboModule.h>
#include <fb/fbjni.h>
#include <memory>
#include <string>
namespace facebook {
namespace react {
class TurboModuleManagerDelegate : public jni::HybridClass<TurboModuleManagerDelegate> {
class TurboModuleManagerDelegate
: public jni::HybridClass<TurboModuleManagerDelegate> {
public:
static auto constexpr kJavaDescriptor = "Lcom/facebook/react/turbomodule/core/TurboModuleManagerDelegate;";
static auto constexpr kJavaDescriptor =
"Lcom/facebook/react/turbomodule/core/TurboModuleManagerDelegate;";
virtual std::shared_ptr<TurboModule> getTurboModule(std::string name, jni::alias_ref<JTurboModule> turboModule, std::shared_ptr<CallInvoker> jsInvoker, std::shared_ptr<CallInvoker> nativeInvoker) = 0;
virtual std::shared_ptr<TurboModule> getTurboModule(std::string name, std::shared_ptr<CallInvoker> jsInvoker) = 0;
virtual std::shared_ptr<TurboModule> getTurboModule(
std::string name,
jni::alias_ref<JTurboModule> turboModule,
std::shared_ptr<CallInvoker> jsInvoker,
std::shared_ptr<CallInvoker> nativeInvoker) = 0;
virtual std::shared_ptr<TurboModule> getTurboModule(
std::string name,
std::shared_ptr<CallInvoker> jsInvoker) = 0;
private:
friend HybridBase;

Просмотреть файл

@ -290,8 +290,8 @@ void CatalystInstanceImpl::handleMemoryPressure(int pressureLevel) {
jni::alias_ref<CallInvokerHolder::javaobject>
CatalystInstanceImpl::getJSCallInvokerHolder() {
if (!jsCallInvokerHolder_) {
jsCallInvokerHolder_ =
jni::make_global(CallInvokerHolder::newObjectCxxArgs(std::make_shared<BridgeJSCallInvoker>(instance_)));
jsCallInvokerHolder_ = jni::make_global(CallInvokerHolder::newObjectCxxArgs(
std::make_shared<BridgeJSCallInvoker>(instance_)));
}
return jsCallInvokerHolder_;
@ -301,7 +301,9 @@ jni::alias_ref<CallInvokerHolder::javaobject>
CatalystInstanceImpl::getNativeCallInvokerHolder() {
if (!nativeCallInvokerHolder_) {
nativeCallInvokerHolder_ =
jni::make_global(CallInvokerHolder::newObjectCxxArgs(std::make_shared<MessageQueueThreadCallInvoker>(moduleMessageQueue_)));
jni::make_global(CallInvokerHolder::newObjectCxxArgs(
std::make_shared<MessageQueueThreadCallInvoker>(
moduleMessageQueue_)));
}
return nativeCallInvokerHolder_;

Просмотреть файл

@ -32,9 +32,8 @@ public:
"Lcom/facebook/react/bridge/CxxModuleWrapperBase;";
static void registerNatives() {
registerHybrid({
makeNativeMethod("getName", CxxModuleWrapperBase::getName)
});
registerHybrid(
{makeNativeMethod("getName", CxxModuleWrapperBase::getName)});
}
// JNI method
@ -44,5 +43,5 @@ public:
virtual std::unique_ptr<xplat::module::CxxModule> getModule() = 0;
};
}
}
} // namespace react
} // namespace facebook

Просмотреть файл

@ -20,18 +20,21 @@ namespace react {
class Instance;
struct JCallback : public jni::JavaClass<JCallback> {
constexpr static auto kJavaDescriptor = "Lcom/facebook/react/bridge/Callback;";
constexpr static auto kJavaDescriptor =
"Lcom/facebook/react/bridge/Callback;";
};
class JCxxCallbackImpl : public jni::HybridClass<JCxxCallbackImpl, JCallback> {
public:
constexpr static auto kJavaDescriptor = "Lcom/facebook/react/bridge/CxxCallbackImpl;";
constexpr static auto kJavaDescriptor =
"Lcom/facebook/react/bridge/CxxCallbackImpl;";
static void registerNatives() {
javaClassStatic()->registerNatives({
makeNativeMethod("nativeInvoke", JCxxCallbackImpl::invoke),
});
}
private:
friend HybridBase;
@ -45,5 +48,5 @@ private:
Callback callback_;
};
}
}
} // namespace react
} // namespace facebook

Просмотреть файл

@ -20,14 +20,17 @@ namespace react {
class JPage : public jni::JavaClass<JPage> {
public:
static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/Inspector$Page;";
static constexpr auto kJavaDescriptor =
"Lcom/facebook/react/bridge/Inspector$Page;";
static jni::local_ref<JPage::javaobject> create(int id, const std::string& title, const std::string& vm);
static jni::local_ref<JPage::javaobject>
create(int id, const std::string &title, const std::string &vm);
};
class JRemoteConnection : public jni::JavaClass<JRemoteConnection> {
public:
static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/Inspector$RemoteConnection;";
static constexpr auto kJavaDescriptor =
"Lcom/facebook/react/bridge/Inspector$RemoteConnection;";
void onMessage(const std::string &message) const;
void onDisconnect() const;
@ -35,7 +38,8 @@ public:
class JLocalConnection : public jni::HybridClass<JLocalConnection> {
public:
static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/Inspector$LocalConnection;";
static constexpr auto kJavaDescriptor =
"Lcom/facebook/react/bridge/Inspector$LocalConnection;";
JLocalConnection(std::unique_ptr<ILocalConnection> connection);
@ -43,20 +47,26 @@ public:
void disconnect();
static void registerNatives();
private:
std::unique_ptr<ILocalConnection> connection_;
};
class JInspector : public jni::HybridClass<JInspector> {
public:
static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/Inspector;";
static constexpr auto kJavaDescriptor =
"Lcom/facebook/react/bridge/Inspector;";
static jni::global_ref<JInspector::javaobject> instance(jni::alias_ref<jclass>);
static jni::global_ref<JInspector::javaobject> instance(
jni::alias_ref<jclass>);
jni::local_ref<jni::JArrayClass<JPage::javaobject>> getPages();
jni::local_ref<JLocalConnection::javaobject> connect(int pageId, jni::alias_ref<JRemoteConnection::javaobject> remote);
jni::local_ref<JLocalConnection::javaobject> connect(
int pageId,
jni::alias_ref<JRemoteConnection::javaobject> remote);
static void registerNatives();
private:
friend HybridBase;
@ -65,7 +75,7 @@ private:
IInspector *inspector_;
};
}
}
} // namespace react
} // namespace facebook
#endif

Просмотреть файл

@ -22,10 +22,11 @@ namespace react {
namespace {
struct JavaJSException : jni::JavaClass<JavaJSException, JThrowable> {
static constexpr auto kJavaDescriptor = "Lcom/facebook/react/devsupport/JSException;";
static constexpr auto kJavaDescriptor =
"Lcom/facebook/react/devsupport/JSException;";
static local_ref<JavaJSException> create(const char* message, const char* stack,
const std::exception& ex) {
static local_ref<JavaJSException>
create(const char *message, const char *stack, const std::exception &ex) {
local_ref<jthrowable> cause = jni::JCppException::create(ex);
return newInstance(make_jstring(message), make_jstring(stack), cause.get());
}
@ -48,31 +49,37 @@ std::function<void()> wrapRunnable(std::function<void()>&& runnable) {
localRunnable();
} catch (const jsi::JSError &ex) {
throwNewJavaException(
JavaJSException::create(ex.getMessage().c_str(), ex.getStack().c_str(), ex)
JavaJSException::create(
ex.getMessage().c_str(), ex.getStack().c_str(), ex)
.get());
}
};
}
}
} // namespace
JMessageQueueThread::JMessageQueueThread(alias_ref<JavaMessageQueueThread::javaobject> jobj) :
m_jobj(make_global(jobj)) {
}
JMessageQueueThread::JMessageQueueThread(
alias_ref<JavaMessageQueueThread::javaobject> jobj)
: m_jobj(make_global(jobj)) {}
void JMessageQueueThread::runOnQueue(std::function<void()> &&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<void(Runnable::javaobject)>("runOnQueue");
method(m_jobj, JNativeRunnable::newObjectCxxArgs(wrapRunnable(std::move(runnable))).get());
static auto method =
JavaMessageQueueThread::javaClassStatic()
->getMethod<void(Runnable::javaobject)>("runOnQueue");
method(
m_jobj,
JNativeRunnable::newObjectCxxArgs(wrapRunnable(std::move(runnable)))
.get());
}
void JMessageQueueThread::runOnQueueSync(std::function<void()> &&runnable) {
static auto jIsOnThread = JavaMessageQueueThread::javaClassStatic()->
getMethod<jboolean()>("isOnThread");
static auto jIsOnThread =
JavaMessageQueueThread::javaClassStatic()->getMethod<jboolean()>(
"isOnThread");
if (jIsOnThread(m_jobj)) {
wrapRunnable(std::move(runnable))();
@ -96,9 +103,11 @@ void JMessageQueueThread::runOnQueueSync(std::function<void()>&& runnable) {
}
void JMessageQueueThread::quitSynchronous() {
static auto method = JavaMessageQueueThread::javaClassStatic()->
getMethod<void()>("quitSynchronous");
static auto method =
JavaMessageQueueThread::javaClassStatic()->getMethod<void()>(
"quitSynchronous");
method(m_jobj);
}
} }
} // namespace react
} // namespace facebook

Просмотреть файл

@ -19,7 +19,8 @@ namespace react {
class JavaMessageQueueThread : public jni::JavaClass<JavaMessageQueueThread> {
public:
static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/queue/MessageQueueThread;";
static constexpr auto kJavaDescriptor =
"Lcom/facebook/react/bridge/queue/MessageQueueThread;";
};
class JMessageQueueThread : public MessageQueueThread {
@ -39,8 +40,8 @@ public:
void runOnQueueSync(std::function<void()> &&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;
@ -52,4 +53,5 @@ private:
global_ref<JavaMessageQueueThread::javaobject> m_jobj;
};
} }
} // namespace react
} // namespace facebook

Просмотреть файл

@ -6,9 +6,9 @@
*/
#include "JReactMarker.h"
#include <mutex>
#include <cxxreact/ReactMarker.h>
#include <fb/fbjni.h>
#include <mutex>
namespace facebook {
namespace react {
@ -26,13 +26,18 @@ void JReactMarker::logMarker(const std::string& marker) {
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<void(std::string, std::string)>("logMarker");
static auto meth =
cls->getStaticMethod<void(std::string, std::string)>("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

Просмотреть файл

@ -7,8 +7,8 @@
#pragma once
#include <string>
#include <fb/fbjni.h>
#include <string>
#include <cxxreact/ReactMarker.h>
@ -17,14 +17,17 @@ namespace react {
class JReactMarker : public facebook::jni::JavaClass<JReactMarker> {
public:
static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/ReactMarker;";
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);
static void logPerfMarker(
const ReactMarker::ReactMarkerId markerId,
const char *tag);
};
}
}
} // namespace react
} // namespace facebook

Просмотреть файл

@ -28,30 +28,33 @@ using namespace facebook::jni;
namespace facebook {
namespace react {
__attribute__((visibility("default")))
AAssetManager *extractAssetManager(alias_ref<JAssetManager::javaobject> assetManager) {
__attribute__((visibility("default"))) AAssetManager *extractAssetManager(
alias_ref<JAssetManager::javaobject> assetManager) {
auto env = Environment::current();
return AAssetManager_fromJava(env, assetManager.get());
}
__attribute__((visibility("default")))
std::unique_ptr<const JSBigString> loadScriptFromAssets(
AAssetManager *manager,
const std::string& assetName) {
__attribute__((visibility("default"))) std::unique_ptr<const JSBigString>
loadScriptFromAssets(AAssetManager *manager, const std::string &assetName) {
#ifdef WITH_FBSYSTRACE
FbSystraceSection s(TRACE_TAG_REACT_CXX_BRIDGE, "reactbridge_jni_loadScriptFromAssets",
"assetName", assetName);
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
AASSET_MODE_STREAMING); // Optimized for sequential read: see
// AssetManager.java for docs
if (asset) {
auto buf = std::make_unique<JSBigBufferString>(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<const JSBigString> loadScriptFromAssets(
}
}
throw std::runtime_error(folly::to<std::string>("Unable to load script. Make sure you're "
"either running a Metro server (run 'react-native start') or that your bundle '", assetName,
throw std::runtime_error(folly::to<std::string>(
"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

Просмотреть файл

@ -23,8 +23,12 @@ struct JAssetManager : jni::JavaClass<JAssetManager> {
/**
* Helper method for loading JS script from android asset
*/
AAssetManager *extractAssetManager(jni::alias_ref<JAssetManager::javaobject> assetManager);
AAssetManager *extractAssetManager(
jni::alias_ref<JAssetManager::javaobject> assetManager);
std::unique_ptr<const JSBigString> loadScriptFromAssets(AAssetManager *assetManager, const std::string& assetName);
std::unique_ptr<const JSBigString> loadScriptFromAssets(
AAssetManager *assetManager,
const std::string &assetName);
} }
} // namespace react
} // namespace facebook

Просмотреть файл

@ -9,13 +9,13 @@
#include <glog/logging.h>
#include <fb/fbjni.h>
#include <folly/json.h>
#include <cxxreact/CxxModule.h>
#include <cxxreact/CxxNativeModule.h>
#include <cxxreact/Instance.h>
#include <cxxreact/JsArgumentHelpers.h>
#include <cxxreact/NativeModule.h>
#include <fb/fbjni.h>
#include <folly/json.h>
#ifdef WITH_FBSYSTRACE
#include <fbsystrace.h>
@ -45,7 +45,8 @@ std::string JMethodDescriptor::getType() const {
}
std::string JavaNativeModule::getName() {
static auto getNameMethod = wrapper_->getClass()->getMethod<jstring()>("getName");
static auto getNameMethod =
wrapper_->getClass()->getMethod<jstring()>("getName");
return getNameMethod(wrapper_)->toStdString();
}
@ -58,23 +59,22 @@ std::vector<MethodDescriptor> JavaNativeModule::getMethods() {
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(
syncMethods_.insert(
syncMethods_.begin() + methodIndex,
MethodInvoker(
desc->getMethod(),
desc->getSignature(),
getName() + "." + methodName,
true
));
true));
}
ret.emplace_back(
std::move(methodName),
std::move(methodType)
);
ret.emplace_back(std::move(methodName), std::move(methodType));
}
return ret;
}
@ -90,9 +90,16 @@ 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<void(jint, ReadableNativeArray::javaobject)>("invoke");
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<void(jint, ReadableNativeArray::javaobject)>(
"invoke");
#ifdef WITH_FBSYSTRACE
if (callId != -1) {
fbsystrace_end_async_flow(TRACE_TAG_REACT_APPS, "native", callId);
@ -105,15 +112,22 @@ void JavaNativeModule::invoke(unsigned int reactMethodId, folly::dynamic&& param
});
}
MethodCallResult JavaNativeModule::callSerializableNativeHook(unsigned int reactMethodId, folly::dynamic&& params) {
MethodCallResult JavaNativeModule::callSerializableNativeHook(
unsigned int reactMethodId,
folly::dynamic &&params) {
// TODO: evaluate whether calling through invoke is potentially faster
if (reactMethodId >= syncMethods_.size()) {
throw std::invalid_argument(
folly::to<std::string>("methodId ", reactMethodId, " out of range [0..", syncMethods_.size(), "]"));
throw std::invalid_argument(folly::to<std::string>(
"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";
CHECK(method.hasValue() && method->isSyncHook())
<< "Trying to invoke a asynchronous method as synchronous hook";
return method->invoke(instance_, wrapper_->getModule(), params);
}
@ -121,10 +135,10 @@ NewJavaNativeModule::NewJavaNativeModule(
std::weak_ptr<Instance> instance,
jni::alias_ref<JavaModuleWrapper::javaobject> wrapper,
std::shared_ptr<MessageQueueThread> messageQueueThread)
: instance_(std::move(instance))
, wrapper_(make_global(wrapper))
, module_(make_global(wrapper->getModule()))
, messageQueueThread_(std::move(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());
@ -143,7 +157,8 @@ NewJavaNativeModule::NewJavaNativeModule(
}
std::string NewJavaNativeModule::getName() {
static auto getNameMethod = wrapper_->getClass()->getMethod<jstring()>("getName");
static auto getNameMethod =
wrapper_->getClass()->getMethod<jstring()>("getName");
return getNameMethod(wrapper_)->toStdString();
}
@ -162,13 +177,22 @@ folly::dynamic NewJavaNativeModule::getConstants() {
}
}
void NewJavaNativeModule::invoke(unsigned int reactMethodId, folly::dynamic&& params, int callId) {
void NewJavaNativeModule::invoke(
unsigned int reactMethodId,
folly::dynamic &&params,
int callId) {
if (reactMethodId >= methods_.size()) {
throw std::invalid_argument(
folly::to<std::string>("methodId ", reactMethodId, " out of range [0..", methods_.size(), "]"));
throw std::invalid_argument(folly::to<std::string>(
"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 {
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);
@ -178,23 +202,34 @@ void NewJavaNativeModule::invoke(unsigned int reactMethodId, folly::dynamic&& pa
});
}
MethodCallResult NewJavaNativeModule::callSerializableNativeHook(unsigned int reactMethodId, folly::dynamic&& params) {
MethodCallResult NewJavaNativeModule::callSerializableNativeHook(
unsigned int reactMethodId,
folly::dynamic &&params) {
if (reactMethodId >= methods_.size()) {
throw std::invalid_argument(
folly::to<std::string>("methodId ", reactMethodId, " out of range [0..", methods_.size(), "]"));
throw std::invalid_argument(folly::to<std::string>(
"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 &&params) {
return methods_[reactMethodId].invoke(instance_, module_.get(), params);
}
jni::local_ref<JReflectMethod::javaobject> JMethodDescriptor::getMethod() const {
static auto method = javaClassStatic()->getField<JReflectMethod::javaobject>("method");
jni::local_ref<JReflectMethod::javaobject> JMethodDescriptor::getMethod()
const {
static auto method =
javaClassStatic()->getField<JReflectMethod::javaobject>("method");
return getFieldValue(method);
}
}
}
} // namespace react
} // namespace facebook

Просмотреть файл

@ -30,12 +30,15 @@ struct JMethodDescriptor : public jni::JavaClass<JMethodDescriptor> {
};
struct JavaModuleWrapper : jni::JavaClass<JavaModuleWrapper> {
static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/JavaModuleWrapper;";
static constexpr auto kJavaDescriptor =
"Lcom/facebook/react/bridge/JavaModuleWrapper;";
jni::local_ref<JBaseJavaModule::javaobject> getModule() {
// This is the call which causes a lazy Java module to actually be
// created.
static auto getModule = javaClassStatic()->getMethod<JBaseJavaModule::javaobject()>("getModule");
static auto getModule =
javaClassStatic()->getMethod<JBaseJavaModule::javaobject()>(
"getModule");
return getModule(self());
}
@ -44,9 +47,13 @@ struct JavaModuleWrapper : jni::JavaClass<JavaModuleWrapper> {
return getName(self())->toStdString();
}
jni::local_ref<jni::JList<JMethodDescriptor::javaobject>::javaobject> getMethodDescriptors() {
static auto getMethods = getClass()
->getMethod<jni::JList<JMethodDescriptor::javaobject>::javaobject()>("getMethodDescriptors");
jni::local_ref<jni::JList<JMethodDescriptor::javaobject>::javaobject>
getMethodDescriptors() {
static auto getMethods =
getClass()
->getMethod<
jni::JList<JMethodDescriptor::javaobject>::javaobject()>(
"getMethodDescriptors");
return getMethods(self());
}
};
@ -57,15 +64,18 @@ class JavaNativeModule : public NativeModule {
std::weak_ptr<Instance> instance,
jni::alias_ref<JavaModuleWrapper::javaobject> wrapper,
std::shared_ptr<MessageQueueThread> messageQueueThread)
: instance_(std::move(instance))
, wrapper_(make_global(wrapper))
, messageQueueThread_(std::move(messageQueueThread)) {}
: instance_(std::move(instance)),
wrapper_(make_global(wrapper)),
messageQueueThread_(std::move(messageQueueThread)) {}
std::string getName() override;
folly::dynamic getConstants() override;
std::vector<MethodDescriptor> 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 &&params, int callId)
override;
MethodCallResult callSerializableNativeHook(
unsigned int reactMethodId,
folly::dynamic &&params) override;
private:
std::weak_ptr<Instance> instance_;
@ -85,8 +95,11 @@ class NewJavaNativeModule : public NativeModule {
std::string getName() override;
std::vector<MethodDescriptor> 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 &&params, int callId)
override;
MethodCallResult callSerializableNativeHook(
unsigned int reactMethodId,
folly::dynamic &&params) override;
private:
std::weak_ptr<Instance> instance_;
@ -96,7 +109,10 @@ class NewJavaNativeModule : public NativeModule {
std::vector<MethodInvoker> methods_;
std::vector<MethodDescriptor> methodDescriptors_;
MethodCallResult invokeInner(unsigned int reactMethodId, folly::dynamic&& params);
MethodCallResult invokeInner(
unsigned int reactMethodId,
folly::dynamic &&params);
};
}}
} // namespace react
} // namespace facebook

Просмотреть файл

@ -13,7 +13,8 @@
namespace facebook {
namespace react {
class JavaScriptExecutorHolder : public jni::HybridClass<JavaScriptExecutorHolder> {
class JavaScriptExecutorHolder
: public jni::HybridClass<JavaScriptExecutorHolder> {
public:
static constexpr auto kJavaDescriptor =
"Lcom/facebook/react/bridge/JavaScriptExecutor;";
@ -30,4 +31,5 @@ class JavaScriptExecutorHolder : public jni::HybridClass<JavaScriptExecutorHolde
std::shared_ptr<JSExecutorFactory> mExecutorFactory;
};
}}
} // namespace react
} // namespace facebook

Просмотреть файл

@ -32,9 +32,12 @@ namespace {
using dynamic_iterator = folly::dynamic::const_iterator;
struct JPromiseImpl : public JavaClass<JPromiseImpl> {
constexpr static auto kJavaDescriptor = "Lcom/facebook/react/bridge/PromiseImpl;";
constexpr static auto kJavaDescriptor =
"Lcom/facebook/react/bridge/PromiseImpl;";
static local_ref<javaobject> create(local_ref<JCallback::javaobject> resolve, local_ref<JCallback::javaobject> reject) {
static local_ref<javaobject> create(
local_ref<JCallback::javaobject> resolve,
local_ref<JCallback::javaobject> reject) {
return newInstance(resolve, reject);
}
};
@ -62,14 +65,16 @@ jint extractInteger(const folly::dynamic& value) {
double dbl = value.getDouble();
jint result = static_cast<jint>(dbl);
if (dbl != result) {
throw std::invalid_argument(
folly::to<std::string>(
"Tried to convert jint argument, but got a non-integral double: ", dbl));
throw std::invalid_argument(folly::to<std::string>(
"Tried to convert jint argument, but got a non-integral double: ",
dbl));
}
return result;
}
local_ref<JCxxCallbackImpl::jhybridobject> extractCallback(std::weak_ptr<Instance>& instance, const folly::dynamic& value) {
local_ref<JCxxCallbackImpl::jhybridobject> extractCallback(
std::weak_ptr<Instance> &instance,
const folly::dynamic &value) {
if (value.isNull()) {
return local_ref<JCxxCallbackImpl::jhybridobject>(nullptr);
} else {
@ -77,7 +82,10 @@ local_ref<JCxxCallbackImpl::jhybridobject> extractCallback(std::weak_ptr<Instanc
}
}
local_ref<JPromiseImpl::javaobject> extractPromise(std::weak_ptr<Instance>& instance, dynamic_iterator& it, dynamic_iterator& end) {
local_ref<JPromiseImpl::javaobject> extractPromise(
std::weak_ptr<Instance> &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>& instance, char type, dynamic_iterator& it, dynamic_iterator& end) {
jvalue extract(
std::weak_ptr<Instance> &instance,
char type,
dynamic_iterator &it,
dynamic_iterator &end) {
CHECK(it != end);
jvalue value;
if (type == 'P') {
@ -118,7 +131,8 @@ jvalue extract(std::weak_ptr<Instance>& instance, char type, dynamic_iterator& i
value.z = static_cast<jboolean>(arg.getBool());
break;
case 'Z':
value.l = JBoolean::valueOf(static_cast<jboolean>(arg.getBool())).release();
value.l =
JBoolean::valueOf(static_cast<jboolean>(arg.getBool())).release();
break;
case 'i':
value.i = extractInteger(arg);
@ -130,7 +144,8 @@ jvalue extract(std::weak_ptr<Instance>& instance, char type, dynamic_iterator& i
value.f = static_cast<jfloat>(extractDouble(arg));
break;
case 'F':
value.l = JFloat::valueOf(static_cast<jfloat>(extractDouble(arg))).release();
value.l =
JFloat::valueOf(static_cast<jfloat>(extractDouble(arg))).release();
break;
case 'd':
value.d = extractDouble(arg);
@ -171,19 +186,27 @@ std::size_t countJsArgs(const std::string& signature) {
return count;
}
}
} // namespace
MethodInvoker::MethodInvoker(alias_ref<JReflectMethod::javaobject> method, std::string signature, std::string traceName, bool isSync)
MethodInvoker::MethodInvoker(
alias_ref<JReflectMethod::javaobject> 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";
CHECK(isSync_ || signature_.at(0) == 'v')
<< "Non-sync hooks cannot have a non-void return type";
}
MethodCallResult MethodInvoker::invoke(std::weak_ptr<Instance>& instance, alias_ref<JBaseJavaModule::javaobject> module, const folly::dynamic& params) {
MethodCallResult MethodInvoker::invoke(
std::weak_ptr<Instance> &instance,
alias_ref<JBaseJavaModule::javaobject> module,
const folly::dynamic &params) {
#ifdef WITH_FBSYSTRACE
fbsystrace::FbSystraceSection s(
TRACE_TAG_REACT_CXX_BRIDGE,
@ -193,7 +216,8 @@ MethodCallResult MethodInvoker::invoke(std::weak_ptr<Instance>& instance, alias_
#endif
if (params.size() != jsArgCount_) {
throw std::invalid_argument(folly::to<std::string>("expected ", jsArgCount_, " arguments, got ", params.size()));
throw std::invalid_argument(folly::to<std::string>(
"expected ", jsArgCount_, " arguments, got ", params.size()));
}
auto env = Environment::current();
@ -208,19 +232,22 @@ MethodCallResult MethodInvoker::invoke(std::weak_ptr<Instance>& instance, alias_
return extract(instance, type, it, end);
});
#define PRIMITIVE_CASE(METHOD) { \
#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) { \
#define PRIMITIVE_CASE_CASTING(METHOD, RESULT_TYPE) \
{ \
auto result = env->Call##METHOD##MethodA(module.get(), method_, args); \
throwPendingJniExceptionAsCppException(); \
return folly::dynamic(static_cast<RESULT_TYPE>(result)); \
}
#define OBJECT_CASE(JNI_CLASS, ACTIONS) { \
#define OBJECT_CASE(JNI_CLASS, ACTIONS) \
{ \
auto jobject = env->CallObjectMethodA(module.get(), method_, args); \
throwPendingJniExceptionAsCppException(); \
if (!jobject) { \
@ -230,7 +257,8 @@ MethodCallResult MethodInvoker::invoke(std::weak_ptr<Instance>& instance, alias_
return folly::dynamic(result->ACTIONS()); \
}
#define OBJECT_CASE_CASTING(JNI_CLASS, ACTIONS, RESULT_TYPE) { \
#define OBJECT_CASE_CASTING(JNI_CLASS, ACTIONS, RESULT_TYPE) \
{ \
auto jobject = env->CallObjectMethodA(module.get(), method_, args); \
throwPendingJniExceptionAsCppException(); \
if (!jobject) { \
@ -277,5 +305,5 @@ MethodCallResult MethodInvoker::invoke(std::weak_ptr<Instance>& instance, alias_
}
}
}
}
} // namespace react
} // namespace facebook

Просмотреть файл

@ -29,18 +29,27 @@ struct JReflectMethod : public jni::JavaClass<JReflectMethod> {
};
struct JBaseJavaModule : public jni::JavaClass<JBaseJavaModule> {
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<JReflectMethod::javaobject> method, std::string signature, std::string traceName, bool isSync);
MethodInvoker(
jni::alias_ref<JReflectMethod::javaobject> method,
std::string signature,
std::string traceName,
bool isSync);
MethodCallResult invoke(std::weak_ptr<Instance>& instance, jni::alias_ref<JBaseJavaModule::javaobject> module, const folly::dynamic& params);
MethodCallResult invoke(
std::weak_ptr<Instance> &instance,
jni::alias_ref<JBaseJavaModule::javaobject> module,
const folly::dynamic &params);
bool isSyncHook() const {
return isSync_;
}
private:
jmethodID method_;
std::string signature_;
@ -49,5 +58,5 @@ private:
bool isSync_;
};
}
}
} // namespace react
} // namespace facebook

Просмотреть файл

@ -25,13 +25,16 @@ class ModuleHolder : public jni::JavaClass<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<std::unique_ptr<NativeModule>> buildNativeModuleList(
std::weak_ptr<Instance> winstance,
jni::alias_ref<jni::JCollection<JavaModuleWrapper::javaobject>::javaobject> javaModules,
jni::alias_ref<jni::JCollection<ModuleHolder::javaobject>::javaobject> cxxModules,
jni::alias_ref<jni::JCollection<JavaModuleWrapper::javaobject>::javaobject>
javaModules,
jni::alias_ref<jni::JCollection<ModuleHolder::javaobject>::javaobject>
cxxModules,
std::shared_ptr<MessageQueueThread> moduleMessageQueue);
}
}
} // namespace react
} // namespace facebook

Просмотреть файл

@ -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());
}
}
@ -44,5 +46,5 @@ void NativeArray::throwIfConsumed() {
exceptions::throwIfObjectAlreadyConsumed(this, "Array already consumed");
}
}
}
} // namespace react
} // namespace facebook

Просмотреть файл

@ -17,7 +17,8 @@ namespace react {
class NativeArray : public jni::HybridClass<NativeArray> {
public:
static constexpr const char* kJavaDescriptor = "Lcom/facebook/react/bridge/NativeArray;";
static constexpr const char *kJavaDescriptor =
"Lcom/facebook/react/bridge/NativeArray;";
jni::local_ref<jstring> toString();
@ -37,4 +38,5 @@ class NativeArray : public jni::HybridClass<NativeArray> {
explicit NativeArray(folly::dynamic array);
};
}}
} // namespace react
} // namespace facebook

Просмотреть файл

@ -18,7 +18,8 @@ namespace facebook {
namespace react {
struct ReadableType : public jni::JavaClass<ReadableType> {
static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/ReadableType;";
static auto constexpr kJavaDescriptor =
"Lcom/facebook/react/bridge/ReadableType;";
static jni::local_ref<ReadableType> getType(folly::dynamic::Type type);
};
@ -30,7 +31,8 @@ extern const char *gUnexpectedNativeTypeExceptionClass;
template <typename T>
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);
}
}

Просмотреть файл

@ -17,7 +17,8 @@ namespace react {
class NativeMap : public jni::HybridClass<NativeMap> {
public:
static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/NativeMap;";
static auto constexpr kJavaDescriptor =
"Lcom/facebook/react/bridge/NativeMap;";
std::string toString();

Просмотреть файл

@ -10,8 +10,8 @@
#include <cxxreact/JSBigString.h>
#include <cxxreact/ModuleRegistry.h>
#include <cxxreact/SystraceSection.h>
#include <fb/assert.h>
#include <fb/Environment.h>
#include <fb/assert.h>
#include <folly/json.h>
#include <jni/LocalReference.h>
#include <jni/LocalString.h>
@ -28,7 +28,8 @@ static std::string executeJSCallWithProxy(
const std::string &methodName,
const folly::dynamic &arguments) {
static auto executeJSCall =
jni::findClassStatic(EXECUTOR_BASECLASS)->getMethod<jstring(jstring, jstring)>("executeJSCall");
jni::findClassStatic(EXECUTOR_BASECLASS)
->getMethod<jstring(jstring, jstring)>("executeJSCall");
auto result = executeJSCall(
executor,
@ -38,15 +39,15 @@ static std::string executeJSCallWithProxy(
}
std::unique_ptr<JSExecutor> ProxyExecutorOneTimeFactory::createJSExecutor(
std::shared_ptr<ExecutorDelegate> delegate, std::shared_ptr<MessageQueueThread>) {
std::shared_ptr<ExecutorDelegate> delegate,
std::shared_ptr<MessageQueueThread>) {
return std::make_unique<ProxyExecutor>(std::move(m_executor), delegate);
}
ProxyExecutor::ProxyExecutor(jni::global_ref<jobject>&& executorInstance,
ProxyExecutor::ProxyExecutor(
jni::global_ref<jobject> &&executorInstance,
std::shared_ptr<ExecutorDelegate> delegate)
: m_executor(std::move(executorInstance))
, m_delegate(delegate)
{}
: m_executor(std::move(executorInstance)), m_delegate(delegate) {}
ProxyExecutor::~ProxyExecutor() {
m_executor.reset();
@ -55,7 +56,6 @@ ProxyExecutor::~ProxyExecutor() {
void ProxyExecutor::loadApplicationScript(
std::unique_ptr<const JSBigString>,
std::string sourceURL) {
folly::dynamic nativeModuleConfig = folly::dynamic::array;
{
@ -67,9 +67,8 @@ void ProxyExecutor::loadApplicationScript(
}
}
folly::dynamic config =
folly::dynamic::object
("remoteModuleConfig", std::move(nativeModuleConfig));
folly::dynamic config = folly::dynamic::object(
"remoteModuleConfig", std::move(nativeModuleConfig));
{
SystraceSection t("setGlobalVariable");
@ -79,13 +78,12 @@ void ProxyExecutor::loadApplicationScript(
}
static auto loadApplicationScript =
jni::findClassStatic(EXECUTOR_BASECLASS)->getMethod<void(jstring)>("loadApplicationScript");
jni::findClassStatic(EXECUTOR_BASECLASS)
->getMethod<void(jstring)>("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.
}
@ -96,29 +94,40 @@ void ProxyExecutor::setBundleRegistry(std::unique_ptr<RAMBundleRegistry>) {
"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");
}
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,
void ProxyExecutor::setGlobalVariable(
std::string propName,
std::unique_ptr<const JSBigString> jsonValue) {
static auto setGlobalVariable =
jni::findClassStatic(EXECUTOR_BASECLASS)->getMethod<void(jstring, jstring)>("setGlobalVariable");
jni::findClassStatic(EXECUTOR_BASECLASS)
->getMethod<void(jstring, jstring)>("setGlobalVariable");
setGlobalVariable(
m_executor.get(),
@ -130,4 +139,5 @@ std::string ProxyExecutor::getDescription() {
return "Chrome";
}
} }
} // namespace react
} // namespace facebook

Просмотреть файл

@ -17,13 +17,13 @@ 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<jobject>&& executorInstance) :
m_executor(std::move(executorInstance)) {}
ProxyExecutorOneTimeFactory(jni::global_ref<jobject> &&executorInstance)
: m_executor(std::move(executorInstance)) {}
virtual std::unique_ptr<JSExecutor> createJSExecutor(
std::shared_ptr<ExecutorDelegate> delegate,
std::shared_ptr<MessageQueueThread> queue) override;
@ -34,7 +34,8 @@ private:
class ProxyExecutor : public JSExecutor {
public:
ProxyExecutor(jni::global_ref<jobject>&& executorInstance,
ProxyExecutor(
jni::global_ref<jobject> &&executorInstance,
std::shared_ptr<ExecutorDelegate> delegate);
virtual ~ProxyExecutor() override;
virtual void loadApplicationScript(
@ -42,8 +43,8 @@ public:
std::string sourceURL) override;
virtual void setBundleRegistry(
std::unique_ptr<RAMBundleRegistry> bundle) override;
virtual void registerBundle(
uint32_t bundleId, const std::string& bundlePath) override;
virtual void registerBundle(uint32_t bundleId, const std::string &bundlePath)
override;
virtual void callFunction(
const std::string &moduleId,
const std::string &methodId,
@ -61,4 +62,5 @@ private:
std::shared_ptr<ExecutorDelegate> m_delegate;
};
} }
} // namespace react
} // namespace facebook

Просмотреть файл

@ -19,12 +19,14 @@ namespace react {
struct WritableNativeMap;
struct WritableArray : jni::JavaClass<WritableArray> {
static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/WritableArray;";
static auto constexpr kJavaDescriptor =
"Lcom/facebook/react/bridge/WritableArray;";
};
struct WritableNativeArray
: public jni::HybridClass<WritableNativeArray, ReadableNativeArray> {
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<jhybriddata> initHybrid(jni::alias_ref<jclass>);
@ -40,5 +42,5 @@ struct WritableNativeArray
static void registerNatives();
};
}
}
} // namespace react
} // namespace facebook

Просмотреть файл

@ -18,11 +18,14 @@ namespace facebook {
namespace react {
struct WritableMap : jni::JavaClass<WritableMap> {
static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/WritableMap;";
static auto constexpr kJavaDescriptor =
"Lcom/facebook/react/bridge/WritableMap;";
};
struct WritableNativeMap : jni::HybridClass<WritableNativeMap, ReadableNativeMap> {
static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/WritableNativeMap;";
struct WritableNativeMap
: jni::HybridClass<WritableNativeMap, ReadableNativeMap> {
static auto constexpr kJavaDescriptor =
"Lcom/facebook/react/bridge/WritableNativeMap;";
WritableNativeMap();
WritableNativeMap(folly::dynamic &&val);

Просмотреть файл

@ -5,13 +5,13 @@
* LICENSE file in the root directory of this source tree.
*/
#include <fb/log.h>
#include <fb/fbjni.h>
#include <cxxreact/CxxModule.h>
#include <cxxreact/JsArgumentHelpers.h>
#include <fb/fbjni.h>
#include <fb/log.h>
#include <mutex>
#include <condition_variable>
#include <mutex>
namespace facebook {
namespace react {
@ -39,17 +39,32 @@ public:
static void bounceArgsCxx(
alias_ref<javaobject> 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<void(jint, jint, jint, jdouble, jdouble, jstring, jstring)>("bounceArgsCxx");
method(obj, iters, a, b, x, y, jni::make_jstring(s).get(), jni::make_jstring(t).get());
javaClassLocal()
->getMethod<void(
jint, jint, jint, jdouble, jdouble, jstring, jstring)>(
"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<CatalystBridgeBenchmarks> {
class CatalystBridgeBenchmarks
: public jni::JavaClass<CatalystBridgeBenchmarks> {
public:
static constexpr auto kJavaDescriptor =
"Lcom/facebook/react/CatalystBridgeBenchmarks;";
@ -87,16 +102,21 @@ public:
return "CxxBenchmarkModule";
}
virtual auto getConstants() -> std::map<std::string, folly::dynamic> override {
virtual auto getConstants()
-> std::map<std::string, folly::dynamic> override {
return std::map<std::string, folly::dynamic>();
}
virtual auto getMethods() -> std::vector<Method> override {
return std::vector<Method>{
Method("bounce", [this] (folly::dynamic args) {
Method(
"bounce",
[this](folly::dynamic args) {
this->bounce(xplat::jsArgAsInt(args, 0));
}),
Method("bounceArgs", [this] (folly::dynamic args) {
Method(
"bounceArgs",
[this](folly::dynamic args) {
this->bounceArgs(
xplat::jsArgAsInt(args, 0),
xplat::jsArgAsInt(args, 1),
@ -119,9 +139,12 @@ public:
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 @@ public:
}
};
void setUp(
alias_ref<CatalystBridgeBenchmarks::javaobject> obj,
alias_ref<JavaJSModule::javaobject> mod) {
@ -138,8 +160,7 @@ void setUp(
jsModule = jni::make_global(mod);
}
void tearDown(
alias_ref<CatalystBridgeBenchmarks::javaobject>) {
void tearDown(alias_ref<CatalystBridgeBenchmarks::javaobject>) {
javaTestInstance.reset();
jsModule.reset();
}
@ -173,7 +194,11 @@ static void stopWatchingLogMessages(JNIEnv*, jclass) {
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;
@ -194,17 +219,27 @@ extern "C" facebook::xplat::module::CxxModule* CxxBenchmarkModule() {
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),
"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", {
"com/facebook/react/CatalystBridgeBenchmarks",
{
makeNativeMethod("runNativeBounce", runBounce),
makeNativeMethod("nativeSetUp", setUp),
makeNativeMethod("nativeTearDown", tearDown),
});
});
}