From fd7270c88667315e338aaeac0101c76853902e5b Mon Sep 17 00:00:00 2001 From: qiuguohua Date: Fri, 24 Jan 2025 13:48:35 +0800 Subject: [PATCH] Synchronize HarmonyOS Next platform from cocos creator 2.4.14 (#18247) * Synchronize the HarmonyOS Next platform update for 2.4.14 --- native/CMakeLists.txt | 1 + .../audio/openharmony/PcmAudioService.cpp | 16 +- .../bindings/jswrapper/jsvm/CommonHeader.h | 46 +++--- .../cocos/bindings/jswrapper/jsvm/Object.cpp | 42 +++-- native/cocos/bindings/jswrapper/jsvm/Object.h | 19 ++- .../bindings/jswrapper/jsvm/ScriptEngine.cpp | 62 ++++--- .../bindings/jswrapper/jsvm/ScriptEngine.h | 5 + .../cocos/bindings/jswrapper/jsvm/Utils.cpp | 43 +++++ native/cocos/bindings/jswrapper/jsvm/Utils.h | 3 + .../bindings/manual/JavaScriptArkTsBridge.cpp | 2 - native/cocos/bindings/manual/jsb_socketio.cpp | 3 + .../cocos/bindings/manual/jsb_websocket.cpp | 4 +- .../bindings/manual/jsb_xmlhttprequest.cpp | 10 ++ .../openharmony/FileUtils-OpenHarmony.cpp | 11 +- .../openharmony/modules/Accelerometer.cpp | 155 +++++++++++++++--- .../CanvasRenderingContext2DDelegate.cpp | 119 ++++++++++---- .../CanvasRenderingContext2DDelegate.h | 16 +- .../platform/openharmony/napi/NapiHelper.cpp | 76 +++++++++ .../source/platforms/harmonyos-next.ts | 2 + templates/harmonyos-next/build-profile.json5 | 2 +- .../src/main/cpp/types/libcocos/index.d.ts | 1 + .../cocos/oh-adapter/sys-ability-polyfill.js | 53 ------ .../{EntryAbility.ts => EntryAbility.ets} | 61 +++---- .../entry/src/main/module.json5 | 2 +- 24 files changed, 532 insertions(+), 222 deletions(-) rename templates/harmonyos-next/entry/src/main/ets/entryability/{EntryAbility.ts => EntryAbility.ets} (50%) diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 2693d445c5..005c8c5f4f 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -3408,6 +3408,7 @@ if(OPENHARMONY) libace_ndk.z.so libz.so librawfile.z.so + libohsensor.so ${CC_EXTERNAL_LIBS} ) if(USE_SE_JSVM) diff --git a/native/cocos/audio/openharmony/PcmAudioService.cpp b/native/cocos/audio/openharmony/PcmAudioService.cpp index e9f2e999cc..09aa62c9e5 100644 --- a/native/cocos/audio/openharmony/PcmAudioService.cpp +++ b/native/cocos/audio/openharmony/PcmAudioService.cpp @@ -28,10 +28,8 @@ THE SOFTWARE. #include "audio/openharmony/PcmAudioService.h" #include "audio/android/AudioMixerController.h" #include "audio/android/cutils/log.h" -#include "audio/android/utils/Compat.h" -namespace cc { -static ccstd::vector __silenceData; //NOLINT(bugprone-reserved-identifier, readability-identifier-naming) +namespace cc { PcmAudioService::PcmAudioService() : _controller(nullptr) { @@ -55,14 +53,13 @@ int32_t PcmAudioService::AudioRendererOnWriteData(OH_AudioRenderer *renderer, int32_t bufferLen) { auto *thiz = reinterpret_cast(userData); if (bufferLen != thiz->_bufferSizeInBytes) { - __silenceData.resize(bufferLen, 0x00); thiz->_bufferSizeInBytes = bufferLen; thiz->_controller->updateBufferSize(thiz->_bufferSizeInBytes); } if (thiz->_controller->hasPlayingTacks()) { if (thiz->_controller->isPaused()) { - memcpy(buffer, __silenceData.data(), bufferLen); + return AUDIO_DATA_CALLBACK_RESULT_INVALID; } else { thiz->_controller->mixOneFrame(); auto *current = thiz->_controller->current(); @@ -70,10 +67,10 @@ int32_t PcmAudioService::AudioRendererOnWriteData(OH_AudioRenderer *renderer, memcpy(buffer, current->buf, current->size < bufferLen ? current->size : bufferLen); } } else { - memcpy(buffer, __silenceData.data(), bufferLen); + return AUDIO_DATA_CALLBACK_RESULT_INVALID; } - return 0; + return AUDIO_DATA_CALLBACK_RESULT_VALID; } int32_t PcmAudioService::AudioRendererOnInterrupt(OH_AudioRenderer *renderer, @@ -126,10 +123,6 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in _bufferSizeInBytes = buffer_size * numChannels * 2; *bufferSizeInBytes = buffer_size; - if (__silenceData.empty()) { - __silenceData.resize(_bufferSizeInBytes, 0x00); - } - ret = OH_AudioRenderer_Start(_audioRenderer); if (ret != AUDIOSTREAM_SUCCESS) { return false; @@ -146,6 +139,7 @@ void PcmAudioService::pause() { void PcmAudioService::resume() { if (_audioRenderer != nullptr) { + OH_AudioRenderer_Flush(_audioRenderer); OH_AudioRenderer_Start(_audioRenderer); } } diff --git a/native/cocos/bindings/jswrapper/jsvm/CommonHeader.h b/native/cocos/bindings/jswrapper/jsvm/CommonHeader.h index c3b5c4b5ef..bc4d9f303d 100644 --- a/native/cocos/bindings/jswrapper/jsvm/CommonHeader.h +++ b/native/cocos/bindings/jswrapper/jsvm/CommonHeader.h @@ -40,34 +40,21 @@ #define NODE_API_ASSERT_RETURN_VOID(env, assertion, message) \ NODE_API_ASSERT_BASE(env, assertion, message, NODE_API_RETVAL_NOTHING) -#define NODE_API_CALL_BASE(env, the_call, ret_val) \ - do { \ - if ((the_call) != JSVM_OK) { \ - assert(false); \ - } \ +#define NODE_API_CALL_BASE(env, the_call, ret_val) \ + do { \ + if ((the_call) != JSVM_OK) { \ + se::internal::logJsException((env), __FILE_NAME__, __LINE__); \ + } \ } while (0) // Returns nullptr if the_call doesn't return JSVM_OK. -#define NODE_API_CALL(status, env, the_call) \ - status = the_call; \ - if (status != JSVM_OK) { \ - bool isPending = false; \ - if (JSVM_OK == OH_JSVM_IsExceptionPending((env), &isPending) && isPending) { \ - JSVM_Value error; \ - if (JSVM_OK == OH_JSVM_GetAndClearLastException((env), &error)) { \ - JSVM_Value stack; \ - OH_JSVM_GetNamedProperty((env), error, "stack", &stack); \ - JSVM_Value message; \ - OH_JSVM_GetNamedProperty((env), error, "message", &message); \ - char stackstr[256]; \ - OH_JSVM_GetValueStringUtf8(env, stack, stackstr, 256, nullptr); \ - SE_LOGE("JSVM error stack: %s", stackstr); \ - char messagestr[256]; \ - OH_JSVM_GetValueStringUtf8(env, message, messagestr, 256, nullptr); \ - SE_LOGE("JSVM error message: %s", messagestr); \ - } \ - } \ - } +#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. #define NODE_API_CALL_RETURN_VOID(env, the_call) \ @@ -79,6 +66,15 @@ #define DECLARE_NODE_API_GETTER(name, func) \ { (name), nullptr, nullptr, (func), nullptr, nullptr, JSVM_DEFAULT, nullptr } +#define JSVM_CALL_BASE(theCall, retVal) \ + do { \ + if((theCall) != JSVM_OK){ \ + return retVal; \ + } \ + } while (0) + +#define JSVM_CALL_RETURN_VOID(theCall) JSVM_CALL_BASE(theCall, NODE_API_RETVAL_NOTHING) + void add_returned_status(JSVM_Env env, const char* key, JSVM_Value object, diff --git a/native/cocos/bindings/jswrapper/jsvm/Object.cpp b/native/cocos/bindings/jswrapper/jsvm/Object.cpp index e859f07851..25163543ae 100644 --- a/native/cocos/bindings/jswrapper/jsvm/Object.cpp +++ b/native/cocos/bindings/jswrapper/jsvm/Object.cpp @@ -36,9 +36,15 @@ namespace se { std::unique_ptr> __objectMap; // Currently, the value `void*` is always nullptr +std::set Object::objBaseSet = {}; + +bool Object::restarting = false; Object::Object() {} Object::~Object() { + if(restarting) { + objBaseSet.insert(this); + } if (__objectMap) { __objectMap->erase(this); } @@ -698,32 +704,37 @@ void Object::weakCallback(JSVM_Env env, void* nativeObject, void* finalizeHint / } void* rawPtr = reinterpret_cast(finalizeHint)->_privateData; Object* seObj = reinterpret_cast(finalizeHint); - Object* rawPtrObj = reinterpret_cast(rawPtr); + + auto it = objBaseSet.find(seObj); + if(it != objBaseSet.end()) { + return; + } + if (seObj->_onCleaingPrivateData) { //called by cleanPrivateData, not release seObj; return; } if (seObj->_clearMappingInFinalizer && rawPtr != nullptr) { auto iter = NativePtrToObjectMap::find(rawPtr); if (iter != NativePtrToObjectMap::end()) { + if (seObj->_finalizeCb != nullptr) { + seObj->_finalizeCb(env, finalizeHint, finalizeHint); + } else { + assert(seObj->_getClass() != nullptr); + if (seObj->_getClass()->_getFinalizeFunction() != nullptr) { + seObj->_getClass()->_getFinalizeFunction()(env, finalizeHint, finalizeHint); + } + } + seObj->decRef(); NativePtrToObjectMap::erase(iter); } else { SE_LOGE("not find ptr in NativePtrToObjectMap"); } } - - if (seObj->_finalizeCb != nullptr) { - seObj->_finalizeCb(env, finalizeHint, finalizeHint); - } else { - assert(seObj->_getClass() != nullptr); - if (seObj->_getClass()->_getFinalizeFunction() != nullptr) { - seObj->_getClass()->_getFinalizeFunction()(env, finalizeHint, finalizeHint); - } - } - seObj->decRef(); } } void Object::setup() { + restarting = false; __objectMap = std::make_unique>(); } @@ -845,6 +856,15 @@ void Object::clearPrivateData(bool clearMapping) { } } +JSVM_Value ObjectRef::getValue(JSVM_Env env) const { + JSVM_Value result; + JSVM_Status status; + NODE_API_CALL(status, env, OH_JSVM_GetReferenceValue(env, _ref, &result)); + assert(status == JSVM_OK); + assert(result != nullptr); + return result; +} + Object* Object::createUTF8String(const std::string& str) { JSVM_Status status; JSVM_Value result; diff --git a/native/cocos/bindings/jswrapper/jsvm/Object.h b/native/cocos/bindings/jswrapper/jsvm/Object.h index 35a4258281..4dd684d2c4 100644 --- a/native/cocos/bindings/jswrapper/jsvm/Object.h +++ b/native/cocos/bindings/jswrapper/jsvm/Object.h @@ -24,6 +24,7 @@ ****************************************************************************/ #pragma once +#include #include #include "../PrivateObject.h" #include "../RefCounter.h" @@ -31,6 +32,7 @@ #include "../config.h" #include "CommonHeader.h" #include "HelperMacros.h" +#include "Utils.h" namespace se { class Class; @@ -49,14 +51,9 @@ public: ~ObjectRef() { deleteRef(); } - JSVM_Value getValue(JSVM_Env env) const { - JSVM_Value result; - JSVM_Status status; - NODE_API_CALL(status, env, OH_JSVM_GetReferenceValue(env, _ref, &result)); - assert(status == JSVM_OK); - assert(result != nullptr); - return result; - } + + JSVM_Value getValue(JSVM_Env env) const; + void initWeakref(JSVM_Env env, JSVM_Value obj) { assert(_ref == nullptr); _obj = obj; @@ -121,6 +118,12 @@ public: BIGUINT64 }; + static std::set objBaseSet; + static bool restarting; + static void resetBaseSet() { + objBaseSet.erase(objBaseSet.begin(), objBaseSet.end()); + } + using BufferContentsFreeFunc = void (*)(void *contents, size_t byteLength, void *userData); struct ExternalArrayBufferCallbackParams { diff --git a/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.cpp b/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.cpp index f3447bcbaf..fc65e21551 100644 --- a/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.cpp +++ b/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.cpp @@ -64,7 +64,7 @@ bool JSB_console_format_log(State& s, const char* prefix, int msgIndex = 0) { int argc = (int)args.size(); if ((argc - msgIndex) == 1) { std::string msg = args[msgIndex].toStringForce(); - SE_LOGD("JS: %s%s\n", prefix, msg.c_str()); + SE_LOGD("JS: %{public}s%{public}s\n", prefix, msg.c_str()); } else if (argc > 1) { std::string msg = args[msgIndex].toStringForce(); size_t pos; @@ -77,8 +77,7 @@ bool JSB_console_format_log(State& s, const char* prefix, int msgIndex = 0) { msg += " " + args[i].toStringForce(); } } - - SE_LOGD("JS: %s%s\n", prefix, msg.c_str()); + SE_LOGD("JS: %{public}s%{public}s\n", prefix, msg.c_str()); } return true; } @@ -138,7 +137,16 @@ SE_BIND_FUNC(JSB_console_assert) ScriptEngine *gSriptEngineInstance = nullptr; -ScriptEngine::ScriptEngine() { OH_JSVM_Init(nullptr); }; +ScriptEngine::ScriptEngine() { + static bool initialized = false; + if (initialized) { + return; + } + JSVM_InitOptions initOptions; + memset(&initOptions, 0, sizeof(initOptions)); + OH_JSVM_Init(&initOptions); + initialized = true; +}; ScriptEngine::~ScriptEngine() = default; @@ -197,7 +205,7 @@ bool ScriptEngine::evalString(const char *scriptStr, ssize_t length, Value *ret, JSVM_Script compiledScript; JSVM_ScriptOrigin scriptOrigin{ .sourceMapUrl = nullptr, - .resourceName = fileName, + .resourceName = fileName ? fileName : "", .resourceLineOffset = 0, .resourceColumnOffset = 0 }; @@ -236,7 +244,7 @@ bool ScriptEngine::init() { for (const auto &hook : _beforeInitHookArray) { hook(); } - + _beforeInitHookArray.clear(); NODE_API_CALL(status, _env, OH_JSVM_CreateVM(nullptr, &_vm)); NODE_API_CALL(status, _env, OH_JSVM_OpenVMScope(_vm, &_vmScope)); NODE_API_CALL(status, _env, OH_JSVM_CreateEnv(_vm, 0, nullptr, &_env)); @@ -329,47 +337,62 @@ void ScriptEngine::cleanup() { if (!_isValid) { return; } - + Object::restarting = true; + Object::resetBaseSet(); SE_LOGD("ScriptEngine::cleanup begin ...\n"); _isInCleanup = true; - + se::AutoHandleScope hs; do{ - se::AutoHandleScope hs; for (const auto &hook : _beforeCleanupHookArray) { hook(); } - _beforeCleanupHookArray.clear(); }while (0); - + _beforeCleanupHookArray.clear(); SAFE_DEC_REF(_globalObj); Object::cleanup(); Class::cleanup(); garbageCollect(); - JSVM_Status status; - NODE_API_CALL(status, _env, OH_JSVM_CloseEnvScope(_env, _envScope)); + __oldConsoleLog.setUndefined(); + __oldConsoleDebug.setUndefined(); + __oldConsoleInfo.setUndefined(); + __oldConsoleWarn.setUndefined(); + __oldConsoleError.setUndefined(); + __oldConsoleAssert.setUndefined(); - NODE_API_CALL(status, _env, OH_JSVM_DestroyEnv(_env)); - NODE_API_CALL(status, _env, OH_JSVM_CloseVMScope(_vm, _vmScope)); - NODE_API_CALL(status, _env, OH_JSVM_DestroyVM(_vm)); - _envScope = nullptr; + JSVM_Env env = _env; _env = nullptr; + + JSVM_Status status; + NODE_API_CALL(status, env, OH_JSVM_CloseEnvScope(env, _envScope)); + + NODE_API_CALL(status, env, OH_JSVM_DestroyEnv(env)); + NODE_API_CALL(status, env, OH_JSVM_CloseVMScope(_vm, _vmScope)); + NODE_API_CALL(status, env, OH_JSVM_DestroyVM(_vm)); + _envScope = nullptr; + env = nullptr; _vmScope = nullptr; _vm = nullptr; _globalObj = nullptr; _isValid = false; + _gcFunc = nullptr; _registerCallbackArray.clear(); for (const auto &hook : _afterCleanupHookArray) { hook(); } + _beforeInitHookArray.clear(); + _afterInitHookArray.clear(); + _beforeCleanupHookArray.clear(); _afterCleanupHookArray.clear(); _isInCleanup = false; NativePtrToObjectMap::destroy(); + _gcFuncValue.setUndefined(); + SE_LOGD("ScriptEngine::cleanup end ...\n"); } @@ -403,8 +426,7 @@ void ScriptEngine::addPermanentRegisterCallback(RegisterCallback cb) { } void ScriptEngine::setExceptionCallback(const ExceptionCallback &cb) { - //not impl - return; + _exceptionCallback = cb; } const std::chrono::steady_clock::time_point &ScriptEngine::getStartTime() const { return _startTime; } @@ -495,6 +517,6 @@ void ScriptEngine::mainLoopUpdate() { void ScriptEngine::throwException(const std::string &errorMessage) { JSVM_Status status; - NODE_API_CALL_RETURN_VOID(getEnv(), OH_JSVM_ThrowError(getEnv(), nullptr, errorMessage.c_str())); + NODE_API_CALL(status, getEnv(), OH_JSVM_ThrowError(getEnv(), nullptr, errorMessage.c_str())); } }; // namespace se diff --git a/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.h b/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.h index 16e87966fa..c0f7d4b17a 100644 --- a/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.h +++ b/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.h @@ -121,6 +121,10 @@ public: */ void setExceptionCallback(const ExceptionCallback &cb); + ExceptionCallback& getExceptionCallback() { + return _exceptionCallback; + } + /** * @brief Grab a snapshot of the current JavaScript execution stack. * @return current stack trace string @@ -300,6 +304,7 @@ private: JSVM_VM _vm = nullptr; JSVM_VMScope _vmScope = nullptr; JSVM_EnvScope _envScope = nullptr; + ExceptionCallback _exceptionCallback; bool _isValid{false}; bool _isGarbageCollecting{false}; diff --git a/native/cocos/bindings/jswrapper/jsvm/Utils.cpp b/native/cocos/bindings/jswrapper/jsvm/Utils.cpp index 7d3381ecde..67c03b2adf 100644 --- a/native/cocos/bindings/jswrapper/jsvm/Utils.cpp +++ b/native/cocos/bindings/jswrapper/jsvm/Utils.cpp @@ -194,5 +194,48 @@ bool setReturnValue(const Value& data, target_value& argv) { return seToJsValue(data, &argv); } + +std::string jsToString(const target_value &value) { + se::Value seValue; + internal::jsToSeValue(value, &seValue); + if (seValue.isString()) { + return seValue.toString(); + } else { + return ""; + } +} + +void logJsException(JSVM_Env env, const char *file, int line) { + bool isPending = false; + JSVM_CALL_RETURN_VOID(OH_JSVM_IsExceptionPending(env, &isPending)); + if (!isPending) { + return; + } + + JSVM_Value error; + JSVM_CALL_RETURN_VOID(OH_JSVM_GetAndClearLastException(env, &error)); + + JSVM_Value name; + JSVM_CALL_RETURN_VOID(OH_JSVM_GetNamedProperty(env, error, "name", &name)); + + JSVM_Value stack; + JSVM_CALL_RETURN_VOID(OH_JSVM_GetNamedProperty(env, error, "stack", &stack)); + + JSVM_Value message; + JSVM_CALL_RETURN_VOID(OH_JSVM_GetNamedProperty(env, error, "stack", &message)); + + std::string nameStr = jsToString(name); + std::string stackStr = jsToString(stack); + std::string messageStr = jsToString(message); + + SE_LOGE("JS exception occurred at %{public}s:%{public}d\n\ + [name]: %{public}s\n\ + [message]: %{public}s\n\ + [stack]: %{public}s", + file, line, nameStr.c_str(), messageStr.c_str(), stackStr.c_str()); + auto exceptionCallback = ScriptEngine::getInstance()->getExceptionCallback(); + exceptionCallback("", messageStr.c_str(), stackStr.c_str()); +} + } // namespace internal }; // namespace se diff --git a/native/cocos/bindings/jswrapper/jsvm/Utils.h b/native/cocos/bindings/jswrapper/jsvm/Utils.h index 2f6925f022..0adb64847c 100644 --- a/native/cocos/bindings/jswrapper/jsvm/Utils.h +++ b/native/cocos/bindings/jswrapper/jsvm/Utils.h @@ -42,5 +42,8 @@ void jsToSeValue(const target_value &value, Value *v); void jsToSeArgs(size_t argc, target_value *argv, ValueArray *outArr); bool seToJsValue(const Value &v, target_value *jsval); void seToJsArgs(JSVM_Env env, const ValueArray &args, std::vector *outArr); +std::string jsToString(const target_value &value); +void logJsException(JSVM_Env env, const char *file, int line); + } // namespace internal } // namespace se diff --git a/native/cocos/bindings/manual/JavaScriptArkTsBridge.cpp b/native/cocos/bindings/manual/JavaScriptArkTsBridge.cpp index 6b5f6b7158..e6aabd2ee4 100644 --- a/native/cocos/bindings/manual/JavaScriptArkTsBridge.cpp +++ b/native/cocos/bindings/manual/JavaScriptArkTsBridge.cpp @@ -187,8 +187,6 @@ bool JavaScriptArkTsBridge::CallInfo::execute(se::Value& rval) { se::Class* __jsb_JavaScriptArkTsBridge_class = nullptr; static bool JavaScriptArkTsBridge_finalize(se::State& s) { - JavaScriptArkTsBridge* cobj = (JavaScriptArkTsBridge*)s.nativeThisObject(); - delete cobj; return true; } SE_BIND_FINALIZE_FUNC(JavaScriptArkTsBridge_finalize) diff --git a/native/cocos/bindings/manual/jsb_socketio.cpp b/native/cocos/bindings/manual/jsb_socketio.cpp index 2b18a66362..b885bfa0ec 100644 --- a/native/cocos/bindings/manual/jsb_socketio.cpp +++ b/native/cocos/bindings/manual/jsb_socketio.cpp @@ -134,6 +134,9 @@ static bool SocketIO_finalize(se::State &s) { // NOLINT(readability-identifier-n auto *cobj = static_cast(s.nativeThisObject()); CC_LOG_INFO("jsbindings: finalizing JS object %p (SocketIO)", cobj); cobj->disconnect(); + if(se::ScriptEngine::getInstance()->isInCleanup()) { + return true; + } auto *delegate = static_cast(cobj->getDelegate()); if (delegate->getRefCount() == 1) { cc::DeferredReleasePool::add(delegate); diff --git a/native/cocos/bindings/manual/jsb_websocket.cpp b/native/cocos/bindings/manual/jsb_websocket.cpp index a96625bca6..9e1f89474c 100644 --- a/native/cocos/bindings/manual/jsb_websocket.cpp +++ b/native/cocos/bindings/manual/jsb_websocket.cpp @@ -256,7 +256,9 @@ static bool webSocketFinalize(se::State &s) { CC_LOG_INFO("WebSocket (%p) isn't closed, try to close it!", cobj); cobj->closeAsync(); } - + if(se::ScriptEngine::getInstance()->isInCleanup()) { + return true; + } static_cast(cobj->getDelegate())->release(); return true; } diff --git a/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp b/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp index fdf44d4835..6249e9e004 100644 --- a/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp +++ b/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp @@ -578,6 +578,16 @@ se::Class *__jsb_XMLHttpRequest_class = nullptr; //NOLINT(readability-identifier static bool XMLHttpRequest_finalize(se::State &s) { //NOLINT(readability-identifier-naming, google-runtime-references) auto *request = static_cast(s.nativeThisObject()); + if(se::ScriptEngine::getInstance()->isInCleanup()) { + request->onloadstart = nullptr; + request->onload = nullptr; + request->onloadend = nullptr; + request->onreadystatechange = nullptr; + request->onabort = nullptr; + request->onerror = nullptr; + request->ontimeout = nullptr; + return true; + } SE_LOGD("XMLHttpRequest_finalize, %p ... \n", request); request->clearCallbacks(); return true; diff --git a/native/cocos/platform/openharmony/FileUtils-OpenHarmony.cpp b/native/cocos/platform/openharmony/FileUtils-OpenHarmony.cpp index c9d0763322..3dbd2cfe25 100644 --- a/native/cocos/platform/openharmony/FileUtils-OpenHarmony.cpp +++ b/native/cocos/platform/openharmony/FileUtils-OpenHarmony.cpp @@ -132,8 +132,8 @@ FileUtils::Status FileUtilsOpenHarmony::getContents(const std::string &filename, } FileUtilsOpenHarmony::~FileUtilsOpenHarmony() { - if (_nativeResourceManager) - OH_ResourceManager_ReleaseNativeResourceManager(_nativeResourceManager); + // if (_nativeResourceManager) + // OH_ResourceManager_ReleaseNativeResourceManager(_nativeResourceManager); } bool FileUtilsOpenHarmony::init() { @@ -185,6 +185,13 @@ bool FileUtilsOpenHarmony::isFileExistInternal(const std::string &strFilePath) c std::string strPath = strFilePath; if (!isAbsolutePath(strPath)) { // Not absolute path, add the default root path at the beginning. strPath.insert(0, _defaultResRootPath); + } else { + FILE *fp = fopen(strFilePath.c_str(), "r"); + if (fp) { + fclose(fp); + return true; + } + return false; } if (nullptr == _nativeResourceManager) { diff --git a/native/cocos/platform/openharmony/modules/Accelerometer.cpp b/native/cocos/platform/openharmony/modules/Accelerometer.cpp index 638e84e607..628eedf7ff 100644 --- a/native/cocos/platform/openharmony/modules/Accelerometer.cpp +++ b/native/cocos/platform/openharmony/modules/Accelerometer.cpp @@ -24,41 +24,146 @@ ****************************************************************************/ #include "platform/openharmony/modules/Accelerometer.h" -#include "platform/openharmony/napi/NapiHelper.h" +#include "sensors/oh_sensor.h" namespace cc { +constexpr Sensor_Type SENSOR_ID[]{SENSOR_TYPE_ACCELEROMETER, SENSOR_TYPE_LINEAR_ACCELERATION, SENSOR_TYPE_GYROSCOPE}; +int64_t sensorSamplePeriod = 200000000; +constexpr int64_t INVALID_VALUE = -1; + +Sensor_Subscriber *g_user[3] = {nullptr, nullptr, nullptr}; +Sensor_SubscriptionId *g_id[3] = {nullptr, nullptr, nullptr}; +Sensor_SubscriptionAttribute *g_attr[3] = {nullptr, nullptr, nullptr}; + +static IAccelerometer::MotionValue motionValue; + +float radiansToDegrees(float radians) { + const float pi = M_PI; + return radians * (180.0 / pi); +} + +void SensorDataCallbackImpl(Sensor_Event *event) { + if (event == nullptr) { + CC_LOG_WARNING("event is null"); + return; + } + int64_t timestamp = INVALID_VALUE; + int32_t ret = OH_SensorEvent_GetTimestamp(event, ×tamp); + if (ret != SENSOR_SUCCESS) { + return; + } + Sensor_Type sensorType; + ret = OH_SensorEvent_GetType(event, &sensorType); + if (ret != SENSOR_SUCCESS) { + return; + } + Sensor_Accuracy accuracy = SENSOR_ACCURACY_UNRELIABLE; + ret = OH_SensorEvent_GetAccuracy(event, &accuracy); + if (ret != SENSOR_SUCCESS) { + return; + } + float *data = nullptr; + uint32_t length = 0; + ret = OH_SensorEvent_GetData(event, &data, &length); + if (ret != SENSOR_SUCCESS) { + return; + } + switch (sensorType) { + case SENSOR_TYPE_ACCELEROMETER: + motionValue.accelerationIncludingGravityX = data[0]; + motionValue.accelerationIncludingGravityY = data[1]; + motionValue.accelerationIncludingGravityZ = -data[2]; + break; + case SENSOR_TYPE_LINEAR_ACCELERATION: + motionValue.accelerationX = data[0]; + motionValue.accelerationY = data[1]; + motionValue.accelerationZ = data[2]; + break; + case SENSOR_TYPE_GYROSCOPE: + motionValue.rotationRateAlpha = radiansToDegrees(data[0]); + motionValue.rotationRateBeta = radiansToDegrees(data[1]); + motionValue.rotationRateGamma = radiansToDegrees(data[2]); + break; + } +} + +static void enableSensor(int index) { + Sensor_Subscriber *gUser = OH_Sensor_CreateSubscriber(); + int32_t ret = OH_SensorSubscriber_SetCallback(gUser, SensorDataCallbackImpl); + if (ret != SENSOR_SUCCESS) { + return; + } + + Sensor_SubscriptionId *id = OH_Sensor_CreateSubscriptionId(); + ret = OH_SensorSubscriptionId_SetType(id, SENSOR_ID[index]); + if (ret != SENSOR_SUCCESS) { + return; + } + + Sensor_SubscriptionAttribute *attr = OH_Sensor_CreateSubscriptionAttribute(); + ret = OH_SensorSubscriptionAttribute_SetSamplingInterval(attr, sensorSamplePeriod); + if (ret != SENSOR_SUCCESS) { + return; + } + + ret = OH_Sensor_Subscribe(id, attr, gUser); + if (ret != SENSOR_SUCCESS) { + return; + } + g_user[index] = gUser; + g_id[index] = id; + g_attr[index] = attr; + + CC_LOG_INFO("Subscriber successful"); +} + +static void disableSensor(int index) { + int32_t ret = -1; + Sensor_SubscriptionId *it = g_id[index]; + Sensor_SubscriptionAttribute *at = g_attr[index]; + Sensor_Subscriber *gUser = g_user[index]; + + if(it == nullptr || at == nullptr || gUser == nullptr) { + return; + } + ret = OH_Sensor_Unsubscribe(it, gUser); + if (ret != SENSOR_SUCCESS) { + return; + } + if (it != nullptr) { + OH_Sensor_DestroySubscriptionId(it); + } + if (at != nullptr) { + OH_Sensor_DestroySubscriptionAttribute(at); + } + if (gUser != nullptr) { + OH_Sensor_DestroySubscriber(gUser); + gUser = nullptr; + } +} void Accelerometer::setAccelerometerEnabled(bool isEnabled) { - //setAccelerometerEnabledJNI(isEnabled); + constexpr int length = sizeof(SENSOR_ID) / sizeof(SENSOR_ID[0]); + if (isEnabled) { + for (uint32_t i = 0; i < length; i++) { + disableSensor(i); + } + for (uint32_t i = 0; i < length; i++) { + enableSensor(i); + } + } else { + for (uint32_t i = 0; i < length; i++) { + disableSensor(i); + } + } } void Accelerometer::setAccelerometerInterval(float interval) { - //setAccelerometerIntervalJNI(interval); + sensorSamplePeriod = static_cast(interval * 1000 * 1000 * 1000); + setAccelerometerEnabled(true); } const Accelerometer::MotionValue &Accelerometer::getDeviceMotionValue() { - static MotionValue motionValue; - Napi::Value ret = NapiHelper::napiCallFunction("getDeviceMotionValue"); - if (!ret.IsArray()) { - return motionValue; - } - - auto v = ret.As(); - if (v.Length() == 9) { - motionValue.accelerationIncludingGravityX = static_cast(v[(uint32_t)0]).As().FloatValue(); - motionValue.accelerationIncludingGravityY = static_cast(v[(uint32_t)1]).As().FloatValue(); - motionValue.accelerationIncludingGravityZ = static_cast(v[(uint32_t)2]).As().FloatValue(); - - motionValue.accelerationX = static_cast(v[(uint32_t)3]).As().FloatValue(); - motionValue.accelerationY = static_cast(v[(uint32_t)4]).As().FloatValue(); - motionValue.accelerationZ = static_cast(v[(uint32_t)5]).As().FloatValue(); - - motionValue.rotationRateAlpha = static_cast(v[(uint32_t)6]).As().FloatValue(); - motionValue.rotationRateBeta = static_cast(v[(uint32_t)7]).As().FloatValue(); - motionValue.rotationRateGamma = static_cast(v[(uint32_t)8]).As().FloatValue(); - } else { - memset(&motionValue, 0, sizeof(motionValue)); - } return motionValue; } diff --git a/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.cpp b/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.cpp index 58b73a02a4..c54d5326bc 100644 --- a/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.cpp +++ b/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.cpp @@ -24,15 +24,33 @@ ****************************************************************************/ #include "platform/openharmony/modules/CanvasRenderingContext2DDelegate.h" -#include "platform/openharmony/OpenHarmonyPlatform.h" #include #include #include -#include +#include #include #include namespace cc { +namespace { +#define CLAMP(V, HI) std::min((V), (HI)) + +void unMultiplyAlpha(unsigned char *ptr, ssize_t size) { + float alpha; + for (int i = 0; i < size; i += 4) { + alpha = (float)ptr[i + 3]; + if (alpha > 0) { + ptr[i] = CLAMP((int)((float)ptr[i] / alpha * 255), 255); + ptr[i + 1] = CLAMP((int)((float)ptr[i + 1] / alpha * 255), 255); + ptr[i + 2] = CLAMP((int)((float)ptr[i + 2] / alpha * 255), 255); + } + } +} +} +enum class TextAlign { LEFT, CENTER, RIGHT }; + +enum class TextBaseline { TOP, MIDDLE, BOTTOM, ALPHABETIC }; + class CanvasRenderingContext2DDelegate::ScopedTypography { public: ScopedTypography(OH_Drawing_Typography* typography) :_typegraphy(typography) {} @@ -74,6 +92,11 @@ CanvasRenderingContext2DDelegate::~CanvasRenderingContext2DDelegate() { _textStyle = nullptr; } + if (_strokeTextStyle) { + OH_Drawing_DestroyTextStyle(_strokeTextStyle); + _strokeTextStyle = nullptr; + } + if(_canvas) { OH_Drawing_CanvasDestroy(_canvas); _canvas = nullptr; @@ -83,6 +106,11 @@ CanvasRenderingContext2DDelegate::~CanvasRenderingContext2DDelegate() { OH_Drawing_BitmapDestroy(_bitmap); _bitmap = nullptr; } + + if (_pen) { + OH_Drawing_PenDestroy(_pen); + _pen = nullptr; + } } void CanvasRenderingContext2DDelegate::recreateBuffer(float w, float h) { @@ -170,20 +198,51 @@ void CanvasRenderingContext2DDelegate::fillRect(float x, float y, float w, float OH_Drawing_CanvasDrawPath(_canvas, path); } +void CanvasRenderingContext2DDelegate::setPremultiply(bool multiply) { _premultiply = multiply; } + + void CanvasRenderingContext2DDelegate::fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) { if (text.empty() || _bufferWidth < 1.0F || _bufferHeight < 1.0F) { return; } Size textSize = {0, 0}; - Point offsetPoint = convertDrawPoint(Point{x, y}, text); + Point offsetPoint = convertDrawPoint(Point{x, y}, text, _textStyle); drawText(text, (int)offsetPoint[0], (int)offsetPoint[1]); + if (!_premultiply) { + unMultiplyAlpha(_imageData.getBytes(), _imageData.getSize()); + } } -void CanvasRenderingContext2DDelegate::strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const { +void CanvasRenderingContext2DDelegate::strokeText(const ccstd::string &text, float x, float y, float /*maxWidth*/) { + if (_pen) { + OH_Drawing_PenDestroy(_pen); + _pen = nullptr; + } + + if (_strokeTextStyle) { + OH_Drawing_DestroyTextStyle(_strokeTextStyle); + _strokeTextStyle = nullptr; + } + + uint8_t r = static_cast(_strokeStyle[0]); + uint8_t g = static_cast(_strokeStyle[1]); + uint8_t b = static_cast(_strokeStyle[2]); + uint8_t a = static_cast(_strokeStyle[3]); + + _strokeTextStyle = OH_Drawing_CreateTextStyle(); + setTextStyle(_strokeTextStyle); + _pen = OH_Drawing_PenCreate(); + OH_Drawing_PenSetColor(_pen, OH_Drawing_ColorSetArgb(a, r, g, b)); + OH_Drawing_PenSetWidth(_pen, _lineWidth); + OH_Drawing_SetTextStyleForegroundPen(_strokeTextStyle, _pen); + + Point offsetPoint = convertDrawPoint(Point{x, y}, text, _strokeTextStyle); + auto typography = createTypography(text, _strokeTextStyle); + OH_Drawing_TypographyPaint(typography->get(), _canvas, offsetPoint[0], offsetPoint[1]); } CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::measureText(const ccstd::string &text) { - auto typography = createTypography(text); + auto typography = createTypography(text, _textStyle); return ccstd::array{static_cast(OH_Drawing_TypographyGetMaxIntrinsicWidth(typography->get())), static_cast(OH_Drawing_TypographyGetHeight(typography->get()))}; } @@ -196,6 +255,9 @@ void CanvasRenderingContext2DDelegate::updateFont(const ccstd::string &fontName, bool /* smallCaps */) { _fontName = fontName; _fontSize = static_cast(fontSize); + _italic = italic; + _bold = bold; + if (_typographyCreate) { OH_Drawing_DestroyTypographyHandler(_typographyCreate); } @@ -216,20 +278,24 @@ void CanvasRenderingContext2DDelegate::updateFont(const ccstd::string &fontName, _typographyCreate = OH_Drawing_CreateTypographyHandler(_typographyStyle, _fontCollection); _textStyle = OH_Drawing_CreateTextStyle(); + setTextStyle(_textStyle); +} + +void CanvasRenderingContext2DDelegate::setTextStyle(OH_Drawing_TextStyle *textStyle) { const char *fontFamilies[1]; - fontFamilies[0] = fontName.c_str(); - OH_Drawing_SetTextStyleFontFamilies(_textStyle, 1, fontFamilies); - + fontFamilies[0] = _fontName.c_str(); + OH_Drawing_SetTextStyleFontFamilies(textStyle, 1, fontFamilies); + if (_fontSize) - OH_Drawing_SetTextStyleFontSize(_textStyle, _fontSize); - if (bold) - OH_Drawing_SetTextStyleFontWeight(_textStyle, FONT_WEIGHT_700); - else - OH_Drawing_SetTextStyleFontWeight(_textStyle, FONT_WEIGHT_400); - if(italic) - OH_Drawing_SetTextStyleFontStyle(_textStyle, FONT_STYLE_ITALIC); - else - OH_Drawing_SetTextStyleFontStyle(_textStyle, FONT_STYLE_NORMAL); + OH_Drawing_SetTextStyleFontSize(textStyle, _fontSize); + if (_bold) + OH_Drawing_SetTextStyleFontWeight(textStyle, FONT_WEIGHT_700); + else + OH_Drawing_SetTextStyleFontWeight(textStyle, FONT_WEIGHT_400); + if (_italic) + OH_Drawing_SetTextStyleFontStyle(textStyle, FONT_STYLE_ITALIC); + else + OH_Drawing_SetTextStyleFontStyle(textStyle, FONT_STYLE_NORMAL); } void CanvasRenderingContext2DDelegate::setTextAlign(TextAlign align) { @@ -264,8 +330,8 @@ void CanvasRenderingContext2DDelegate::removeCustomFont() { // x, y offset value int CanvasRenderingContext2DDelegate::drawText(const ccstd::string &text, int x, int y) { - auto typography = createTypography(text); - OH_Drawing_TypographyPaint(typography->get(), _canvas, x, y); + auto typography = createTypography(text, _textStyle); + OH_Drawing_TypographyPaint(typography->get(), _canvas, (double)x, (double)y); return 0; } @@ -282,10 +348,11 @@ void CanvasRenderingContext2DDelegate::deleteBitmap() { void CanvasRenderingContext2DDelegate::fillTextureData() { } -ccstd::array CanvasRenderingContext2DDelegate::convertDrawPoint(Point point, const ccstd::string &text) { - auto typography = createTypography(text); +ccstd::array CanvasRenderingContext2DDelegate::convertDrawPoint(Point point, const ccstd::string &text, OH_Drawing_TextStyle *textStyle) { + auto typography = createTypography(text, textStyle); Size textSize {static_cast(OH_Drawing_TypographyGetMaxIntrinsicWidth(typography->get())), static_cast(OH_Drawing_TypographyGetHeight(typography->get()))}; + if (_textAlign == TextAlign::CENTER) { point[0] -= textSize[0] / 2.0f; } else if (_textAlign == TextAlign::RIGHT) { @@ -306,8 +373,8 @@ ccstd::array CanvasRenderingContext2DDelegate::convertDrawPoint(Point return point; } -std::unique_ptr CanvasRenderingContext2DDelegate::createTypography(const ccstd::string &text) { - OH_Drawing_TypographyHandlerPushTextStyle(_typographyCreate, _textStyle); +std::unique_ptr CanvasRenderingContext2DDelegate::createTypography(const ccstd::string &text, OH_Drawing_TextStyle *textStyle) { + OH_Drawing_TypographyHandlerPushTextStyle(_typographyCreate, textStyle); OH_Drawing_TypographyHandlerAddText(_typographyCreate, text.c_str()); OH_Drawing_TypographyHandlerPopTextStyle(_typographyCreate); OH_Drawing_Typography* typography = OH_Drawing_CreateTypography(_typographyCreate); @@ -332,12 +399,6 @@ void CanvasRenderingContext2DDelegate::fillImageData(const Data & /* imageData * float /* offsetY */) { } -void CanvasRenderingContext2DDelegate::strokeText(const ccstd::string & /* text */, - float /* x */, - float /* y */, - float /* maxWidth */) { -} - void CanvasRenderingContext2DDelegate::rect(float /* x */, float /* y */, float /* w */, diff --git a/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.h b/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.h index 479fd1b9b4..b5d8bfafd7 100644 --- a/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.h +++ b/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.h @@ -66,7 +66,7 @@ public: void clearRect(float /*x*/, float /*y*/, float w, float h) override; void fillRect(float x, float y, float w, float h) override; void fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) override; - void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const; + void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; Size measureText(const ccstd::string &text) override; void updateFont(const ccstd::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override; void setTextAlign(TextAlign align) override; @@ -79,13 +79,13 @@ public: void setLineCap(const ccstd::string &lineCap) override; void setLineJoin(const ccstd::string &lineCap) override; void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; - void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; void rect(float x, float y, float w, float h) override; void setShadowBlur(float blur)override{} void setShadowColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a) override{} void setShadowOffsetX(float offsetX) override{} void setShadowOffsetY(float offsetY) override{} void updateData() override; + void setTextStyle(OH_Drawing_TextStyle *textStyle); private: static wchar_t * utf8ToUtf16(const ccstd::string &str, int *pRetLen = nullptr); void removeCustomFont(); @@ -94,10 +94,11 @@ private: void prepareBitmap(int nWidth, int nHeight); void deleteBitmap(); void fillTextureData(); - ccstd::array convertDrawPoint(Point point, const ccstd::string &text); + ccstd::array convertDrawPoint(Point point, const ccstd::string &text, OH_Drawing_TextStyle *textStyle); class ScopedTypography; - std::unique_ptr createTypography(const ccstd::string &text); + std::unique_ptr createTypography(const ccstd::string &text, OH_Drawing_TextStyle *textStyle); + void setPremultiply(bool multiply); public: int _screen{0}; @@ -116,6 +117,9 @@ private: OH_Drawing_TypographyCreate* _typographyCreate{nullptr}; OH_Drawing_FontCollection* _fontCollection{nullptr}; OH_Drawing_TextStyle* _textStyle{nullptr}; + OH_Drawing_TextStyle *_strokeTextStyle{nullptr}; + OH_Drawing_Pen *_pen{nullptr}; + cc::Data _imageData; ccstd::string _curFontPath; int _savedDC{0}; @@ -131,6 +135,10 @@ private: TextBaseline _textBaseLine{TextBaseline::TOP}; Color4F _fillStyle{0}; Color4F _strokeStyle{0}; + bool _bold{false}; + bool _italic{false}; + bool _premultiply{true}; + }; } // namespace cc diff --git a/native/cocos/platform/openharmony/napi/NapiHelper.cpp b/native/cocos/platform/openharmony/napi/NapiHelper.cpp index e453dcfea1..3f357c595e 100644 --- a/native/cocos/platform/openharmony/napi/NapiHelper.cpp +++ b/native/cocos/platform/openharmony/napi/NapiHelper.cpp @@ -402,9 +402,85 @@ Napi::Env NapiHelper::getWorkerEnv() { return gWorkerEnv; } +static bool sevalue_to_napivalue(const se::Value &seVal, Napi::Value *napiVal, Napi::Env env); + +static bool seobject_to_napivalue(se::Object *seObj, Napi::Value *napiVal, Napi::Env env) { + auto napiObj = Napi::Object::New(env); + std::vector allKeys; + bool ok = seObj->getAllKeys(&allKeys); + if (ok && !allKeys.empty()) { + for (const auto &key : allKeys) { + Napi::Value napiProp; + se::Value prop; + ok = seObj->getProperty(key.c_str(), &prop); + if (ok) { + ok = sevalue_to_napivalue(prop, &napiProp, env); + if (ok) { + napiObj.Set(key.c_str(), napiProp); + } + } + } + } + *napiVal = napiObj; + return true; +} + +static bool sevalue_to_napivalue(const se::Value &seVal, Napi::Value *napiVal, Napi::Env env) { + // Only supports number or {tag: number, url: string} now + if (seVal.isNumber()) { + *napiVal = Napi::Number::New(env, seVal.toDouble()); + } else if (seVal.isString()) { + *napiVal = Napi::String::New(env, seVal.toString().c_str()); + } else if (seVal.isBoolean()) { + *napiVal = Napi::Boolean::New(env, seVal.toBoolean()); + } else if (seVal.isObject()) { + seobject_to_napivalue(seVal.toObject(), napiVal, env); + } else { + CC_LOG_WARNING("sevalue_to_napivalue, Unsupported type: %d", static_cast(seVal.getType())); + return false; + } + + return true; +} + +Napi::Value evalString(const Napi::CallbackInfo &info){ + Napi::Env env = info.Env(); + size_t argc = info.Length(); + if (argc != 1) { + Napi::Error::New(env, "Wrong argument count, 1 expected!").ThrowAsJavaScriptException(); + return env.Undefined(); + } + + if (!info[0].IsString()) { + Napi::TypeError::New(env, "string expected!").ThrowAsJavaScriptException(); + return env.Undefined(); + } + + std::string value = info[0].As().ToString(); + + if (!se::ScriptEngine::getInstance()->isValid()) { + CC_LOG_WARNING("ScriptEngine has not been initialized"); + return env.Undefined(); + } + + se::AutoHandleScope hs; + + size_t length = value.length(); + char* cValue = new char[length + 1]; + strcpy(cValue, value.c_str()); + se::Value ret; + se::ScriptEngine::getInstance()->evalString(cValue, length, &ret); + delete[] cValue; + Napi::Value result; + sevalue_to_napivalue(ret, &result, env); + + return result; +} + /* static */ Napi::Object NapiHelper::init(Napi::Env env, Napi::Object exports) { exports["getContext"] = Napi::Function::New(env, getContext); + exports["evalString"] = Napi::Function::New(env, evalString); bool ret = exportFunctions(exports); if (!ret) { CC_LOG_ERROR("NapiHelper init failed"); diff --git a/scripts/native-pack-tool/source/platforms/harmonyos-next.ts b/scripts/native-pack-tool/source/platforms/harmonyos-next.ts index 7ce1005923..a31a1801ca 100644 --- a/scripts/native-pack-tool/source/platforms/harmonyos-next.ts +++ b/scripts/native-pack-tool/source/platforms/harmonyos-next.ts @@ -108,6 +108,8 @@ export class HarmonyOSNextPackTool extends NativePackTool { const packageJson = this.readJSON5Sync(packageJsonPath); packageJson.name = this.params.projectName; writeFileSync(packageJsonPath, JSON5.stringify(packageJson, null, 4)); + + await this.encrypteScripts(); return true; } diff --git a/templates/harmonyos-next/build-profile.json5 b/templates/harmonyos-next/build-profile.json5 index fa5207f958..279d7f7d1f 100644 --- a/templates/harmonyos-next/build-profile.json5 +++ b/templates/harmonyos-next/build-profile.json5 @@ -6,7 +6,7 @@ { "name": "default", "signingConfig": "default", - "compatibleSdkVersion": "5.0.0(12)", + "compatibleSdkVersion": "5.0.1(13)", "runtimeOS": "HarmonyOS" } ], diff --git a/templates/harmonyos-next/entry/src/main/cpp/types/libcocos/index.d.ts b/templates/harmonyos-next/entry/src/main/cpp/types/libcocos/index.d.ts index d70687261b..4b57978db5 100644 --- a/templates/harmonyos-next/entry/src/main/cpp/types/libcocos/index.d.ts +++ b/templates/harmonyos-next/entry/src/main/cpp/types/libcocos/index.d.ts @@ -28,3 +28,4 @@ interface context { } export const getContext: (type: ContextType) => context; +export const evalString: (value: string) => any; diff --git a/templates/harmonyos-next/entry/src/main/ets/cocos/oh-adapter/sys-ability-polyfill.js b/templates/harmonyos-next/entry/src/main/ets/cocos/oh-adapter/sys-ability-polyfill.js index 74b33024e4..d22164ecd7 100644 --- a/templates/harmonyos-next/entry/src/main/ets/cocos/oh-adapter/sys-ability-polyfill.js +++ b/templates/harmonyos-next/entry/src/main/ets/cocos/oh-adapter/sys-ability-polyfill.js @@ -26,7 +26,6 @@ import display from '@ohos.display'; import I18n from '@ohos.i18n'; import deviceInfo from '@ohos.deviceInfo'; import batteryInfo from '@ohos.batteryInfo'; -import sensor from '@ohos.sensor'; import connection from '@ohos.net.connection' import vibrator from '@ohos.vibrator'; import process from '@ohos.process'; @@ -88,58 +87,6 @@ globalThis.getDeviceOrientation = function () { return displayClass.rotation; } -function radiansToDegrees(radians) { - var pi = Math.PI; - return radians * (180/pi); -} - -let sDeviceMotionValues = []; -try { - sensor.on(sensor.SensorId.ACCELEROMETER, function (data) { - sDeviceMotionValues[0] = data.x; - sDeviceMotionValues[1] = data.y; - sDeviceMotionValues[2] = -data.z; - }, - { interval: 200000000 } - ); -} catch (err) { - sDeviceMotionValues[0] = 0; - sDeviceMotionValues[1] = 0; - sDeviceMotionValues[2] = 0; -} - -try { - sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, function(data){ - sDeviceMotionValues[3] = data.x; - sDeviceMotionValues[4] = data.y; - sDeviceMotionValues[5] = data.z; - }, - {interval: 200000000} - ); -} catch (err) { - sDeviceMotionValues[3] = 0; - sDeviceMotionValues[4] = 0; - sDeviceMotionValues[5] = 0; -} -try { - sensor.on(sensor.SensorId.GYROSCOPE, function(data){ - sDeviceMotionValues[6] = radiansToDegrees(data.x); - sDeviceMotionValues[7] = radiansToDegrees(data.y); - sDeviceMotionValues[8] = radiansToDegrees(data.z); - }, - {interval: 200000000} - ); -} catch (err) { - sDeviceMotionValues[6] = 0; - sDeviceMotionValues[7] = 0; - sDeviceMotionValues[8] = 0; -} - -globalThis.getDeviceMotionValue = function () { - return sDeviceMotionValues; -} - - globalThis.getNetworkType = function () { let netHandle = connection.getDefaultNetSync(); if(netHandle && netHandle.netId != 0) { diff --git a/templates/harmonyos-next/entry/src/main/ets/entryability/EntryAbility.ts b/templates/harmonyos-next/entry/src/main/ets/entryability/EntryAbility.ets similarity index 50% rename from templates/harmonyos-next/entry/src/main/ets/entryability/EntryAbility.ts rename to templates/harmonyos-next/entry/src/main/ets/entryability/EntryAbility.ets index 313242bd1b..7a93777b7b 100644 --- a/templates/harmonyos-next/entry/src/main/ets/entryability/EntryAbility.ts +++ b/templates/harmonyos-next/entry/src/main/ets/entryability/EntryAbility.ets @@ -2,12 +2,19 @@ import UIAbility from '@ohos.app.ability.UIAbility'; import cocos from 'libcocos.so'; import { ContextType } from '../common/Constants'; import window from '@ohos.window'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { AbilityConstant, Want } from '@kit.AbilityKit'; const nativeContext = cocos.getContext(ContextType.ENGINE_UTILS); const nativeAppLifecycle = cocos.getContext(ContextType.APP_LIFECYCLE); - +enum windowStageType { + hide, + show +} export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { + private windowStageType: windowStageType = windowStageType.hide; + + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { globalThis.abilityWant = want; nativeAppLifecycle.onCreate(); nativeContext.resourceManagerInit(this.context.resourceManager); @@ -21,36 +28,25 @@ export default class EntryAbility extends UIAbility { nativeContext.writablePathInit(this.context.cacheDir); // Get the Main window instance - let windowClass = null; - windowStage.getMainWindow((err, data) => { + let windowClass: window.Window | undefined = undefined; + windowStage.getMainWindow((err: BusinessError, data) => { if (err.code) { console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err)); return; } windowClass = data; - console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data)); - - // 设置窗口为全屏布局,配合设置导航栏、状态栏是否显示,与主窗口显示保持协调一致。 - let isLayoutFullScreen = true; - windowClass.setWindowLayoutFullScreen(isLayoutFullScreen, (err) => { - if (err.code) { - console.error('Failed to set the window layout to full-screen mode. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the window layout to full-screen mode.'); - }); - - // 设置状态栏和导航栏是否显示。例如,需全部显示,该参数设置为['status', 'navigation'];不设置,则默认不显示。 - let visibleBar = []; - windowClass.setWindowSystemBarEnable(visibleBar, (err) => { - if (err.code) { - console.error('Failed to set the system bar to be invisible. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the system bar to be invisible.'); + // Set whether to display the status bar and navigation bar. If they are not displayed, [] is displayed. + let systemBarPromise = windowClass.setWindowSystemBarEnable([]); + // Whether the window layout is displayed in full screen mode + let fullScreenPromise = windowClass.setWindowLayoutFullScreen(true); + // Sets whether the screen is always on. + let keepScreenOnPromise = windowClass.setWindowKeepScreenOn(true); + Promise.all([systemBarPromise, fullScreenPromise, keepScreenOnPromise]).then(() => { + console.info('Succeeded in setting the window'); + }).catch((err:BusinessError) => { + console.error('Failed to set the window, cause ' + JSON.stringify(err)); }); }); - // Main window is created, set main page for this ability windowStage.loadContent("pages/index", (err, data) => { if (err.code) { @@ -62,10 +58,10 @@ export default class EntryAbility extends UIAbility { let stageEventType: window.WindowStageEventType = data; switch (stageEventType) { case window.WindowStageEventType.RESUMED: - nativeAppLifecycle.onShow(); + this.onChangeWinodowStageType(windowStageType.show); break; case window.WindowStageEventType.PAUSED: - nativeAppLifecycle.onHide(); + this.onChangeWinodowStageType(windowStageType.hide); break; default: break; @@ -79,11 +75,18 @@ export default class EntryAbility extends UIAbility { onForeground() { // Ability has brought to foreground - nativeAppLifecycle.onShow(); + this.onChangeWinodowStageType(windowStageType.show); } onBackground() { // Ability has back to background - nativeAppLifecycle.onHide(); + this.onChangeWinodowStageType(windowStageType.hide); + } + + onChangeWinodowStageType(type: windowStageType) { + if (this.windowStageType != type) { + this.windowStageType = type; + this.windowStageType === windowStageType.show ? nativeAppLifecycle.onShow() : nativeAppLifecycle.onHide(); + } } } diff --git a/templates/harmonyos-next/entry/src/main/module.json5 b/templates/harmonyos-next/entry/src/main/module.json5 index b94a66f8ba..4c0ddc392f 100644 --- a/templates/harmonyos-next/entry/src/main/module.json5 +++ b/templates/harmonyos-next/entry/src/main/module.json5 @@ -20,7 +20,7 @@ "abilities": [ { "name": "EntryAbility", - "srcEntry": "./ets/entryability/EntryAbility.ts", + "srcEntry": "./ets/entryability/EntryAbility.ets", "description": "$string:MainAbility_desc", "orientation": "portrait", "icon": "$media:icon",