[ci skip][AUTO]: Automated clang-format update: 3a76374539 (#277)

This commit is contained in:
cocos-robot
2026-08-15 15:32:58 +00:00
parent 18456b6706
commit cdd07414a3
257 changed files with 3090 additions and 3195 deletions
+27 -27
View File
@@ -40,16 +40,16 @@ int32_t sorting2DCount{0};
CC_FORCE_INLINE void fillIndexBuffers(RenderDrawInfo* drawInfo) { // NOLINT(readability-convert-member-functions-to-static)
uint16_t* ib = drawInfo->getIDataBuffer();
UIMeshBuffer* buffer = drawInfo->getMeshBuffer();
uint32_t indexOffset = buffer->getIndexOffset();
uint16_t* indexb = drawInfo->getIbBuffer();
uint32_t indexCount = drawInfo->getIbCount();
memcpy(&ib[indexOffset], indexb, indexCount * sizeof(uint16_t));
indexOffset += indexCount;
buffer->setIndexOffset(indexOffset);
}
@@ -83,7 +83,7 @@ CC_FORCE_INLINE void fillColor(RenderEntity* entity, RenderDrawInfo* drawInfo) {
uint32_t size = drawInfo->getVbCount() * stride;
float* vbBuffer = drawInfo->getVbBuffer();
Color temp = entity->getColor();
uint32_t offset = 0;
for (int i = 0; i < size; i += stride) {
offset = i + 5;
@@ -91,9 +91,9 @@ CC_FORCE_INLINE void fillColor(RenderEntity* entity, RenderDrawInfo* drawInfo) {
// Spine set 'UIRenderer._useVertexOpacity = true', it uses RGBA32 (4 bytes) color and fills color in Skeleton._updateColor and spine/simple.ts assembler.
// So for Spine rendering, it will never go here to fill color.
vbBuffer[offset] = static_cast<float>(temp.r) / 255.0F;
vbBuffer[offset+1] = static_cast<float>(temp.g) / 255.0F;
vbBuffer[offset+2] = static_cast<float>(temp.b) / 255.0F;
vbBuffer[offset+3] = entity->getOpacity();
vbBuffer[offset + 1] = static_cast<float>(temp.g) / 255.0F;
vbBuffer[offset + 2] = static_cast<float>(temp.b) / 255.0F;
vbBuffer[offset + 3] = entity->getOpacity();
}
}
@@ -110,7 +110,7 @@ Batcher2d::Batcher2d(Root* root)
_root = root;
_device = _root->getDevice();
_stencilManager = StencilManager::getInstance();
_recordedRendererInfoQueue.reserve(100);
}
@@ -138,7 +138,7 @@ Batcher2d::~Batcher2d() { // NOLINT
_maskAttributes.clear();
}
ccstd::vector<RecordedRendererInfo> &Batcher2d::getRecordedRendererInfoQueue() {
ccstd::vector<RecordedRendererInfo>& Batcher2d::getRecordedRendererInfoQueue() {
return _recordedRendererInfoQueue;
}
@@ -170,11 +170,11 @@ void Batcher2d::fillBuffersAndMergeBatches() {
for (auto* rootNode : _rootNodeArr) {
// _batches will add by generateBatch
walk(rootNode, 1, false);
if (ENABLE_SORTING_2D && sorting2DCount > 0) {
flushRecordedUIRenderers();
}
generateBatch(_currEntity, _currDrawInfo);
auto* scene = rootNode->getScene()->getRenderScene();
@@ -186,7 +186,7 @@ void Batcher2d::fillBuffersAndMergeBatches() {
}
}
void Batcher2d::handleUIRenderer(RenderEntity *entity) { // NOLINT(misc-no-recursion)
void Batcher2d::handleUIRenderer(RenderEntity* entity) { // NOLINT(misc-no-recursion)
uint32_t size = entity->getRenderDrawInfosSize();
for (uint32_t i = 0; i < size; i++) {
auto* drawInfo = entity->getRenderDrawInfoAt(i);
@@ -195,25 +195,25 @@ void Batcher2d::handleUIRenderer(RenderEntity *entity) { // NOLINT(misc-no-recur
entity->setVBColorDirty(false);
}
int32_t Batcher2d::recordUIRenderer(RenderEntity *entity) {
int32_t Batcher2d::recordUIRenderer(RenderEntity* entity) {
if (!ENABLE_SORTING_2D) return -1;
auto &queue = getRecordedRendererInfoQueue();
auto &info = queue.emplace_back();
auto& queue = getRecordedRendererInfoQueue();
auto& info = queue.emplace_back();
info.renderEntity = entity;
return static_cast<int32_t>(queue.size() - 1);
}
void Batcher2d::flushRecordedUIRenderers() { // NOLINT(misc-no-recursion)
if (!ENABLE_SORTING_2D) return;
auto &queue = getRecordedRendererInfoQueue();
auto& queue = getRecordedRendererInfoQueue();
if (queue.empty()) return;
std::stable_sort(queue.begin(), queue.end(), [](const auto &a, const auto &b){
std::stable_sort(queue.begin(), queue.end(), [](const auto& a, const auto& b) {
return a.renderEntity->getPriority() < b.renderEntity->getPriority();
});
for (const auto &info : queue) {
auto *entity = info.renderEntity;
for (const auto& info : queue) {
auto* entity = info.renderEntity;
if (entity) {
handleUIRenderer(entity);
}
@@ -227,13 +227,13 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { /
}
bool breakWalk = false;
auto* entity = static_cast<RenderEntity*>(node->getUserData());
const bool isCurrentColorDirty = node->_isColorDirty() || parentColorDirty;
const float localOpacity = node->_getLocalOpacity();
// Keep the same logic as which in batcher-2d.ts
const float finalOpacity = parentOpacity * localOpacity * (entity ? entity->getColorAlpha() : 1.F);
node->_setFinalOpacity(finalOpacity);
const bool visible = math::isNotEqualF(finalOpacity, 0);
if (entity) {
@@ -244,7 +244,7 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { /
entity->setOpacity(finalOpacity);
entity->setVBColorDirty(true);
}
if (ENABLE_SORTING_2D && sorting2DCount > 0) {
if (entity->getIsMask()) {
flushRecordedUIRenderers();
@@ -257,7 +257,7 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { /
handleUIRenderer(entity);
}
}
if (entity->getRenderEntityType() == RenderEntityType::CROSSED) {
breakWalk = true;
}
@@ -271,7 +271,7 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { /
walk(child, thisOpacity, isCurrentColorDirty);
}
}
if (isCurrentColorDirty) {
node->_setColorDirty(false);
}
@@ -283,7 +283,7 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { /
flushRecordedUIRenderers();
}
}
if (visible && _stencilManager->getMaskStackSize() > 0) {
handlePostRender(entity);
}
@@ -521,7 +521,7 @@ void Batcher2d::generateBatch(RenderEntity* entity, RenderDrawInfo* drawInfo) {
curdrawBatch->setFirstIndex(indexOffset);
curdrawBatch->setIndexCount(indexCount);
curdrawBatch->fillPass(_currMaterial, depthStencil, dssHash);
const auto &passes = curdrawBatch->getPasses();
const auto& passes = curdrawBatch->getPasses();
if (!passes.empty()) {
const auto& pass = passes.at(0);
if (entity->getUseLocal()) {
+7 -7
View File
@@ -41,13 +41,13 @@ using UIMeshBufferArray = ccstd::vector<UIMeshBuffer*>;
using UIMeshBufferMap = ccstd::unordered_map<uint16_t, UIMeshBufferArray>;
struct RecordedRendererInfo {
RenderEntity *renderEntity{nullptr};
RenderEntity* renderEntity{nullptr};
};
class Batcher2d final {
public:
static void setSorting2DCount(int32_t v);
Batcher2d();
explicit Batcher2d(Root* root);
~Batcher2d();
@@ -87,10 +87,10 @@ private:
void createClearModel();
gfx::DescriptorSet* getDescriptorSet(gfx::Texture* texture, gfx::Sampler* sampler, const gfx::DescriptorSetLayout* dsLayout);
ccstd::vector<RecordedRendererInfo> &getRecordedRendererInfoQueue();
void handleUIRenderer(RenderEntity *entity);
int32_t recordUIRenderer(RenderEntity *entity);
ccstd::vector<RecordedRendererInfo>& getRecordedRendererInfoQueue();
void handleUIRenderer(RenderEntity* entity);
int32_t recordUIRenderer(RenderEntity* entity);
void flushRecordedUIRenderers();
StencilManager* _stencilManager{nullptr};
@@ -103,7 +103,7 @@ private:
// manage memory manually
ccstd::vector<scene::DrawBatch2D*> _batches;
memop::Pool<scene::DrawBatch2D> _drawBatchPool;
ccstd::vector<RecordedRendererInfo> _recordedRendererInfoQueue;
// weak reference
+5 -5
View File
@@ -24,8 +24,8 @@
#pragma once
#include "2d/renderer/UIMeshBuffer.h"
#include "base/Ptr.h"
#include "base/Macros.h"
#include "base/Ptr.h"
#include "base/TypeDef.h"
#include "bindings/utils/BindingUtils.h"
#include "core/ArrayBuffer.h"
@@ -115,7 +115,7 @@ public:
inline void setIsMeshBuffer(bool isMeshBuffer) {
_drawInfoAttrs._isMeshBuffer = isMeshBuffer ? 1 : 0;
}
inline bool isVertexPositionInWorld() const {
return _drawInfoAttrs._isVertexPositionInWorld != 0;
}
@@ -262,9 +262,9 @@ private:
struct DrawInfoAttrs {
RenderDrawInfoType _drawInfoType{RenderDrawInfoType::COMP};
bool _vertDirty{false};
uint8_t _isMeshBuffer: 1;
uint8_t _isVertexPositionInWorld: 1;
uint8_t _padding: 6;
uint8_t _isMeshBuffer : 1;
uint8_t _isVertexPositionInWorld : 1;
uint8_t _padding : 6;
uint8_t _stride{0};
uint16_t _bufferId{0};
uint16_t _accId{0};
+2 -2
View File
@@ -33,11 +33,11 @@ RenderEntity::RenderEntity(RenderEntityType type) : _renderEntityType(type) {
} else {
ccnew_placement(&_dynamicDrawInfos) ccstd::vector<RenderDrawInfo*>();
}
_entityAttrLayout.enabledIndex = 0;
_entityAttrLayout.useLocal = 0;
_entityAttrLayout.paddings = 0;
_entitySharedBufferActor.initialize(&_entityAttrLayout, sizeof(EntityAttrLayout));
}
+9 -9
View File
@@ -49,7 +49,7 @@ enum class MaskMode : uint8_t {
MASK_NODE_INVERTED
};
enum class FillColorType: uint8_t {
enum class FillColorType : uint8_t {
COLOR = 0,
VERTEX,
};
@@ -62,9 +62,9 @@ struct EntityAttrLayout {
uint8_t colorA{255};
uint8_t maskMode{0};
FillColorType fillColorType{FillColorType::COLOR};
uint8_t enabledIndex: 1;
uint8_t useLocal: 1;
uint8_t paddings: 6;
uint8_t enabledIndex : 1;
uint8_t useLocal : 1;
uint8_t paddings : 6;
uint8_t paddings2{0};
};
@@ -99,7 +99,7 @@ public:
inline void setUseLocal(bool useLocal) {
_entityAttrLayout.useLocal = useLocal;
}
inline FillColorType getFillColorType() const { return _entityAttrLayout.fillColorType; }
inline Node* getNode() const { return _node; }
@@ -142,7 +142,7 @@ public:
inline RenderDrawInfo* getRenderDrawInfoAt(uint32_t index) {
return _renderEntityType == RenderEntityType::STATIC ? &(_staticDrawInfos[index]) : _dynamicDrawInfos[index];
}
inline uint32_t getPriority() const { return _entityAttrLayout.priority; }
private:
@@ -152,7 +152,7 @@ private:
// weak reference
Node* _renderTransform{nullptr};
bindings::NativeMemorySharedToScriptActor _entitySharedBufferActor;
union {
@@ -160,13 +160,13 @@ private:
ccstd::vector<RenderDrawInfo*> _dynamicDrawInfos;
};
EntityAttrLayout _entityAttrLayout;
StencilStage _stencilStage{StencilStage::DISABLED};
RenderEntityType _renderEntityType{RenderEntityType::STATIC};
uint8_t _staticDrawInfoSize{0};
bool _vbColorDirty{true};
uint8_t _paddings[1];
float _opacity{1.0F};
};
+3 -3
View File
@@ -23,12 +23,12 @@
****************************************************************************/
#pragma once
#include "base/Ptr.h"
#include "base/Macros.h"
#include "base/Ptr.h"
#include "base/TypeDef.h"
#include "renderer/gfx-base/GFXInputAssembler.h"
#include "renderer/gfx-base/GFXDef-common.h"
#include "renderer/gfx-base/GFXBuffer.h"
#include "renderer/gfx-base/GFXDef-common.h"
#include "renderer/gfx-base/GFXInputAssembler.h"
namespace cc {
+4 -4
View File
@@ -58,13 +58,13 @@ void UIModelProxy::activeSubModels() {
auto* vertexBuffer = _device->createBuffer({
gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST,
gfx::MemoryUsageBit::DEVICE,
65536 * _stride, // Uint16 can address 65536 vertices (indices 0–65535)
65536 * _stride, // Uint16 can address 65536 vertices (indices 0–65535)
_stride,
});
auto* indexBuffer = _device->createBuffer({
gfx::BufferUsageBit::INDEX | gfx::BufferUsageBit::TRANSFER_DST,
gfx::MemoryUsageBit::DEVICE,
65536 * sizeof(uint16_t) * 2, // Uint16 can address 65536 vertices (indices 0–65535)
65536 * sizeof(uint16_t) * 2, // Uint16 can address 65536 vertices (indices 0–65535)
sizeof(uint16_t),
});
gfx::BufferList vbReference;
@@ -133,8 +133,8 @@ void UIModelProxy::clear() {
return;
}
const auto& subModels = _model->getSubModels();
for (const auto &subModel : subModels) {
auto *ia = subModel->getInputAssembler();
for (const auto& subModel : subModels) {
auto* ia = subModel->getInputAssembler();
ia->setVertexCount(0);
ia->setIndexCount(0);
}
+2 -2
View File
@@ -531,14 +531,14 @@ void Mesh::initialize() {
uint32_t vertexCount = _struct.vertexBundles[prim.vertexBundelIndices[0]].view.count;
#if CC_OPTIMIZE_MESH_DATA
if (vertexCount <= 65536) { // Uint16 can address 65536 vertices (indices 0–65535)
dstStride >>= 1; // Reduce to short.
dstStride >>= 1; // Reduce to short.
dstSize >>= 1;
} else if (!gfxDevice->hasFeature(gfx::Feature::ELEMENT_INDEX_UINT)) {
continue; // Ignore this primitive
}
#else
if (!gfxDevice->hasFeature(gfx::Feature::ELEMENT_INDEX_UINT)) {
if (vertexCount > 65536) { // Uint16 can address 65536 vertices (indices 0–65535)
if (vertexCount > 65536) { // Uint16 can address 65536 vertices (indices 0–65535)
CC_LOG_WARNING("Device does not support UINT element index type and vertexCount (%u) is larger than ushort", vertexCount);
continue;
}
+1 -1
View File
@@ -310,7 +310,7 @@ Mesh::ICreateInfo MeshUtils::createDynamicMeshInfo(const IDynamicGeometry &geome
if (aOptions.has_value()) {
options = aOptions.value();
}
gfx::AttributeList attributes;
uint32_t stream = 0U;
@@ -25,8 +25,8 @@
#define LOG_TAG "AudioDecoderSLES"
#include "base/Macros.h"
#include "audio/android/AudioDecoderSLES.h"
#include "base/Macros.h"
#include "platform/FileUtils.h"
#include <mutex>
+50 -50
View File
@@ -29,9 +29,9 @@
#include <unistd.h>
// for native asset manager
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <android/log.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <android/log.h>
#endif
#include <sys/types.h>
@@ -45,11 +45,11 @@
#include "base/UTF8.h"
#include "base/memory/Memory.h"
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include "platform/android/FileUtils-android.h"
#include "platform/java/jni/JniHelper.h"
#include "platform/java/jni/JniImp.h"
#include "platform/android/FileUtils-android.h"
#include "platform/java/jni/JniHelper.h"
#include "platform/java/jni/JniImp.h"
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include "cocos/platform/openharmony/FileUtils-OpenHarmony.h"
#include "cocos/platform/openharmony/FileUtils-OpenHarmony.h"
#endif
#include "audio/android/AudioDecoder.h"
@@ -68,20 +68,20 @@ namespace {
AudioEngineImpl *gAudioImpl = nullptr;
int outputSampleRate = 44100;
#if CC_PLATFORM == CC_PLATFORM_ANDROID
int bufferSizeInFrames = 192;
int bufferSizeInFrames = 192;
#endif
void getAudioInfo() {
#if CC_PLATFORM == CC_PLATFORM_ANDROID
JNIEnv * env = JniHelper::getEnv();
jclass audioSystem = env->FindClass("android/media/AudioSystem");
jmethodID method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputSamplingRate", "()I");
outputSampleRate = env->CallStaticIntMethod(audioSystem, method);
method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputFrameCount", "()I");
bufferSizeInFrames = env->CallStaticIntMethod(audioSystem, method);
JNIEnv *env = JniHelper::getEnv();
jclass audioSystem = env->FindClass("android/media/AudioSystem");
jmethodID method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputSamplingRate", "()I");
outputSampleRate = env->CallStaticIntMethod(audioSystem, method);
method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputFrameCount", "()I");
bufferSizeInFrames = env->CallStaticIntMethod(audioSystem, method);
#else
// In openharmony, setting to 48K does not cause audio delays
outputSampleRate = 48000;
outputSampleRate = 48000;
#endif
}
} // namespace
@@ -123,8 +123,8 @@ static int fdGetter(const ccstd::string &url, off_t *start, off_t *length) {
AAsset_close(asset);
}
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
FileUtilsOpenHarmony* fileUtils = dynamic_cast<FileUtilsOpenHarmony*>(FileUtils::getInstance());
if(fileUtils) {
FileUtilsOpenHarmony *fileUtils = dynamic_cast<FileUtilsOpenHarmony *>(FileUtils::getInstance());
if (fileUtils) {
RawFileDescriptor64 descriptor;
fileUtils->getRawFileDescriptor(url, descriptor);
fd = descriptor.fd;
@@ -189,27 +189,27 @@ bool AudioEngineImpl::init() {
CC_LOG_ERROR("get the engine interface fail");
break;
}
#if CC_PLATFORM == CC_PLATFORM_ANDROID
// create output mix
const SLInterfaceID outputMixIIDs[] = {};
const SLboolean outputMixReqs[] = {};
result = (*_engineEngine)->CreateOutputMix(_engineEngine, &_outputMixObject, 0, outputMixIIDs, outputMixReqs);
if (SL_RESULT_SUCCESS != result) {
CC_LOG_ERROR("create output mix fail");
break;
}
#if CC_PLATFORM == CC_PLATFORM_ANDROID
// create output mix
const SLInterfaceID outputMixIIDs[] = {};
const SLboolean outputMixReqs[] = {};
result = (*_engineEngine)->CreateOutputMix(_engineEngine, &_outputMixObject, 0, outputMixIIDs, outputMixReqs);
if (SL_RESULT_SUCCESS != result) {
CC_LOG_ERROR("create output mix fail");
break;
}
// realize the output mix
result = (*_outputMixObject)->Realize(_outputMixObject, SL_BOOLEAN_FALSE);
if (SL_RESULT_SUCCESS != result) {
CC_LOG_ERROR("realize the output mix fail");
break;
}
// realize the output mix
result = (*_outputMixObject)->Realize(_outputMixObject, SL_BOOLEAN_FALSE);
if (SL_RESULT_SUCCESS != result) {
CC_LOG_ERROR("realize the output mix fail");
break;
}
_audioPlayerProvider = ccnew AudioPlayerProvider(_engineEngine, _outputMixObject, outputSampleRate, bufferSizeInFrames, fdGetter, &gCallerThreadUtils);
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
_audioPlayerProvider = ccnew AudioPlayerProvider(_engineEngine, outputSampleRate, fdGetter, &gCallerThreadUtils);
#endif
_audioPlayerProvider = ccnew AudioPlayerProvider(_engineEngine, _outputMixObject, outputSampleRate, bufferSizeInFrames, fdGetter, &gCallerThreadUtils);
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
_audioPlayerProvider = ccnew AudioPlayerProvider(_engineEngine, outputSampleRate, fdGetter, &gCallerThreadUtils);
#endif
ret = true;
} while (false);
@@ -227,14 +227,14 @@ int AudioEngineImpl::play2d(const ccstd::string &filePath, bool loop, float volu
auto audioId = AudioEngine::INVALID_AUDIO_ID;
do {
#if CC_PLATFORM == CC_PLATFORM_ANDROID
if (_engineEngine == nullptr || _audioPlayerProvider == nullptr) {
break;
}
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
if (_audioPlayerProvider == nullptr)
break;
#endif
#if CC_PLATFORM == CC_PLATFORM_ANDROID
if (_engineEngine == nullptr || _audioPlayerProvider == nullptr) {
break;
}
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
if (_audioPlayerProvider == nullptr)
break;
#endif
auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
@@ -443,12 +443,12 @@ PCMHeader AudioEngineImpl::getPCMHeader(const char *url) {
CC_LOG_DEBUG("file %s pcm data already cached", url);
return header;
}
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#if CC_PLATFORM == CC_PLATFORM_ANDROID
AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(_engineEngine, fileFullPath, bufferSizeInFrames, outputSampleRate, fdGetter);
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(
_engineEngine, fileFullPath, _audioPlayerProvider->getBufferSizeInFrames(), outputSampleRate, fdGetter);
#endif
#endif
if (decoder == nullptr) {
CC_LOG_DEBUG("decode %s failed, the file formate might not support", url);
return header;
@@ -482,12 +482,12 @@ ccstd::vector<uint8_t> AudioEngineImpl::getOriginalPCMBuffer(const char *url, ui
if (_audioPlayerProvider->getPcmData(url, data)) {
CC_LOG_DEBUG("file %s pcm data already cached", url);
} else {
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#if CC_PLATFORM == CC_PLATFORM_ANDROID
AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(_engineEngine, fileFullPath, bufferSizeInFrames, outputSampleRate, fdGetter);
#else
#else
AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(
_engineEngine, fileFullPath, _audioPlayerProvider->getBufferSizeInFrames(), outputSampleRate, fdGetter);
#endif
#endif
if (decoder == nullptr) {
CC_LOG_DEBUG("decode %s failed, the file formate might not support", url);
return pcmData;
+2 -2
View File
@@ -26,9 +26,9 @@
#include <SLES/OpenSLES.h>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <SLES/OpenSLES_Android.h>
#include <SLES/OpenSLES_Android.h>
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include <SLES/OpenSLES_Platform.h>
#include <SLES/OpenSLES_Platform.h>
#endif
#include <functional>
#include "audio/include/AudioDef.h"
+18 -18
View File
@@ -17,9 +17,9 @@
#pragma once
#include <cstdint>
#include <sys/types.h>
#include <pthread.h>
#include <sys/types.h>
#include <cstdint>
#include "audio/android/AudioBufferProvider.h"
#include "audio/android/AudioResamplerPublic.h"
@@ -160,7 +160,7 @@ private:
struct track_t;
typedef void (*hook_t)(track_t *t, int32_t *output, size_t numOutFrames, int32_t *temp, int32_t *aux); //NOLINT(modernize-use-using)
static const int BLOCKSIZE = 16; // 4 cache lines
static const int BLOCKSIZE = 16; // 4 cache lines
struct track_t {
uint32_t needs;
@@ -288,19 +288,19 @@ private:
};
// bitmask of allocated track names, where bit 0 corresponds to TRACK0 etc.
uint32_t mTrackNames;// NOLINT(readability-identifier-naming)
uint32_t mTrackNames; // NOLINT(readability-identifier-naming)
// bitmask of configured track names; ~0 if maxNumTracks == MAX_NUM_TRACKS,
// but will have fewer bits set if maxNumTracks < MAX_NUM_TRACKS
const uint32_t mConfiguredNames;// NOLINT(readability-identifier-naming)
const uint32_t mConfiguredNames; // NOLINT(readability-identifier-naming)
const uint32_t mSampleRate;// NOLINT(readability-identifier-naming)
const uint32_t mSampleRate; // NOLINT(readability-identifier-naming)
//cjh NBLog::Writer mDummyLog;
public:
//cjh void setLog(NBLog::Writer* log);
private:
state_t mState __attribute__((aligned(32)));// NOLINT(readability-identifier-naming)
state_t mState __attribute__((aligned(32))); // NOLINT(readability-identifier-naming)
// Call after changing either the enabled status of a track, or parameters of an enabled track.
// OK to call more often than that, but unnecessary.
@@ -309,19 +309,19 @@ private:
bool setChannelMasks(int name,
audio_channel_mask_t trackChannelMask, audio_channel_mask_t mixerChannelMask);
static void track__genericResample(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__nop(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__16BitsStereo(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__16BitsMono(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__genericResample(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__nop(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__16BitsStereo(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__16BitsMono(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void volumeRampStereo(track_t *t, int32_t *out, size_t frameCount, int32_t *temp, int32_t *aux);
static void volumeStereo(track_t *t, int32_t *out, size_t frameCount, int32_t *temp,
int32_t *aux);
static void process__validate(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__nop(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__genericNoResampling(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__genericResampling(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__OneTrack16BitsStereoNoResampling(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__validate(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__nop(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__genericNoResampling(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__genericResampling(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__OneTrack16BitsStereoNoResampling(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static int64_t calculateOutputPTS(const track_t &t, int64_t basePTS,
int outputFrameIndex);
@@ -347,11 +347,11 @@ private:
// multi-format process hooks
template <int MIXTYPE, typename TO, typename TI, typename TA>
static void process_NoResampleOneTrack(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process_NoResampleOneTrack(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
// multi-format track hooks
template <int MIXTYPE, typename TO, typename TI, typename TA>
static void track__Resample(track_t *t, TO *out, size_t frameCount, TO *temp __unused, TA *aux);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__Resample(track_t *t, TO *out, size_t frameCount, TO *temp __unused, TA *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
template <int MIXTYPE, typename TO, typename TI, typename TA>
static void track__NoResample(track_t *t, TO *out, size_t frameCount, TO *temp __unused, TA *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
@@ -33,8 +33,8 @@
#include "base/std/container/vector.h"
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
// for openharmony platform, buffer size is 4458 in normal latency mode, 240 in fast latency mode
#define MAX_AUDIO_BUFFER_SIZE 4458
// for openharmony platform, buffer size is 4458 in normal latency mode, 240 in fast latency mode
#define MAX_AUDIO_BUFFER_SIZE 4458
#endif
namespace cc {
@@ -42,14 +42,14 @@
#include "base/ThreadPool.h"
#include "base/memory/Memory.h"
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <sys/system_properties.h>
#include "audio/android/UrlAudioPlayer.h"
#include "audio/android/PcmAudioService.h"
#include <sys/system_properties.h>
#include "audio/android/PcmAudioService.h"
#include "audio/android/UrlAudioPlayer.h"
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include "cocos/platform/FileUtils.h"
#include "cocos/platform/openharmony/FileUtils-OpenHarmony.h"
#include "audio/openharmony/UrlAudioPlayer.h"
#include "audio/openharmony/PcmAudioService.h"
#include "audio/openharmony/PcmAudioService.h"
#include "audio/openharmony/UrlAudioPlayer.h"
#include "cocos/platform/FileUtils.h"
#include "cocos/platform/openharmony/FileUtils-OpenHarmony.h"
#endif
#include <algorithm> // for std::find_if
#include <cstdlib>
@@ -107,12 +107,9 @@ AudioPlayerProvider::AudioPlayerProvider(SLEngineItf engineItf, SLObjectItf outp
}
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
AudioPlayerProvider::AudioPlayerProvider(SLEngineItf engineItf, int deviceSampleRate,
const FdGetterCallback &fdGetterCallback,
const FdGetterCallback &fdGetterCallback,
ICallerThreadUtils *callerThreadUtils)
: _engineItf(engineItf), _deviceSampleRate(deviceSampleRate), _fdGetterCallback(fdGetterCallback),
_callerThreadUtils(callerThreadUtils), _pcmAudioService(nullptr),
_mixController(nullptr), _threadPool(LegacyThreadPool::newCachedThreadPool(1, 8, 5, 2, 2))
{
: _engineItf(engineItf), _deviceSampleRate(deviceSampleRate), _fdGetterCallback(fdGetterCallback), _callerThreadUtils(callerThreadUtils), _pcmAudioService(nullptr), _mixController(nullptr), _threadPool(LegacyThreadPool::newCachedThreadPool(1, 8, 5, 2, 2)) {
_mixController = ccnew AudioMixerController(_deviceSampleRate, 2);
_pcmAudioService = ccnew PcmAudioService();
_pcmAudioService->init(_mixController, 2, deviceSampleRate, &_bufferSizeInFrames);
@@ -364,13 +361,13 @@ AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo(
fileSize = length;
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
RawFileDescriptor64 descriptor;
FileUtilsOpenHarmony* fileUtils = static_cast<FileUtilsOpenHarmony*>(FileUtils::getInstance());
if(!fileUtils) {
FileUtilsOpenHarmony *fileUtils = static_cast<FileUtilsOpenHarmony *>(FileUtils::getInstance());
if (!fileUtils) {
return info;
}
FileUtils::Status status = fileUtils->getRawFileDescriptor(audioFilePath, descriptor);
if(status != FileUtils::Status::OK || descriptor.fd<= 0) {
if (status != FileUtils::Status::OK || descriptor.fd <= 0) {
ALOGE("Failed to open file descriptor for %s", audioFilePath.c_str());
return info;
}
@@ -412,9 +409,9 @@ bool AudioPlayerProvider::isSmallFile(const AudioFileInfo &info) { //NOLINT(read
extension = audioFileInfo.url.substr(pos);
}
auto *iter = std::find_if(std::begin(gAudioFileIndicator), std::end(gAudioFileIndicator),
[&extension](const AudioFileIndicator &judge) -> bool {
return judge.extension == extension;
});
[&extension](const AudioFileIndicator &judge) -> bool {
return judge.extension == extension;
});
if (iter != std::end(gAudioFileIndicator)) {
// ALOGV("isSmallFile: found: %s: ", iter->extension.c_str());
@@ -472,19 +469,18 @@ UrlAudioPlayer *AudioPlayerProvider::createUrlAudioPlayer(
}
#if CC_PLATFORM == CC_PLATFORM_ANDROID
SLuint32 locatorType = info.assetFd->getFd() > 0 ? SL_DATALOCATOR_ANDROIDFD : SL_DATALOCATOR_URI;
auto *urlPlayer = new (std::nothrow) UrlAudioPlayer(_engineItf, _outputMixObject, _callerThreadUtils);
bool ret = urlPlayer->prepare(info.url, locatorType, info.assetFd, info.start, info.length);
auto *urlPlayer = new (std::nothrow) UrlAudioPlayer(_engineItf, _outputMixObject, _callerThreadUtils);
bool ret = urlPlayer->prepare(info.url, locatorType, info.assetFd, info.start, info.length);
if (!ret) {
SL_SAFE_DELETE(urlPlayer);
}
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
auto urlPlayer = new (std::nothrow) UrlAudioPlayer(_callerThreadUtils);
bool ret = urlPlayer->prepare(info.url, info.assetFd, info.start, info.length);
if (!ret)
{
if (urlPlayer != nullptr) {
if (!ret) {
if (urlPlayer != nullptr) {
delete urlPlayer;
urlPlayer = nullptr;
urlPlayer = nullptr;
}
}
#endif
+17 -18
View File
@@ -18,9 +18,9 @@
#include <cstdint>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <android/log.h>
#include <sys/system_properties.h>
#include <sys/types.h>
#include <android/log.h>
#include <sys/system_properties.h>
#include <sys/types.h>
#endif
#include "audio/android/AudioBufferProvider.h"
@@ -108,21 +108,20 @@ protected:
int64_t calculateOutputPTS(int outputFrameIndex);
const int32_t mChannelCount;// NOLINT(readability-identifier-naming)
const int32_t mSampleRate;// NOLINT(readability-identifier-naming)
int32_t mInSampleRate;// NOLINT(readability-identifier-naming)
AudioBufferProvider::Buffer mBuffer;// NOLINT(readability-identifier-naming)
const int32_t mChannelCount; // NOLINT(readability-identifier-naming)
const int32_t mSampleRate; // NOLINT(readability-identifier-naming)
int32_t mInSampleRate; // NOLINT(readability-identifier-naming)
AudioBufferProvider::Buffer mBuffer; // NOLINT(readability-identifier-naming)
union {
int16_t mVolume[2];// NOLINT(readability-identifier-naming)
uint32_t mVolumeRL;// NOLINT(readability-identifier-naming)
int16_t mVolume[2]; // NOLINT(readability-identifier-naming)
uint32_t mVolumeRL; // NOLINT(readability-identifier-naming)
};
int16_t mTargetVolume[2];// NOLINT(readability-identifier-naming)
size_t mInputIndex;// NOLINT(readability-identifier-naming)
int32_t mPhaseIncrement;// NOLINT(readability-identifier-naming)
uint32_t mPhaseFraction;// NOLINT(readability-identifier-naming)
uint64_t mLocalTimeFreq;// NOLINT(readability-identifier-naming)
int64_t mPTS;// NOLINT(readability-identifier-naming)
int16_t mTargetVolume[2]; // NOLINT(readability-identifier-naming)
size_t mInputIndex; // NOLINT(readability-identifier-naming)
int32_t mPhaseIncrement; // NOLINT(readability-identifier-naming)
uint32_t mPhaseFraction; // NOLINT(readability-identifier-naming)
uint64_t mLocalTimeFreq; // NOLINT(readability-identifier-naming)
int64_t mPTS; // NOLINT(readability-identifier-naming)
// returns the inFrameCount required to generate outFrameCount frames.
//
@@ -155,7 +154,7 @@ protected:
return (static_cast<size_t>(outFrameCount) * mInSampleRate + (mSampleRate - 1)) / mSampleRate;
}
inline float clampFloatVol(float volume) {//NOLINT(readability-identifier-naming, readability-convert-member-functions-to-static)
inline float clampFloatVol(float volume) { //NOLINT(readability-identifier-naming, readability-convert-member-functions-to-static)
float ret = 0.0F;
if (volume > UNITY_GAIN_FLOAT) {
ret = UNITY_GAIN_FLOAT;
@@ -166,7 +165,7 @@ protected:
}
private:
const src_quality mQuality;// NOLINT(readability-identifier-naming)
const src_quality mQuality; // NOLINT(readability-identifier-naming)
// Return 'true' if the quality level is supported without explicit request
static bool qualityIsSupported(src_quality quality);
@@ -19,8 +19,8 @@
#include <stdint.h>
#include <sys/types.h>
#include "audio/android/AudioResampler.h"
#include "audio/android/AudioBufferProvider.h"
#include "audio/android/AudioResampler.h"
namespace cc {
// ----------------------------------------------------------------------------
+2 -2
View File
@@ -29,9 +29,9 @@
#include <SLES/OpenSLES.h>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <SLES/OpenSLES_Android.h>
#include <SLES/OpenSLES_Android.h>
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include <SLES/OpenSLES_Platform.h>
#include <SLES/OpenSLES_Platform.h>
#endif
#include <functional>
+19 -19
View File
@@ -25,28 +25,28 @@
#define LOG_TAG "PcmAudioService"
#include "base/Macros.h"
#include "audio/android/PcmAudioService.h"
#include "audio/android/AudioMixerController.h"
#include "audio/android/utils/Compat.h"
#include "base/Macros.h"
namespace cc {
static ccstd::vector<char> __silenceData;//NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static ccstd::vector<char> __silenceData; //NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
#define AUDIO_PLAYER_BUFFER_COUNT (2)
class SLPcmAudioPlayerCallbackProxy {
public:
#if CC_PLATFORM == CC_PLATFORM_ANDROID
static void samplePlayerCallback(CCSLBufferQueueItf bq, void *context) {
static void samplePlayerCallback(CCSLBufferQueueItf bq, void *context){
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
static void samplePlayerCallback(CCSLBufferQueueItf bq, void *context, SLuint32 size) {
#endif
auto *thiz = reinterpret_cast<PcmAudioService *>(context);
thiz->bqFetchBufferCallback(bq);
}
};
thiz->bqFetchBufferCallback(bq);
}
}; // namespace cc
PcmAudioService::PcmAudioService(SLEngineItf engineItf, SLObjectItf outputMixObject)
: _engineItf(engineItf), _outputMixObj(outputMixObject), _playObj(nullptr), _playItf(nullptr), _volumeItf(nullptr), _bufferQueueItf(nullptr), _numChannels(-1), _sampleRate(-1), _bufferSizeInBytes(0), _controller(nullptr) {
@@ -59,12 +59,12 @@ PcmAudioService::~PcmAudioService() {
}
bool PcmAudioService::enqueue() {
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
// We need to call this interface in openharmony, otherwise there will be noise
SLuint8 *buffer = nullptr;
SLuint32 size = 0;
(*_bufferQueueItf)->GetBuffer(_bufferQueueItf, &buffer, &size);
#endif
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
// We need to call this interface in openharmony, otherwise there will be noise
SLuint8 *buffer = nullptr;
SLuint32 size = 0;
(*_bufferQueueItf)->GetBuffer(_bufferQueueItf, &buffer, &size);
#endif
if (_controller->hasPlayingTacks()) {
if (_controller->isPaused()) {
SLresult r = (*_bufferQueueItf)->Enqueue(_bufferQueueItf, __silenceData.data(), __silenceData.size());
@@ -141,7 +141,7 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in
SLresult r;
r = (*_engineItf)->CreateAudioPlayer(_engineItf, &_playObj, &source, &sink, sizeof(ids) / sizeof(ids[0]), ids, req);//NOLINT(bugprone-sizeof-expression)
r = (*_engineItf)->CreateAudioPlayer(_engineItf, &_playObj, &source, &sink, sizeof(ids) / sizeof(ids[0]), ids, req); //NOLINT(bugprone-sizeof-expression)
SL_RETURN_VAL_IF_FAILED(r, false, "CreateAudioPlayer failed");
r = (*_playObj)->Realize(_playObj, SL_BOOLEAN_FALSE);
@@ -162,12 +162,12 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in
if (__silenceData.empty()) {
__silenceData.resize(_numChannels * _bufferSizeInBytes, 0x00);
}
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
// We need to call this interface in openharmony, otherwise there will be noise
SLuint8 *buffer = nullptr;
SLuint32 size = 0;
(*_bufferQueueItf)->GetBuffer(_bufferQueueItf, &buffer, &size);
#endif
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
// We need to call this interface in openharmony, otherwise there will be noise
SLuint8 *buffer = nullptr;
SLuint32 size = 0;
(*_bufferQueueItf)->GetBuffer(_bufferQueueItf, &buffer, &size);
#endif
r = (*_bufferQueueItf)->Enqueue(_bufferQueueItf, __silenceData.data(), __silenceData.size());
SL_RETURN_VAL_IF_FAILED(r, false, "_bufferQueueItf Enqueue failed");
@@ -26,17 +26,17 @@
#define LOG_TAG "UrlAudioPlayer"
#include "audio/android/UrlAudioPlayer.h"
#include "audio/android/ICallerThreadUtils.h"
#include "base/std/container/vector.h"
#include "base/Macros.h"
#include <cmath>
#include <algorithm> // for std::find
#include <cmath>
#include "audio/android/ICallerThreadUtils.h"
#include "base/Macros.h"
#include "base/std/container/vector.h"
namespace {
std::mutex __playerContainerMutex;//NOLINT(bugprone-reserved-identifier,readability-identifier-naming)
ccstd::vector<cc::UrlAudioPlayer *> __playerContainer;//NOLINT(bugprone-reserved-identifier,readability-identifier-naming)
std::once_flag __onceFlag;//NOLINT(bugprone-reserved-identifier,readability-identifier-naming)
std::mutex __playerContainerMutex; //NOLINT(bugprone-reserved-identifier,readability-identifier-naming)
ccstd::vector<cc::UrlAudioPlayer *> __playerContainer; //NOLINT(bugprone-reserved-identifier,readability-identifier-naming)
std::once_flag __onceFlag; //NOLINT(bugprone-reserved-identifier,readability-identifier-naming)
} // namespace
@@ -216,7 +216,7 @@ float UrlAudioPlayer::getDuration() const {
if (duration == SL_TIME_UNKNOWN) {
return -1.0F;
} else {// NOLINT(readability-else-after-return)
} else { // NOLINT(readability-else-after-return)
const_cast<UrlAudioPlayer *>(this)->_duration = duration / 1000.0F;
if (_duration <= 0) {
+3 -3
View File
@@ -22,10 +22,10 @@
#include <strings.h>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <sys/cdefs.h>
#include <sys/cdefs.h>
#endif
#ifdef __cplusplus
#ifdef __cplusplus
extern "C" {
#endif
@@ -41,7 +41,7 @@ static inline int popcountll(unsigned long long x) {
return __builtin_popcountll(x);
}
#ifdef __cplusplus
#ifdef __cplusplus
}
#endif
+35 -36
View File
@@ -34,10 +34,10 @@
#include <time.h>
#include <unistd.h>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <android/log.h>
#include <android/log.h>
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include <hilog/log.h>
#define LOG_VERBOSE LOG_INFO
#include <hilog/log.h>
#define LOG_VERBOSE LOG_INFO
#endif
#ifdef __cplusplus
@@ -90,11 +90,11 @@ extern "C" {
* Simplified macro to send a verbose log message using the current LOG_TAG.
*/
#ifndef ALOGV
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define __ALOGV(...) ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define __ALOGV(...) ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__))
#endif
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define __ALOGV(...) ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define __ALOGV(...) ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__))
#endif
#if LOG_NDEBUG
#define ALOGV(...) \
do { \
@@ -413,23 +413,23 @@ extern "C" {
* is -inverted- from the normal assert() semantics.
*/
#ifndef LOG_ALWAYS_FATAL_IF
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define LOG_ALWAYS_FATAL_IF(cond, ...) \
((__predict_false(cond)) \
? ((void)android_printAssert(#cond, LOG_TAG, ##__VA_ARGS__)) \
: (void)0)
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define LOG_ALWAYS_FATAL_IF(cond, ...) ((void)0 )
#endif
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define LOG_ALWAYS_FATAL_IF(cond, ...) \
((__predict_false(cond)) \
? ((void)android_printAssert(#cond, LOG_TAG, ##__VA_ARGS__)) \
: (void)0)
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define LOG_ALWAYS_FATAL_IF(cond, ...) ((void)0)
#endif
#endif
#ifndef LOG_ALWAYS_FATAL
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define LOG_ALWAYS_FATAL(...) \
(((void)android_printAssert(NULL, LOG_TAG, ##__VA_ARGS__)))
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define LOG_ALWAYS_FATAL(...) ((void) OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#endif
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define LOG_ALWAYS_FATAL(...) \
(((void)android_printAssert(NULL, LOG_TAG, ##__VA_ARGS__)))
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define LOG_ALWAYS_FATAL(...) ((void)OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#endif
#endif
/*
@@ -476,26 +476,25 @@ extern "C" {
* The second argument may be NULL or "" to indicate the "global" tag.
*/
#ifndef ALOG
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define ALOG(priority, tag, ...) \
LOG_PRI(ANDROID_##priority, tag, __VA_ARGS__)
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define ALOG(priority, tag, ...) \
LOG_PRI(priority, tag, __VA_ARGS__)
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define ALOG(priority, tag, ...) \
LOG_PRI(ANDROID_##priority, tag, __VA_ARGS__)
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define ALOG(priority, tag, ...) \
LOG_PRI(priority, tag, __VA_ARGS__)
#endif
#endif
#endif
/*
* Log macro that allows you to specify a number for the priority.
*/
#ifndef LOG_PRI
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define LOG_PRI(priority, tag, ...) \
android_printLog(priority, tag, __VA_ARGS__)
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define LOG_PRI(priority, tag, ...) ((void) OH_LOG_Print(LOG_APP, priority, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#endif
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define LOG_PRI(priority, tag, ...) \
android_printLog(priority, tag, __VA_ARGS__)
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define LOG_PRI(priority, tag, ...) ((void)OH_LOG_Print(LOG_APP, priority, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#endif
#endif
/*
+8 -9
View File
@@ -17,16 +17,15 @@
#ifndef COCOS_LIB_UTILS_COMPAT_H
#define COCOS_LIB_UTILS_COMPAT_H
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <unistd.h>
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>
#include <unistd.h>
#elif CC_PLATFORM == CC_PLATFORM_WINDOWS
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include <SLES/OpenSLES_OpenHarmony.h>
#include <SLES/OpenSLES_Platform.h>
#include <SLES/OpenSLES_OpenHarmony.h>
#include <SLES/OpenSLES_Platform.h>
#endif
#if defined(__APPLE__)
@@ -97,11 +96,11 @@ static inline ssize_t pwrite64(int fd, const void *buf, size_t nbytes, off64_t o
#if CC_PLATFORM == CC_PLATFORM_ANDROID
typedef SLAndroidSimpleBufferQueueItf CCSLBufferQueueItf;
#define CC_SL_IDD_BUFFER_QUEUE SL_IID_ANDROIDSIMPLEBUFFERQUEUE
#define CC_SL_IDD_BUFFER_QUEUE SL_IID_ANDROIDSIMPLEBUFFERQUEUE
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
typedef SLOHBufferQueueItf CCSLBufferQueueItf;
#define CC_SL_IDD_BUFFER_QUEUE SL_IID_OH_BUFFERQUEUE
#define __unused
#define CC_SL_IDD_BUFFER_QUEUE SL_IID_OH_BUFFERQUEUE
#define __unused
#endif
#endif /* COCOS_LIB_UTILS_COMPAT_H */
+1 -1
View File
@@ -17,8 +17,8 @@
#ifndef COCOS_ERRORS_H
#define COCOS_ERRORS_H
#include <sys/types.h>
#include <errno.h>
#include <sys/types.h>
namespace cc {
+1 -1
View File
@@ -27,8 +27,8 @@
#import <OpenAL/al.h>
#include <mutex>
#include <functional>
#include <mutex>
#include "base/std/container/string.h"
#include "audio/apple/AudioMacros.h"
@@ -19,7 +19,7 @@
#include <stdint.h>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <sys/cdefs.h>
#include <sys/cdefs.h>
#endif
#include "audio/android/audio.h"
@@ -25,7 +25,7 @@
#include <stdio.h>
#include <stdlib.h>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <sys/cdefs.h>
#include <sys/cdefs.h>
#endif
/* The memcpy_* conversion routines are designed to work in-place on same dst as src
@@ -178,7 +178,7 @@ bool AudioEngineImpl::init() {
alcMakeContextCurrent(sALContext);
std::fill(std::begin(_alSources), std::end(_alSources), 0);
std::fill(std::begin(_alSources), std::end(_alSources), 0);
alGenSources(MAX_AUDIOINSTANCES, _alSources);
auto alError = alGetError();
@@ -26,9 +26,9 @@ THE SOFTWARE.
#define LOG_TAG "PcmAudioService"
#include "audio/openharmony/PcmAudioService.h"
#include <deviceinfo.h>
#include "audio/android/AudioMixerController.h"
#include "audio/android/cutils/log.h"
#include <deviceinfo.h>
namespace cc {
@@ -106,10 +106,10 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in
OH_AudioRenderer_Callbacks callbacks;
static int sdkApi = OH_GetSdkApiVersion();
if(sdkApi >= 21) {
if (sdkApi >= 21) {
callbacks.OH_AudioRenderer_OnWriteData = nullptr;
} else {
callbacks.OH_AudioRenderer_OnWriteData = reinterpret_cast<int32_t (*)(OH_AudioRenderer*,void* ,void* ,int32_t)>(AudioRendererOnWriteData);
callbacks.OH_AudioRenderer_OnWriteData = reinterpret_cast<int32_t (*)(OH_AudioRenderer *, void *, void *, int32_t)>(AudioRendererOnWriteData);
}
callbacks.OH_AudioRenderer_OnInterruptEvent = AudioRendererOnInterrupt;
callbacks.OH_AudioRenderer_OnError = nullptr;
@@ -118,9 +118,9 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in
if (ret != AUDIOSTREAM_SUCCESS) {
return false;
}
if(sdkApi >= 21) {
ret = OH_AudioStreamBuilder_SetRendererWriteDataCallback(_builder, AudioRendererOnWriteData, this);
if (sdkApi >= 21) {
ret = OH_AudioStreamBuilder_SetRendererWriteDataCallback(_builder, AudioRendererOnWriteData, this);
if (ret != AUDIOSTREAM_SUCCESS) {
return false;
}
@@ -26,8 +26,8 @@ THE SOFTWARE.
#define LOG_TAG "UrlAudioPlayer"
#include "audio/openharmony/UrlAudioPlayer.h"
#include <map>
#include <algorithm> // for std::find
#include <map>
#include "audio/android/ICallerThreadUtils.h"
#include "audio/android/cutils/log.h"
#include "cocos/application/ApplicationManager.h"
+12 -12
View File
@@ -209,23 +209,23 @@ void Log::logMessage(LogType type, LogLevel level, const char *formats, ...) {
::LogLevel ohosLoglevel = ::LogLevel::LOG_DEBUG;
switch (level) {
case LogLevel::LEVEL_DEBUG:
ohosLoglevel = ::LogLevel::LOG_DEBUG;
break;
ohosLoglevel = ::LogLevel::LOG_DEBUG;
break;
case LogLevel::INFO:
ohosLoglevel = ::LogLevel::LOG_INFO;
break;
ohosLoglevel = ::LogLevel::LOG_INFO;
break;
case LogLevel::WARN:
ohosLoglevel = ::LogLevel::LOG_WARN;
break;
ohosLoglevel = ::LogLevel::LOG_WARN;
break;
case LogLevel::ERR:
ohosLoglevel = ::LogLevel::LOG_ERROR;
break;
ohosLoglevel = ::LogLevel::LOG_ERROR;
break;
case LogLevel::FATAL:
ohosLoglevel = ::LogLevel::LOG_FATAL;
break;
ohosLoglevel = ::LogLevel::LOG_FATAL;
break;
default:
ohosLoglevel = ::LogLevel::LOG_INFO;
break;
ohosLoglevel = ::LogLevel::LOG_INFO;
break;
}
OH_LOG_Print(LOG_APP, ohosLoglevel, LOG_DOMAIN, "HMG_LOG", "%{public}s", buff);
#else
+3 -3
View File
@@ -346,7 +346,7 @@ void Scheduler::runFunctionsToBePerformedInCocosThread() {
// fixed #4123: Save the callback functions, they must be invoked after '_performMutex.unlock()', otherwise if new functions are added in callback, it will cause thread deadlock.
auto temp = std::move(_functionsToPerform);
_performMutex.unlock();
auto iter = temp.begin();
for (; iter != temp.end(); ++iter) {
nowTime = std::chrono::steady_clock::now();
@@ -355,10 +355,10 @@ void Scheduler::runFunctionsToBePerformedInCocosThread() {
if (passedMS > 16) {
break;
}
(*iter)();
}
std::lock_guard<std::mutex> lk(_performMutex);
_functionsToPerform.insert(_functionsToPerform.begin(), std::make_move_iterator(iter), std::make_move_iterator(temp.end()));
}
+1 -1
View File
@@ -268,7 +268,7 @@ public:
* @js NA
*/
void removeAllFunctionsToBePerformedInCocosThread();
void runFunctionsToBePerformedInCocosThread();
bool isCurrentTargetSalvaged() const { return _currentTargetSalvaged; };
+25 -25
View File
@@ -42,38 +42,38 @@ using index_t = int32_t;
#define CC_ENUM_CONVERSION_OPERATOR(T) \
inline std::underlying_type_t<T> toNumber(const T v) { return static_cast<std::underlying_type_t<T>>(v); }
#define CC_ENUM_BITWISE_OPERATORS(T) \
constexpr bool operator!(const T v) { return !static_cast<std::underlying_type_t<T>>(v); } \
constexpr T operator~(const T v) { return static_cast<T>(~static_cast<std::underlying_type_t<T>>(v)); } \
#define CC_ENUM_BITWISE_OPERATORS(T) \
constexpr bool operator!(const T v) { return !static_cast<std::underlying_type_t<T>>(v); } \
constexpr T operator~(const T v) { return static_cast<T>(~static_cast<std::underlying_type_t<T>>(v)); } \
constexpr bool operator||(const T lhs, const T rhs) { return (static_cast<std::underlying_type_t<T>>(lhs) || static_cast<std::underlying_type_t<T>>(rhs)); } \
constexpr bool operator&&(const T lhs, const T rhs) { return (static_cast<std::underlying_type_t<T>>(lhs) && static_cast<std::underlying_type_t<T>>(rhs)); } \
constexpr T operator|(const T lhs, const T rhs) { return static_cast<T>(static_cast<std::underlying_type_t<T>>(lhs) | static_cast<std::underlying_type_t<T>>(rhs)); } \
constexpr T operator&(const T lhs, const T rhs) { return static_cast<T>(static_cast<std::underlying_type_t<T>>(lhs) & static_cast<std::underlying_type_t<T>>(rhs)); } \
constexpr T operator^(const T lhs, const T rhs) { return static_cast<T>(static_cast<std::underlying_type_t<T>>(lhs) ^ static_cast<std::underlying_type_t<T>>(rhs)); } \
constexpr T operator+(const T lhs, const T rhs) { return static_cast<T>(static_cast<std::underlying_type_t<T>>(lhs) + static_cast<std::underlying_type_t<T>>(rhs)); } \
constexpr T operator+(const T lhs, bool rhs) { return static_cast<T>(static_cast<std::underlying_type_t<T>>(lhs) + rhs); } \
constexpr T operator+(const T lhs, bool rhs) { return static_cast<T>(static_cast<std::underlying_type_t<T>>(lhs) + rhs); } \
constexpr void operator|=(T &lhs, const T rhs) { lhs = static_cast<T>(static_cast<std::underlying_type_t<T>>(lhs) | static_cast<std::underlying_type_t<T>>(rhs)); } \
constexpr void operator&=(T &lhs, const T rhs) { lhs = static_cast<T>(static_cast<std::underlying_type_t<T>>(lhs) & static_cast<std::underlying_type_t<T>>(rhs)); } \
constexpr void operator^=(T &lhs, const T rhs) { lhs = static_cast<T>(static_cast<std::underlying_type_t<T>>(lhs) ^ static_cast<std::underlying_type_t<T>>(rhs)); } \
constexpr bool hasFlag(const T flags, const T flagToTest) { \
using ValueType = std::underlying_type_t<T>; \
CC_ASSERT((static_cast<ValueType>(flagToTest) & (static_cast<ValueType>(flagToTest) - 1)) == 0); \
return (static_cast<ValueType>(flags) & static_cast<ValueType>(flagToTest)) != 0; \
} \
constexpr bool hasAnyFlags(const T flags, const T flagsToTest) { \
using ValueType = std::underlying_type_t<T>; \
return (static_cast<ValueType>(flags) & static_cast<ValueType>(flagsToTest)) != 0; \
} \
constexpr bool hasAllFlags(const T flags, const T flagsToTest) { \
using ValueType = std::underlying_type_t<T>; \
return (static_cast<ValueType>(flags) & static_cast<ValueType>(flagsToTest)) == static_cast<ValueType>(flagsToTest); \
} \
constexpr T addFlags(T &flags, const T flagsToAdd) { \
flags |= flagsToAdd; \
return flags; \
} \
constexpr T removeFlags(T &flags, const T flagsToRemove) { \
flags &= ~flagsToRemove; \
return flags; \
} \
constexpr bool hasFlag(const T flags, const T flagToTest) { \
using ValueType = std::underlying_type_t<T>; \
CC_ASSERT((static_cast<ValueType>(flagToTest) & (static_cast<ValueType>(flagToTest) - 1)) == 0); \
return (static_cast<ValueType>(flags) & static_cast<ValueType>(flagToTest)) != 0; \
} \
constexpr bool hasAnyFlags(const T flags, const T flagsToTest) { \
using ValueType = std::underlying_type_t<T>; \
return (static_cast<ValueType>(flags) & static_cast<ValueType>(flagsToTest)) != 0; \
} \
constexpr bool hasAllFlags(const T flags, const T flagsToTest) { \
using ValueType = std::underlying_type_t<T>; \
return (static_cast<ValueType>(flags) & static_cast<ValueType>(flagsToTest)) == static_cast<ValueType>(flagsToTest); \
} \
constexpr T addFlags(T &flags, const T flagsToAdd) { \
flags |= flagsToAdd; \
return flags; \
} \
constexpr T removeFlags(T &flags, const T flagsToRemove) { \
flags &= ~flagsToRemove; \
return flags; \
} \
CC_ENUM_CONVERSION_OPERATOR(T)
+2 -2
View File
@@ -34,8 +34,8 @@
#include "ConvertUTF/ConvertUTF.h"
#if CC_USE_SIMD_UTF
#include "simdutf/simdutf.cpp" //NOLINT
#include "simdutf/simdutf.h"
#include "simdutf/simdutf.cpp" //NOLINT
#include "simdutf/simdutf.h"
#endif
#include "base/Log.h"
+1 -1
View File
@@ -24,8 +24,8 @@
#include "MessageQueue.h"
#include "AutoReleasePool.h"
#include "base/Utils.h"
#include "base/Log.h"
#include "base/Utils.h"
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <unistd.h>
@@ -37,7 +37,7 @@ HandleObject::HandleObject(Object *obj)
}
}
HandleObject::HandleObject(HandleObject &&o) noexcept{
HandleObject::HandleObject(HandleObject &&o) noexcept {
_obj = o._obj;
o._obj = nullptr;
}
@@ -49,7 +49,7 @@ HandleObject::~HandleObject() {
}
}
HandleObject& HandleObject::operator=(HandleObject &&o) noexcept {
HandleObject &HandleObject::operator=(HandleObject &&o) noexcept {
_obj = o._obj;
o._obj = nullptr;
return *this;
@@ -98,10 +98,10 @@ public:
return (_obj == nullptr);
}
HandleObject(HandleObject &&) noexcept;
HandleObject& operator=(HandleObject &&) noexcept;
HandleObject &operator=(HandleObject &&) noexcept;
HandleObject(const HandleObject &) = delete;
HandleObject& operator=(const HandleObject &) = delete;
HandleObject &operator=(const HandleObject &) = delete;
void *operator new(size_t size) = delete;
void operator delete(void *, size_t) = delete;
@@ -169,12 +169,12 @@ private:
if (kls != nullptr && kls != itr->second->_getClass()) {
continue;
}
// JS object may be null when it is obtained on zhe JSVM brach of the 5.1 ROMS
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSVM
if(itr->second->_getJSObject() == nullptr) {
continue;
}
#endif
// JS object may be null when it is obtained on zhe JSVM brach of the 5.1 ROMS
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSVM
if (itr->second->_getJSObject() == nullptr) {
continue;
}
#endif
eleCount++;
CC_ASSERT_LT(eleCount, 2);
eachCallback(itr->second);
-2
View File
@@ -43,12 +43,10 @@
#include "chakracore/Object.h"
#endif
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_NAPI
#include "napi/Object.h"
#endif
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSVM
#include "jsvm/Object.h"
#endif
@@ -27,10 +27,10 @@
#include <cmath>
#include <memory>
#include <type_traits>
#include "base/HasMemberFunction.h"
#include "base/Ptr.h"
#include "base/RefCounted.h"
#include "base/memory/Memory.h"
#include "base/HasMemberFunction.h"
namespace se {
@@ -116,7 +116,7 @@ public:
explicit CCIntrusivePtrPrivateObject(const cc::IntrusivePtr<T> &p) : _ptr(p) {}
explicit CCIntrusivePtrPrivateObject(cc::IntrusivePtr<T> &&p) : _ptr(std::move(p)) {}
~CCIntrusivePtrPrivateObject() override {
if constexpr (cc::has_setScriptObject<T,void(se::Object *)>::value) {
if constexpr (cc::has_setScriptObject<T, void(se::Object *)>::value) {
_ptr->setScriptObject(nullptr);
}
}
+1 -1
View File
@@ -24,13 +24,13 @@
****************************************************************************/
#include "Value.h"
#include <cassert>
#include <cctype>
#include <cmath>
#include <cstdint>
#include <sstream>
#include <type_traits>
#include "Object.h"
#include <cassert>
namespace se {
+7 -7
View File
@@ -36,11 +36,11 @@
#define SCRIPT_ENGINE_JSVM 6
#ifndef SCRIPT_ENGINE_TYPE
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define SCRIPT_ENGINE_TYPE SCRIPT_ENGINE_NAPI
#else
#define SCRIPT_ENGINE_TYPE SCRIPT_ENGINE_V8
#endif
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define SCRIPT_ENGINE_TYPE SCRIPT_ENGINE_NAPI
#else
#define SCRIPT_ENGINE_TYPE SCRIPT_ENGINE_V8
#endif
#endif
#define SE_LOG_TO_JS_ENV 0 // print log to JavaScript environment, for example DevTools
@@ -65,9 +65,9 @@ CC_FORMAT_HINT(3, 4)
void selogMessage(cc::LogLevel level, const char *tag, const char *format, ...);
#if CC_DEBUG
#define SE_LOGD(...) selogMessage(cc::LogLevel::LEVEL_DEBUG, "D/", ##__VA_ARGS__)
#define SE_LOGD(...) selogMessage(cc::LogLevel::LEVEL_DEBUG, "D/", ##__VA_ARGS__)
#else
#define SE_LOGD(...)
#define SE_LOGD(...)
#endif
#define SE_LOGE(...) selogMessage(cc::LogLevel::ERR, "E/", ##__VA_ARGS__)
@@ -3,7 +3,7 @@
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#include "callback_queue.h"
#include "callback_queue.h"
namespace node {
@@ -11,87 +11,87 @@ template <typename R, typename... Args>
template <typename Fn>
std::unique_ptr<typename CallbackQueue<R, Args...>::Callback>
CallbackQueue<R, Args...>::CreateCallback(Fn&& fn, CallbackFlags::Flags flags) {
return std::make_unique<CallbackImpl<Fn>>(std::move(fn), flags);
return std::make_unique<CallbackImpl<Fn>>(std::move(fn), flags);
}
template <typename R, typename... Args>
std::unique_ptr<typename CallbackQueue<R, Args...>::Callback>
CallbackQueue<R, Args...>::Shift() {
std::unique_ptr<Callback> ret = std::move(head_);
if (ret) {
head_ = ret->get_next();
if (!head_)
tail_ = nullptr; // The queue is now empty.
size_--;
}
return ret;
std::unique_ptr<Callback> ret = std::move(head_);
if (ret) {
head_ = ret->get_next();
if (!head_)
tail_ = nullptr; // The queue is now empty.
size_--;
}
return ret;
}
template <typename R, typename... Args>
void CallbackQueue<R, Args...>::Push(std::unique_ptr<Callback> cb) {
Callback* prev_tail = tail_;
Callback* prev_tail = tail_;
size_++;
tail_ = cb.get();
if (prev_tail != nullptr)
prev_tail->set_next(std::move(cb));
else
head_ = std::move(cb);
size_++;
tail_ = cb.get();
if (prev_tail != nullptr)
prev_tail->set_next(std::move(cb));
else
head_ = std::move(cb);
}
template <typename R, typename... Args>
void CallbackQueue<R, Args...>::ConcatMove(CallbackQueue<R, Args...>&& other) {
size_ += other.size_;
if (tail_ != nullptr)
tail_->set_next(std::move(other.head_));
else
head_ = std::move(other.head_);
tail_ = other.tail_;
other.tail_ = nullptr;
other.size_ = 0;
size_ += other.size_;
if (tail_ != nullptr)
tail_->set_next(std::move(other.head_));
else
head_ = std::move(other.head_);
tail_ = other.tail_;
other.tail_ = nullptr;
other.size_ = 0;
}
template <typename R, typename... Args>
size_t CallbackQueue<R, Args...>::size() const {
return size_.load();
return size_.load();
}
template <typename R, typename... Args>
CallbackQueue<R, Args...>::Callback::Callback(CallbackFlags::Flags flags)
: flags_(flags) {}
: flags_(flags) {}
template <typename R, typename... Args>
CallbackFlags::Flags CallbackQueue<R, Args...>::Callback::flags() const {
return flags_;
return flags_;
}
template <typename R, typename... Args>
std::unique_ptr<typename CallbackQueue<R, Args...>::Callback>
CallbackQueue<R, Args...>::Callback::get_next() {
return std::move(next_);
return std::move(next_);
}
template <typename R, typename... Args>
void CallbackQueue<R, Args...>::Callback::set_next(
std::unique_ptr<Callback> next) {
next_ = std::move(next);
next_ = std::move(next);
}
template <typename R, typename... Args>
template <typename Fn>
CallbackQueue<R, Args...>::CallbackImpl<Fn>::CallbackImpl(
Fn&& callback, CallbackFlags::Flags flags)
: Callback(flags),
callback_(std::move(callback)) {}
: Callback(flags),
callback_(std::move(callback)) {}
template <typename R, typename... Args>
template <typename Fn>
R CallbackQueue<R, Args...>::CallbackImpl<Fn>::Call(Args... args) {
return callback_(std::forward<Args>(args)...);
return callback_(std::forward<Args>(args)...);
}
} // namespace node
} // namespace node
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#endif // SRC_CALLBACK_QUEUE_INL_H_
#endif // SRC_CALLBACK_QUEUE_INL_H_
@@ -3,14 +3,14 @@
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#include <atomic>
#include <atomic>
namespace node {
namespace CallbackFlags {
enum Flags {
kUnrefed = 0,
kRefed = 1,
kUnrefed = 0,
kRefed = 1,
};
}
@@ -22,57 +22,57 @@ enum Flags {
// should be run even if nothing else is keeping the event loop alive.
template <typename R, typename... Args>
class CallbackQueue {
public:
class Callback {
public:
explicit inline Callback(CallbackFlags::Flags flags);
public:
class Callback {
public:
explicit inline Callback(CallbackFlags::Flags flags);
virtual ~Callback() = default;
virtual R Call(Args... args) = 0;
virtual ~Callback() = default;
virtual R Call(Args... args) = 0;
inline CallbackFlags::Flags flags() const;
inline CallbackFlags::Flags flags() const;
private:
inline std::unique_ptr<Callback> get_next();
inline void set_next(std::unique_ptr<Callback> next);
private:
inline std::unique_ptr<Callback> get_next();
inline void set_next(std::unique_ptr<Callback> next);
CallbackFlags::Flags flags_;
std::unique_ptr<Callback> next_;
CallbackFlags::Flags flags_;
std::unique_ptr<Callback> next_;
friend class CallbackQueue;
};
friend class CallbackQueue;
};
template <typename Fn>
inline std::unique_ptr<Callback> CreateCallback(
Fn&& fn, CallbackFlags::Flags);
template <typename Fn>
inline std::unique_ptr<Callback> CreateCallback(
Fn&& fn, CallbackFlags::Flags);
inline std::unique_ptr<Callback> Shift();
inline void Push(std::unique_ptr<Callback> cb);
// ConcatMove adds elements from 'other' to the end of this list, and clears
// 'other' afterwards.
inline void ConcatMove(CallbackQueue&& other);
inline std::unique_ptr<Callback> Shift();
inline void Push(std::unique_ptr<Callback> cb);
// ConcatMove adds elements from 'other' to the end of this list, and clears
// 'other' afterwards.
inline void ConcatMove(CallbackQueue&& other);
// size() is atomic and may be called from any thread.
inline size_t size() const;
// size() is atomic and may be called from any thread.
inline size_t size() const;
private:
template <typename Fn>
class CallbackImpl final : public Callback {
public:
CallbackImpl(Fn&& callback, CallbackFlags::Flags flags);
R Call(Args... args) override;
private:
template <typename Fn>
class CallbackImpl final : public Callback {
public:
CallbackImpl(Fn&& callback, CallbackFlags::Flags flags);
R Call(Args... args) override;
private:
Fn callback_;
};
private:
Fn callback_;
};
std::atomic<size_t> size_ {0};
std::unique_ptr<Callback> head_;
Callback* tail_ = nullptr;
std::atomic<size_t> size_{0};
std::unique_ptr<Callback> head_;
Callback* tail_ = nullptr;
};
} // namespace node
} // namespace node
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#endif // SRC_CALLBACK_QUEUE_H_
#endif // SRC_CALLBACK_QUEUE_H_
File diff suppressed because it is too large Load Diff
@@ -24,10 +24,10 @@
#define JSVM_ARRAYSIZE(array) node::arraysize((array))
#define JSVM_FIXED_ONE_BYTE_STRING(isolate, string) \
node::FIXED_ONE_BYTE_STRING((isolate), (string))
#define JSVM_FIXED_ONE_BYTE_STRING(isolate, string) \
node::FIXED_ONE_BYTE_STRING((isolate), (string))
#define JSVM_PRIVATE_KEY(isolate, suffix) \
#define JSVM_PRIVATE_KEY(isolate, suffix) \
(v8impl::GetIsolateData(isolate)->jsvm_##suffix##_key.Get(isolate))
namespace v8impl {
@@ -38,10 +38,10 @@ using Persistent = v8::Global<T>;
using PersistentToLocal = node::PersistentToLocal;
inline void OnFatalError(const char* location,
const char* message) {
//cjh node::OnFatalError(location, message);
const char* message) {
//cjh node::OnFatalError(location, message);
}
} // end of namespace v8impl
} // end of namespace v8impl
#endif // SRC_JS_NATIVE_API_V8_INTERNALS_H_
#endif // SRC_JS_NATIVE_API_V8_INTERNALS_H_
@@ -43,42 +43,42 @@
*/
// This file needs to be compatible with C compilers.
#include <stdbool.h> // NOLINT(modernize-deprecated-headers)
#include <stddef.h> // NOLINT(modernize-deprecated-headers)
#include <stdbool.h> // NOLINT(modernize-deprecated-headers)
#include <stddef.h> // NOLINT(modernize-deprecated-headers)
// Use INT_MAX, this should only be consumed by the pre-processor anyway.
#define JSVM_VERSION_EXPERIMENTAL 2147483647
#ifndef JSVM_VERSION
#ifdef JSVM_EXPERIMENTAL
#define JSVM_VERSION JSVM_VERSION_EXPERIMENTAL
#else
// The baseline version for JSVM-API.
// The JSVM_VERSION controls which version will be used by default when
// compilling a native addon. If the addon developer specifically wants to use
// functions available in a new version of JSVM-API that is not yet ported in all
// LTS versions, they can set JSVM_VERSION knowing that they have specifically
// depended on that version.
#define JSVM_VERSION 8
#endif
#ifdef JSVM_EXPERIMENTAL
#define JSVM_VERSION JSVM_VERSION_EXPERIMENTAL
#else
// The baseline version for JSVM-API.
// The JSVM_VERSION controls which version will be used by default when
// compilling a native addon. If the addon developer specifically wants to use
// functions available in a new version of JSVM-API that is not yet ported in all
// LTS versions, they can set JSVM_VERSION knowing that they have specifically
// depended on that version.
#define JSVM_VERSION 8
#endif
#endif
#include "jsvm_types.h"
#ifndef JSVM_EXTERN
#ifdef _WIN32
/**
#ifdef _WIN32
/**
* @brief externally visible.
*
* @since 11
*/
#define JSVM_EXTERN __declspec(dllexport)
#elif defined(__wasm__)
#define JSVM_EXTERN \
__attribute__((visibility("default"))) \
__attribute__((__import_module__("jsvm")))
#else
#define JSVM_EXTERN __attribute__((visibility("default")))
#endif
#define JSVM_EXTERN __declspec(dllexport)
#elif defined(__wasm__)
#define JSVM_EXTERN \
__attribute__((visibility("default"))) \
__attribute__((__import_module__("jsvm")))
#else
#define JSVM_EXTERN __attribute__((visibility("default")))
#endif
#endif
/**
@@ -89,11 +89,11 @@
#define JSVM_AUTO_LENGTH SIZE_MAX
#ifdef __cplusplus
#define EXTERN_C_START extern "C" {
#define EXTERN_C_END }
#define EXTERN_C_START extern "C" {
#define EXTERN_C_END }
#else
#define EXTERN_C_START
#define EXTERN_C_END
#define EXTERN_C_START
#define EXTERN_C_END
#endif
EXTERN_C_START
@@ -657,7 +657,6 @@ JSVM_EXTERN JSVM_Status OH_JSVM_GetReferenceValue(JSVM_Env env,
JSVM_EXTERN JSVM_Status OH_JSVM_CreateArray(JSVM_Env env,
JSVM_Value* result);
/**
* @brief This API returns a JSVM-API value corresponding to a JavaScript Array type. The Array's length property
* is set to the passed-in length parameter. However, the underlying buffer is not guaranteed to be pre-allocated
@@ -707,7 +706,7 @@ JSVM_EXTERN JSVM_Status OH_JSVM_CreateArraybuffer(JSVM_Env env,
*/
JSVM_Status JSVM_CDECL OH_JSVM_AllocateArrayBufferBackingStoreData(size_t byteLength,
JSVM_InitializedFlag initialized,
void **data);
void** data);
/**
* @brief This API release the memory of an array buffer backing store.
@@ -718,7 +717,7 @@ JSVM_Status JSVM_CDECL OH_JSVM_AllocateArrayBufferBackingStoreData(size_t byteLe
* Returns {@link JSVM_INVALID_ARG } if data is null pointer.\n
* @since 12
*/
JSVM_Status JSVM_CDECL OH_JSVM_FreeArrayBufferBackingStoreData(void *data);
JSVM_Status JSVM_CDECL OH_JSVM_FreeArrayBufferBackingStoreData(void* data);
/**
* @brief This API create an array buffer using the backing store data.
@@ -738,11 +737,11 @@ JSVM_Status JSVM_CDECL OH_JSVM_FreeArrayBufferBackingStoreData(void *data);
* @since 12
*/
JSVM_Status JSVM_CDECL OH_JSVM_CreateArrayBufferFromBackingStoreData(JSVM_Env env,
void *data,
void* data,
size_t backingStoreSize,
size_t offset,
size_t arrayBufferSize,
JSVM_Value *result);
JSVM_Value* result);
/**
* @brief This API does not observe leap seconds; they are ignored, as ECMAScript aligns with POSIX time specification.
@@ -1850,7 +1849,7 @@ JSVM_EXTERN JSVM_Status OH_JSVM_CallFunction(JSVM_Env env,
const JSVM_Value* argv,
JSVM_Value* result);
/**
/**
* @brief This API allows an add-on author to create a function object in native
* code. This is the primary mechanism to allow calling into the add-on's native
* code from JavaScript.The newly created function is not automatically visible
@@ -1876,7 +1875,7 @@ JSVM_EXTERN JSVM_Status OH_JSVM_CreateFunction(JSVM_Env env,
JSVM_Callback cb,
JSVM_Value* result);
/**
/**
* @brief This method is used within a callback function to retrieve details about
* the call like the arguments and the this pointer from a given callback info.
*
@@ -2770,12 +2769,12 @@ JSVM_EXTERN JSVM_Status OH_JSVM_OpenInspectorWithName(JSVM_Env env,
* @since 12
*/
JSVM_EXTERN JSVM_Status OH_JSVM_CompileWasmModule(JSVM_Env env,
const uint8_t *wasmBytecode,
const uint8_t* wasmBytecode,
size_t wasmBytecodeLength,
const uint8_t *cacheData,
const uint8_t* cacheData,
size_t cacheDataLength,
bool *cacheRejected,
JSVM_Value *wasmModule);
bool* cacheRejected,
JSVM_Value* wasmModule);
/**
* @brief Compile the function with the specified index in the WebAssembly module
@@ -2853,4 +2852,3 @@ EXTERN_C_END
/** @} */
#endif /* ARK_RUNTIME_JSVM_JSVM_H */
@@ -42,20 +42,20 @@
* @since 11
*/
#include <stdbool.h> // NOLINT(modernize-deprecated-headers)
#include <stddef.h> // NOLINT(modernize-deprecated-headers)
#include <stdint.h> // NOLINT(modernize-deprecated-headers)
#include <stdbool.h> // NOLINT(modernize-deprecated-headers)
#if !defined __cplusplus || (defined(_MSC_VER) && _MSC_VER < 1900)
typedef uint16_t char16_t;
#endif
#ifndef JSVM_CDECL
#ifdef _WIN32
#define JSVM_CDECL __cdecl
#else
#define JSVM_CDECL
#endif
#ifdef _WIN32
#define JSVM_CDECL __cdecl
#else
#define JSVM_CDECL
#endif
#endif
/**
@@ -142,7 +142,6 @@ typedef struct JSVM_CallbackInfo__* JSVM_CallbackInfo;
*/
typedef struct JSVM_Deferred__* JSVM_Deferred;
/**
* @brief Callback function pointer and data for user-provided native function which are to exposed to js via JSVM-API.
*
@@ -150,7 +149,7 @@ typedef struct JSVM_Deferred__* JSVM_Deferred;
*/
typedef struct {
JSVM_Value(JSVM_CDECL* callback)(JSVM_Env env,
JSVM_CallbackInfo info);
JSVM_CallbackInfo info);
void* data;
} JSVM_CallbackStruct;
@@ -699,12 +698,12 @@ typedef struct {
JSVM_CompileOptionId id;
/** option content. */
union {
/** ptr type. */
void *ptr;
/** int type. */
int num;
/** bool type. */
bool boolean;
/** ptr type. */
void* ptr;
/** int type. */
int num;
/** bool type. */
bool boolean;
} content;
} JSVM_CompileOptions;
@@ -715,7 +714,7 @@ typedef struct {
*/
typedef struct {
/** cache pointer. */
uint8_t *cache;
uint8_t* cache;
/** length. */
size_t length;
} JSVM_CodeCache;
@@ -751,7 +750,7 @@ typedef enum {
*/
typedef const struct {
/** profile pointer. */
int *profile;
int* profile;
/** length. */
size_t length;
} JSVM_CompileProfile;
@@ -26,50 +26,44 @@
#define NODE_MINOR_VERSION 20
#define NODE_PATCH_VERSION 1
#define NODE_VERSION_IS_LTS 1
#define NODE_VERSION_IS_LTS 1
#define NODE_VERSION_LTS_CODENAME "Hydrogen"
#define NODE_VERSION_IS_RELEASE 1
#ifndef NODE_STRINGIFY
#define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n)
#define NODE_STRINGIFY_HELPER(n) #n
#define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n)
#define NODE_STRINGIFY_HELPER(n) #n
#endif
#ifndef NODE_RELEASE
#define NODE_RELEASE "node"
#define NODE_RELEASE "node"
#endif
#ifndef NODE_TAG
# if NODE_VERSION_IS_RELEASE
# define NODE_TAG ""
# else
# define NODE_TAG "-pre"
# endif
#if NODE_VERSION_IS_RELEASE
#define NODE_TAG ""
#else
#define NODE_TAG "-pre"
#endif
#else
// NODE_TAG is passed without quotes when rc.exe is run from msbuild
# define NODE_EXE_VERSION NODE_STRINGIFY(NODE_MAJOR_VERSION) "." \
NODE_STRINGIFY(NODE_MINOR_VERSION) "." \
NODE_STRINGIFY(NODE_PATCH_VERSION) \
NODE_STRINGIFY(NODE_TAG)
// NODE_TAG is passed without quotes when rc.exe is run from msbuild
#define NODE_EXE_VERSION NODE_STRINGIFY(NODE_MAJOR_VERSION) \
"." NODE_STRINGIFY(NODE_MINOR_VERSION) "." NODE_STRINGIFY(NODE_PATCH_VERSION) \
NODE_STRINGIFY(NODE_TAG)
#endif
# define NODE_VERSION_STRING NODE_STRINGIFY(NODE_MAJOR_VERSION) "." \
NODE_STRINGIFY(NODE_MINOR_VERSION) "." \
NODE_STRINGIFY(NODE_PATCH_VERSION) \
NODE_TAG
#define NODE_VERSION_STRING NODE_STRINGIFY(NODE_MAJOR_VERSION) \
"." NODE_STRINGIFY(NODE_MINOR_VERSION) "." NODE_STRINGIFY(NODE_PATCH_VERSION) \
NODE_TAG
#ifndef NODE_EXE_VERSION
# define NODE_EXE_VERSION NODE_VERSION_STRING
#define NODE_EXE_VERSION NODE_VERSION_STRING
#endif
#define NODE_VERSION "v" NODE_VERSION_STRING
#define NODE_VERSION_AT_LEAST(major, minor, patch) \
(( (major) < NODE_MAJOR_VERSION) \
|| ((major) == NODE_MAJOR_VERSION && (minor) < NODE_MINOR_VERSION) \
|| ((major) == NODE_MAJOR_VERSION && \
(minor) == NODE_MINOR_VERSION && (patch) <= NODE_PATCH_VERSION))
(((major) < NODE_MAJOR_VERSION) || ((major) == NODE_MAJOR_VERSION && (minor) < NODE_MINOR_VERSION) || ((major) == NODE_MAJOR_VERSION && (minor) == NODE_MINOR_VERSION && (patch) <= NODE_PATCH_VERSION))
/**
* Node.js will refuse to load modules that weren't compiled against its own
@@ -99,4 +93,4 @@
// specified. It must be always 8.
#define NODE_API_DEFAULT_MODULE_API_VERSION 8
#endif // SRC_NODE_VERSION_H_
#endif // SRC_NODE_VERSION_H_
File diff suppressed because it is too large Load Diff
+13 -13
View File
@@ -51,7 +51,7 @@ Class *Class::create(const std::string &clsName, se::Object *parent, Object *par
return cls;
}
Class* Class::create(const std::initializer_list<const char *> &classPath, se::Object *parent, Object *parentProto, JSVM_Callback ctor) {
Class *Class::create(const std::initializer_list<const char *> &classPath, se::Object *parent, Object *parentProto, JSVM_Callback ctor) {
se::AutoHandleScope scope;
se::Object *currentParent = parent;
se::Value tmp;
@@ -64,7 +64,7 @@ Class* Class::create(const std::initializer_list<const char *> &classPath, se::O
}
bool Class::init(const std::string &clsName, Object *parent, Object *parentProto, JSVM_Callback ctor) {
_name = clsName;
_name = clsName;
_parent = parent;
if (_parent != nullptr)
_parent->incRef();
@@ -86,7 +86,7 @@ JSVM_Value Class::_defaultCtor(JSVM_Env env, JSVM_CallbackInfo info) {
return thisArg;
}
void Class::defineProperty(const char* name, JSVM_Callback g, JSVM_Callback s) {
void Class::defineProperty(const char *name, JSVM_Callback g, JSVM_Callback s) {
_properties.push_back({name, nullptr, nullptr, g, s, 0, JSVM_DEFAULT_JSPROPERTY});
}
@@ -96,18 +96,18 @@ void Class::defineProperty(const std::initializer_list<const char *> &names, JSV
}
}
void Class::defineStaticProperty(const char* name, JSVM_Callback g, JSVM_Callback s) {
if(g != nullptr && s != nullptr)
void Class::defineStaticProperty(const char *name, JSVM_Callback g, JSVM_Callback s) {
if (g != nullptr && s != nullptr)
_properties.push_back({name, nullptr, nullptr, g, s, 0, JSVM_STATIC});
}
void Class::defineFunction(const char* name, JSVM_Callback func) {
// When JSVM defines a function, it needs to add the enum attribute, otherwise JS cannot traverse the function
void Class::defineFunction(const char *name, JSVM_Callback func) {
// When JSVM defines a function, it needs to add the enum attribute, otherwise JS cannot traverse the function
_properties.push_back({name, nullptr, func, nullptr, nullptr, nullptr, JSVM_JSPROPERTY_NO_RECEIVER_CHECK});
}
void Class::defineStaticFunction(const char* name, JSVM_Callback func) {
_properties.push_back({name, nullptr, func, nullptr, nullptr, 0, JSVM_PropertyAttributes((int)JSVM_STATIC|(int)JSVM_WRITABLE)});
void Class::defineStaticFunction(const char *name, JSVM_Callback func) {
_properties.push_back({name, nullptr, func, nullptr, nullptr, 0, JSVM_PropertyAttributes((int)JSVM_STATIC | (int)JSVM_WRITABLE)});
}
bool Class::defineStaticProperty(const char *name, const Value &v, PropertyAttribute attribute /* = PropertyAttribute::NONE */) {
@@ -129,7 +129,7 @@ JSVM_Finalize Class::_getFinalizeFunction() const {
bool Class::install() {
auto env = ScriptEngine::getEnv();
JSVM_Value cons;
JSVM_Value cons;
JSVM_Status status;
NODE_API_CALL(status, env, OH_JSVM_DefineClass(env, _name.c_str(), -1, _ctorFunc, _properties.size(), _properties.data(), &cons));
if (_parentProto) {
@@ -147,7 +147,7 @@ bool Class::install() {
_proto->root();
}
return true;
return true;
}
JSVM_Status Class::inherit(JSVM_Env env, JSVM_Value subclass, JSVM_Value superProto) {
@@ -205,7 +205,7 @@ JSVM_Ref Class::_getCtorRef() const {
JSVM_Value Class::_getCtorFunc() const {
assert(_constructor);
JSVM_Value result = nullptr;
JSVM_Value result = nullptr;
JSVM_Status status;
NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_GetReferenceValue(ScriptEngine::getEnv(), _constructor, &result));
return result;
@@ -231,7 +231,7 @@ void Class::destroy() {
}
_ctor.reset();
}
OH_JSVM_DeleteReference(ScriptEngine::getEnv(), _constructor);
}
+33 -34
View File
@@ -24,11 +24,11 @@
****************************************************************************/
#pragma once
#include <string>
#include <optional>
#include <string>
#include "../Define.h"
#include "CommonHeader.h"
#include "Object.h"
#include "../Define.h"
namespace se {
class Class {
@@ -36,49 +36,48 @@ public:
static Class *create(const std::string &clsName, se::Object *parent, Object *parentProto, JSVM_Callback ctor = nullptr);
static Class *create(const std::initializer_list<const char *> &classPath, se::Object *parent, Object *parentProto, JSVM_Callback ctor = nullptr);
void defineFunction(const char* name, JSVM_Callback func);
void defineProperty(const char* name, JSVM_Callback g, JSVM_Callback s);
void defineProperty(const std::initializer_list<const char *> &names, JSVM_Callback g, JSVM_Callback s);
void defineFunction(const char *name, JSVM_Callback func);
void defineProperty(const char *name, JSVM_Callback g, JSVM_Callback s);
void defineProperty(const std::initializer_list<const char *> &names, JSVM_Callback g, JSVM_Callback s);
void defineStaticFunction(const char* name, JSVM_Callback func);
void defineStaticProperty(const char* name, JSVM_Callback g, JSVM_Callback s);
bool defineStaticProperty(const char *name, const Value &value, PropertyAttribute attribute = PropertyAttribute::NONE);
void defineStaticFunction(const char *name, JSVM_Callback func);
void defineStaticProperty(const char *name, JSVM_Callback g, JSVM_Callback s);
bool defineStaticProperty(const char *name, const Value &value, PropertyAttribute attribute = PropertyAttribute::NONE);
static JSVM_Value _createJSObjectWithClass(Class *cls);
void defineFinalizeFunction(JSVM_Finalize func);
static JSVM_Value _createJSObjectWithClass(Class *cls);
void defineFinalizeFunction(JSVM_Finalize func);
JSVM_Finalize _getFinalizeFunction() const;
Object * getProto() const;
bool install();
JSVM_Status inherit(JSVM_Env env, JSVM_Value subclass, JSVM_Value superclass);
JSVM_Ref _getCtorRef() const;
JSVM_Value _getCtorFunc() const;
const char * getName() const { return _name.c_str(); }
static void setExports(JSVM_Value *expPtr) { _exports = expPtr; }
Object *getProto() const;
bool install();
JSVM_Status inherit(JSVM_Env env, JSVM_Value subclass, JSVM_Value superclass);
JSVM_Ref _getCtorRef() const;
JSVM_Value _getCtorFunc() const;
const char *getName() const { return _name.c_str(); }
static void setExports(JSVM_Value *expPtr) { _exports = expPtr; }
static void cleanup();
// Private API used in wrapper
void _setCtor(Object *obj); // NOLINT(readability-identifier-naming)
void _setCtor(Object *obj); // NOLINT(readability-identifier-naming)
inline const std::optional<Object *> &_getCtor() const { return _ctor; } // NOLINT(readability-identifier-naming)
private:
Class();
~Class();
bool init(const std::string &clsName, Object *parent, Object *parentProto, JSVM_Callback ctor = nullptr);
void destroy();
bool init(const std::string &clsName, Object *parent, Object *parentProto, JSVM_Callback ctor = nullptr);
void destroy();
static JSVM_Value _defaultCtor(JSVM_Env env, JSVM_CallbackInfo info);
private:
std::optional<Object *> _ctor;
static JSVM_Value * _exports;
std::string _name;
Object * _parent = nullptr;
Object * _proto = nullptr;
Object * _parentProto = nullptr;
JSVM_CallbackStruct _ctorStruct = {Class::_defaultCtor,nullptr};
JSVM_Callback _ctorFunc = &_ctorStruct;
JSVM_Ref _constructor = nullptr;
std::vector<JSVM_PropertyDescriptor> _properties;
JSVM_Finalize _finalizeFunc = nullptr;
std::optional<Object *> _ctor;
static JSVM_Value *_exports;
std::string _name;
Object *_parent = nullptr;
Object *_proto = nullptr;
Object *_parentProto = nullptr;
JSVM_CallbackStruct _ctorStruct = {Class::_defaultCtor, nullptr};
JSVM_Callback _ctorFunc = &_ctorStruct;
JSVM_Ref _constructor = nullptr;
std::vector<JSVM_PropertyDescriptor> _properties;
JSVM_Finalize _finalizeFunc = nullptr;
};
}; // namespace se
@@ -26,9 +26,9 @@
#pragma once
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include "ark_runtime/jsvm.h"
#include "ark_runtime/jsvm.h"
#else
#include "jsvm.h"
#include "jsvm.h"
#endif
#include "platform/openharmony/napi/native_common.h"
@@ -52,22 +52,22 @@
} \
} while (0)
#define NODE_API_CALL_RESULT(status, env, the_call, ret_val) \
do { \
status = the_call; \
if (status != JSVM_OK) { \
se::internal::logJsException((env), __FILE_NAME__, __LINE__); \
return ret_val; \
} \
#define NODE_API_CALL_RESULT(status, env, the_call, ret_val) \
do { \
status = the_call; \
if (status != JSVM_OK) { \
se::internal::logJsException((env), __FILE_NAME__, __LINE__); \
return ret_val; \
} \
} while (0)
// Returns nullptr if the_call doesn't return JSVM_OK.
#define NODE_API_CALL(status, env, the_call) \
do { \
status = the_call; \
if (status != JSVM_OK) { \
se::internal::logJsException((env), __FILE_NAME__, __LINE__); \
} \
#define NODE_API_CALL(status, env, the_call) \
do { \
status = the_call; \
if (status != JSVM_OK) { \
se::internal::logJsException((env), __FILE_NAME__, __LINE__); \
} \
} while (0)
// Returns empty if the_call doesn't return JSVM_OK.
@@ -82,7 +82,7 @@
#define JSVM_CALL_BASE(theCall, retVal) \
do { \
if((theCall) != JSVM_OK){ \
if ((theCall) != JSVM_OK) { \
return retVal; \
} \
} while (0)
@@ -39,10 +39,10 @@ SE_HOT JSVM_Value jsbFunctionWrapper(JSVM_Env env, JSVM_CallbackInfo info, se_fu
JSVM_Value args[15];
NODE_API_CALL(status, env, OH_JSVM_GetCbInfo(env, info, &argc, args, &_this, NULL));
void* nativeThisObject = nullptr;
void *nativeThisObject = nullptr;
status = OH_JSVM_Unwrap(env, _this, &nativeThisObject);
se::internal::jsToSeArgs(argc, args, &seArgs);
se::State state(reinterpret_cast<se::Object*>(nativeThisObject), seArgs);
se::State state(reinterpret_cast<se::Object *>(nativeThisObject), seArgs);
ret = func(state);
if (!ret) {
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", funcName, __FILE__, __LINE__);
@@ -110,9 +110,9 @@ SE_HOT JSVM_Value jsbGetterWrapper(JSVM_Env env, JSVM_CallbackInfo info, se_func
JSVM_Status status;
NODE_API_CALL(status, env,
OH_JSVM_GetCbInfo(env, info, nullptr, nullptr, &_this, nullptr));
void* obj = nullptr;
void *obj = nullptr;
status = OH_JSVM_Unwrap(env, _this, &obj);
se::State state(reinterpret_cast<se::Object*>(obj));
se::State state(reinterpret_cast<se::Object *>(obj));
bool ret = func(state);
if (!ret) {
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", funcName, __FILE__, __LINE__);
@@ -134,9 +134,9 @@ SE_HOT JSVM_Value jsbSetterWrapper(JSVM_Env env, JSVM_CallbackInfo info, se_func
se::ValueArray args2;
args2.reserve(10);
args2.push_back(std::move(data));
void* nativeThisObject = nullptr;
void *nativeThisObject = nullptr;
status = OH_JSVM_Unwrap(env, _this, &nativeThisObject);
se::State state(reinterpret_cast<se::Object*>(nativeThisObject), args2);
se::State state(reinterpret_cast<se::Object *>(nativeThisObject), args2);
bool ret = func(state);
if (!ret) {
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", funcName, __FILE__, __LINE__);
@@ -30,10 +30,10 @@
#include <hilog/log.h>
#ifndef LOGI
#define LOGI(...) ((void) OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#define LOGW(...) ((void) OH_LOG_Print(LOG_APP, LOG_WARN, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#define LOGE(...) ((void) OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#define LOGD(...) ((void) OH_LOG_Print(LOG_APP, LOG_DEBUG, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#define LOGI(...) ((void)OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#define LOGW(...) ((void)OH_LOG_Print(LOG_APP, LOG_WARN, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#define LOGE(...) ((void)OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#define LOGD(...) ((void)OH_LOG_Print(LOG_APP, LOG_DEBUG, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#endif
#else
#define LOGI CC_LOG_INFO
@@ -80,67 +80,66 @@ constexpr inline T *SE_THIS_OBJECT(STATE &s) { // NOLINT(readability-identifier-
#define SE_QUOTEME(x) SE_QUOTEME_(x)
#define SE_REPORT_ERROR(fmt, ...) SE_LOGE("[ERROR] (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__)
#define SE_BIND_PROP_GET_IMPL(funcName, postFix) \
JSVM_Value funcName##postFix##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \
return jsbGetterWrapper(env, info, funcName, #funcName); \
} \
JSVM_CallbackStruct funcName##postFix##RegistryStruct = {(funcName##postFix##Registry),nullptr};
#define SE_BIND_PROP_GET_IMPL(funcName, postFix) \
JSVM_Value funcName##postFix##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \
return jsbGetterWrapper(env, info, funcName, #funcName); \
} \
JSVM_CallbackStruct funcName##postFix##RegistryStruct = {(funcName##postFix##Registry), nullptr};
#define SE_BIND_PROP_GET(funcName) SE_BIND_PROP_GET_IMPL(funcName, )
#define SE_BIND_FUNC_AS_PROP_GET(funcName) SE_BIND_PROP_GET_IMPL(funcName, _asGetter)
#define SE_BIND_PROP_SET_IMPL(funcName, postFix) \
JSVM_Value funcName##postFix##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \
return jsbSetterWrapper(env, info, funcName, #funcName); \
} \
JSVM_CallbackStruct funcName##postFix##RegistryStruct = {(funcName##postFix##Registry),nullptr};
#define SE_BIND_PROP_SET_IMPL(funcName, postFix) \
JSVM_Value funcName##postFix##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \
return jsbSetterWrapper(env, info, funcName, #funcName); \
} \
JSVM_CallbackStruct funcName##postFix##RegistryStruct = {(funcName##postFix##Registry), nullptr};
#define SE_BIND_PROP_SET(funcName) SE_BIND_PROP_SET_IMPL(funcName, )
#define SE_BIND_FUNC_AS_PROP_SET(funcName) SE_BIND_PROP_SET_IMPL(funcName, _asSetter)
#define SE_DECLARE_FUNC(funcName) \
JSVM_Value funcName##Registry(JSVM_Env env, JSVM_CallbackInfo info); \
extern JSVM_CallbackStruct funcName##RegistryStruct;
#define SE_DECLARE_FUNC(funcName) \
JSVM_Value funcName##Registry(JSVM_Env env, JSVM_CallbackInfo info); \
extern JSVM_CallbackStruct funcName##RegistryStruct;
#define SE_BIND_FUNC(funcName) \
JSVM_Value funcName##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \
return jsbFunctionWrapper(env, info, funcName, #funcName); \
} \
JSVM_CallbackStruct funcName##RegistryStruct = {(funcName##Registry),nullptr};
#define SE_BIND_FUNC(funcName) \
JSVM_Value funcName##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \
return jsbFunctionWrapper(env, info, funcName, #funcName); \
} \
JSVM_CallbackStruct funcName##RegistryStruct = {(funcName##Registry), nullptr};
#define SE_BIND_FUNC_FAST(funcName) \
JSVM_Value funcName##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \
JSVM_Status status; \
JSVM_Value _this; \
size_t argc = 15; \
JSVM_Value args[15]; \
void *nativeThisObject = nullptr; \
NODE_API_CALL(status, env, OH_JSVM_GetCbInfo(env, info, &argc, args, &_this, NULL)); \
status = OH_JSVM_Unwrap(env, _this, &nativeThisObject); \
auto *nativeObject = nativeThisObject != nullptr ? ((se::Object*)nativeThisObject)->getPrivateData() : nullptr; \
funcName(nativeObject); \
return nullptr; \
} \
JSVM_CallbackStruct funcName##RegistryStruct = {(funcName##Registry),nullptr};
#define SE_BIND_CTOR(funcName, cls, finalizeCb) \
JSVM_Value funcName##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \
return jsbConstructorWrapper(env, info, funcName, _SE(finalizeCb), cls, #funcName); \
} \
JSVM_CallbackStruct funcName##RegistryStruct = {(funcName##Registry),nullptr};
#define SE_BIND_FUNC_FAST(funcName) \
JSVM_Value funcName##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \
JSVM_Status status; \
JSVM_Value _this; \
size_t argc = 15; \
JSVM_Value args[15]; \
void *nativeThisObject = nullptr; \
NODE_API_CALL(status, env, OH_JSVM_GetCbInfo(env, info, &argc, args, &_this, NULL)); \
status = OH_JSVM_Unwrap(env, _this, &nativeThisObject); \
auto *nativeObject = nativeThisObject != nullptr ? ((se::Object *)nativeThisObject)->getPrivateData() : nullptr; \
funcName(nativeObject); \
return nullptr; \
} \
JSVM_CallbackStruct funcName##RegistryStruct = {(funcName##Registry), nullptr};
#define SE_BIND_CTOR(funcName, cls, finalizeCb) \
JSVM_Value funcName##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \
return jsbConstructorWrapper(env, info, funcName, _SE(finalizeCb), cls, #funcName); \
} \
JSVM_CallbackStruct funcName##RegistryStruct = {(funcName##Registry), nullptr};
#define SE_BIND_SUB_CLS_CTOR SE_BIND_CTOR
#define SE_DECLARE_FINALIZE_FUNC(funcName) \
void funcName##RegistryStruct(JSVM_Env env, void *nativeObject, void * /*finalize_hint*/); \
#define SE_DECLARE_FINALIZE_FUNC(funcName) \
void funcName##RegistryStruct(JSVM_Env env, void *nativeObject, void * /*finalize_hint*/);
#define SE_BIND_FINALIZE_FUNC(funcName) \
void funcName##RegistryStruct(JSVM_Env env, void *nativeObject, void *hint /*finalize_hint*/) { \
if (nativeObject == nullptr) { \
return; \
} \
jsbFinalizeWrapper(nativeObject, funcName, #funcName); \
#define SE_BIND_FINALIZE_FUNC(funcName) \
void funcName##RegistryStruct(JSVM_Env env, void *nativeObject, void *hint /*finalize_hint*/) { \
if (nativeObject == nullptr) { \
return; \
} \
jsbFinalizeWrapper(nativeObject, funcName, #funcName); \
}
#define _SE(name) &(name##RegistryStruct)
#define _SE(name) &(name##RegistryStruct)
+21 -23
View File
@@ -38,7 +38,7 @@ namespace se {
std::unique_ptr<std::unordered_set<Object*>> __objectSet;
std::unordered_set<Object*> __objectSetToBeReleasedInCleanup;
Object::Object(): _objRef(this) {}
Object::Object() : _objRef(this) {}
Object::~Object() {
if (!_destructInFinalizer && _cls != nullptr) {
// Remove wrap will ensure that we release the underlying `v8impl::Reference` that the private wrap associates with.
@@ -46,7 +46,7 @@ Object::~Object() {
// We just do this if `_cls` is not null since only JSB objects get wrapped,
OH_JSVM_RemoveWrap(_env, _objRef.getValue(_env), nullptr);
}
if (__objectSet) {
__objectSet->erase(this);
}
@@ -65,7 +65,7 @@ bool Object::setProperty(const char* name, const Value& data) {
JSVM_Status status;
JSVM_Value jsVal;
bool ret = internal::seToJsValue(data, &jsVal);
if(!ret) {
if (!ret) {
return false;
}
NODE_API_CALL(status, _env, OH_JSVM_SetNamedProperty(_env, _objRef.getValue(_env), name, jsVal));
@@ -119,7 +119,7 @@ void Object::setPrivateObject(PrivateObjectBase* data) {
// Passing nullptr to the `result` parameter to make JSVM mangle the lifecycle of `v8impl::Reference`
NODE_API_CALL(status, _env, OH_JSVM_Wrap(_env, tmpThis, this, weakCallback, this /* finalize_hint */, nullptr));
// WORKAROUND: See the explain in `ObjectRef::deleteRef` about why we need to `decRef` here.
_objRef.decRef(_env);
//
@@ -163,7 +163,7 @@ bool Object::setArrayElement(uint32_t index, const Value& data) {
JSVM_Status status;
JSVM_Value val;
bool ret = internal::seToJsValue(data, &val);
if(!ret) {
if (!ret) {
return false;
}
NODE_API_CALL_RESULT(status, _env, OH_JSVM_SetElement(_env, _objRef.getValue(_env), index, val), false);
@@ -521,7 +521,7 @@ bool Object::getAllKeys(std::vector<std::string>* allKeys) const {
if (status == JSVM_OK) {
size_t result = 0;
NODE_API_CALL(status, _env, OH_JSVM_GetValueStringUtf8(_env, val, nullptr, 0, &result));
if(status == JSVM_OK){
if (status == JSVM_OK) {
result += 1;
char buffer[result];
NODE_API_CALL(status, _env, OH_JSVM_GetValueStringUtf8(_env, val, buffer, sizeof(buffer), &result));
@@ -558,14 +558,14 @@ bool Object::call(const ValueArray& args, Object* thisObject, Value* rval) {
argv.reserve(10);
argc = args.size();
bool valid = internal::seToJsArgs(_env, args, &argv);
if(!valid) {
if (!valid) {
SE_LOGE("Failed to convert arguments from se::Value to JSVM_Value");
return false;
}
JSVM_Value return_val;
JSVM_Status status;
assert(isFunction());
if(thisObject != nullptr && !thisObject->_getJSObject()) {
if (thisObject != nullptr && !thisObject->_getJSObject()) {
SE_LOGE("Invalid 'this' object passed to function call (JS object is invalid or released)");
return false;
}
@@ -575,7 +575,7 @@ bool Object::call(const ValueArray& args, Object* thisObject, Value* rval) {
undefinedValue;
});
NODE_API_CALL_RESULT(status, _env,
OH_JSVM_CallFunction(_env, thisObj, _getJSObject(), argc, argv.data(), &return_val), false);
OH_JSVM_CallFunction(_env, thisObj, _getJSObject(), argc, argv.data(), &return_val), false);
if (rval) {
internal::jsToSeValue(return_val, rval);
}
@@ -703,7 +703,7 @@ void Object::sendWeakCallback(JSVM_Env env, void* nativeObject, void* finalizeHi
void Object::setClearMappingInFinalizer(bool v) {
_clearMappingInFinalizer = v;
// The lifecycle of Spine and Dragonbones c++ objects are controlled by their runtime.
// See the `cc::setSpineObjectDisposeCallback` invocation in jsb_spine_manuall.cpp.
// It listens on spine C++ objects's destruction and when the callback comes,
@@ -727,7 +727,7 @@ void Object::weakCallback(JSVM_Env env, void* nativeObject, void* finalizeHint /
if (seObj->_onCleaingPrivateData) { //called by cleanPrivateData, not release seObj;
return;
}
if(!NativePtrToObjectMap::isValid()) {
if (!NativePtrToObjectMap::isValid()) {
return;
}
if (seObj->_clearMappingInFinalizer && rawPtr != nullptr) {
@@ -747,9 +747,9 @@ void Object::weakCallback(JSVM_Env env, void* nativeObject, void* finalizeHint /
seObj->_getClass()->_getFinalizeFunction()(env, finalizeHint, finalizeHint);
}
}
__objectSetToBeReleasedInCleanup.erase(seObj);
seObj->_destructInFinalizer = true;
seObj->decRef();
}
@@ -780,14 +780,14 @@ void Object::cleanup() {
}
obj->decRef();
}
for (auto *obj : __objectSetToBeReleasedInCleanup) {
for (auto* obj : __objectSetToBeReleasedInCleanup) {
obj->decRef();
}
__objectSetToBeReleasedInCleanup.clear();
NativePtrToObjectMap::clear();
if (__objectSet) {
for (const auto& obj : *__objectSet) {
cls = obj->_getClass();
@@ -890,20 +890,19 @@ Object* Object::createPromise() {
return object;
}
ObjectRef::ObjectRef(Object *parent)
ObjectRef::ObjectRef(Object* parent)
: _parent(parent) {
}
ObjectRef::~ObjectRef() {
deleteRef();
}
void ObjectRef::init(JSVM_Env env, JSVM_Value obj) {
assert(_ref == nullptr);
_obj = obj;
_env = env;
// There is a bug in JSVM implementation:
// If we initialize the reference to 0 which means weak reference in JSVM,
// then we call the JSVM API in the following order:
@@ -915,7 +914,7 @@ void ObjectRef::init(JSVM_Env env, JSVM_Value obj) {
//
OH_JSVM_CreateReference(_env, _obj, 1, &_ref);
}
JSVM_Value ObjectRef::getValue(JSVM_Env env) const {
JSVM_Value r = nullptr;
JSVM_Status status;
@@ -1010,7 +1009,7 @@ void ObjectRef::deleteRef() {
In `se::Object::setPrivateObject`, after invoking `OH_JSVM_Wrap`, we need to call `ObjectRef::decRef` to reset
the object state to weak, which makes sure that weak callback get called.
*/
// If we have already been in the weak callback ( finalizer ), no need to apply this workaround fix.
if (!_parent->_destructInFinalizer) {
// WORKAROUND HERE
@@ -1023,4 +1022,3 @@ void ObjectRef::deleteRef() {
}
} // namespace se
@@ -24,8 +24,9 @@
****************************************************************************/
#pragma once
#include <set>
#include <cassert>
#include <set>
#include <unordered_map>
#include "../PrivateObject.h"
#include "../RefCounter.h"
#include "../Value.h"
@@ -33,7 +34,6 @@
#include "CommonHeader.h"
#include "HelperMacros.h"
#include "Utils.h"
#include <unordered_map>
namespace se {
class Class;
@@ -47,12 +47,12 @@ private:
JSVM_Ref _ref{nullptr};
JSVM_Env _env{nullptr};
JSVM_Value _obj{nullptr};
Object* _parent{nullptr};
Object *_parent{nullptr};
public:
ObjectRef(Object *parent);
~ObjectRef();
JSVM_Value getValue(JSVM_Env env) const;
void init(JSVM_Env env, JSVM_Value obj);
void incRef(JSVM_Env env);
@@ -76,7 +76,7 @@ public:
BIGINT64,
BIGUINT64
};
using BufferContentsFreeFunc = void (*)(void *contents, size_t byteLength, void *userData);
struct ExternalArrayBufferCallbackParams {
@@ -458,9 +458,9 @@ private:
uint32_t _rootCount = 0;
bool _onCleaingPrivateData = false;
internal::PrivateData *_internalData;
static std::unordered_map<Object*, JSVM_Deferred> resolverMap;
static std::unordered_map<Object *, JSVM_Deferred> resolverMap;
friend class ObjectRef;
friend class ScriptEngine;
};
@@ -27,14 +27,14 @@
#include <sstream>
#include "../MappingUtils.h"
#include "Class.h"
#include "CommonHeader.h"
#include "State.h"
#include "Utils.h"
#include "CommonHeader.h"
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include "ark_runtime/jsvm.h"
#include "ark_runtime/jsvm.h"
#else
#include "jsvm.h"
#include "jsvm.h"
#endif
#define _EXPOSE_GC "__jsb_gc__"
@@ -61,11 +61,11 @@ se::Value __oldConsoleWarn;
se::Value __oldConsoleError;
se::Value __oldConsoleAssert;
bool JSB_console_format_log(State& s, cc::LogLevel level, int msgIndex = 0) {
bool JSB_console_format_log(State &s, cc::LogLevel level, int msgIndex = 0) {
if (msgIndex < 0)
return false;
const auto& args = s.args();
const auto &args = s.args();
int argc = (int)args.size();
if ((argc - msgIndex) == 1) {
std::string msg = args[msgIndex].toStringForce();
@@ -73,37 +73,37 @@ bool JSB_console_format_log(State& s, cc::LogLevel level, int msgIndex = 0) {
} else if (argc > 1) {
std::string msg = args[msgIndex].toStringForce();
size_t pos;
for (int i = (msgIndex+1); i < argc; ++i) {
for (int i = (msgIndex + 1); i < argc; ++i) {
pos = msg.find("%");
if (pos != std::string::npos && pos != (msg.length()-1) &&
(msg[pos+1] == 'd' || msg[pos+1] == 's' || msg[pos+1] == 'f')) {
msg.replace(pos, 2, args[i].toStringForce());
} else {
msg += " " + args[i].toStringForce();
}
if (pos != std::string::npos && pos != (msg.length() - 1) &&
(msg[pos + 1] == 'd' || msg[pos + 1] == 's' || msg[pos + 1] == 'f')) {
msg.replace(pos, 2, args[i].toStringForce());
} else {
msg += " " + args[i].toStringForce();
}
}
cc::Log::logMessage(cc::LogType::KERNEL, level, "JS: %s", msg.c_str());
}
return true;
}
bool JSB_console_log(State& s) {
bool JSB_console_log(State &s) {
JSB_console_format_log(s, cc::LogLevel::LEVEL_DEBUG);
__oldConsoleLog.toObject()->call(s.args(), s.thisObject());
return true;
}
SE_BIND_FUNC(JSB_console_log)
bool JSB_console_debug(State& s) {
bool JSB_console_debug(State &s) {
JSB_console_format_log(s, cc::LogLevel::LEVEL_DEBUG);
__oldConsoleDebug.toObject()->call(s.args(), s.thisObject());
return true;
}
SE_BIND_FUNC(JSB_console_debug)
bool JSB_console_info(State& s) {
bool JSB_console_info(State &s) {
JSB_console_format_log(s, cc::LogLevel::INFO);
__oldConsoleInfo.toObject()->call(s.args(), s.thisObject());
return true;
@@ -111,15 +111,15 @@ bool JSB_console_info(State& s) {
SE_BIND_FUNC(JSB_console_info)
bool JSB_console_warn(State& s) {
bool JSB_console_warn(State &s) {
JSB_console_format_log(s, cc::LogLevel::WARN);
__oldConsoleWarn.toObject()->call(s.args(), s.thisObject());
return true;
}
SE_BIND_FUNC(JSB_console_warn)
bool JSB_console_error(State& s) {
bool JSB_console_error(State &s) {
JSB_console_format_log(s, cc::LogLevel::ERR);
__oldConsoleError.toObject()->call(s.args(), s.thisObject());
return true;
@@ -127,8 +127,8 @@ bool JSB_console_error(State& s) {
SE_BIND_FUNC(JSB_console_error)
bool JSB_console_assert(State& s) {
const auto& args = s.args();
bool JSB_console_assert(State &s) {
const auto &args = s.args();
if (!args.empty()) {
if (args[0].isBoolean() && !args[0].toBoolean()) {
JSB_console_format_log(s, cc::LogLevel::WARN, 1);
@@ -184,11 +184,11 @@ bool ScriptEngine::runScript(const std::string &path, Value *ret /* = nullptr */
}
bool ScriptEngine::evalString(const char *scriptStr, ssize_t length, Value *ret, const char *fileName) {
length = length < 0 ? strlen(scriptStr) :length;
length = length < 0 ? strlen(scriptStr) : length;
JSVM_Status status;
JSVM_Value jsvmStr;
JSVM_Value jsvmStr;
NODE_API_CALL(status, _env, OH_JSVM_CreateStringUtf8(_env, scriptStr, length, &jsvmStr));
if(status != JSVM_OK) {
if (status != JSVM_OK) {
CC_LOG_ERROR("ScriptEngine::evalString, create string failed, fileName = %s", fileName);
return false;
}
@@ -202,32 +202,31 @@ bool ScriptEngine::evalString(const char *scriptStr, ssize_t length, Value *ret,
.sourceMapUrl = nullptr,
.resourceName = fileName ? fileName : "",
.resourceLineOffset = 0,
.resourceColumnOffset = 0
};
.resourceColumnOffset = 0};
NODE_API_CALL(status, _env,
OH_JSVM_CompileScriptWithOrigin(_env, jsvmStr, cachedData, cacheLength, false, &cacheRejected,&scriptOrigin, &compiledScript));
if(status != JSVM_OK) {
CC_LOG_ERROR("ScriptEngine::evalSting, compile failed, fileName = %s", fileName);
return false;
NODE_API_CALL(status, _env,
OH_JSVM_CompileScriptWithOrigin(_env, jsvmStr, cachedData, cacheLength, false, &cacheRejected, &scriptOrigin, &compiledScript));
if (status != JSVM_OK) {
CC_LOG_ERROR("ScriptEngine::evalSting, compile failed, fileName = %s", fileName);
return false;
}
JSVM_Value result;
NODE_API_CALL(status, _env, OH_JSVM_RunScript(_env, compiledScript, &result));
if(status != JSVM_OK) {
CC_LOG_ERROR("ScriptEngine::evelSting, run failed, fileName = %s", fileName);
return false;
if (status != JSVM_OK) {
CC_LOG_ERROR("ScriptEngine::evelSting, run failed, fileName = %s", fileName);
return false;
}
// NOTE: Currently, we don't support JSVM code cache saving/loading.
// So creating code cache here is useless and wastes memory.
// if(!cachedData || cacheRejected) {
// NODE_API_CALL(status, _env,
// OH_JSVM_CreateCodeCache(_env, compiledScript, (const uint8_t **)&cachedData, &cacheLength));
// }
if(ret) {
// if(!cachedData || cacheRejected) {
// NODE_API_CALL(status, _env,
// OH_JSVM_CreateCodeCache(_env, compiledScript, (const uint8_t **)&cachedData, &cacheLength));
// }
if (ret) {
internal::jsToSeValue(result, ret);
}
@@ -236,7 +235,7 @@ bool ScriptEngine::evalString(const char *scriptStr, ssize_t length, Value *ret,
bool ScriptEngine::init() {
JSVM_Status status;
JSVM_Value result;
JSVM_Value result;
for (const auto &hook : _beforeInitHookArray) {
hook();
@@ -248,7 +247,7 @@ bool ScriptEngine::init() {
NODE_API_CALL(status, _env, OH_JSVM_OpenEnvScope(_env, &_envScope));
se::AutoHandleScope hs;
uint32_t jsvmVersion = 0;
NODE_API_CALL(status, _env, OH_JSVM_GetVersion(_env, &jsvmVersion));
SE_LOGD("Initializing JSVM, version: %u\n", jsvmVersion);
@@ -284,9 +283,9 @@ bool ScriptEngine::init() {
_globalObj->defineFunction("log", _SE(JSB_console_log));
_globalObj->defineFunction("forceGC", _SE(__forceGC));
_globalObj->getProperty(_EXPOSE_GC, &_gcFuncValue);
if(_gcFuncValue.isObject() && _gcFuncValue.toObject()->isFunction()) {
if (_gcFuncValue.isObject() && _gcFuncValue.toObject()->isFunction()) {
_gcFunc = _gcFuncValue.toObject();
} else {
_gcFunc = nullptr;
@@ -303,7 +302,7 @@ bool ScriptEngine::init() {
}
Object *ScriptEngine::getGlobalObject() const { return _globalObj; }
void ScriptEngine::closeEngine() {
JSVM_Env env = _env;
_env = nullptr;
@@ -327,16 +326,16 @@ bool ScriptEngine::start() {
if (!init()) {
return false;
}
// debugger
// debugger
if (isDebuggerEnabled()) {
if(_debuggerServerAddr == "0.0.0.0") {
OH_JSVM_OpenInspector(_env, "localhost", _debuggerServerPort);
if (_debuggerServerAddr == "0.0.0.0") {
OH_JSVM_OpenInspector(_env, "localhost", _debuggerServerPort);
} else {
OH_JSVM_OpenInspector(_env, _debuggerServerAddr.c_str(), _debuggerServerPort);
}
SE_LOGD("Debugger listening..., visit [ http://localhost:%d/json ] to configuration debugging information and copy the devtoolsFrontendUrl value to the browser!", _debuggerServerPort);
if(_isWaitForConnect) {
if (_isWaitForConnect) {
OH_JSVM_WaitForDebugger(_env, true);
}
}
@@ -373,11 +372,11 @@ void ScriptEngine::cleanup() {
SE_LOGD("ScriptEngine::cleanup begin ...\n");
_isInCleanup = true;
se::AutoHandleScope hs;
do{
do {
for (const auto &hook : _beforeCleanupHookArray) {
hook();
}
}while (0);
} while (0);
_beforeCleanupHookArray.clear();
SAFE_DEC_REF(_globalObj);
@@ -393,7 +392,7 @@ void ScriptEngine::cleanup() {
__oldConsoleAssert.setUndefined();
_globalObj = nullptr;
_isValid = false;
_isValid = false;
_gcFunc = nullptr;
_registerCallbackArray.clear();
@@ -409,7 +408,7 @@ void ScriptEngine::cleanup() {
_isInCleanup = false;
NativePtrToObjectMap::destroy();
_gcFuncValue.setUndefined();
SE_LOGD("ScriptEngine::cleanup end ...\n");
}
@@ -477,16 +476,16 @@ void ScriptEngine::clearException() {
}
void ScriptEngine::garbageCollect() {
CC_LOG_DEBUG("GC begin ..., (js->native map) size: %d",(int)NativePtrToObjectMap::size());
CC_LOG_DEBUG("GC begin ..., (js->native map) size: %d", (int)NativePtrToObjectMap::size());
if(_gcFunc == nullptr) {
if (_gcFunc == nullptr) {
JSVM_Status status;
NODE_API_CALL(status, _env, OH_JSVM_MemoryPressureNotification(_env, JSVM_MEMORY_PRESSURE_LEVEL_CRITICAL));
} else {
_gcFunc->call({}, nullptr);
}
CC_LOG_DEBUG("GC end ..., (js->native map) size: %d",(int)NativePtrToObjectMap::size());
CC_LOG_DEBUG("GC end ..., (js->native map) size: %d", (int)NativePtrToObjectMap::size());
}
bool ScriptEngine::isGarbageCollecting() const {
@@ -35,7 +35,7 @@ using HandleScope = JSVM_HandleScope;
namespace se {
class AutoHandleScope {
public:
// This interface needs to be implemented in JSVM, similar to V8.
// This interface needs to be implemented in JSVM, similar to V8.
// Ref:https://nodejs.org/docs/latest-v17.x/api/n-api.html#object-lifetime-management
AutoHandleScope();
~AutoHandleScope();
@@ -43,7 +43,7 @@ public:
private:
HandleScope _handleScope;
};
using RegisterCallback = bool (*)(Object *);
using RegisterCallback = bool (*)(Object *);
using ExceptionCallback = std::function<void(const char *, const char *, const char *)>; // location, message, stack
class ScriptEngine {
@@ -80,8 +80,8 @@ public:
/**
* @brief Shut down the JSVM engine, because cleanup doesn't destroy all objects immediately.
*/
void closeEngine();
void closeEngine();
/**
* @brief Sets the delegate for file operation.
* @param delegate[in] The delegate instance for file operation.
@@ -126,9 +126,9 @@ public:
*/
void setExceptionCallback(const ExceptionCallback &cb);
ExceptionCallback& getExceptionCallback() {
return _exceptionCallback;
}
ExceptionCallback &getExceptionCallback() {
return _exceptionCallback;
}
/**
* @brief Grab a snapshot of the current JavaScript execution stack.
@@ -150,7 +150,7 @@ public:
* @param[in] cb A callback for registering a native binding module.
* @note This method just add a callback to a vector, callbacks is invoked in `start` method.
*/
void addPermanentRegisterCallback(RegisterCallback cb);
void addPermanentRegisterCallback(RegisterCallback cb);
/**
* @brief Starts the script engine.
@@ -206,7 +206,7 @@ public:
Object *getGlobalObject() const;
static JSVM_Env getEnv();
static void setEnv(JSVM_Env env);
static void setEnv(JSVM_Env env);
/**
* @brief Adds a callback for registering a native binding module.
@@ -272,12 +272,12 @@ public:
*/
void throwException(const std::string &errorMessage);
/**
/**
* @brief for jsvm_new_instance, skip constructor.
*/
void _setNeedCallConstructor(bool need);
/**
/**
* @brief for jsvm_new_instance, skip constructor.
*/
bool _needCallConstructor();
@@ -292,7 +292,7 @@ public:
void handlePromiseExceptions();
private:
FileOperationDelegate _fileOperationDelegate;
FileOperationDelegate _fileOperationDelegate;
std::vector<RegisterCallback> _registerCallbackArray;
std::vector<RegisterCallback> _permRegisterCallbackArray;
@@ -301,12 +301,12 @@ private:
std::vector<std::function<void()>> _beforeCleanupHookArray;
std::vector<std::function<void()>> _afterCleanupHookArray;
Object * _globalObj = nullptr;
Object *_globalObj = nullptr;
Value _gcFuncValue;
Object *_gcFunc{nullptr};
JSVM_Env _env = nullptr;
JSVM_VM _vm = nullptr;
JSVM_Env _env = nullptr;
JSVM_VM _vm = nullptr;
JSVM_VMScope _vmScope = nullptr;
JSVM_EnvScope _envScope = nullptr;
ExceptionCallback _exceptionCallback;
@@ -316,7 +316,7 @@ private:
bool _isInCleanup{false};
bool _isErrorHandleWorking{false};
bool _isneedCallConstructor{true};
bool _isWaitForConnect{false};
uint32_t _debuggerServerPort{0};
ccstd::string _debuggerServerAddr;
+19 -18
View File
@@ -24,9 +24,9 @@
****************************************************************************/
#include "Utils.h"
#include "Class.h"
#include "CommonHeader.h"
#include "ScriptEngine.h"
#include "Class.h"
#define MAX_STRING_LENS 1024
@@ -35,20 +35,20 @@ namespace internal {
void jsToSeValue(const target_value& value, Value* v) {
assert(v != nullptr);
auto env = ScriptEngine::getEnv();
JSVM_Status status;
JSVM_Status status;
JSVM_ValueType valType;
int64_t iRet = 0;
double dRet = 0.0;
bool bRet = false;
bool lossless = false;
size_t len = 0;
void* privateObjPtr = nullptr;
void* nativePtr = nullptr;
Object* obj = nullptr;
int64_t iRet = 0;
double dRet = 0.0;
bool bRet = false;
bool lossless = false;
size_t len = 0;
void* privateObjPtr = nullptr;
void* nativePtr = nullptr;
Object* obj = nullptr;
if (!value) {
valType = JSVM_ValueType::JSVM_UNDEFINED;
}else {
} else {
NODE_API_CALL(status, env, OH_JSVM_Typeof(env, value, &valType));
}
@@ -106,7 +106,7 @@ void jsToSeValue(const target_value& value, Value* v) {
obj = reinterpret_cast<Object*>(privateObjPtr);
obj->incRef();
}
if (obj == nullptr) {
obj = Object::_createJSObject(env, value, nullptr);
}
@@ -141,7 +141,7 @@ bool seToJsValue(const Value& v, target_value* outJsVal) {
NODE_API_CALL(status, env, OH_JSVM_CreateDouble(env, v.toDouble(), outJsVal));
ret = (status == JSVM_OK);
break;
case Value::Type::String:
case Value::Type::String:
NODE_API_CALL(status, env, OH_JSVM_CreateStringUtf8(env, v.toString().c_str(), v.toString().length(), outJsVal));
ret = (status == JSVM_OK);
break;
@@ -151,7 +151,7 @@ bool seToJsValue(const Value& v, target_value* outJsVal) {
break;
case Value::Type::Object:
*outJsVal = v.toObject()->_getJSObject();
ret = (outJsVal != nullptr);
ret = (outJsVal != nullptr);
break;
case Value::Type::Null:
NODE_API_CALL(status, env, OH_JSVM_GetNull(env, outJsVal));
@@ -199,7 +199,7 @@ bool setReturnValue(const Value& data, target_value& argv) {
return seToJsValue(data, &argv);
}
std::string jsToString(const target_value &value) {
std::string jsToString(const target_value& value) {
se::Value seValue;
internal::jsToSeValue(value, &seValue);
if (seValue.isString()) {
@@ -209,7 +209,7 @@ std::string jsToString(const target_value &value) {
}
}
void logJsException(JSVM_Env env, const char *file, int line) {
void logJsException(JSVM_Env env, const char* file, int line) {
bool isPending = false;
JSVM_CALL_RETURN_VOID(OH_JSVM_IsExceptionPending(env, &isPending));
if (!isPending) {
@@ -232,11 +232,12 @@ void logJsException(JSVM_Env env, const char *file, int line) {
std::string stackStr = jsToString(stack);
std::string messageStr = jsToString(message);
CC_LOG_ERROR("JS exception occurred at %s:%d\n\
CC_LOG_ERROR(
"JS exception occurred at %s:%d\n\
[name]: %s\n\
[message]: %s\n\
[stack]: %s",
file, line, nameStr.c_str(), messageStr.c_str(), stackStr.c_str());
file, line, nameStr.c_str(), messageStr.c_str(), stackStr.c_str());
auto exceptionCallback = ScriptEngine::getInstance()->getExceptionCallback();
exceptionCallback("", messageStr.c_str(), stackStr.c_str());
}
+1 -1
View File
@@ -33,7 +33,7 @@ namespace internal {
using target_value = JSVM_Value;
struct PrivateData {
void * data;
void *data;
Object *seObj;
};
+12 -12
View File
@@ -51,7 +51,7 @@ Class *Class::create(const std::string &clsName, se::Object *parent, Object *par
return cls;
}
Class* Class::create(const std::initializer_list<const char *> &classPath, se::Object *parent, Object *parentProto, napi_callback ctor) {
Class *Class::create(const std::initializer_list<const char *> &classPath, se::Object *parent, Object *parentProto, napi_callback ctor) {
se::AutoHandleScope scope;
se::Object *currentParent = parent;
se::Value tmp;
@@ -64,7 +64,7 @@ Class* Class::create(const std::initializer_list<const char *> &classPath, se::O
}
bool Class::init(const std::string &clsName, Object *parent, Object *parentProto, napi_callback ctor) {
_name = clsName;
_name = clsName;
_parent = parent;
if (_parent != nullptr)
_parent->incRef();
@@ -86,7 +86,7 @@ napi_value Class::_defaultCtor(napi_env env, napi_callback_info info) {
return _this;
}
void Class::defineProperty(const char* name, napi_callback g, napi_callback s) {
void Class::defineProperty(const char *name, napi_callback g, napi_callback s) {
_properties.push_back({name, nullptr, nullptr, g, s, 0, napi_default_jsproperty, 0});
}
@@ -96,8 +96,8 @@ void Class::defineProperty(const std::initializer_list<const char *> &names, nap
}
}
void Class::defineStaticProperty(const char* name, napi_callback g, napi_callback s) {
if(g != nullptr && s != nullptr)
void Class::defineStaticProperty(const char *name, napi_callback g, napi_callback s) {
if (g != nullptr && s != nullptr)
_properties.push_back({name, nullptr, nullptr, g, s, 0, napi_static, 0});
}
@@ -109,12 +109,12 @@ bool Class::defineStaticProperty(const char *name, const Value &v, PropertyAttri
return true;
}
void Class::defineFunction(const char* name, napi_callback func) {
// When Napi defines a function, it needs to add the enum attribute, otherwise JS cannot traverse the function
void Class::defineFunction(const char *name, napi_callback func) {
// When Napi defines a function, it needs to add the enum attribute, otherwise JS cannot traverse the function
_properties.push_back({name, nullptr, func, nullptr, nullptr, nullptr, napi_default_jsproperty, nullptr});
}
void Class::defineStaticFunction(const char* name, napi_callback func) {
void Class::defineStaticFunction(const char *name, napi_callback func) {
_properties.push_back({name, nullptr, func, nullptr, nullptr, 0, napi_static, 0});
}
@@ -128,7 +128,7 @@ napi_finalize Class::_getFinalizeFunction() const {
}
void Class::install() {
napi_value cons;
napi_value cons;
napi_status status;
NODE_API_CALL(status, ScriptEngine::getEnv(), napi_define_class(ScriptEngine::getEnv(), _name.c_str(), -1, _ctorFunc, nullptr, _properties.size(), _properties.data(), &cons));
if (_parentProto) {
@@ -172,7 +172,7 @@ napi_status Class::inherit(napi_env env, napi_value subclass, napi_value superPr
return napi_ok;
}
argv[1] = superProto;
status = napi_call_function(env, objectClass, setProto, 2, argv, &callbackResult);
status = napi_call_function(env, objectClass, setProto, 2, argv, &callbackResult);
if (status != napi_ok) {
LOGE("ace zbclog napi_call_function setProto 1 %{public}d", status);
return napi_ok;
@@ -191,7 +191,7 @@ napi_value Class::_createJSObjectWithClass(Class *cls) {
return nullptr;
}
se::ScriptEngine::getInstance()->_setNeedCallConstructor(false);
NODE_API_CALL(status, ScriptEngine::getEnv(), napi_new_instance( ScriptEngine::getEnv(), clsCtor, 0, nullptr, &obj));
NODE_API_CALL(status, ScriptEngine::getEnv(), napi_new_instance(ScriptEngine::getEnv(), clsCtor, 0, nullptr, &obj));
se::ScriptEngine::getInstance()->_setNeedCallConstructor(true);
return obj;
}
@@ -207,7 +207,7 @@ napi_ref Class::_getCtorRef() const {
napi_value Class::_getCtorFunc() const {
assert(_constructor);
napi_value result = nullptr;
napi_value result = nullptr;
napi_status status;
NODE_API_CALL(status, ScriptEngine::getEnv(), napi_get_reference_value(ScriptEngine::getEnv(), _constructor, &result));
return result;
+29 -30
View File
@@ -25,9 +25,9 @@
#pragma once
#include <string>
#include "../Define.h"
#include "CommonHeader.h"
#include "Object.h"
#include "../Define.h"
#include "base/std/optional.h"
namespace se {
@@ -36,27 +36,26 @@ public:
static Class *create(const std::string &clsName, se::Object *parent, Object *parentProto, napi_callback ctor = nullptr);
static Class *create(const std::initializer_list<const char *> &classPath, se::Object *parent, Object *parentProto, napi_callback ctor = nullptr);
void defineFunction(const char* name, napi_callback func);
void defineProperty(const char* name, napi_callback g, napi_callback s);
void defineProperty(const std::initializer_list<const char *> &names, napi_callback g, napi_callback s);
void defineFunction(const char *name, napi_callback func);
void defineProperty(const char *name, napi_callback g, napi_callback s);
void defineProperty(const std::initializer_list<const char *> &names, napi_callback g, napi_callback s);
void defineStaticFunction(const char* name, napi_callback func);
void defineStaticProperty(const char* name, napi_callback g, napi_callback s);
bool defineStaticProperty(const char *name, const Value &value, PropertyAttribute attribute = PropertyAttribute::NONE);
void defineStaticFunction(const char *name, napi_callback func);
void defineStaticProperty(const char *name, napi_callback g, napi_callback s);
bool defineStaticProperty(const char *name, const Value &value, PropertyAttribute attribute = PropertyAttribute::NONE);
static napi_value _createJSObjectWithClass(Class *cls);
void defineFinalizeFunction(napi_finalize func);
static napi_value _createJSObjectWithClass(Class *cls);
void defineFinalizeFunction(napi_finalize func);
napi_finalize _getFinalizeFunction() const;
Object * getProto() const;
void install();
napi_status inherit(napi_env env, napi_value subclass, napi_value superclass);
napi_ref _getCtorRef() const;
napi_value _getCtorFunc() const;
const char * getName() const { return _name.c_str(); }
static void setExports(napi_value *expPtr) { _exports = expPtr; }
Object *getProto() const;
void install();
napi_status inherit(napi_env env, napi_value subclass, napi_value superclass);
napi_ref _getCtorRef() const;
napi_value _getCtorFunc() const;
const char *getName() const { return _name.c_str(); }
static void setExports(napi_value *expPtr) { _exports = expPtr; }
static void cleanup();
// Private API used in wrapper
void _setCtor(Object *obj); // NOLINT(readability-identifier-naming)
@@ -64,20 +63,20 @@ public:
private:
Class();
~Class();
bool init(const std::string &clsName, Object *parent, Object *parentProto, napi_callback ctor = nullptr);
void destroy();
bool init(const std::string &clsName, Object *parent, Object *parentProto, napi_callback ctor = nullptr);
void destroy();
static napi_value _defaultCtor(napi_env env, napi_callback_info info);
private:
ccstd::optional<Object *> _ctor;
static napi_value * _exports;
std::string _name;
Object * _parent = nullptr;
Object * _proto = nullptr;
Object * _parentProto = nullptr;
napi_callback _ctorFunc = Class::_defaultCtor;
napi_ref _constructor = nullptr;
ccstd::optional<Object *> _ctor;
static napi_value *_exports;
std::string _name;
Object *_parent = nullptr;
Object *_proto = nullptr;
Object *_parentProto = nullptr;
napi_callback _ctorFunc = Class::_defaultCtor;
napi_ref _constructor = nullptr;
std::vector<napi_property_descriptor> _properties;
napi_finalize _finalizeFunc = nullptr;
napi_finalize _finalizeFunc = nullptr;
};
}; // namespace se
@@ -64,10 +64,10 @@
#define DECLARE_NODE_API_GETTER(name, func) \
{ (name), nullptr, nullptr, (func), nullptr, nullptr, napi_default, nullptr }
void add_returned_status(napi_env env,
void add_returned_status(napi_env env,
const char* key,
napi_value object,
char* expected_message,
napi_value object,
char* expected_message,
napi_status expected_status,
napi_status actual_status);
@@ -30,10 +30,10 @@
#include <hilog/log.h>
#ifndef LOGI
#define LOGI(...) ((void) OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#define LOGW(...) ((void) OH_LOG_Print(LOG_APP, LOG_WARN, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#define LOGE(...) ((void) OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#define LOGD(...) ((void) OH_LOG_Print(LOG_APP, LOG_DEBUG, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#define LOGI(...) ((void)OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#define LOGW(...) ((void)OH_LOG_Print(LOG_APP, LOG_WARN, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#define LOGE(...) ((void)OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#define LOGD(...) ((void)OH_LOG_Print(LOG_APP, LOG_DEBUG, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#endif
#else
#define LOGI
@@ -91,17 +91,17 @@ constexpr inline T *SE_THIS_OBJECT(STATE &s) { // NOLINT(readability-identifier-
#define SE_QUOTEME(x) SE_QUOTEME_(x)
#define SE_REPORT_ERROR(fmt, ...) SE_LOGE("[ERROR] (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__)
#define SE_BIND_PROP_GET_IMPL(funcName, postFix) \
napi_value funcName##postFix##Registry(napi_env env, napi_callback_info info) { \
return jsbGetterWrapper(env, info, funcName, #funcName); \
#define SE_BIND_PROP_GET_IMPL(funcName, postFix) \
napi_value funcName##postFix##Registry(napi_env env, napi_callback_info info) { \
return jsbGetterWrapper(env, info, funcName, #funcName); \
}
#define SE_BIND_PROP_GET(funcName) SE_BIND_PROP_GET_IMPL(funcName, )
#define SE_BIND_FUNC_AS_PROP_GET(funcName) SE_BIND_PROP_GET_IMPL(funcName, _asGetter)
#define SE_BIND_PROP_SET_IMPL(funcName, postFix) \
napi_value funcName##postFix##Registry(napi_env env, napi_callback_info info) { \
return jsbSetterWrapper(env, info, funcName, #funcName); \
#define SE_BIND_PROP_SET_IMPL(funcName, postFix) \
napi_value funcName##postFix##Registry(napi_env env, napi_callback_info info) { \
return jsbSetterWrapper(env, info, funcName, #funcName); \
}
#define SE_BIND_PROP_SET(funcName) SE_BIND_PROP_SET_IMPL(funcName, )
@@ -110,10 +110,10 @@ constexpr inline T *SE_THIS_OBJECT(STATE &s) { // NOLINT(readability-identifier-
#define SE_DECLARE_FUNC(funcName) \
napi_value funcName##Registry(napi_env env, napi_callback_info info)
#define SE_BIND_FUNC(funcName) \
napi_value funcName##Registry( \
napi_env env, napi_callback_info info) { \
return jsbFunctionWrapper(env, info, funcName, #funcName); \
#define SE_BIND_FUNC(funcName) \
napi_value funcName##Registry( \
napi_env env, napi_callback_info info) { \
return jsbFunctionWrapper(env, info, funcName, #funcName); \
}
#define SE_BIND_FUNC_FAST(funcName) \
@@ -130,10 +130,10 @@ constexpr inline T *SE_THIS_OBJECT(STATE &s) { // NOLINT(readability-identifier-
return nullptr; \
}
#define SE_BIND_CTOR(funcName, cls, finalizeCb) \
napi_value funcName##Registry( \
napi_env env, napi_callback_info info) { \
return jsbConstructorWrapper(env, info, funcName, _SE(finalizeCb), cls, #funcName); \
#define SE_BIND_CTOR(funcName, cls, finalizeCb) \
napi_value funcName##Registry( \
napi_env env, napi_callback_info info) { \
return jsbConstructorWrapper(env, info, funcName, _SE(finalizeCb), cls, #funcName); \
}
#define SE_BIND_SUB_CLS_CTOR SE_BIND_CTOR
@@ -142,12 +142,11 @@ constexpr inline T *SE_THIS_OBJECT(STATE &s) { // NOLINT(readability-identifier-
void funcName##Registry( \
napi_env env, void *nativeObject, void * /*finalize_hint*/);
#define SE_BIND_FINALIZE_FUNC(funcName) \
void funcName##Registry( \
napi_env env, void *nativeObject, void *hint /*finalize_hint*/) { \
if (nativeObject == nullptr) { \
return; \
} \
jsbFinalizeWrapper(nativeObject, funcName, #funcName); \
#define SE_BIND_FINALIZE_FUNC(funcName) \
void funcName##Registry( \
napi_env env, void *nativeObject, void *hint /*finalize_hint*/) { \
if (nativeObject == nullptr) { \
return; \
} \
jsbFinalizeWrapper(nativeObject, funcName, #funcName); \
}
@@ -35,7 +35,7 @@
namespace se {
std::unique_ptr<std::unordered_map<Object*, void*>> __objectMap; // Currently, the value `void*` is always nullptr
Object::Object(): _objRef(this) {}
Object::Object() : _objRef(this) {}
Object::~Object() {
if (!_destructInFinalizer && _cls != nullptr) {
napi_remove_wrap(_env, _objRef.getValue(_env), nullptr);
@@ -738,18 +738,16 @@ void Object::clearPrivateData(bool clearMapping) {
}
}
ObjectRef::ObjectRef(Object *parent)
ObjectRef::ObjectRef(Object* parent)
: _parent(parent) {
}
ObjectRef::~ObjectRef() {
deleteRef();
}
napi_value ObjectRef::getValue(napi_env env) const {
napi_value result;
napi_value result;
napi_status status;
NODE_API_CALL(status, env, napi_get_reference_value(env, _ref, &result));
assert(status == napi_ok);
@@ -776,7 +774,7 @@ void ObjectRef::deleteRef() {
if (!_ref) {
return;
}
if(!_parent->_destructInFinalizer) {
if (!_parent->_destructInFinalizer) {
// Similar to jsvm, please read the comments inside jsvm.
napi_reference_ref(_env, _ref, nullptr);
}
+13 -15
View File
@@ -25,22 +25,22 @@
#pragma once
#include <cassert>
#include "../PrivateObject.h"
#include "../RefCounter.h"
#include "../Value.h"
#include "../config.h"
#include "CommonHeader.h"
#include "HelperMacros.h"
#include "../PrivateObject.h"
#include "base/std/container/unordered_map.h"
namespace se {
class Class;
class ObjectRef {
private:
napi_ref _ref{nullptr};
napi_env _env{nullptr};
napi_ref _ref{nullptr};
napi_env _env{nullptr};
napi_value _obj{nullptr};
Object* _parent{nullptr};
Object *_parent{nullptr};
public:
ObjectRef(Object *parent);
@@ -77,7 +77,7 @@ public:
void *contents{nullptr};
size_t byteLength{0};
void *userData{0};
};
};
Object();
~Object();
@@ -192,7 +192,6 @@ public:
return static_cast<se::CCIntrusivePtrPrivateObject<T> *>(_privateObject)->getData();
}
template <typename T>
inline T *getTypedPrivateData() const {
return reinterpret_cast<T *>(getPrivateData());
@@ -204,7 +203,6 @@ public:
*/
void clearPrivateData(bool clearMapping = true);
/**
* @brief Sets whether to clear the mapping of native object & se::Object in finalizer
*/
@@ -415,9 +413,9 @@ public:
*/
static Object *getObjectWithPtr(void *ptr);
Class * _getClass() const; // NOLINT(readability-identifier-naming)
Class *_getClass() const; // NOLINT(readability-identifier-naming)
napi_value _getJSObject() const;
void _setFinalizeCallback(napi_finalize finalizeCb); // NOLINT(readability-identifier-naming)
void _setFinalizeCallback(napi_finalize finalizeCb); // NOLINT(readability-identifier-naming)
/**
* @brief Returns the string for describing current object.
* @return The string for describing current object.
@@ -432,16 +430,16 @@ private:
static void cleanup();
private:
ObjectRef _objRef;
napi_finalize _finalizeCb = nullptr;
ObjectRef _objRef;
napi_finalize _finalizeCb = nullptr;
bool _clearMappingInFinalizer = true;
bool _destructInFinalizer = false;
void *_privateData = nullptr;
PrivateObjectBase *_privateObject = nullptr;
napi_env _env = nullptr;
Class * _cls = nullptr;
uint32_t _rootCount = 0;
bool _onCleaingPrivateData = false;
napi_env _env = nullptr;
Class *_cls = nullptr;
uint32_t _rootCount = 0;
bool _onCleaingPrivateData = false;
friend class ObjectRef;
friend class ScriptEngine;
@@ -24,12 +24,12 @@
****************************************************************************/
#include "ScriptEngine.h"
#include <napi/native_api.h>
#include <sstream>
#include "../MappingUtils.h"
#include "Class.h"
#include "Utils.h"
#include "CommonHeader.h"
#include <napi/native_api.h>
#include "Utils.h"
#include "base/std/container/array.h"
namespace se {
@@ -43,7 +43,7 @@ AutoHandleScope::~AutoHandleScope() {
ScriptEngine *gSriptEngineInstance = nullptr;
ScriptEngine::ScriptEngine() {};
ScriptEngine::ScriptEngine(){};
ScriptEngine::~ScriptEngine() = default;
@@ -85,8 +85,8 @@ bool ScriptEngine::runScript(const std::string &path, Value *ret /* = nullptr */
bool ScriptEngine::evalString(const char *scriptStr, ssize_t length, Value *ret, const char *fileName) {
napi_status status;
napi_value script;
napi_value result;
napi_value script;
napi_value result;
length = length < 0 ? NAPI_AUTO_LENGTH : length;
status = napi_create_string_utf8(ScriptEngine::getEnv(), scriptStr, length, &script);
LOGI("eval :%{public}s", scriptStr);
@@ -96,7 +96,7 @@ bool ScriptEngine::evalString(const char *scriptStr, ssize_t length, Value *ret,
bool ScriptEngine::init() {
napi_status status;
napi_value result;
napi_value result;
for (const auto &hook : _beforeInitHookArray) {
hook();
@@ -171,7 +171,7 @@ void ScriptEngine::cleanup() {
garbageCollect();
_globalObj = nullptr;
_isValid = false;
_isValid = false;
_registerCallbackArray.clear();
@@ -35,7 +35,7 @@ using HandleScope = napi_handle_scope;
namespace se {
class AutoHandleScope {
public:
// This interface needs to be implemented in NAPI, similar to V8.
// This interface needs to be implemented in NAPI, similar to V8.
// Ref:https://nodejs.org/docs/latest-v17.x/api/n-api.html#object-lifetime-management
AutoHandleScope();
~AutoHandleScope();
@@ -43,7 +43,7 @@ public:
private:
HandleScope _handleScope;
};
using RegisterCallback = bool (*)(Object *);
using RegisterCallback = bool (*)(Object *);
using ExceptionCallback = std::function<void(const char *, const char *, const char *)>; // location, message, stack
class ScriptEngine {
@@ -197,7 +197,7 @@ public:
Object *getGlobalObject() const;
static napi_env getEnv();
static void setEnv(napi_env env);
static void setEnv(napi_env env);
/**
* @brief Adds a callback for registering a native binding module.
@@ -263,12 +263,12 @@ public:
*/
void throwException(const std::string &errorMessage);
/**
/**
* @brief for napi_new_instance, skip constructor.
*/
void _setNeedCallConstructor(bool need);
/**
/**
* @brief for napi_new_instance, skip constructor.
*/
bool _needCallConstructor();
@@ -283,7 +283,7 @@ public:
void handlePromiseExceptions();
private:
FileOperationDelegate _fileOperationDelegate;
FileOperationDelegate _fileOperationDelegate;
std::vector<RegisterCallback> _registerCallbackArray;
std::vector<RegisterCallback> _permRegisterCallbackArray;
@@ -292,8 +292,8 @@ private:
std::vector<std::function<void()>> _beforeCleanupHookArray;
std::vector<std::function<void()>> _afterCleanupHookArray;
Object * _globalObj = nullptr;
napi_env _env = nullptr;
Object *_globalObj = nullptr;
napi_env _env = nullptr;
bool _isValid{false};
bool _isGarbageCollecting{false};
+13 -13
View File
@@ -24,9 +24,9 @@
****************************************************************************/
#include "Utils.h"
#include "Class.h"
#include "CommonHeader.h"
#include "ScriptEngine.h"
#include "Class.h"
#define MAX_STRING_LENS 1024
@@ -34,20 +34,20 @@ namespace se {
namespace internal {
void jsToSeValue(const target_value& value, Value* v) {
assert(v != nullptr);
napi_status status;
napi_status status;
napi_valuetype valType;
int64_t iRet = 0;
double dRet = 0.0;
bool bRet = false;
bool lossless = false;
size_t len = 0;
void* privateObjPtr = nullptr;
void* nativePtr = nullptr;
Object* obj = nullptr;
int64_t iRet = 0;
double dRet = 0.0;
bool bRet = false;
bool lossless = false;
size_t len = 0;
void* privateObjPtr = nullptr;
void* nativePtr = nullptr;
Object* obj = nullptr;
if (!value) {
valType = napi_valuetype::napi_undefined;
}else {
} else {
NODE_API_CALL(status, ScriptEngine::getEnv(), napi_typeof(ScriptEngine::getEnv(), value, &valType));
}
@@ -132,7 +132,7 @@ void jsToSeArgs(size_t argc, target_value* argv, ValueArray* outArr) {
bool seToJsValue(const Value& v, target_value* outJsVal) {
assert(outJsVal != nullptr);
bool ret = false;
bool ret = false;
napi_status status = napi_ok;
switch (v.getType()) {
case Value::Type::Number:
@@ -149,7 +149,7 @@ bool seToJsValue(const Value& v, target_value* outJsVal) {
break;
case Value::Type::Object:
*outJsVal = v.toObject()->_getJSObject();
ret = (outJsVal != nullptr);
ret = (outJsVal != nullptr);
break;
case Value::Type::Null:
NODE_API_CALL(status, ScriptEngine::getEnv(), napi_get_null(ScriptEngine::getEnv(), outJsVal));
+1 -1
View File
@@ -33,7 +33,7 @@ namespace internal {
using target_value = napi_value;
struct PrivateData {
void * data;
void *data;
Object *seObj;
};
@@ -25,91 +25,91 @@
#pragma once
#ifndef FOUNDATION_ACE_NAPI_INTERFACES_KITS_NAPI_NATIVE_COMMON_H
#define FOUNDATION_ACE_NAPI_INTERFACES_KITS_NAPI_NATIVE_COMMON_H
#define FOUNDATION_ACE_NAPI_INTERFACES_KITS_NAPI_NATIVE_COMMON_H
#define DEPRECATED __attribute__((__deprecated__))
#define DEPRECATED __attribute__((__deprecated__))
#ifndef NAPI_VERSION
#define NAPI_VERSION 8
#endif
#ifndef NAPI_VERSION
#define NAPI_VERSION 8
#endif
#define NAPI_RETVAL_NOTHING
#define NAPI_RETVAL_NOTHING
#define GET_AND_THROW_LAST_ERROR(env) \
do { \
const napi_extended_error_info* errorInfo = nullptr; \
napi_get_last_error_info((env), &errorInfo); \
bool isPending = false; \
napi_is_exception_pending((env), &isPending); \
if (!isPending && errorInfo != nullptr) { \
const char* errorMessage = \
errorInfo->error_message != nullptr ? errorInfo->error_message : "empty error message"; \
napi_throw_error((env), nullptr, errorMessage); \
} \
} while (0)
#define GET_AND_THROW_LAST_ERROR(env) \
do { \
const napi_extended_error_info* errorInfo = nullptr; \
napi_get_last_error_info((env), &errorInfo); \
bool isPending = false; \
napi_is_exception_pending((env), &isPending); \
if (!isPending && errorInfo != nullptr) { \
const char* errorMessage = \
errorInfo->error_message != nullptr ? errorInfo->error_message : "empty error message"; \
napi_throw_error((env), nullptr, errorMessage); \
} \
} while (0)
#define NAPI_ASSERT_BASE(env, assertion, message, retVal) \
do { \
if (!(assertion)) { \
napi_throw_error((env), nullptr, "assertion (" #assertion ") failed: " message); \
return retVal; \
} \
} while (0)
#define NAPI_ASSERT_BASE(env, assertion, message, retVal) \
do { \
if (!(assertion)) { \
napi_throw_error((env), nullptr, "assertion (" #assertion ") failed: " message); \
return retVal; \
} \
} while (0)
#define NAPI_ASSERT(env, assertion, message) NAPI_ASSERT_BASE(env, assertion, message, nullptr)
#define NAPI_ASSERT(env, assertion, message) NAPI_ASSERT_BASE(env, assertion, message, nullptr)
#define NAPI_ASSERT_RETURN_VOID(env, assertion, message) NAPI_ASSERT_BASE(env, assertion, message, NAPI_RETVAL_NOTHING)
#define NAPI_ASSERT_RETURN_VOID(env, assertion, message) NAPI_ASSERT_BASE(env, assertion, message, NAPI_RETVAL_NOTHING)
#define NAPI_CALL_BASE(env, theCall, retVal) \
do { \
if ((theCall) != napi_ok) { \
GET_AND_THROW_LAST_ERROR((env)); \
return retVal; \
} \
} while (0)
#define NAPI_CALL_BASE(env, theCall, retVal) \
do { \
if ((theCall) != napi_ok) { \
GET_AND_THROW_LAST_ERROR((env)); \
return retVal; \
} \
} while (0)
#define NAPI_CALL(env, theCall) NAPI_CALL_BASE(env, theCall, nullptr)
#define NAPI_CALL(env, theCall) NAPI_CALL_BASE(env, theCall, nullptr)
#define NAPI_CALL_RETURN_VOID(env, theCall) NAPI_CALL_BASE(env, theCall, NAPI_RETVAL_NOTHING)
#define NAPI_CALL_RETURN_VOID(env, theCall) NAPI_CALL_BASE(env, theCall, NAPI_RETVAL_NOTHING)
#define DECLARE_NAPI_PROPERTY(name, val) \
{ \
(name), nullptr, nullptr, nullptr, nullptr, val, napi_default, nullptr \
}
#define DECLARE_NAPI_PROPERTY(name, val) \
{ \
(name), nullptr, nullptr, nullptr, nullptr, val, napi_default, nullptr \
}
#define DECLARE_NAPI_STATIC_PROPERTY(name, val) \
{ \
(name), nullptr, nullptr, nullptr, nullptr, val, napi_static, nullptr \
}
#define DECLARE_NAPI_STATIC_PROPERTY(name, val) \
{ \
(name), nullptr, nullptr, nullptr, nullptr, val, napi_static, nullptr \
}
#define DECLARE_NAPI_FUNCTION(name, func) \
{ \
(name), nullptr, (func), nullptr, nullptr, nullptr, napi_default, nullptr \
}
#define DECLARE_NAPI_FUNCTION(name, func) \
{ \
(name), nullptr, (func), nullptr, nullptr, nullptr, napi_default, nullptr \
}
#define DECLARE_NAPI_FUNCTION_WITH_DATA(name, func, data) \
{ \
(name), nullptr, (func), nullptr, nullptr, nullptr, napi_default, data \
}
#define DECLARE_NAPI_FUNCTION_WITH_DATA(name, func, data) \
{ \
(name), nullptr, (func), nullptr, nullptr, nullptr, napi_default, data \
}
#define DECLARE_NAPI_STATIC_FUNCTION(name, func) \
{ \
(name), nullptr, (func), nullptr, nullptr, nullptr, napi_static, nullptr \
}
#define DECLARE_NAPI_STATIC_FUNCTION(name, func) \
{ \
(name), nullptr, (func), nullptr, nullptr, nullptr, napi_static, nullptr \
}
#define DECLARE_NAPI_GETTER(name, getter) \
{ \
(name), nullptr, nullptr, (getter), nullptr, nullptr, napi_default, nullptr \
}
#define DECLARE_NAPI_GETTER(name, getter) \
{ \
(name), nullptr, nullptr, (getter), nullptr, nullptr, napi_default, nullptr \
}
#define DECLARE_NAPI_SETTER(name, setter) \
{ \
(name), nullptr, nullptr, nullptr, (setter), nullptr, napi_default, nullptr \
}
#define DECLARE_NAPI_SETTER(name, setter) \
{ \
(name), nullptr, nullptr, nullptr, (setter), nullptr, napi_default, nullptr \
}
#define DECLARE_NAPI_GETTER_SETTER(name, getter, setter) \
{ \
(name), nullptr, nullptr, (getter), (setter), nullptr, napi_default, nullptr \
}
#define DECLARE_NAPI_GETTER_SETTER(name, getter, setter) \
{ \
(name), nullptr, nullptr, (getter), (setter), nullptr, napi_default, nullptr \
}
#endif /* FOUNDATION_ACE_NAPI_INTERFACES_KITS_NAPI_NATIVE_COMMON_H */
@@ -25,7 +25,6 @@
#pragma once
#include "v8.h"
#include <algorithm>
#include <chrono>
#include <map>
@@ -36,6 +35,7 @@
#include "base/Log.h"
#include "base/Macros.h"
#include "base/std/container/string.h"
#include "v8.h"
// #define RECORD_JSB_INVOKING
@@ -24,8 +24,8 @@
****************************************************************************/
#include "Object.h"
#include "v8/HelperMacros.h"
#include "application/ApplicationManager.h"
#include "v8/HelperMacros.h"
// Use node::Buffer to replace v8 api,to avoid link err in editor platform.
#if CC_EDITOR && CC_PLATFORM == CC_PLATFORM_WINDOWS
@@ -164,7 +164,7 @@ Object *Object::createPlainObject() {
return obj;
}
std::unordered_map<Object*, v8::Persistent<v8::Promise::Resolver>*> Object::resolverMap;
std::unordered_map<Object *, v8::Persistent<v8::Promise::Resolver> *> Object::resolverMap;
void Object::resolverPromise(Object *object, const Value &value) {
auto it = resolverMap.find(object);
@@ -172,7 +172,7 @@ void Object::resolverPromise(Object *object, const Value &value) {
v8::Isolate *isolate = __isolate;
v8::HandleScope scope(isolate);
v8::Local<v8::Context> context = isolate->GetCurrentContext();
auto* resolver = it->second;
auto *resolver = it->second;
v8::Local<v8::Value> v8Val;
se::internal::seToJsValue(__isolate, value, &v8Val);
resolver->Get(isolate)->Resolve(context, v8Val).ToChecked();
@@ -188,7 +188,7 @@ void Object::rejectPromise(Object *object, const Value &value) {
v8::Isolate *isolate = __isolate;
v8::HandleScope scope(isolate);
v8::Local<v8::Context> context = isolate->GetCurrentContext();
auto* resolver = it->second;
auto *resolver = it->second;
v8::Local<v8::Value> v8Val;
se::internal::seToJsValue(isolate, value, &v8Val);
resolver->Get(isolate)->Reject(context, v8Val).ToChecked();
+1 -1
View File
@@ -708,7 +708,7 @@ private:
ccstd::string _objectCreationStackFrame;
#endif
static std::unordered_map<Object*, v8::Persistent<v8::Promise::Resolver>*> resolverMap;
static std::unordered_map<Object *, v8::Persistent<v8::Promise::Resolver> *> resolverMap;
friend class ScriptEngine;
friend class JSBPersistentHandleVisitor;
@@ -480,7 +480,7 @@ void ScriptEngine::cleanup() {
hook();
}
_beforeCleanupHookArray.clear();
// Clear unhandled promises
_unhandledPromises.clear();
_ignoreUnhandledPromises = false;
+2 -2
View File
@@ -248,8 +248,8 @@ ExternalStringResource::ExternalStringResource(std::u16string &&s)
: _s(std::move(s)) {
}
const uint16_t* ExternalStringResource::data() const {
return reinterpret_cast<const uint16_t*>(_s.data());
const uint16_t *ExternalStringResource::data() const {
return reinterpret_cast<const uint16_t *>(_s.data());
}
size_t ExternalStringResource::length() const {
+2 -2
View File
@@ -54,8 +54,8 @@ class ExternalStringResource : public v8::String::ExternalStringResource {
public:
explicit ExternalStringResource(std::u16string &&s);
~ExternalStringResource() override = default;
const uint16_t* data() const override;
const uint16_t *data() const override;
size_t length() const override;
void Dispose() override;
@@ -10,8 +10,8 @@
#if (SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8) && SE_ENABLE_INSPECTOR
#include <string.h>
#include <assert.h>
#include <string.h>
#if defined(_MSC_VER)
#include <stdlib.h>
@@ -391,11 +391,11 @@ public:
explicit ChannelImpl(V8Inspector *inspector,
InspectorSessionDelegate *delegate)
: delegate_(delegate) {
#if V8_MAJOR_VERSION > 10 || (V8_MAJOR_VERSION == 10 && V8_MINOR_VERSION > 3)
#if V8_MAJOR_VERSION > 10 || (V8_MAJOR_VERSION == 10 && V8_MINOR_VERSION > 3)
session_ = inspector->connect(1, this, StringView(), v8_inspector::V8Inspector::ClientTrustLevel::kFullyTrusted);
#else
#else
session_ = inspector->connect(1, this, StringView());
#endif
#endif
}
virtual ~ChannelImpl() {}
@@ -1,13 +1,13 @@
#include "inspector_io.h"
#if (SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8) && SE_ENABLE_INSPECTOR
#include "inspector_socket_server.h"
#include "env.h"
#include "inspector_socket_server.h"
#include "node.h"
//cjh #include "node_crypto.h"
#include "node_mutex.h"
#include "v8-inspector.h"
#include "util.h"
#include "v8-inspector.h"
#include "zlib.h"
#include "libplatform/libplatform.h"
@@ -9,9 +9,9 @@
#include "node_mutex.h"
#include "uv.h"
#include <stddef.h>
#include <deque>
#include <memory>
#include <stddef.h>
#if !HAVE_INSPECTOR
#error("This header can only be used when inspector is enabled")
@@ -28,8 +28,8 @@
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#include "util.h"
#include <cstring>
#include "util.h"
#if defined(_MSC_VER)
#include <intrin.h>
@@ -316,7 +316,8 @@ public:
// Current maximum capacity of the buffer with which SetLength() can be used
// without first calling AllocateSufficientStorage().
size_t capacity() const {
return IsAllocated() ? capacity_ : IsInvalidated() ? 0 : kStackStorageSize;
return IsAllocated() ? capacity_ : IsInvalidated() ? 0
: kStackStorageSize;
}
// Make sure enough space for `storage` entries is available.
+53 -58
View File
@@ -2,44 +2,44 @@
#include "bindings/auto/jsb_box2d_auto.h"
#include "bindings/manual/jsb_global.h"
#define GET_THIS() \
do {\
if (_thisObject != nullptr) { \
_thisObject->decRef(); \
} \
_thisObject = thisObject; \
_thisObject->incRef(); \
} while(0)
#define GET_THIS() \
do { \
if (_thisObject != nullptr) { \
_thisObject->decRef(); \
} \
_thisObject = thisObject; \
_thisObject->incRef(); \
} while (0)
#define GET_JS_PROPERTY(name) \
do {\
if (_cb##name != nullptr) { \
_cb##name->decRef(); \
_cb##name = nullptr; \
} \
se::Value callbackVal; \
bool ok = thisObject->getProperty(#name, &callbackVal); \
CC_ASSERT(ok && callbackVal.isObject() && callbackVal.toObject()->isFunction()); \
se::Object* callbackObj = callbackVal.toObject(); \
callbackObj->incRef(); \
_cb##name = callbackObj; \
} while(0)
#define GET_JS_PROPERTY(name) \
do { \
if (_cb##name != nullptr) { \
_cb##name->decRef(); \
_cb##name = nullptr; \
} \
se::Value callbackVal; \
bool ok = thisObject->getProperty(#name, &callbackVal); \
CC_ASSERT(ok&& callbackVal.isObject() && callbackVal.toObject()->isFunction()); \
se::Object* callbackObj = callbackVal.toObject(); \
callbackObj->incRef(); \
_cb##name = callbackObj; \
} while (0)
#define SAFE_RELEASE_CALLBACK(name) \
do {\
if (_cb##name != nullptr) { \
_cb##name->decRef(); \
_cb##name = nullptr; \
} \
} while(0)
do { \
if (_cb##name != nullptr) { \
_cb##name->decRef(); \
_cb##name = nullptr; \
} \
} while (0)
#define SAFE_RELEASE_THIS() \
do { \
if (_thisObject != nullptr) { \
_thisObject->decRef(); \
_thisObject = nullptr; \
} \
} while(0)
#define SAFE_RELEASE_THIS() \
do { \
if (_thisObject != nullptr) { \
_thisObject->decRef(); \
_thisObject = nullptr; \
} \
} while (0)
JSBQueryCallback::JSBQueryCallback() {
_args.resize(1);
@@ -50,11 +50,11 @@ JSBQueryCallback::~JSBQueryCallback() {
SAFE_RELEASE_CALLBACK(ReportFixture);
}
void JSBQueryCallback::initWithThis(se::Object *thisObject) {
void JSBQueryCallback::initWithThis(se::Object* thisObject) {
GET_THIS();
GET_JS_PROPERTY(ReportFixture);
}
bool JSBQueryCallback::ReportFixture(b2Fixture* fixture) {
se::AutoHandleScope hs;
if (_cbReportFixture == nullptr) {
@@ -69,17 +69,15 @@ bool JSBQueryCallback::ReportFixture(b2Fixture* fixture) {
if (rval.isBoolean()) {
return rval.toBoolean();
}
return false;
}
JSBRayCastCallback::JSBRayCastCallback() {
_args.resize(4);
}
void JSBRayCastCallback::initWithThis(se::Object *thisObject) {
void JSBRayCastCallback::initWithThis(se::Object* thisObject) {
GET_THIS();
GET_JS_PROPERTY(ReportFixture);
}
@@ -88,14 +86,14 @@ JSBRayCastCallback::~JSBRayCastCallback() {
SAFE_RELEASE_THIS();
SAFE_RELEASE_CALLBACK(ReportFixture);
}
float JSBRayCastCallback::ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float fraction) {
se::AutoHandleScope hs;
if (_cbReportFixture == nullptr) {
return 0.F;
}
bool ok = nativevalue_to_se(fixture, _args[0]);
SE_PRECONDITION2(ok, 0.F, "Error processing arguments");
ok = nativevalue_to_se(point, _args[1]);
@@ -110,7 +108,7 @@ float JSBRayCastCallback::ReportFixture(b2Fixture* fixture, const b2Vec2& point,
if (rval.isNumber()) {
return rval.toFloat();
}
return 0.F;
}
@@ -131,7 +129,7 @@ JSBB2Draw::~JSBB2Draw() {
SAFE_RELEASE_CALLBACK(DrawPoint);
}
void JSBB2Draw::initWithThis(se::Object *thisObject) {
void JSBB2Draw::initWithThis(se::Object* thisObject) {
GET_THIS();
GET_JS_PROPERTY(DrawPolygon);
GET_JS_PROPERTY(DrawSolidPolygon);
@@ -142,7 +140,7 @@ void JSBB2Draw::initWithThis(se::Object *thisObject) {
GET_JS_PROPERTY(DrawPoint);
}
void JSBB2Draw::DrawPolygonWithCallback(se::Object *cbObj, const b2Vec2* vertices, int32 vertexCount, const b2Color& color) {
void JSBB2Draw::DrawPolygonWithCallback(se::Object* cbObj, const b2Vec2* vertices, int32 vertexCount, const b2Color& color) {
if (cbObj == nullptr || vertexCount <= 0 || vertices == nullptr) {
return;
}
@@ -151,7 +149,7 @@ void JSBB2Draw::DrawPolygonWithCallback(se::Object *cbObj, const b2Vec2* vertice
ccstd::vector<b2Vec2> verticeArray;
verticeArray.resize(vertexCount);
memcpy(verticeArray.data(), vertices, sizeof(b2Vec2) * vertexCount);
bool ok = nativevalue_to_se(verticeArray, _args3[0]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
ok = nativevalue_to_se(vertexCount, _args3[1]);
@@ -172,7 +170,6 @@ void JSBB2Draw::DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, cons
DrawPolygonWithCallback(_cbDrawSolidPolygon, vertices, vertexCount, color);
}
/// Draw a circle.
void JSBB2Draw::DrawCircle(const b2Vec2& center, float radius, const b2Color& color) {
if (_cbDrawCircle == nullptr) {
@@ -180,7 +177,7 @@ void JSBB2Draw::DrawCircle(const b2Vec2& center, float radius, const b2Color& co
}
se::AutoHandleScope hs;
bool ok = nativevalue_to_se(center, _args3[0]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
ok = nativevalue_to_se(radius, _args3[1]);
@@ -232,7 +229,7 @@ void JSBB2Draw::DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& c
/// Draw a transform. Choose your own length scale.
/// @param xf a transform.
void JSBB2Draw::DrawTransform(const b2Transform& xf) {
if (_cbDrawTransform== nullptr) {
if (_cbDrawTransform == nullptr) {
return;
}
@@ -251,7 +248,7 @@ void JSBB2Draw::DrawPoint(const b2Vec2& p, float size, const b2Color& color) {
}
se::AutoHandleScope hs;
bool ok = nativevalue_to_se(p, _args3[0]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
ok = nativevalue_to_se(size, _args3[1]);
@@ -261,8 +258,6 @@ void JSBB2Draw::DrawPoint(const b2Vec2& p, float size, const b2Color& color) {
_cbDrawPoint->call(_args3, _thisObject);
}
// b2ContactListener
@@ -278,7 +273,7 @@ JSB_b2ContactListener::~JSB_b2ContactListener() {
SAFE_RELEASE_CALLBACK(PostSolve);
}
void JSB_b2ContactListener::initWithThis(se::Object *thisObject) {
void JSB_b2ContactListener::initWithThis(se::Object* thisObject) {
GET_THIS();
GET_JS_PROPERTY(BeginContact);
GET_JS_PROPERTY(EndContact);
@@ -316,12 +311,12 @@ void JSB_b2ContactListener::PreSolve(b2Contact* contact, const b2Manifold* oldMa
bool ok = nativevalue_to_se(contact, _args2[0]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
static b2Manifold gManifold;
gManifold = *oldManifold;
ok = nativevalue_to_se(gManifold, _args2[1]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
ok = _cbPreSolve->call(_args2, _thisObject);
}
@@ -333,11 +328,11 @@ void JSB_b2ContactListener::PostSolve(b2Contact* contact, const b2ContactImpulse
bool ok = nativevalue_to_se(contact, _args2[0]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
static b2ContactImpulse gImpulse;
gImpulse = *impulse;
ok = nativevalue_to_se(gImpulse, _args2[1]);
SE_PRECONDITION2_VOID(ok, "Error processing arguments");
ok = _cbPostSolve->call(_args2, _thisObject);
}
+41 -42
View File
@@ -1,35 +1,35 @@
#pragma once
#include "box2d/box2d.h"
#include "bindings/jswrapper/SeApi.h"
#include "box2d/box2d.h"
class JSBQueryCallback : public b2QueryCallback {
public:
JSBQueryCallback();
~JSBQueryCallback();
void initWithThis(se::Object *thisObject);
void initWithThis(se::Object* thisObject);
bool ReportFixture(b2Fixture* fixture) override;
private:
se::Object *_cbReportFixture{};
se::Object *_thisObject{};
se::Object* _cbReportFixture{};
se::Object* _thisObject{};
se::ValueArray _args;
};
class JSBRayCastCallback : public b2RayCastCallback {
class JSBRayCastCallback : public b2RayCastCallback {
public:
JSBRayCastCallback();
~JSBRayCastCallback();
void initWithThis(se::Object *thisObject);
void initWithThis(se::Object* thisObject);
float ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float fraction) override;
private:
se::Object *_cbReportFixture{};
se::Object *_thisObject{};
se::Object* _cbReportFixture{};
se::Object* _thisObject{};
se::ValueArray _args;
};
@@ -37,11 +37,12 @@ class JSBB2Draw : public b2Draw {
public:
JSBB2Draw();
~JSBB2Draw();
void initWithThis(se::Object *thisObject);
void initWithThis(se::Object* thisObject);
private:
void DrawPolygonWithCallback(se::Object *cbObj, const b2Vec2* vertices, int32 vertexCount, const b2Color& color);
void DrawPolygonWithCallback(se::Object* cbObj, const b2Vec2* vertices, int32 vertexCount, const b2Color& color);
public:
/// Draw a closed polygon provided in CCW order.
void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) override;
@@ -49,13 +50,12 @@ public:
/// Draw a solid closed polygon provided in CCW order.
void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) override;
/// Draw a circle.
void DrawCircle(const b2Vec2& center, float radius, const b2Color& color) override;
/// Draw a solid circle.
void DrawSolidCircle(const b2Vec2& center, float radius, const b2Vec2& axis, const b2Color& color) override;
/// Draw a line segment.
void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) override;
@@ -65,30 +65,29 @@ public:
/// Draw a point.
void DrawPoint(const b2Vec2& p, float size, const b2Color& color) override;
/// Set the drawing flags.
inline void SetFlags(uint32 flags) { b2Draw::SetFlags(flags); }
/// Get the drawing flags.
inline uint32 GetFlags() const { return b2Draw::GetFlags(); };
inline uint32 GetFlags() const { return b2Draw::GetFlags(); };
/// Append flags to the current flags.
inline void AppendFlags(uint32 flags) { b2Draw::AppendFlags(flags); }
/// Clear flags from the current flags.
inline void ClearFlags(uint32 flags) { b2Draw::ClearFlags(flags); }
private:
se::Object *_cbDrawPolygon{};
se::Object *_cbDrawSolidPolygon{};
se::Object *_cbDrawCircle{};
se::Object *_cbDrawSolidCircle{};
se::Object *_cbDrawSegment{};
se::Object *_cbDrawTransform{};
se::Object *_cbDrawPoint{};
se::Object *_thisObject{};
se::Object* _cbDrawPolygon{};
se::Object* _cbDrawSolidPolygon{};
se::Object* _cbDrawCircle{};
se::Object* _cbDrawSolidCircle{};
se::Object* _cbDrawSegment{};
se::Object* _cbDrawTransform{};
se::Object* _cbDrawPoint{};
se::Object* _thisObject{};
se::ValueArray _args1;
se::ValueArray _args3;
se::ValueArray _args4;
@@ -99,19 +98,19 @@ class JSB_b2ContactListener : public b2ContactListener {
public:
JSB_b2ContactListener();
~JSB_b2ContactListener();
void initWithThis(se::Object *thisObject);
void initWithThis(se::Object* thisObject);
void BeginContact(b2Contact* contact) override;
void EndContact(b2Contact* contact) override;
void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override;
void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) override;
private:
se::Object *_thisObject{};
se::Object *_cbBeginContact{};
se::Object *_cbEndContact{};
se::Object *_cbPreSolve{};
se::Object *_cbPostSolve{};
se::Object* _thisObject{};
se::Object* _cbBeginContact{};
se::Object* _cbEndContact{};
se::Object* _cbPreSolve{};
se::Object* _cbPostSolve{};
se::ValueArray _args1;
se::ValueArray _args2;
};
@@ -107,13 +107,12 @@ bool JavaScriptArkTsBridge::CallInfo::execute(se::Value& rval) {
module_name = pos != std::string::npos ? pathStr.substr(0, pos).c_str() : "entry";
}
char* module_info = __getModuleInfo(module_name);
std::promise<cc::CallbackParamType> promise;
std::function<void(cc::CallbackParamType)> cb = [&promise](cc::CallbackParamType message) {
promise.set_value(message);
};
cc::CallParam *callParam = new cc::CallParam{_isSyn, cb, _paramStr, module_info, _clsPath, method};
cc::CallParam* callParam = new cc::CallParam{_isSyn, cb, _paramStr, module_info, _clsPath, method};
if (_isSyn) {
cc::JSFunction::getFunction("executeMethodSync").invoke(callParam);
} else {
@@ -154,8 +153,8 @@ static bool JavaScriptArkTsBridge_callStaticMethod(se::State& s) {
methodName = seval_to_type<std::string>(args[1], ok);
SE_PRECONDITION2(ok, false, "Converting methodName failed!");
if(argc > 2) {
if (argc > 2) {
paramStr = seval_to_type<std::string>(args[2], ok);
SE_PRECONDITION2(ok, false, "Converting paramStr failed!");
}
@@ -24,7 +24,7 @@
#pragma once
namespace se {
class Object;
class Object;
}
bool register_javascript_arkTs_bridge(se::Object* obj);
@@ -22,15 +22,14 @@ private:
TempFloatArray tempFloatArray;
bool js_b2World_SetContactListener(se::State& s)
{
bool js_b2World_SetContactListener(se::State &s) {
CC_UNUSED bool ok = true;
const auto& args = s.args();
const auto &args = s.args();
size_t argc = args.size();
b2World *arg1 = (b2World *) NULL ;
JSB_b2ContactListener *arg2 = (JSB_b2ContactListener *) NULL ;
b2World *arg1 = (b2World *)NULL;
JSB_b2ContactListener *arg2 = (JSB_b2ContactListener *)NULL;
if(argc != 1) {
if (argc != 1) {
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
return false;
}
@@ -41,20 +40,18 @@ bool js_b2World_SetContactListener(se::State& s)
SE_PRECONDITION2(ok, false, "Error processing arguments");
(arg1)->SetContactListener(arg2);
return true;
}
SE_BIND_FUNC(js_b2World_SetContactListener)
bool js_b2World_SetDebugDraw(se::State& s)
{
bool js_b2World_SetDebugDraw(se::State &s) {
CC_UNUSED bool ok = true;
const auto& args = s.args();
const auto &args = s.args();
size_t argc = args.size();
b2World *arg1 = (b2World *) NULL ;
JSBB2Draw *arg2 = (JSBB2Draw *) NULL ;
b2World *arg1 = (b2World *)NULL;
JSBB2Draw *arg2 = (JSBB2Draw *)NULL;
if(argc != 1) {
if (argc != 1) {
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
return false;
}
@@ -65,22 +62,20 @@ bool js_b2World_SetDebugDraw(se::State& s)
SE_PRECONDITION2(ok, false, "Error processing arguments");
(arg1)->SetDebugDraw(arg2);
return true;
}
SE_BIND_FUNC(js_b2World_SetDebugDraw)
bool js_b2World_QueryAABB(se::State& s)
{
bool js_b2World_QueryAABB(se::State &s) {
CC_UNUSED bool ok = true;
const auto& args = s.args();
const auto &args = s.args();
size_t argc = args.size();
b2World *arg1 = (b2World *) NULL ;
JSBQueryCallback *arg2 = (JSBQueryCallback *) NULL ;
b2AABB *arg3 = 0 ;
b2AABB temp3 ;
b2World *arg1 = (b2World *)NULL;
JSBQueryCallback *arg2 = (JSBQueryCallback *)NULL;
b2AABB *arg3 = 0;
b2AABB temp3;
if(argc != 2) {
if (argc != 2) {
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2);
return false;
}
@@ -94,26 +89,24 @@ bool js_b2World_QueryAABB(se::State& s)
SE_PRECONDITION2(ok, false, "Error processing arguments");
arg3 = &temp3;
((b2World const *)arg1)->QueryAABB(arg2,(b2AABB const &)*arg3);
((b2World const *)arg1)->QueryAABB(arg2, (b2AABB const &)*arg3);
return true;
}
SE_BIND_FUNC(js_b2World_QueryAABB)
bool js_b2World_RayCast(se::State& s)
{
bool js_b2World_RayCast(se::State &s) {
CC_UNUSED bool ok = true;
const auto& args = s.args();
const auto &args = s.args();
size_t argc = args.size();
b2World *arg1 = (b2World *) NULL ;
JSBRayCastCallback *arg2 = (JSBRayCastCallback *) NULL ;
b2Vec2 *arg3 = 0 ;
b2Vec2 *arg4 = 0 ;
b2Vec2 temp3 ;
b2Vec2 temp4 ;
b2World *arg1 = (b2World *)NULL;
JSBRayCastCallback *arg2 = (JSBRayCastCallback *)NULL;
b2Vec2 *arg3 = 0;
b2Vec2 *arg4 = 0;
b2Vec2 temp3;
b2Vec2 temp4;
if(argc != 3) {
if (argc != 3) {
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 3);
return false;
}
@@ -127,26 +120,23 @@ bool js_b2World_RayCast(se::State& s)
SE_PRECONDITION2(ok, false, "Error processing arguments");
arg3 = &temp3;
ok &= sevalue_to_native(args[2], &temp4, s.thisObject());
SE_PRECONDITION2(ok, false, "Error processing arguments");
arg4 = &temp4;
((b2World const *)arg1)->RayCast(arg2,(b2Vec2 const &)*arg3,(b2Vec2 const &)*arg4);
((b2World const *)arg1)->RayCast(arg2, (b2Vec2 const &)*arg3, (b2Vec2 const &)*arg4);
return true;
}
SE_BIND_FUNC(js_b2World_RayCast)
bool js_Contact_GetWorldManifold(se::State& s)
{
bool js_Contact_GetWorldManifold(se::State &s) {
CC_UNUSED bool ok = true;
const auto& args = s.args();
const auto &args = s.args();
size_t argc = args.size();
b2Contact *arg1 = (b2Contact *) NULL ;
b2Contact *arg1 = (b2Contact *)NULL;
if(argc != 1) {
if (argc != 1) {
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
return false;
}
@@ -172,7 +162,7 @@ bool js_Contact_GetWorldManifold(se::State& s)
se::Value points;
worldManifoldObj->getProperty("points", &points);
if (points.isObject() && points.toObject()->isArray()) {
auto* pointsObj = points.toObject();
auto *pointsObj = points.toObject();
for (uint32_t i = 0; i < b2_maxManifoldPoints; ++i) {
se::Value e;
if (pointsObj->getArrayElement(i, &e) && e.isObject()) {
@@ -187,7 +177,7 @@ bool js_Contact_GetWorldManifold(se::State& s)
se::Value separations;
worldManifoldObj->getProperty("separations", &separations);
if (separations.isObject() && separations.toObject()->isArray()) {
auto* separationsObj = separations.toObject();
auto *separationsObj = separations.toObject();
for (uint32_t i = 0; i < b2_maxManifoldPoints; ++i) {
separationsObj->setArrayElement(i, se::Value(worldManifold.separations[i]));
}
@@ -198,9 +188,9 @@ bool js_Contact_GetWorldManifold(se::State& s)
}
SE_BIND_FUNC(js_Contact_GetWorldManifold)
bool js_b2PolygonShape_Set(se::State& s) {
bool js_b2PolygonShape_Set(se::State &s) {
CC_UNUSED bool ok = true;
const auto& args = s.args();
const auto &args = s.args();
size_t argc = args.size();
if (argc != 2) {
return false;
@@ -359,7 +349,7 @@ bool js_ChainShape_m_vertices_get(se::State &s) {
}
SE_BIND_PROP_GET(js_ChainShape_m_vertices_get)
} // namespace {
} // namespace
bool register_all_box2d_manual(se::Object *obj) { // NOLINT
// Get the ns
@@ -390,12 +380,12 @@ bool register_all_box2d_manual(se::Object *obj) { // NOLINT
__jsb_b2ContactImpulse_proto->defineProperty("normalImpulses", _SE(js_ContactImpulse_normalImpulses_get), nullptr);
__jsb_b2ContactImpulse_proto->defineProperty("tangentImpulses", _SE(js_ContactImpulse_tangentImpulses_get), nullptr);
__jsb_b2PolygonShape_proto->defineProperty("m_vertices", _SE(js_PolygonShape_m_vertices_get), nullptr);
__jsb_b2PolygonShape_proto->defineProperty("m_normals", _SE(js_PolygonShape_m_normals_get), nullptr);
__jsb_b2ChainShape_proto->defineProperty("m_vertices", _SE(js_ChainShape_m_vertices_get), nullptr);
nsObj->setProperty("maxFloat", se::Value(b2_maxFloat));
nsObj->setProperty("epsilon", se::Value(b2_epsilon));
nsObj->setProperty("pi", se::Value(b2_pi));
@@ -738,7 +738,6 @@ static bool js_readFile_doJob(const ccstd::string &fullPath, typename ReadFileDo
return false;
}
if constexpr (std::is_same_v<T, ccstd::string> && isJson) {
// TODO(cjh): OpenHarmony NAPI support
#if SCRIPT_ENGINE_TYPE != SCRIPT_ENGINE_NAPI
@@ -40,8 +40,8 @@
#include "bindings/jswrapper/HandleObject.h"
#include "bindings/jswrapper/SeApi.h"
#include "bindings/manual/jsb_classtype.h"
#include "jsb_conversions_spec.h"
#include "core/data/JSBNativeDataHolder.h"
#include "jsb_conversions_spec.h"
#if CC_USE_SPINE
#include "cocos/editor-support/spine-creator-support/spine-cocos2dx.h"
@@ -725,7 +725,7 @@ sevalue_to_native(const se::Value &from, T **to, se::Object * /*ctx*/) { // NOLI
}
// duplicate extern to resolve the circular reference jsb_cocos_auto.h
// see jsb_cocos_auto.h
// see jsb_cocos_auto.h
extern se::Class *__jsb_cc_JSBNativeDataHolder_class; // NOLINT
template <typename T>
@@ -43,7 +43,7 @@
#include "bindings/auto/jsb_assets_auto.h"
#include "bindings/auto/jsb_cocos_auto.h"
#if CC_USE_PHYSICS_PHYSX
#include "bindings/auto/jsb_physics_auto.h"
#include "bindings/auto/jsb_physics_auto.h"
#endif
#include "cocos/core/geometry/Geometry.h"
#include "scene/Fog.h"
@@ -51,11 +51,11 @@
#include "scene/Skybox.h"
#if CC_USE_SPINE
#include "cocos/editor-support/spine-creator-support/Vector2.h"
#include "cocos/editor-support/spine-creator-support/Vector2.h"
#endif
#if CC_USE_BOX2D_JSB
#include "bindings/auto/jsb_box2d_auto.h"
#include "bindings/auto/jsb_box2d_auto.h"
#endif
///////////////////////// utils /////////////////////////
@@ -39,7 +39,7 @@
#endif
#if CC_USE_BOX2D_JSB
#include "box2d/box2d.h"
#include "box2d/box2d.h"
#endif
namespace cc {
@@ -377,11 +377,11 @@ inline bool sevalue_to_native(const se::Value &from, ccstd::string **to, se::Obj
bool sevalue_to_native(const se::Value &from, cc::ValueMap *to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming)
bool sevalue_to_native(const se::Value &from, ccstd::vector<bool> *to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming)
bool sevalue_to_native(const se::Value &from, ccstd::vector<bool> *to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming)
bool sevalue_to_native(const se::Value &from, ccstd::variant<ccstd::string, bool> *to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming)
bool sevalue_to_native(const se::Value &from, ccstd::vector<unsigned char> *to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming)
bool sevalue_to_native(const se::Value &from, cc::IPropertyValue *to, se::Object *ctx); // NOLINT(readability-identifier-naming)
inline bool sevalue_to_native(const se::Value & /*from*/, ccstd::monostate * /*to*/, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming)
bool sevalue_to_native(const se::Value &from, ccstd::vector<unsigned char> *to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming)
bool sevalue_to_native(const se::Value &from, cc::IPropertyValue *to, se::Object *ctx); // NOLINT(readability-identifier-naming)
inline bool sevalue_to_native(const se::Value & /*from*/, ccstd::monostate * /*to*/, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming)
// nothing todo
return false;
}
@@ -646,8 +646,8 @@ bool sevalue_to_native(const se::Value &from, b2Vec2 *to, se::Object * /*unused*
bool sevalue_to_native(const se::Value &from, b2Vec3 *to, se::Object * /*unused*/);
bool sevalue_to_native(const se::Value &from, b2Color *to, se::Object * /*unused*/);
bool nativevalue_to_se(const b2Vec2 &from, se::Value &to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming)
bool nativevalue_to_se(const b2Vec3 &from, se::Value &to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming)
bool nativevalue_to_se(const b2Vec2 &from, se::Value &to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming)
bool nativevalue_to_se(const b2Vec3 &from, se::Value &to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming)
bool nativevalue_to_se(const b2Color &from, se::Value &to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming)
#endif //CC_USE_BOX2D_JSB
+1 -1
View File
@@ -28,7 +28,7 @@
#include "jsb_global_init.h"
namespace cc {
class LegacyThreadPool;
class LegacyThreadPool;
}
extern cc::LegacyThreadPool *gIOThreadPool;
@@ -49,8 +49,8 @@
#include "cocos/bindings/manual/jsb_scene_manual.h"
#include "cocos/bindings/manual/jsb_xmlhttprequest.h"
#if CC_USE_BOX2D_JSB
#include "cocos/bindings/manual/jsb_box2d_manual.h"
#include "cocos/bindings/auto/jsb_box2d_auto.h"
#include "cocos/bindings/auto/jsb_box2d_auto.h"
#include "cocos/bindings/manual/jsb_box2d_manual.h"
#endif
#if USE_GFX_RENDERER
@@ -58,9 +58,9 @@ static bool js_network_Downloader_createDownloadTask(se::State &s) { // NOLINT(r
ccstd::string arg1;
ccstd::string identifier;
ccstd::unordered_map<ccstd::string, ccstd::string> header;
std::shared_ptr<const cc::network::DownloadTask> result;
ok &= sevalue_to_native(args[0], &arg0);
ok &= sevalue_to_native(args[1], &arg1);
if (args[2].isString()) {
@@ -84,13 +84,13 @@ static bool js_network_Downloader_createDownloadTask(se::State &s) { // NOLINT(r
"js_network_Downloader_createDownloadTask : Error processing arguments");
return true;
}
if (argc == 4) {
ccstd::string arg0;
ccstd::string arg1;
ccstd::unordered_map<ccstd::string, ccstd::string> arg2;
ccstd::string arg3;
ok &= sevalue_to_native(args[0], &arg0);
ok &= sevalue_to_native(args[1], &arg1);
ok &= sevalue_to_native(args[2], &arg2);
@@ -310,7 +310,7 @@ bool register_all_network_manual(se::Object * /*obj*/) { // NOLINT(readability-i
__jsb_cc_network_Downloader_proto->defineProperty("onError", nullptr, _SE(js_network_Downloader_setOnError_asSetter));
__jsb_cc_network_Downloader_proto->defineFunction("createDownloadTask",
_SE(js_network_Downloader_createDownloadTask));
__jsb_cc_network_Downloader_proto->defineFunction("createDownloadFileTask", // deprecated since v3.6, use createDownloadTask instead.
__jsb_cc_network_Downloader_proto->defineFunction("createDownloadFileTask", // deprecated since v3.6, use createDownloadTask instead.
_SE(js_network_Downloader_createDownloadTask));
__jsb_cc_network_Downloader_proto->defineFunction("setOnTaskError",
_SE(js_network_Downloader_setOnTaskError)); // deprecated since v3.6
+3 -3
View File
@@ -27,8 +27,8 @@
#include "base/std/container/unordered_map.h"
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include <string>
#include <native_drawing/drawing_text_declaration.h>
#include <native_drawing/drawing_text_declaration.h>
#include <string>
#endif
namespace se {
class Object;
@@ -38,5 +38,5 @@ bool register_platform_bindings(se::Object *obj); // NOLINT[readability-identifi
const ccstd::unordered_map<ccstd::string, ccstd::string> &getFontFamilyNameMap();
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
const std::string defaultFontKey = "openharmony_system_font";
const std::unordered_map<std::string, OH_Drawing_FontCollection*>& getFontFamilyCollectionMap();
const std::unordered_map<std::string, OH_Drawing_FontCollection *> &getFontFamilyCollectionMap();
#endif
@@ -25,20 +25,19 @@
#include "jsb_platform.h"
#include <native_drawing/drawing_font_collection.h>
#include <native_drawing/drawing_register_font.h>
#include <regex>
#include "cocos/bindings/jswrapper/SeApi.h"
#include "cocos/bindings/manual/jsb_conversions.h"
#include "cocos/bindings/manual/jsb_global_init.h"
#include "cocos/platform/FileUtils.h"
#include <native_drawing/drawing_font_collection.h>
#include <native_drawing/drawing_register_font.h>
#include <regex>
using namespace cc;
static std::unordered_map<std::string, OH_Drawing_FontCollection*> _fontCollectionMap = {
{ defaultFontKey, OH_Drawing_CreateSharedFontCollection() }
};
static std::unordered_map<std::string, OH_Drawing_FontCollection *> _fontCollectionMap = {
{defaultFontKey, OH_Drawing_CreateSharedFontCollection()}};
const std::unordered_map<std::string, OH_Drawing_FontCollection*>& getFontFamilyCollectionMap() {
const std::unordered_map<std::string, OH_Drawing_FontCollection *> &getFontFamilyCollectionMap() {
return _fontCollectionMap;
}
@@ -49,31 +48,29 @@ const std::unordered_map<std::string, std::string> &getFontFamilyNameMap() {
}
static bool JSB_loadFont(se::State &s) {
const auto& args = s.args();
const auto &args = s.args();
size_t argc = args.size();
CC_UNUSED bool ok = true;
if (argc >= 1) {
s.rval().setNull();
std::string fontFamily;
ok &= seval_to_std_string(args[0], &fontFamily);
SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: fontFamily");
std::string source;
ok &= seval_to_std_string(args[1], &source);
SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: source");
std::string fontFilePath;
std::regex re("url\\(\\s*'\\s*(.*?)\\s*'\\s*\\)");
std::match_results<std::string::const_iterator> results;
if (std::regex_search(source.cbegin(), source.cend(), results, re))
{
if (std::regex_search(source.cbegin(), source.cend(), results, re)) {
fontFilePath = results[1].str();
}
fontFilePath = FileUtils::getInstance()->fullPathForFilename(fontFilePath);
if (fontFilePath.empty())
{
if (fontFilePath.empty()) {
SE_LOGE("Font (%s) doesn't exist!", fontFilePath.c_str());
return true;
}
@@ -87,10 +84,10 @@ static bool JSB_loadFont(se::State &s) {
OH_Drawing_RegisterFontBuffer(_fontCollection, fontFamily.c_str(), bufferData.getBytes(), bufferData.getSize());
_fontCollectionMap.emplace(fontFamily, _fontCollection);
s.rval().setString(fontFamily);
return true;
}
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
return false;
}
@@ -23,12 +23,12 @@
****************************************************************************/
#include "jsb_scene_manual.h"
#include "application/ApplicationManager.h"
#include "bindings/auto/jsb_gfx_auto.h"
#include "bindings/auto/jsb_scene_auto.h"
#include "core/Root.h"
#include "core/scene-graph/Node.h"
#include "scene/Model.h"
#include "application/ApplicationManager.h"
#ifndef JSB_ALLOC
#define JSB_ALLOC(kls, ...) ccnew kls(__VA_ARGS__)
@@ -689,7 +689,7 @@ static bool js_Model_setInstancedAttribute(se::State &s) // NOLINT(readability-i
if (val.toObject()->isArray()) {
uint32_t len = 0;
val.toObject()->getArrayLength(&len);
cc::Float32Array value(len);
se::Value dataVal;

Some files were not shown because too many files have changed in this diff Show More