From e68506916c5fef71bff72bd3317a2c0fb31e72ea Mon Sep 17 00:00:00 2001 From: qiuguohua Date: Mon, 20 Mar 2023 14:18:52 +0800 Subject: [PATCH] Develop branch adapts to openharmony (#14582) --- cocos/core/geometry/geometry-native-ext.ts | 10 +- cocos/core/settings.ts | 7 + native/CMakeLists.txt | 155 ++- native/cmake/predefine.cmake | 13 + native/cocos/audio/AudioEngine.cpp | 3 +- .../cocos/audio/android/AudioDecoderSLES.cpp | 78 +- native/cocos/audio/android/AudioDecoderSLES.h | 9 +- .../cocos/audio/android/AudioEngine-inl.cpp | 42 +- native/cocos/audio/android/AudioEngine-inl.h | 4 + native/cocos/audio/android/AudioMixer.h | 61 +- .../audio/android/AudioPlayerProvider.cpp | 51 +- native/cocos/audio/android/AudioResampler.h | 57 +- native/cocos/audio/android/OpenSLHelper.h | 5 + .../cocos/audio/android/PcmAudioService.cpp | 46 +- native/cocos/audio/android/PcmAudioService.h | 6 +- native/cocos/audio/android/UrlAudioPlayer.cpp | 51 +- native/cocos/audio/android/audio.h | 1 - native/cocos/audio/android/cutils/bitops.h | 13 +- native/cocos/audio/android/cutils/log.h | 17 + native/cocos/audio/android/utils/Compat.h | 19 + native/cocos/audio/android/utils/Utils.cpp | 1 - .../cocos/audio/common/utils/include/format.h | 2 + .../audio/common/utils/include/primitives.h | 3 + .../audio/common/utils/include/tinysndfile.h | 3 +- native/cocos/base/Log.cpp | 25 + native/cocos/base/TypeDef.h | 2 +- native/cocos/bindings/jswrapper/Object.h | 5 + native/cocos/bindings/jswrapper/SeApi.h | 4 + native/cocos/bindings/jswrapper/Value.cpp | 1 + native/cocos/bindings/jswrapper/config.h | 5 + .../cocos/bindings/jswrapper/napi/Class.cpp | 247 ++++ native/cocos/bindings/jswrapper/napi/Class.h | 83 ++ .../bindings/jswrapper/napi/CommonHeader.h | 74 + .../bindings/jswrapper/napi/HelperMacros.cpp | 145 ++ .../bindings/jswrapper/napi/HelperMacros.h | 153 +++ .../cocos/bindings/jswrapper/napi/Object.cpp | 738 ++++++++++ native/cocos/bindings/jswrapper/napi/Object.h | 493 +++++++ .../bindings/jswrapper/napi/ScriptEngine.cpp | 312 +++++ .../bindings/jswrapper/napi/ScriptEngine.h | 305 +++++ native/cocos/bindings/jswrapper/napi/SeApi.h | 32 + .../cocos/bindings/jswrapper/napi/Utils.cpp | 196 +++ native/cocos/bindings/jswrapper/napi/Utils.h | 46 + .../bindings/jswrapper/napi/native_common.h | 115 ++ .../bindings/manual/jsb_audio_manual.cpp | 1 - .../cocos/bindings/manual/jsb_conversions.h | 2 - native/cocos/bindings/manual/jsb_global.cpp | 4 + .../cocos/bindings/manual/jsb_global_init.cpp | 2 + .../bindings/manual/jsb_module_register.cpp | 12 +- .../manual/jsb_platform_openharmony.cpp | 52 + native/cocos/engine/Engine.cpp | 2 +- .../cocos/network/WebSocket-libwebsockets.cpp | 4 +- native/cocos/platform/BasePlatform.cpp | 4 + .../platform/interfaces/modules/Device.cpp | 23 + .../platform/interfaces/modules/Device.h | 3 + .../canvas/CanvasRenderingContext2D.cpp | 4 +- .../openharmony/FileUtils-OpenHarmony.cpp | 285 ++++ .../openharmony/FileUtils-OpenHarmony.h | 75 + .../openharmony/OpenHarmonyPlatform.cpp | 287 ++++ .../openharmony/OpenHarmonyPlatform.h | 82 ++ .../openharmony/WorkerMessageQueue.cpp | 49 + .../platform/openharmony/WorkerMessageQueue.h | 67 + .../openharmony/modules/Accelerometer.cpp | 62 + .../openharmony/modules/Accelerometer.h | 50 + .../platform/openharmony/modules/Battery.cpp | 37 + .../platform/openharmony/modules/Battery.h | 37 + .../CanvasRenderingContext2DDelegate.cpp | 335 +++++ .../CanvasRenderingContext2DDelegate.h | 136 ++ .../platform/openharmony/modules/Screen.cpp | 85 ++ .../platform/openharmony/modules/Screen.h | 51 + .../platform/openharmony/modules/System.cpp | 106 ++ .../platform/openharmony/modules/System.h | 67 + .../openharmony/modules/SystemWindow.cpp | 89 ++ .../openharmony/modules/SystemWindow.h | 63 + .../modules/SystemWindowManager.cpp | 63 + .../openharmony/modules/SystemWindowManager.h | 50 + .../platform/openharmony/napi/NapiHelper.cpp | 330 +++++ .../platform/openharmony/napi/NapiHelper.h | 115 ++ .../platform/openharmony/napi/NapiInit.cpp | 63 + .../cocos/ui/edit-box/EditBox-openharmony.cpp | 113 ++ .../cocos/ui/edit-box/EditBox-openharmony.h | 50 + native/cocos/ui/videoplayer/VideoPlayer.h | 3 +- native/cocos/ui/webview/WebView-inl.h | 2 +- .../ui/webview/WebViewImpl-openharmony.cpp | 333 +++++ .../ui/webview/WebViewImpl-openharmony.h | 43 + native/external-config.json | 2 +- native/utils/clear-platform.js | 4 +- pal/env/native/env.ts | 54 +- pal/screen-adapter/native/screen-adapter.ts | 9 +- platforms/native/builtin/index.js | 25 +- platforms/native/engine/index.js | 5 +- platforms/native/engine/jsb-gfx.js | 3 +- platforms/native/engine/jsb-loader.js | 5 +- .../engine/jsb-videoplayer-openharmony.js | 421 ++++++ scripts/build-engine/package-lock.json | 2 +- scripts/build-engine/package.json | 2 +- scripts/build-engine/src/constant-manager.ts | 12 + scripts/build-engine/src/index.ts | 15 +- scripts/native-pack-tool/package.json | 3 +- scripts/native-pack-tool/source/index.ts | 2 + .../source/platforms/openharmony.ts | 217 +++ scripts/native-pack-tool/source/utils.ts | 2 +- templates/cmake/openharmony.cmake | 18 + templates/openharmony/.gitignore | 6 + templates/openharmony/AppScope/app.json5 | 11 + .../resources/base/element/string.json | 8 + .../resources/base/media/app_icon.png | Bin 0 -> 9915 bytes templates/openharmony/CMakeLists.txt | 19 + templates/openharmony/build-profile.json5 | 26 + templates/openharmony/entry/.gitignore | 4 + .../openharmony/entry/build-profile.json5 | 22 + templates/openharmony/entry/hvigorfile.js | 2 + templates/openharmony/entry/package-lock.json | 5 + templates/openharmony/entry/package.json | 14 + .../openharmony/entry/src/main/cpp/README.md | 1 + .../main/ets/Application/GameAbilityStage.ts | 30 + .../src/main/ets/MainAbility/MainAbility.ts | 67 + .../src/main/ets/cocos/WorkerManager.ets | 54 + .../entry/src/main/ets/cocos/game.ts | 110 ++ .../cocos/jsb-adapter/sys-ability-polyfill.js | 168 +++ .../entry/src/main/ets/common/Constants.ts | 40 + .../entry/src/main/ets/common/PortProxy.ts | 75 + .../main/ets/components/CocosVideoPlayer.ets | 113 ++ .../src/main/ets/components/CocosWebview.ets | 78 ++ .../src/main/ets/components/EditBoxDialog.ets | 68 + .../entry/src/main/ets/pages/index.ets | 288 ++++ .../src/main/ets/workers/cocos_worker.ts | 98 ++ .../openharmony/entry/src/main/module.json5 | 65 + .../main/resources/base/element/color.json | 8 + .../main/resources/base/element/string.json | 20 + .../src/main/resources/base/media/icon.png | Bin 0 -> 9915 bytes .../resources/base/profile/main_pages.json | 5 + .../entry/src/main/resources/rawfile/.keep | 0 templates/openharmony/hvigorfile.js | 2 + templates/openharmony/package-lock.json | 1212 +++++++++++++++++ templates/openharmony/package.json | 21 + 135 files changed, 10084 insertions(+), 236 deletions(-) create mode 100644 native/cocos/bindings/jswrapper/napi/Class.cpp create mode 100644 native/cocos/bindings/jswrapper/napi/Class.h create mode 100644 native/cocos/bindings/jswrapper/napi/CommonHeader.h create mode 100644 native/cocos/bindings/jswrapper/napi/HelperMacros.cpp create mode 100644 native/cocos/bindings/jswrapper/napi/HelperMacros.h create mode 100644 native/cocos/bindings/jswrapper/napi/Object.cpp create mode 100644 native/cocos/bindings/jswrapper/napi/Object.h create mode 100644 native/cocos/bindings/jswrapper/napi/ScriptEngine.cpp create mode 100644 native/cocos/bindings/jswrapper/napi/ScriptEngine.h create mode 100644 native/cocos/bindings/jswrapper/napi/SeApi.h create mode 100644 native/cocos/bindings/jswrapper/napi/Utils.cpp create mode 100644 native/cocos/bindings/jswrapper/napi/Utils.h create mode 100644 native/cocos/bindings/jswrapper/napi/native_common.h create mode 100644 native/cocos/bindings/manual/jsb_platform_openharmony.cpp create mode 100644 native/cocos/platform/openharmony/FileUtils-OpenHarmony.cpp create mode 100644 native/cocos/platform/openharmony/FileUtils-OpenHarmony.h create mode 100644 native/cocos/platform/openharmony/OpenHarmonyPlatform.cpp create mode 100644 native/cocos/platform/openharmony/OpenHarmonyPlatform.h create mode 100644 native/cocos/platform/openharmony/WorkerMessageQueue.cpp create mode 100644 native/cocos/platform/openharmony/WorkerMessageQueue.h create mode 100644 native/cocos/platform/openharmony/modules/Accelerometer.cpp create mode 100644 native/cocos/platform/openharmony/modules/Accelerometer.h create mode 100644 native/cocos/platform/openharmony/modules/Battery.cpp create mode 100644 native/cocos/platform/openharmony/modules/Battery.h create mode 100644 native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.cpp create mode 100644 native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.h create mode 100644 native/cocos/platform/openharmony/modules/Screen.cpp create mode 100644 native/cocos/platform/openharmony/modules/Screen.h create mode 100644 native/cocos/platform/openharmony/modules/System.cpp create mode 100644 native/cocos/platform/openharmony/modules/System.h create mode 100644 native/cocos/platform/openharmony/modules/SystemWindow.cpp create mode 100644 native/cocos/platform/openharmony/modules/SystemWindow.h create mode 100644 native/cocos/platform/openharmony/modules/SystemWindowManager.cpp create mode 100644 native/cocos/platform/openharmony/modules/SystemWindowManager.h create mode 100644 native/cocos/platform/openharmony/napi/NapiHelper.cpp create mode 100644 native/cocos/platform/openharmony/napi/NapiHelper.h create mode 100644 native/cocos/platform/openharmony/napi/NapiInit.cpp create mode 100644 native/cocos/ui/edit-box/EditBox-openharmony.cpp create mode 100644 native/cocos/ui/edit-box/EditBox-openharmony.h create mode 100644 native/cocos/ui/webview/WebViewImpl-openharmony.cpp create mode 100644 native/cocos/ui/webview/WebViewImpl-openharmony.h create mode 100644 platforms/native/engine/jsb-videoplayer-openharmony.js create mode 100644 scripts/native-pack-tool/source/platforms/openharmony.ts create mode 100644 templates/cmake/openharmony.cmake create mode 100644 templates/openharmony/.gitignore create mode 100644 templates/openharmony/AppScope/app.json5 create mode 100644 templates/openharmony/AppScope/resources/base/element/string.json create mode 100644 templates/openharmony/AppScope/resources/base/media/app_icon.png create mode 100644 templates/openharmony/CMakeLists.txt create mode 100644 templates/openharmony/build-profile.json5 create mode 100644 templates/openharmony/entry/.gitignore create mode 100644 templates/openharmony/entry/build-profile.json5 create mode 100644 templates/openharmony/entry/hvigorfile.js create mode 100644 templates/openharmony/entry/package-lock.json create mode 100644 templates/openharmony/entry/package.json create mode 100644 templates/openharmony/entry/src/main/cpp/README.md create mode 100644 templates/openharmony/entry/src/main/ets/Application/GameAbilityStage.ts create mode 100644 templates/openharmony/entry/src/main/ets/MainAbility/MainAbility.ts create mode 100644 templates/openharmony/entry/src/main/ets/cocos/WorkerManager.ets create mode 100644 templates/openharmony/entry/src/main/ets/cocos/game.ts create mode 100644 templates/openharmony/entry/src/main/ets/cocos/jsb-adapter/sys-ability-polyfill.js create mode 100644 templates/openharmony/entry/src/main/ets/common/Constants.ts create mode 100644 templates/openharmony/entry/src/main/ets/common/PortProxy.ts create mode 100644 templates/openharmony/entry/src/main/ets/components/CocosVideoPlayer.ets create mode 100644 templates/openharmony/entry/src/main/ets/components/CocosWebview.ets create mode 100644 templates/openharmony/entry/src/main/ets/components/EditBoxDialog.ets create mode 100644 templates/openharmony/entry/src/main/ets/pages/index.ets create mode 100644 templates/openharmony/entry/src/main/ets/workers/cocos_worker.ts create mode 100644 templates/openharmony/entry/src/main/module.json5 create mode 100644 templates/openharmony/entry/src/main/resources/base/element/color.json create mode 100644 templates/openharmony/entry/src/main/resources/base/element/string.json create mode 100644 templates/openharmony/entry/src/main/resources/base/media/icon.png create mode 100644 templates/openharmony/entry/src/main/resources/base/profile/main_pages.json create mode 100644 templates/openharmony/entry/src/main/resources/rawfile/.keep create mode 100644 templates/openharmony/hvigorfile.js create mode 100644 templates/openharmony/package-lock.json create mode 100644 templates/openharmony/package.json diff --git a/cocos/core/geometry/geometry-native-ext.ts b/cocos/core/geometry/geometry-native-ext.ts index 7fe2dcd038..fc623b7159 100644 --- a/cocos/core/geometry/geometry-native-ext.ts +++ b/cocos/core/geometry/geometry-native-ext.ts @@ -87,7 +87,10 @@ const defineAttrFloat = (kls: Constructor, attr: string) => { // __nativeFields__ is defined in jsb_geometry_manual.cpp const desc: FieldDesc = (kls as any).__nativeFields__[attr]; const cacheKey = `_$_${attr}`; - console.assert(desc.fieldSize === 4, `field ${attr} size ${desc.fieldSize}`); + if (!window.oh) { + // openharmony does not support the console.assert interface at this time. + console.assert(desc.fieldSize === 4, `field ${attr} size ${desc.fieldSize}`); + } Object.defineProperty(kls.prototype, desc.fieldName, { configurable: true, enumerable: true, @@ -117,7 +120,10 @@ const defineAttrInt = (kls: Constructor, attr: string) => { console.error(`attr ${attr} not defined in class ${kls.toString()}`); } const cacheKey = `_$_${attr}`; - console.assert(desc.fieldSize === 4, `field ${attr} size ${desc.fieldSize}`); + if (!window.oh) { + // openharmony does not support the console.assert interface at this time. + console.assert(desc.fieldSize === 4, `field ${attr} size ${desc.fieldSize}`); + } Object.defineProperty(kls.prototype, desc.fieldName, { configurable: true, enumerable: true, diff --git a/cocos/core/settings.ts b/cocos/core/settings.ts index e25104bb09..135e4692b8 100644 --- a/cocos/core/settings.ts +++ b/cocos/core/settings.ts @@ -25,6 +25,7 @@ import { HTML5, TAOBAO, TAOBAO_MINIGAME } from 'internal:constants'; import { legacyCC } from './global-exports'; declare const fsUtils: any; +declare const require: (path: string) => Promise; /** * @zh @@ -74,6 +75,12 @@ export class Settings { } } if (!path) return Promise.resolve(); + + if (window.oh) { + // TODO(qgh):OpenHarmony temporarily does not support reading json that is not in the resource directory + this._settings = require('../settings.json'); + return Promise.resolve(); + } return new Promise((resolve, reject) => { if (!HTML5 && !path.startsWith('http')) { // TODO: readJsonSync not working on Taobao IDE diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 0d1dc4184a..9b6010fcc6 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -103,16 +103,21 @@ if(NOT USE_SOCKET) set(USE_WEBSOCKET_SERVER OFF) endif() -if(OHOS) +if(OPENHARMONY AND OHOS) set(CC_USE_GLES2 OFF) endif() ## disable videoplay on non-mobile platforms -if(NOT ANDROID AND NOT IOS AND NOT OHOS) +if(NOT ANDROID AND NOT IOS AND NOT OHOS AND NOT OPENHARMONY) set(USE_VIDEO OFF) set(USE_WEBVIEW OFF) endif() +if(OPENHARMONY) + set(USE_SE_V8 OFF) + set(USE_SE_NAPI ON) +endif() + ## disable middleware when dragonbones and spine are disabled if(NOT USE_DRAGONBONES AND NOT USE_SPINE) set(USE_MIDDLEWARE OFF) @@ -282,7 +287,7 @@ NO_WERROR cocos/audio/common/utils/primitives.cpp cocos/audio/oalsoft/AudioPlayer.cpp cocos/audio/oalsoft/AudioPlayer.h ) - elseif(ANDROID) + elseif(ANDROID OR OPENHARMONY) cocos_source_files( cocos/audio/common/utils/include/primitives.h cocos/audio/common/utils/include/format.h @@ -538,6 +543,16 @@ elseif(ANDROID) cocos/platform/android/AndroidPlatform.cpp cocos/platform/android/AndroidPlatform.h ) +elseif(OPENHARMONY) + cocos_source_files( + cocos/platform/openharmony/napi/NapiHelper.cpp + cocos/platform/openharmony/napi/NapiHelper.h + + cocos/platform/openharmony/WorkerMessageQueue.cpp + cocos/platform/openharmony/WorkerMessageQueue.h + cocos/platform/openharmony/OpenHarmonyPlatform.cpp + cocos/platform/openharmony/OpenHarmonyPlatform.h + ) elseif(OHOS) cocos_source_files( cocos/platform/ohos/OhosPlatform.cpp @@ -567,6 +582,7 @@ cocos_source_files( ) ############ platform : Interface definition +if(NOT OPENHARMONY) cocos_source_files( cocos/platform/interfaces/modules/Device.cpp cocos/platform/interfaces/modules/Device.h @@ -582,6 +598,16 @@ cocos_source_files( cocos/platform/interfaces/modules/XRCommon.h cocos/platform/interfaces/modules/IXRInterface.h ) +elseif(OPENHARMONY) + cocos_source_files( + cocos/platform/interfaces/modules/ISystem.h + cocos/platform/interfaces/modules/ISystem.cpp + cocos/platform/interfaces/modules/ISystemWindow.h + cocos/platform/interfaces/modules/Device.cpp + cocos/platform/interfaces/modules/Device.h + cocos/platform/interfaces/modules/IScreen.h + ) +endif() cocos_source_files( cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp @@ -598,6 +624,11 @@ elseif(WINDOWS) cocos/platform/win32/modules/CanvasRenderingContext2DDelegate.cpp cocos/platform/win32/modules/CanvasRenderingContext2DDelegate.h ) +elseif(OPENHARMONY) + cocos_source_files( + cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.cpp + cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.h + ) elseif(ANDROID OR OHOS) cocos_source_files( cocos/platform/java/modules/CanvasRenderingContext2DDelegate.cpp @@ -649,6 +680,27 @@ if(WINDOWS) cocos/platform/win32/modules/SystemWindowManager.h ) endif() +elseif(OPENHARMONY) + cocos_source_files( + cocos/platform/openharmony/modules/System.cpp + cocos/platform/openharmony/modules/System.h + cocos/platform/openharmony/modules/SystemWindow.cpp + cocos/platform/openharmony/modules/SystemWindow.h + cocos/platform/openharmony/modules/Screen.cpp + cocos/platform/openharmony/modules/Screen.h + cocos/platform/openharmony/modules/Accelerometer.cpp + cocos/platform/openharmony/modules/Accelerometer.h + cocos/platform/openharmony/modules/Battery.cpp + cocos/platform/openharmony/modules/Battery.h + cocos/platform/openharmony/modules/System.cpp + cocos/platform/openharmony/modules/SystemWindow.cpp + cocos/platform/openharmony/modules/SystemWindowManager.h + cocos/platform/openharmony/modules/SystemWindowManager.cpp + cocos/platform/empty/modules/Network.cpp + cocos/platform/empty/modules/Network.h + cocos/platform/empty/modules/Vibrator.cpp + cocos/platform/empty/modules/Vibrator.h + ) elseif(ANDROID OR OHOS) cocos_source_files( cocos/platform/java/modules/Accelerometer.cpp @@ -679,6 +731,8 @@ if(ANDROID) cocos/platform/android/modules/System.cpp cocos/platform/android/modules/System.h ) +elseif(OPENHARMONY) + # Because there will be a definition of OHOS in harmonyos, it is necessary to define the macro of OPENHARMONY. elseif(OHOS) cocos_source_files( cocos/platform/ohos/modules/Screen.cpp @@ -892,6 +946,9 @@ cocos_source_files( cocos/network/Downloader.cpp cocos/network/Downloader.h cocos/network/DownloaderImpl.h +) +# The xmlhttprequest module of OpenHarmony is implemented in the ts layer +cocos_source_files( cocos/network/HttpClient.h cocos/network/HttpCookie.cpp cocos/network/HttpCookie.h @@ -934,7 +991,7 @@ if(APPLE) endif() endif() -if(ANDROID OR OHOS) +if(ANDROID OR (NOT OPENHARMONY AND OHOS)) cocos_source_files( cocos/network/Downloader-java.cpp cocos/network/Downloader-java.h @@ -954,14 +1011,14 @@ if(NOT APPLE AND USE_SOCKET) endif() endif() -if(WINDOWS OR LINUX OR QNX) +if(WINDOWS OR LINUX OR QNX OR OPENHARMONY) cocos_source_files( NO_WERROR cocos/network/Downloader-curl.cpp cocos/network/Downloader-curl.h ) endif() -if(WINDOWS OR MACOSX OR LINUX OR QNX) +if(WINDOWS OR MACOSX OR LINUX OR QNX OR OPENHARMONY) cocos_source_files( NO_WERROR NO_UBUILD cocos/network/HttpClient.cpp ) @@ -1030,6 +1087,12 @@ elseif(ANDROID) cocos/platform/android/FileUtils-android.cpp cocos/platform/android/FileUtils-android.h ) +elseif(OPENHARMONY) + # Because there will be a definition of OHOS in harmonyos, it is necessary to define the macro of OPENHARMONY. + cocos_source_files(MODULE ccfilesystem + cocos/platform/openharmony/FileUtils-OpenHarmony.cpp + cocos/platform/openharmony/FileUtils-OpenHarmony.h + ) elseif(OHOS) set(CC_JNI_SRC_FILES ${CWD}/cocos/platform/ohos/jni/JniCocosAbility.cpp @@ -2023,14 +2086,14 @@ cocos_source_files( ######## auto cocos_source_files( + NO_WERROR NO_UBUILD cocos/bindings/auto/jsb_network_auto.cpp + cocos/bindings/auto/jsb_network_auto.h NO_WERROR NO_UBUILD cocos/bindings/auto/jsb_cocos_auto.cpp cocos/bindings/auto/jsb_cocos_auto.h NO_WERROR NO_UBUILD cocos/bindings/auto/jsb_extension_auto.cpp cocos/bindings/auto/jsb_extension_auto.h NO_WERROR NO_UBUILD cocos/bindings/auto/jsb_gfx_auto.cpp cocos/bindings/auto/jsb_gfx_auto.h - NO_WERROR NO_UBUILD cocos/bindings/auto/jsb_network_auto.cpp - cocos/bindings/auto/jsb_network_auto.h NO_WERROR NO_UBUILD cocos/bindings/auto/jsb_pipeline_auto.cpp cocos/bindings/auto/jsb_pipeline_auto.h NO_WERROR NO_UBUILD cocos/bindings/auto/jsb_scene_auto.cpp @@ -2047,6 +2110,7 @@ cocos_source_files( cocos/bindings/auto/jsb_2d_auto.h ) + if(USE_AUDIO) cocos_source_files( NO_WERROR NO_UBUILD cocos/bindings/auto/jsb_audio_auto.cpp @@ -2371,6 +2435,14 @@ if(USE_MIDDLEWARE) endif() ######## manual +cocos_source_files( + NO_WERROR cocos/bindings/manual/jsb_network_manual.cpp + cocos/bindings/manual/jsb_network_manual.h + NO_WERROR cocos/bindings/manual/jsb_xmlhttprequest.cpp + cocos/bindings/manual/jsb_xmlhttprequest.h + +) + cocos_source_files( cocos/bindings/manual/jsb_classtype.cpp cocos/bindings/manual/jsb_classtype.h @@ -2429,6 +2501,10 @@ if(ANDROID) cocos/bindings/manual/JavaScriptJavaBridge.cpp cocos/bindings/manual/JavaScriptJavaBridge.h ) +elseif(OPENHARMONY) + cocos_source_files( + cocos/bindings/manual/jsb_platform_openharmony.cpp + ) elseif(OHOS) cocos_source_files( cocos/bindings/manual/jsb_platform_ohos.cpp @@ -2531,6 +2607,23 @@ if(USE_SE_SM) ) endif() +if(USE_SE_NAPI) + cocos_source_files(MODULE ccbindings + cocos/bindings/jswrapper/napi/Class.cpp + cocos/bindings/jswrapper/napi/Class.h + cocos/bindings/jswrapper/napi/CommonHeader.h + cocos/bindings/jswrapper/napi/HelperMacros.h + cocos/bindings/jswrapper/napi/HelperMacros.cpp + cocos/bindings/jswrapper/napi/Object.cpp + cocos/bindings/jswrapper/napi/Object.h + NO_WERROR cocos/bindings/jswrapper/napi/ScriptEngine.cpp + cocos/bindings/jswrapper/napi/ScriptEngine.h + cocos/bindings/jswrapper/napi/SeApi.h + NO_WERROR cocos/bindings/jswrapper/napi/Utils.cpp + cocos/bindings/jswrapper/napi/Utils.h + ) +endif() + cocos_source_files(MODULE ccbindings cocos/bindings/jswrapper/config.h cocos/bindings/jswrapper/config.cpp @@ -2579,7 +2672,7 @@ if(USE_EDIT_BOX) ) endif() -if(ANDROID OR IOS OR OHOS) +if(NOT OPENHARMONY AND (ANDROID OR IOS OR OHOS)) if(USE_VIDEO) cocos_source_files( cocos/ui/videoplayer/VideoPlayer.h @@ -2610,6 +2703,20 @@ if(ANDROID) cocos/ui/webview/WebViewImpl-android.cpp ) endif() +elseif(OPENHARMONY) + if(USE_EDIT_BOX) + cocos_source_files( + cocos/ui/edit-box/EditBox-openharmony.h + cocos/ui/edit-box/EditBox-openharmony.cpp + ) + endif() + if(USE_WEBVIEW) + cocos_source_files( + cocos/ui/webview/WebViewImpl-java.h + cocos/ui/webview/WebViewImpl-openharmony.h + cocos/ui/webview/WebViewImpl-openharmony.cpp + ) + endif() elseif(OHOS) if(USE_EDIT_BOX) cocos_source_files( @@ -2785,6 +2892,8 @@ if(USE_MODULES) target_link_libraries(ccfilesystem PUBLIC cocos_jni ) + elseif(OPENHARMONY) + elseif(OHOS) target_link_libraries(cclog PUBLIC hilog_ndk.z @@ -2835,7 +2944,7 @@ if(USE_MODULES) endif() -if(ANDROID OR OHOS) +if(ANDROID OR (NOT OPENHARMONY AND OHOS)) cc_enable_werror("${CC_JNI_SRC_FILES}") add_library(cocos_jni STATIC ${CC_JNI_SRC_FILES}) target_include_directories(cocos_jni PUBLIC @@ -3044,7 +3153,7 @@ if(ANDROID) ) endif() -if(OHOS) +if(NOT OPENHARMONY AND OHOS) target_link_libraries(${ENGINE_NAME} PUBLIC EGL GLESv3 @@ -3058,6 +3167,30 @@ if(OHOS) ) endif() +if(OPENHARMONY) + find_library( # Sets the name of the path variable. + EGL-lib + # Specifies the name of the NDK library that + # you want CMake to locate. + EGL ) + find_library( # Sets the name of the path variable. + GLESv3-lib + # Specifies the name of the NDK library that + # you want CMake to locate. + GLESv3) + + find_library( hilog-lib + hilog_ndk.z ) + + find_library( libace-lib + libace_ndk.z ) + + target_link_libraries(${ENGINE_NAME} PUBLIC + ${EGL-lib} ${GLESv3-lib} ${hilog-lib} libace_napi.z.so libace_ndk.z.so libz.so libuv.so libnative_drawing.so librawfile.z.so libOpenSLES.so + ${CC_EXTERNAL_LIBS} + ) +endif() + if(APPLE) target_compile_options(${ENGINE_NAME} PRIVATE diff --git a/native/cmake/predefine.cmake b/native/cmake/predefine.cmake index e9799f7da5..7a0fc551ab 100644 --- a/native/cmake/predefine.cmake +++ b/native/cmake/predefine.cmake @@ -8,6 +8,7 @@ set(CC_PLATFORM_LINUX 6) set(CC_PLATFORM_QNX 7) set(CC_PLATFORM_NX 8) set(CC_PLATFORM_EMSCRIPTEN 9) +set(CC_PLATFORM_OPENHARMONY 10) set(CC_PLATFORM 1) if(NX) @@ -62,6 +63,15 @@ elseif(${CMAKE_SYSTEM_NAME} MATCHES "QNX") set(PLATFORM_FOLDER qnx) set(CC_PLATFORM ${CC_PLATFORM_QNX}) add_definitions(-D__QNX__=1) +elseif(OPENHARMONY) + set(OPENHARMONY TRUE) + set(CC_PLATFORM ${CC_PLATFORM_OPENHARMONY}) + add_definitions(-D__OPENHARMONY__=1) + set(PLATFORM_FOLDER openharmony) + set(CMAKE_CXX_FLAGS "-fvisibility=hidden -fvisibility-inlines-hidden ${CMAKE_CXX_FLAGS}") + if("${OHOS_ARCH}" STREQUAL "armeabi-v7a") + set(CMAKE_CXX_FLAGS "-march=armv7a ${CMAKE_CXX_FLAGS}") + endif() elseif(${CMAKE_SYSTEM_NAME} MATCHES "Emscripten") set(CC_WGPU_WASM TRUE) set(CC_PLATFORM ${CC_PLATFORM_EMSCRIPTEN}) @@ -90,6 +100,7 @@ add_definitions(-DCC_PLATFORM_OHOS=${CC_PLATFORM_OHOS}) add_definitions(-DCC_PLATFORM_LINUX=${CC_PLATFORM_LINUX}) add_definitions(-DCC_PLATFORM_QNX=${CC_PLATFORM_QNX}) add_definitions(-DCC_PLATFORM_NX=${CC_PLATFORM_NX}) +add_definitions(-DCC_PLATFORM_OPENHARMONY=${CC_PLATFORM_OPENHARMONY}) add_definitions(-DCC_PLATFORM_EMSCRIPTEN=${CC_PLATFORM_EMSCRIPTEN}) add_definitions(-DCC_PLATFORM=${CC_PLATFORM}) @@ -269,6 +280,8 @@ elseif(LINUX) include(${CMAKE_CURRENT_LIST_DIR}/../../templates/cmake/linux.cmake) elseif(ANDROID) include(${CMAKE_CURRENT_LIST_DIR}/../../templates/cmake/android.cmake) +elseif(OPENHARMONY) + include(${CMAKE_CURRENT_LIST_DIR}/../../templates/cmake/openharmony.cmake) elseif(OHOS) include(${CMAKE_CURRENT_LIST_DIR}/../../templates/cmake/ohos.cmake) elseif(QNX) diff --git a/native/cocos/audio/AudioEngine.cpp b/native/cocos/audio/AudioEngine.cpp index 611296ab81..1da6c8f1e1 100644 --- a/native/cocos/audio/AudioEngine.cpp +++ b/native/cocos/audio/AudioEngine.cpp @@ -34,7 +34,8 @@ #include "base/std/container/queue.h" #include "platform/FileUtils.h" -#if CC_PLATFORM == CC_PLATFORM_ANDROID +#if CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OPENHARMONY + // OpenHarmony and Android use the same audio playback module #include "audio/android/AudioEngine-inl.h" #elif CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_MACOS #include "audio/apple/AudioEngine-inl.h" diff --git a/native/cocos/audio/android/AudioDecoderSLES.cpp b/native/cocos/audio/android/AudioDecoderSLES.cpp index 7085158493..43b7a147cd 100644 --- a/native/cocos/audio/android/AudioDecoderSLES.cpp +++ b/native/cocos/audio/android/AudioDecoderSLES.cpp @@ -25,6 +25,7 @@ #define LOG_TAG "AudioDecoderSLES" +#include "base/Macros.h" #include "audio/android/AudioDecoderSLES.h" #include "platform/FileUtils.h" @@ -54,13 +55,13 @@ namespace cc { //----------------------------------------------------------------- -static std::mutex __SLPlayerMutex; +static std::mutex __SLPlayerMutex; //NOLINT(bugprone-reserved-identifier, readability-identifier-naming) static int toBufferSizeInBytes(int bufferSizeInFrames, int sampleSize, int channelCount) { return bufferSizeInFrames * sampleSize * channelCount; } -static int BUFFER_SIZE_IN_BYTES = 0; +static int BUFFER_SIZE_IN_BYTES = 0; // NOLINT(readability-identifier-naming) static void checkMetaData(int index, const char *key) { if (index != -1) { @@ -75,17 +76,17 @@ public: //----------------------------------------------------------------- /* Callback for "prefetch" events, here used to detect audio resource opening errors */ static void prefetchEventCallback(SLPrefetchStatusItf caller, void *context, SLuint32 event) { - AudioDecoderSLES *thiz = reinterpret_cast(context); + auto *thiz = reinterpret_cast(context); thiz->prefetchCallback(caller, event); } - static void decPlayCallback(SLAndroidSimpleBufferQueueItf queueItf, void *context) { - AudioDecoderSLES *thiz = reinterpret_cast(context); + static void decPlayCallback(CCSLBufferQueueItf queueItf, void *context) { + auto *thiz = reinterpret_cast(context); thiz->decodeToPcmCallback(queueItf); } static void decProgressCallback(SLPlayItf caller, void *context, SLuint32 event) { - AudioDecoderSLES *thiz = reinterpret_cast(context); + auto *thiz = reinterpret_cast(context); thiz->decodeProgressCallback(caller, event); } }; @@ -116,7 +117,7 @@ bool AudioDecoderSLES::init(SLEngineItf engineItf, const ccstd::string &url, int _fdGetterCallback = fdGetterCallback; BUFFER_SIZE_IN_BYTES = toBufferSizeInBytes(bufferSizeInFrames, 2, 2); - _pcmData = (char *)malloc(NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES); + _pcmData = static_cast(malloc(NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES)); memset(_pcmData, 0x00, NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES); return true; } @@ -125,13 +126,14 @@ bool AudioDecoderSLES::init(SLEngineItf engineItf, const ccstd::string &url, int } bool AudioDecoderSLES::decodeToPcm() { +#if CC_PLATFORM == CC_PLATFORM_ANDROID SLresult result; /* Objects this application uses: one audio player */ SLObjectItf player; /* Interfaces for the audio player */ - SLAndroidSimpleBufferQueueItf decBuffQueueItf; + CCSLBufferQueueItf decBuffQueueItf; SLPrefetchStatusItf prefetchItf; SLPlayItf playItf; SLMetadataExtractionItf mdExtrItf; @@ -174,7 +176,8 @@ bool AudioDecoderSLES::decodeToPcm() { decSource.pFormat = &formatMime; if (_url[0] != '/') { - off_t start = 0, length = 0; + off_t start = 0; + off_t length = 0; ccstd::string relativePath; size_t position = _url.find("@assets/"); @@ -197,7 +200,7 @@ bool AudioDecoderSLES::decodeToPcm() { decSource.pLocator = &locFd; } else { - decUri = {SL_DATALOCATOR_URI, (SLchar *)_url.c_str()}; + decUri = {SL_DATALOCATOR_URI, (SLchar *)_url.c_str()}; // NOLINT(google-readability-casting) decSource.pLocator = &decUri; } @@ -214,8 +217,8 @@ bool AudioDecoderSLES::decodeToPcm() { pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; pcm.endianness = SL_BYTEORDER_LITTLEENDIAN; - decDest.pLocator = (void *)&decBuffQueue; - decDest.pFormat = (void *)&pcm; + decDest.pLocator = reinterpret_cast(&decBuffQueue); + decDest.pFormat = reinterpret_cast(&pcm); { std::lock_guard lk(__SLPlayerMutex); @@ -230,7 +233,7 @@ bool AudioDecoderSLES::decodeToPcm() { } /* Get the play interface which is implicit */ - result = (*player)->GetInterface(player, SL_IID_PLAY, (void *)&playItf); + result = (*player)->GetInterface(player, SL_IID_PLAY, reinterpret_cast(&playItf)); SL_RETURN_VAL_IF_FAILED(result, false, "GetInterface SL_IID_PLAY failed"); /* Set up the player callback to get events during the decoding */ @@ -251,22 +254,22 @@ bool AudioDecoderSLES::decodeToPcm() { /* Get the buffer queue interface which was explicitly requested */ result = (*player)->GetInterface(player, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, - (void *)&decBuffQueueItf); + reinterpret_cast(&decBuffQueueItf)); SL_RETURN_VAL_IF_FAILED(result, false, "GetInterface SL_IID_ANDROIDSIMPLEBUFFERQUEUE failed"); /* Get the prefetch status interface which was explicitly requested */ - result = (*player)->GetInterface(player, SL_IID_PREFETCHSTATUS, (void *)&prefetchItf); + result = (*player)->GetInterface(player, SL_IID_PREFETCHSTATUS, reinterpret_cast(&prefetchItf)); SL_RETURN_VAL_IF_FAILED(result, false, "GetInterface SL_IID_PREFETCHSTATUS failed"); /* Get the metadata extraction interface which was explicitly requested */ - result = (*player)->GetInterface(player, SL_IID_METADATAEXTRACTION, (void *)&mdExtrItf); + result = (*player)->GetInterface(player, SL_IID_METADATAEXTRACTION, reinterpret_cast(&mdExtrItf)); SL_RETURN_VAL_IF_FAILED(result, false, "GetInterface SL_IID_METADATAEXTRACTION failed"); /* ------------------------------------------------------ */ /* Initialize the callback and its context for the decoding buffer queue */ _decContext.playItf = playItf; _decContext.metaItf = mdExtrItf; - _decContext.pDataBase = (int8_t *)_pcmData; + _decContext.pDataBase = reinterpret_cast(_pcmData); _decContext.pData = _decContext.pDataBase; _decContext.size = NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES; @@ -331,8 +334,11 @@ bool AudioDecoderSLES::decodeToPcm() { // can make assumptions about the size of the keys and their matching values (all SLuint32) SLuint32 itemCount; result = (*mdExtrItf)->GetItemCount(mdExtrItf, &itemCount); - SLuint32 i, keySize, valueSize; - SLMetadataInfo *keyInfo, *value; + SLuint32 i; + SLuint32 keySize; + SLuint32 valueSize; + SLMetadataInfo *keyInfo; + SLMetadataInfo *value; for (i = 0; i < itemCount; i++) { keyInfo = nullptr; keySize = 0; @@ -344,7 +350,7 @@ bool AudioDecoderSLES::decodeToPcm() { result = (*mdExtrItf)->GetValueSize(mdExtrItf, i, &valueSize); SL_RETURN_VAL_IF_FAILED(result, false, "GetValueSize(%d) failed", (int)i); - keyInfo = (SLMetadataInfo *)malloc(keySize); + keyInfo = reinterpret_cast(malloc(keySize)); if (nullptr != keyInfo) { result = (*mdExtrItf)->GetKey(mdExtrItf, i, keySize, keyInfo); @@ -353,17 +359,17 @@ bool AudioDecoderSLES::decodeToPcm() { ALOGV("key[%d] size=%d, name=%s, value size=%d", (int)i, (int)keyInfo->size, keyInfo->data, (int)valueSize); /* find out the key index of the metadata we're interested in */ - if (!strcmp((char *)keyInfo->data, ANDROID_KEY_PCMFORMAT_NUMCHANNELS)) { + if (!strcmp(reinterpret_cast(keyInfo->data), ANDROID_KEY_PCMFORMAT_NUMCHANNELS)) { _numChannelsKeyIndex = i; - } else if (!strcmp((char *)keyInfo->data, ANDROID_KEY_PCMFORMAT_SAMPLERATE)) { + } else if (!strcmp(reinterpret_cast(keyInfo->data), ANDROID_KEY_PCMFORMAT_SAMPLERATE)) { _sampleRateKeyIndex = i; - } else if (!strcmp((char *)keyInfo->data, ANDROID_KEY_PCMFORMAT_BITSPERSAMPLE)) { + } else if (!strcmp(reinterpret_cast(keyInfo->data), ANDROID_KEY_PCMFORMAT_BITSPERSAMPLE)) { _bitsPerSampleKeyIndex = i; - } else if (!strcmp((char *)keyInfo->data, ANDROID_KEY_PCMFORMAT_CONTAINERSIZE)) { + } else if (!strcmp(reinterpret_cast(keyInfo->data), ANDROID_KEY_PCMFORMAT_CONTAINERSIZE)) { _containerSizeKeyIndex = i; - } else if (!strcmp((char *)keyInfo->data, ANDROID_KEY_PCMFORMAT_CHANNELMASK)) { + } else if (!strcmp(reinterpret_cast(keyInfo->data), ANDROID_KEY_PCMFORMAT_CHANNELMASK)) { _channelMaskKeyIndex = i; - } else if (!strcmp((char *)keyInfo->data, ANDROID_KEY_PCMFORMAT_ENDIANNESS)) { + } else if (!strcmp(reinterpret_cast(keyInfo->data), ANDROID_KEY_PCMFORMAT_ENDIANNESS)) { _endiannessKeyIndex = i; } free(keyInfo); @@ -411,10 +417,11 @@ bool AudioDecoderSLES::decodeToPcm() { ALOGV("After destroy player ..."); _result.numFrames = - _result.pcmBuffer->size() / _result.numChannels / (_result.bitsPerSample / 8); + static_cast(_result.pcmBuffer->size() / _result.numChannels / (_result.bitsPerSample / 8)); ccstd::string info = _result.toString(); ALOGI("Original audio info: %s, total size: %d", info.c_str(), (int)_result.pcmBuffer->size()); +#endif return true; } @@ -440,7 +447,7 @@ void AudioDecoderSLES::queryAudioInfo() { ALOGV("Content duration is unknown (in dec callback)"); } else { ALOGV("Content duration is %dms (in dec callback)", (int)durationInMsec); - _result.duration = durationInMsec / 1000.0f; + _result.duration = durationInMsec / 1000.0F; } /* used to query metadata values */ @@ -454,27 +461,27 @@ void AudioDecoderSLES::queryAudioInfo() { // pcmMetaData->size == sizeof(SLuint32) // but the call was successful for the PCM format keys, so those conditions are implied - _result.sampleRate = *((SLuint32 *)pcmMetaData.data); + _result.sampleRate = *reinterpret_cast(pcmMetaData.data); result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _numChannelsKeyIndex, PCM_METADATA_VALUE_SIZE, &pcmMetaData); SL_RETURN_IF_FAILED(result, "%s GetValue _numChannelsKeyIndex failed", __FUNCTION__); - _result.numChannels = *((SLuint32 *)pcmMetaData.data); + _result.numChannels = *reinterpret_cast(pcmMetaData.data); result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _bitsPerSampleKeyIndex, PCM_METADATA_VALUE_SIZE, &pcmMetaData); SL_RETURN_IF_FAILED(result, "%s GetValue _bitsPerSampleKeyIndex failed", __FUNCTION__) - _result.bitsPerSample = *((SLuint32 *)pcmMetaData.data); + _result.bitsPerSample = *reinterpret_cast(pcmMetaData.data); result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _containerSizeKeyIndex, PCM_METADATA_VALUE_SIZE, &pcmMetaData); SL_RETURN_IF_FAILED(result, "%s GetValue _containerSizeKeyIndex failed", __FUNCTION__) - _result.containerSize = *((SLuint32 *)pcmMetaData.data); + _result.containerSize = *reinterpret_cast(pcmMetaData.data); result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _channelMaskKeyIndex, PCM_METADATA_VALUE_SIZE, &pcmMetaData); SL_RETURN_IF_FAILED(result, "%s GetValue _channelMaskKeyIndex failed", __FUNCTION__) - _result.channelMask = *((SLuint32 *)pcmMetaData.data); + _result.channelMask = *reinterpret_cast(pcmMetaData.data); result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _endiannessKeyIndex, PCM_METADATA_VALUE_SIZE, &pcmMetaData); SL_RETURN_IF_FAILED(result, "%s GetValue _endiannessKeyIndex failed", __FUNCTION__) - _result.endianness = *((SLuint32 *)pcmMetaData.data); + _result.endianness = *reinterpret_cast(pcmMetaData.data); _formatQueried = true; } @@ -500,6 +507,7 @@ void AudioDecoderSLES::prefetchCallback(SLPrefetchStatusItf caller, SLuint32 eve /* Callback for "playback" events, i.e. event happening during decoding */ void AudioDecoderSLES::decodeProgressCallback(SLPlayItf caller, SLuint32 event) { + CC_UNUSED_PARAM(caller); if (SL_PLAYEVENT_HEADATEND & event) { ALOGV("SL_PLAYEVENT_HEADATEND"); if (!_isDecodingCallbackInvoked) { @@ -519,7 +527,7 @@ void AudioDecoderSLES::decodeProgressCallback(SLPlayItf caller, SLuint32 event) //----------------------------------------------------------------- /* Callback for decoding buffer queue events */ -void AudioDecoderSLES::decodeToPcmCallback(SLAndroidSimpleBufferQueueItf queueItf) { +void AudioDecoderSLES::decodeToPcmCallback(CCSLBufferQueueItf queueItf) { _isDecodingCallbackInvoked = true; ALOGV("%s ...", __FUNCTION__); _counter++; diff --git a/native/cocos/audio/android/AudioDecoderSLES.h b/native/cocos/audio/android/AudioDecoderSLES.h index bbc520c872..2f9cdc3bdc 100644 --- a/native/cocos/audio/android/AudioDecoderSLES.h +++ b/native/cocos/audio/android/AudioDecoderSLES.h @@ -28,22 +28,23 @@ #include #include #include "audio/android/AudioDecoder.h" +#include "audio/android/utils/Compat.h" namespace cc { class AudioDecoderSLES : public AudioDecoder { protected: AudioDecoderSLES(); - virtual ~AudioDecoderSLES(); + ~AudioDecoderSLES() override; bool init(SLEngineItf engineItf, const ccstd::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback); - virtual bool decodeToPcm() override; + bool decodeToPcm() override; private: void queryAudioInfo(); void signalEos(); - void decodeToPcmCallback(SLAndroidSimpleBufferQueueItf queueItf); + void decodeToPcmCallback(CCSLBufferQueueItf queueItf); void prefetchCallback(SLPrefetchStatusItf caller, SLuint32 event); void decodeProgressCallback(SLPlayItf caller, SLuint32 event); @@ -74,7 +75,7 @@ private: std::condition_variable _eosCondition; /* Structure for passing information to callback function */ - typedef struct CallbackCntxt_ { + typedef struct CallbackCntxt_ { //NOLINT(modernize-use-using, readability-identifier-naming) SLPlayItf playItf; SLMetadataExtractionItf metaItf; SLuint32 size; diff --git a/native/cocos/audio/android/AudioEngine-inl.cpp b/native/cocos/audio/android/AudioEngine-inl.cpp index c8edb66a8a..77e5a908a6 100644 --- a/native/cocos/audio/android/AudioEngine-inl.cpp +++ b/native/cocos/audio/android/AudioEngine-inl.cpp @@ -28,9 +28,12 @@ #include // for native asset manager +#if CC_PLATFORM == CC_PLATFORM_ANDROID #include #include #include +#endif + #include #include #include @@ -41,9 +44,13 @@ #include "base/Scheduler.h" #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" +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY +#include "cocos/platform/openharmony/FileUtils-OpenHarmony.h" +#endif #include "audio/android/AudioDecoder.h" #include "audio/android/AudioDecoderProvider.h" @@ -60,15 +67,26 @@ using namespace cc; //NOLINT namespace { AudioEngineImpl *gAudioImpl = nullptr; int outputSampleRate = 44100; -int bufferSizeInFrames = 192; +#if CC_PLATFORM == CC_PLATFORM_ANDROID +int bufferSizeInFrames = 192; +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY +// TODO(hack) : There is currently a bug in the opensles module, +// so openharmony must configure a fixed size, otherwise the callback will be suspended +int bufferSizeInFrames = 2048; +#endif void getAudioInfo() { - 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); +#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); +#else + // In openharmony, setting to 48K does not cause audio delays + outputSampleRate = 48000; +#endif } } // namespace @@ -94,6 +112,7 @@ static CallerThreadUtils gCallerThreadUtils; static int fdGetter(const ccstd::string &url, off_t *start, off_t *length) { int fd = -1; +#if CC_PLATFORM == CC_PLATFORM_ANDROID if (cc::FileUtilsAndroid::getObbFile() != nullptr) { int64_t startV; int64_t lenV; @@ -107,7 +126,14 @@ static int fdGetter(const ccstd::string &url, off_t *start, off_t *length) { fd = AAsset_openFileDescriptor(asset, start, length); AAsset_close(asset); } - +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + FileUtilsOpenHarmony* fileUtils = dynamic_cast(FileUtils::getInstance()); + if(fileUtils) { + RawFileDescriptor descriptor; + fileUtils->getRawFileDescriptor(url, descriptor); + fd = descriptor.fd; + } +#endif if (fd <= 0) { ALOGE("Failed to open file descriptor for '%s'", url.c_str()); } diff --git a/native/cocos/audio/android/AudioEngine-inl.h b/native/cocos/audio/android/AudioEngine-inl.h index 99fcd8943e..1af9ca63c0 100644 --- a/native/cocos/audio/android/AudioEngine-inl.h +++ b/native/cocos/audio/android/AudioEngine-inl.h @@ -25,7 +25,11 @@ #pragma once #include +#if CC_PLATFORM == CC_PLATFORM_ANDROID #include +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY +#include +#endif #include #include "audio/include/AudioDef.h" #include "base/RefCounted.h" diff --git a/native/cocos/audio/android/AudioMixer.h b/native/cocos/audio/android/AudioMixer.h index 076467de69..729c1db2ef 100644 --- a/native/cocos/audio/android/AudioMixer.h +++ b/native/cocos/audio/android/AudioMixer.h @@ -17,7 +17,7 @@ #pragma once -#include +#include #include #include @@ -26,6 +26,7 @@ #include "audio/android/AudioResampler.h" #include "audio/android/audio.h" +#include "audio/android/utils/Compat.h" // IDEA: This is actually unity gain, which might not be max in future, expressed in U.12 #define MAX_GAIN_INT AudioMixer::UNITY_GAIN_INT @@ -53,7 +54,7 @@ public: static const uint32_t MAX_NUM_CHANNELS_TO_DOWNMIX = AUDIO_CHANNEL_COUNT_MAX; static const uint16_t UNITY_GAIN_INT = 0x1000; - static const CONSTEXPR float UNITY_GAIN_FLOAT = 1.0f; + static const CONSTEXPR float UNITY_GAIN_FLOAT = 1.0F; enum { // names @@ -140,7 +141,7 @@ public: private: enum { // IDEA: this representation permits up to 8 channels - NEEDS_CHANNEL_COUNT__MASK = 0x00000007, + NEEDS_CHANNEL_COUNT__MASK = 0x00000007, // NOLINT(bugprone-reserved-identifier) }; enum { @@ -157,8 +158,7 @@ private: struct state_t; struct track_t; - typedef void (*hook_t)(track_t *t, int32_t *output, size_t numOutFrames, int32_t *temp, - int32_t *aux); + 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 struct track_t { @@ -255,12 +255,12 @@ private: bool needsRamp() { return (volumeInc[0] | volumeInc[1] | auxInc) != 0; } bool setResampler(uint32_t trackSampleRate, uint32_t devSampleRate); - bool doesResample() const { return resampler != NULL; } - void resetResampler() { - if (resampler != NULL) resampler->reset(); + bool doesResample() const { return resampler != nullptr; } + void resetResampler() const { + if (resampler != nullptr) resampler->reset(); } void adjustVolumeRamp(bool aux, bool useFloat = false); - size_t getUnreleasedFrames() const { return resampler != NULL ? resampler->getUnreleasedFrames() : 0; }; + size_t getUnreleasedFrames() const { return resampler != nullptr ? resampler->getUnreleasedFrames() : 0; }; status_t prepareForDownmix(); void unprepareForDownmix(); @@ -270,7 +270,7 @@ private: void reconfigureBufferProviders(); }; - typedef void (*process_hook_t)(state_t *state, int64_t pts); + typedef void (*process_hook_t)(state_t *state, int64_t pts); // NOLINT(modernize-use-using) // pad to 32-bytes to fill cache line struct state_t { @@ -287,19 +287,19 @@ private: }; // bitmask of allocated track names, where bit 0 corresponds to TRACK0 etc. - uint32_t mTrackNames; + 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; + const uint32_t mConfiguredNames;// NOLINT(readability-identifier-naming) - const uint32_t mSampleRate; + 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))); + 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. @@ -308,24 +308,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); - static void track__nop(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux); - static void track__16BitsStereo(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, - int32_t *aux); - static void track__16BitsMono(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, - int32_t *aux); - static void volumeRampStereo(track_t *t, int32_t *out, size_t frameCount, int32_t *temp, - int32_t *aux); + 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); - static void process__nop(state_t *state, int64_t pts); - static void process__genericNoResampling(state_t *state, int64_t pts); - static void process__genericResampling(state_t *state, int64_t pts); - static void process__OneTrack16BitsStereoNoResampling(state_t *state, - int64_t pts); + 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); @@ -351,15 +346,13 @@ private: // multi-format process hooks template - static void process_NoResampleOneTrack(state_t *state, int64_t pts); + static void process_NoResampleOneTrack(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming) // multi-format track hooks template - static void track__Resample(track_t *t, TO *out, size_t frameCount, - TO *temp __unused, TA *aux); + 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 - static void track__NoResample(track_t *t, TO *out, size_t frameCount, - TO *temp __unused, TA *aux); + static void track__NoResample(track_t *t, TO *out, size_t frameCount, TO *temp __unused, TA *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming) static void convertMixerFormat(void *out, audio_format_t mixerOutFormat, void *in, audio_format_t mixerInFormat, size_t sampleCount); diff --git a/native/cocos/audio/android/AudioPlayerProvider.cpp b/native/cocos/audio/android/AudioPlayerProvider.cpp index 9df58e00b3..7817bfde3b 100644 --- a/native/cocos/audio/android/AudioPlayerProvider.cpp +++ b/native/cocos/audio/android/AudioPlayerProvider.cpp @@ -29,7 +29,6 @@ #include "base/Log.h" #define LOG_TAG "AudioPlayerProvider" -#include #include // for std::find_if #include #include @@ -44,11 +43,21 @@ #include "audio/android/utils/Utils.h" #include "base/ThreadPool.h" #include "base/memory/Memory.h" +#if CC_PLATFORM == CC_PLATFORM_ANDROID +#include +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY +#include "cocos/platform/FileUtils.h" +#include "cocos/platform/openharmony/FileUtils-OpenHarmony.h" +#endif +#include // for std::find_if +#include +#include namespace cc { static int getSystemAPILevel() { static int sSystemApiLevel = -1; +#if CC_PLATFORM == CC_PLATFORM_ANDROID if (sSystemApiLevel > 0) { return sSystemApiLevel; } @@ -61,6 +70,10 @@ static int getSystemAPILevel() { } sSystemApiLevel = apiLevel; return apiLevel; +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + // TODO(qgh): On the openharmony platform, pcm streaming must be used + return std::numeric_limits::max(); +#endif } struct AudioFileIndicator { @@ -311,7 +324,7 @@ AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo( off_t start = 0; off_t length = 0; int assetFd = -1; - +#if CC_PLATFORM == CC_PLATFORM_ANDROID if (audioFilePath[0] != '/') { ccstd::string relativePath; size_t position = audioFilePath.find("@assets/"); @@ -341,11 +354,23 @@ AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo( return info; } } - info.url = audioFilePath; info.assetFd = std::make_shared(assetFd); info.start = start; info.length = fileSize; +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + FileUtilsOpenHarmony* fileUtils = dynamic_cast(FileUtils::getInstance()); + if(!fileUtils) { + return info; + } + + RawFileDescriptor descriptor; + fileUtils->getRawFileDescriptor(audioFilePath, descriptor); + info.url = audioFilePath; + info.assetFd = std::make_shared(descriptor.fd); + info.start = descriptor.start; + info.length = descriptor.length; +#endif ALOGV("(%s) file size: %ld", audioFilePath.c_str(), fileSize); @@ -353,6 +378,10 @@ AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo( } bool AudioPlayerProvider::isSmallFile(const AudioFileInfo &info) { //NOLINT(readability-convert-member-functions-to-static) +#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY + // TODO(qgh): OpenHarmony system does not support this function yet + return true; +#endif //REFINE: If file size is smaller than 100k, we think it's a small file. This value should be set by developers. auto &audioFileInfo = const_cast(info); size_t judgeCount = sizeof(gAudioFileIndicator) / sizeof(gAudioFileIndicator[0]); @@ -362,9 +391,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()); @@ -420,10 +449,14 @@ UrlAudioPlayer *AudioPlayerProvider::createUrlAudioPlayer( ALOGE("createUrlAudioPlayer failed, url is empty!"); return nullptr; } - +#if CC_PLATFORM == CC_PLATFORM_ANDROID SLuint32 locatorType = info.assetFd->getFd() > 0 ? SL_DATALOCATOR_ANDROIDFD : SL_DATALOCATOR_URI; - auto *urlPlayer = ccnew UrlAudioPlayer(_engineItf, _outputMixObject, _callerThreadUtils); - bool ret = urlPlayer->prepare(info.url, locatorType, info.assetFd, info.start, info.length); +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + SLuint32 locatorType = SL_DATALOCATOR_URI; +#endif + + 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); } diff --git a/native/cocos/audio/android/AudioResampler.h b/native/cocos/audio/android/AudioResampler.h index 171846f7c0..9fdf9c2334 100644 --- a/native/cocos/audio/android/AudioResampler.h +++ b/native/cocos/audio/android/AudioResampler.h @@ -16,10 +16,12 @@ #pragma once +#include +#if CC_PLATFORM == CC_PLATFORM_ANDROID #include -#include #include #include +#endif #include "audio/android/AudioBufferProvider.h" @@ -28,7 +30,7 @@ //#include //#include -#include +#include #include "audio/android/audio.h" namespace cc { @@ -42,7 +44,7 @@ public: // NOTE: high quality SRC will only be supported for // certain fixed rate conversions. Sample rate cannot be // changed dynamically. - enum src_quality { + enum src_quality { // NOLINT(readability-identifier-naming) DEFAULT_QUALITY = 0, LOW_QUALITY = 1, MED_QUALITY = 2, @@ -50,7 +52,7 @@ public: VERY_HIGH_QUALITY = 4, }; - static const CONSTEXPR float UNITY_GAIN_FLOAT = 1.0f; + static const CONSTEXPR float UNITY_GAIN_FLOAT = 1.0F; static AudioResampler *create(audio_format_t format, int inChannelCount, int32_t sampleRate, src_quality quality = DEFAULT_QUALITY); @@ -90,13 +92,13 @@ public: protected: // number of bits for phase fraction - 30 bits allows nearly 2x downsampling - static const int kNumPhaseBits = 30; + static const int kNumPhaseBits = 30; // NOLINT(readability-identifier-naming) // phase mask for fraction - static const uint32_t kPhaseMask = (1LU << kNumPhaseBits) - 1; + static const uint32_t kPhaseMask = (1LU << kNumPhaseBits) - 1; // NOLINT(readability-identifier-naming) // multiplier to calculate fixed point phase increment - static const double kPhaseMultiplier; + static const double kPhaseMultiplier; // NOLINT(readability-identifier-naming) AudioResampler(int inChannelCount, int32_t sampleRate, src_quality quality); @@ -106,20 +108,21 @@ protected: int64_t calculateOutputPTS(int outputFrameIndex); - const int32_t mChannelCount; - const int32_t mSampleRate; - int32_t mInSampleRate; - AudioBufferProvider::Buffer mBuffer; + + 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]; - uint32_t mVolumeRL; + int16_t mVolume[2];// NOLINT(readability-identifier-naming) + uint32_t mVolumeRL;// NOLINT(readability-identifier-naming) }; - int16_t mTargetVolume[2]; - size_t mInputIndex; - int32_t mPhaseIncrement; - uint32_t mPhaseFraction; - uint64_t mLocalTimeFreq; - int64_t mPTS; + 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. // @@ -148,32 +151,32 @@ protected: // inFrameCount = (mPhaseIncrement * (outFrameCount - 1) + mPhaseFraction) / phaseWrapLimit; // phaseWrapLimit is the wraparound (1 << kNumPhaseBits), if not specified explicitly. // - inline size_t getInFrameCountRequired(size_t outFrameCount) { + inline size_t getInFrameCountRequired(size_t outFrameCount) const { return (static_cast(outFrameCount) * mInSampleRate + (mSampleRate - 1)) / mSampleRate; } - inline float clampFloatVol(float volume) { + inline float clampFloatVol(float volume) {//NOLINT(readability-identifier-naming, readability-convert-member-functions-to-static) + float ret = 0.0F; if (volume > UNITY_GAIN_FLOAT) { - return UNITY_GAIN_FLOAT; + ret = UNITY_GAIN_FLOAT; } else if (volume >= 0.) { - return volume; + ret = volume; } - return 0.; // NaN or negative volume maps to 0. + return ret; // NaN or negative volume maps to 0. } private: - const src_quality mQuality; + 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); // For pthread_once() - static void init_routine(); + static void init_routine(); // NOLINT(readability-identifier-naming) // Return the estimated CPU load for specific resampler in MHz. // The absolute number is irrelevant, it's the relative values that matter. static uint32_t qualityMHz(src_quality quality); }; - // ---------------------------------------------------------------------------- } // namespace cc diff --git a/native/cocos/audio/android/OpenSLHelper.h b/native/cocos/audio/android/OpenSLHelper.h index bc5af78424..d1621d5f3a 100644 --- a/native/cocos/audio/android/OpenSLHelper.h +++ b/native/cocos/audio/android/OpenSLHelper.h @@ -28,7 +28,12 @@ #include "audio/android/cutils/log.h" #include +#if CC_PLATFORM == CC_PLATFORM_ANDROID #include +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY +#include +#endif + #include #include "base/std/container/string.h" diff --git a/native/cocos/audio/android/PcmAudioService.cpp b/native/cocos/audio/android/PcmAudioService.cpp index da5d63f786..4989d0a92e 100644 --- a/native/cocos/audio/android/PcmAudioService.cpp +++ b/native/cocos/audio/android/PcmAudioService.cpp @@ -25,19 +25,25 @@ #define LOG_TAG "PcmAudioService" +#include "base/Macros.h" #include "audio/android/PcmAudioService.h" #include "audio/android/AudioMixerController.h" +#include "audio/android/utils/Compat.h" namespace cc { -static ccstd::vector __silenceData; +static ccstd::vector __silenceData;//NOLINT(bugprone-reserved-identifier, readability-identifier-naming) #define AUDIO_PLAYER_BUFFER_COUNT (2) class SLPcmAudioPlayerCallbackProxy { public: - static void samplePlayerCallback(SLAndroidSimpleBufferQueueItf bq, void *context) { - PcmAudioService *thiz = reinterpret_cast(context); +#if CC_PLATFORM == CC_PLATFORM_ANDROID + 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(context); thiz->bqFetchBufferCallback(bq); } }; @@ -53,6 +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 (_controller->hasPlayingTacks()) { if (_controller->isPaused()) { SLresult r = (*_bufferQueueItf)->Enqueue(_bufferQueueItf, __silenceData.data(), __silenceData.size()); @@ -60,7 +72,7 @@ bool PcmAudioService::enqueue() { } else { _controller->mixOneFrame(); - auto current = _controller->current(); + auto *current = _controller->current(); ALOG_ASSERT(current != nullptr, "current buffer is nullptr ..."); SLresult r = (*_bufferQueueItf)->Enqueue(_bufferQueueItf, current->buf, current->size); SL_RETURN_VAL_IF_FAILED(r, false, "enqueue failed!"); @@ -73,7 +85,8 @@ bool PcmAudioService::enqueue() { return true; } -void PcmAudioService::bqFetchBufferCallback(SLAndroidSimpleBufferQueueItf bq) { +void PcmAudioService::bqFetchBufferCallback(CCSLBufferQueueItf bq) { + CC_UNUSED_PARAM(bq); // IDEA: PcmAudioService instance may be destroyed, we need to find a way to wait... // It's in sub thread enqueue(); @@ -93,16 +106,20 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in SLDataFormat_PCM formatPcm = { SL_DATAFORMAT_PCM, - (SLuint32)numChannels, - (SLuint32)sampleRate * 1000, + static_cast(numChannels), + static_cast(sampleRate * 1000), SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16, channelMask, SL_BYTEORDER_LITTLEENDIAN}; +#if CC_PLATFORM == CC_PLATFORM_ANDROID SLDataLocator_AndroidSimpleBufferQueue locBufQueue = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, AUDIO_PLAYER_BUFFER_COUNT}; +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + SLDataLocator_BufferQueue locBufQueue = {SL_DATALOCATOR_BUFFERQUEUE, AUDIO_PLAYER_BUFFER_COUNT}; +#endif SLDataSource source = {&locBufQueue, &formatPcm}; SLDataLocator_OutputMix locOutmix = { @@ -113,7 +130,7 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in const SLInterfaceID ids[] = { SL_IID_PLAY, SL_IID_VOLUME, - SL_IID_ANDROIDSIMPLEBUFFERQUEUE, + CC_SL_IDD_BUFFER_QUEUE, }; const SLboolean req[] = { @@ -124,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); + 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); @@ -136,8 +153,8 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in r = (*_playObj)->GetInterface(_playObj, SL_IID_VOLUME, &_volumeItf); SL_RETURN_VAL_IF_FAILED(r, false, "GetInterface SL_IID_VOLUME failed"); - r = (*_playObj)->GetInterface(_playObj, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &_bufferQueueItf); - SL_RETURN_VAL_IF_FAILED(r, false, "GetInterface SL_IID_ANDROIDSIMPLEBUFFERQUEUE failed"); + r = (*_playObj)->GetInterface(_playObj, CC_SL_IDD_BUFFER_QUEUE, &_bufferQueueItf); + SL_RETURN_VAL_IF_FAILED(r, false, "GetInterface CC_SL_IDD_BUFFER_QUEUE failed"); r = (*_bufferQueueItf)->RegisterCallback(_bufferQueueItf, SLPcmAudioPlayerCallbackProxy::samplePlayerCallback, this); SL_RETURN_VAL_IF_FAILED(r, false, "_bufferQueueItf RegisterCallback failed"); @@ -145,7 +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 r = (*_bufferQueueItf)->Enqueue(_bufferQueueItf, __silenceData.data(), __silenceData.size()); SL_RETURN_VAL_IF_FAILED(r, false, "_bufferQueueItf Enqueue failed"); diff --git a/native/cocos/audio/android/PcmAudioService.h b/native/cocos/audio/android/PcmAudioService.h index 90a8a8e650..1fe69e44d9 100644 --- a/native/cocos/audio/android/PcmAudioService.h +++ b/native/cocos/audio/android/PcmAudioService.h @@ -31,6 +31,7 @@ #include #include +#include "audio/android/utils/Compat.h" namespace cc { @@ -51,19 +52,18 @@ private: bool enqueue(); - void bqFetchBufferCallback(SLAndroidSimpleBufferQueueItf bq); + void bqFetchBufferCallback(CCSLBufferQueueItf bq); void pause(); void resume(); -private: SLEngineItf _engineItf; SLObjectItf _outputMixObj; SLObjectItf _playObj; SLPlayItf _playItf; SLVolumeItf _volumeItf; - SLAndroidSimpleBufferQueueItf _bufferQueueItf; + CCSLBufferQueueItf _bufferQueueItf; int _numChannels; int _sampleRate; diff --git a/native/cocos/audio/android/UrlAudioPlayer.cpp b/native/cocos/audio/android/UrlAudioPlayer.cpp index 002f336168..881f49bd53 100644 --- a/native/cocos/audio/android/UrlAudioPlayer.cpp +++ b/native/cocos/audio/android/UrlAudioPlayer.cpp @@ -28,15 +28,15 @@ #include "audio/android/UrlAudioPlayer.h" #include "audio/android/ICallerThreadUtils.h" #include "base/std/container/vector.h" - -#include +#include "base/Macros.h" +#include #include // for std::find namespace { -std::mutex __playerContainerMutex; -ccstd::vector __playerContainer; -std::once_flag __onceFlag; +std::mutex __playerContainerMutex;//NOLINT(bugprone-reserved-identifier,readability-identifier-naming) +ccstd::vector __playerContainer;//NOLINT(bugprone-reserved-identifier,readability-identifier-naming) +std::once_flag __onceFlag;//NOLINT(bugprone-reserved-identifier,readability-identifier-naming) } // namespace @@ -45,7 +45,7 @@ namespace cc { class SLUrlAudioPlayerCallbackProxy { public: static void playEventCallback(SLPlayItf caller, void *context, SLuint32 playEvent) { - UrlAudioPlayer *thiz = (UrlAudioPlayer *)context; + auto *thiz = reinterpret_cast(context); // We must use a mutex for the whole block of the following function invocation. std::lock_guard lk(__playerContainerMutex); auto iter = std::find(__playerContainer.begin(), __playerContainer.end(), thiz); @@ -56,7 +56,7 @@ public: }; UrlAudioPlayer::UrlAudioPlayer(SLEngineItf engineItf, SLObjectItf outputMixObject, ICallerThreadUtils *callerThreadUtils) -: _engineItf(engineItf), _outputMixObj(outputMixObject), _callerThreadUtils(callerThreadUtils), _id(-1), _assetFd(nullptr), _playObj(nullptr), _playItf(nullptr), _seekItf(nullptr), _volumeItf(nullptr), _volume(0.0f), _duration(0.0f), _isLoop(false), _isAudioFocus(true), _state(State::INVALID), _playEventCallback(nullptr), _isDestroyed(std::make_shared(false)) { +: _engineItf(engineItf), _outputMixObj(outputMixObject), _callerThreadUtils(callerThreadUtils), _id(-1), _assetFd(nullptr), _playObj(nullptr), _playItf(nullptr), _seekItf(nullptr), _volumeItf(nullptr), _volume(0.0F), _duration(0.0F), _isLoop(false), _isAudioFocus(true), _state(State::INVALID), _playEventCallback(nullptr), _isDestroyed(std::make_shared(false)) { std::call_once(__onceFlag, []() { __playerContainer.reserve(10); }); @@ -83,6 +83,7 @@ UrlAudioPlayer::~UrlAudioPlayer() { } void UrlAudioPlayer::playEventCallback(SLPlayItf caller, SLuint32 playEvent) { + CC_UNUSED_PARAM(caller); // Note that it's on sub thread, please don't invoke OpenSLES API on sub thread if (playEvent == SL_PLAYEVENT_HEADATEND) { std::shared_ptr isDestroyed = _isDestroyed; @@ -179,7 +180,7 @@ void UrlAudioPlayer::play() { } void UrlAudioPlayer::setVolumeToSLPlayer(float volume) { - int dbVolume = 2000 * log10(volume); + int dbVolume = static_cast(2000 * log10(volume)); if (dbVolume < SL_MILLIBEL_MIN) { dbVolume = SL_MILLIBEL_MIN; } @@ -200,7 +201,7 @@ float UrlAudioPlayer::getVolume() const { void UrlAudioPlayer::setAudioFocus(bool isFocus) { _isAudioFocus = isFocus; - float volume = _isAudioFocus ? _volume : 0.0f; + float volume = _isAudioFocus ? _volume : 0.0F; setVolumeToSLPlayer(volume); } @@ -211,15 +212,15 @@ float UrlAudioPlayer::getDuration() const { SLmillisecond duration; SLresult r = (*_playItf)->GetDuration(_playItf, &duration); - SL_RETURN_VAL_IF_FAILED(r, 0.0f, "UrlAudioPlayer::getDuration failed"); + SL_RETURN_VAL_IF_FAILED(r, 0.0F, "UrlAudioPlayer::getDuration failed"); if (duration == SL_TIME_UNKNOWN) { - return -1.0f; - } else { - const_cast(this)->_duration = duration / 1000.0f; + return -1.0F; + } else {// NOLINT(readability-else-after-return) + const_cast(this)->_duration = duration / 1000.0F; if (_duration <= 0) { - return -1.0f; + return -1.0F; } } return _duration; @@ -228,12 +229,12 @@ float UrlAudioPlayer::getDuration() const { float UrlAudioPlayer::getPosition() const { SLmillisecond millisecond; SLresult r = (*_playItf)->GetPosition(_playItf, &millisecond); - SL_RETURN_VAL_IF_FAILED(r, 0.0f, "UrlAudioPlayer::getPosition failed"); - return millisecond / 1000.0f; + SL_RETURN_VAL_IF_FAILED(r, 0.0F, "UrlAudioPlayer::getPosition failed"); + return millisecond / 1000.0F; } bool UrlAudioPlayer::setPosition(float pos) { - SLmillisecond millisecond = 1000.0f * pos; + SLmillisecond millisecond = 1000.0F * pos; SLresult r = (*_seekItf)->SetPosition(_seekItf, millisecond, SL_SEEKMODE_ACCURATE); SL_RETURN_VAL_IF_FAILED(r, false, "UrlAudioPlayer::setPosition %f failed", pos); return true; @@ -242,14 +243,14 @@ bool UrlAudioPlayer::setPosition(float pos) { bool UrlAudioPlayer::prepare(const ccstd::string &url, SLuint32 locatorType, std::shared_ptr assetFd, int start, int length) { _url = url; - _assetFd = assetFd; - + _assetFd = std::move(assetFd); +#if CC_PLATFORM == CC_PLATFORM_ANDROID const char *locatorTypeStr = "UNKNOWN"; - if (locatorType == SL_DATALOCATOR_ANDROIDFD) + if (locatorType == SL_DATALOCATOR_ANDROIDFD) { locatorTypeStr = "SL_DATALOCATOR_ANDROIDFD"; - else if (locatorType == SL_DATALOCATOR_URI) + } else if (locatorType == SL_DATALOCATOR_URI) { locatorTypeStr = "SL_DATALOCATOR_URI"; - else { + } else { ALOGE("Oops, invalid locatorType: %d", (int)locatorType); return false; } @@ -274,7 +275,7 @@ bool UrlAudioPlayer::prepare(const ccstd::string &url, SLuint32 locatorType, std locFd = {locatorType, _assetFd->getFd(), start, length}; audioSrc.pLocator = &locFd; } else if (locatorType == SL_DATALOCATOR_URI) { - locUri = {locatorType, (SLchar *)_url.c_str()}; + locUri = {locatorType, (SLchar *)_url.c_str()}; // NOLINT(google-readability-casting) audioSrc.pLocator = &locUri; ALOGV("locUri: locatorType: %d", (int)locUri.locatorType); } @@ -315,8 +316,8 @@ bool UrlAudioPlayer::prepare(const ccstd::string &url, SLuint32 locatorType, std setState(State::INITIALIZED); - setVolume(1.0f); - + setVolume(1.0F); +#endif return true; } diff --git a/native/cocos/audio/android/audio.h b/native/cocos/audio/android/audio.h index c790eca215..36d55573a7 100644 --- a/native/cocos/audio/android/audio.h +++ b/native/cocos/audio/android/audio.h @@ -27,7 +27,6 @@ // ---------------------------------------------------------------------------- -#include #include #include "audio/android/cutils/bitops.h" diff --git a/native/cocos/audio/android/cutils/bitops.h b/native/cocos/audio/android/cutils/bitops.h index 0c12575668..215872f6ea 100644 --- a/native/cocos/audio/android/cutils/bitops.h +++ b/native/cocos/audio/android/cutils/bitops.h @@ -20,9 +20,14 @@ #include #include #include -#include -__BEGIN_DECLS +#if CC_PLATFORM == CC_PLATFORM_ANDROID +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif static inline int popcount(unsigned int x) { return __builtin_popcount(x); @@ -36,6 +41,8 @@ static inline int popcountll(unsigned long long x) { return __builtin_popcountll(x); } -__END_DECLS +#ifdef __cplusplus +} +#endif #endif /* COCOS_CUTILS_BITOPS_H */ diff --git a/native/cocos/audio/android/cutils/log.h b/native/cocos/audio/android/cutils/log.h index c7c5e5386d..22eacb3bd1 100644 --- a/native/cocos/audio/android/cutils/log.h +++ b/native/cocos/audio/android/cutils/log.h @@ -33,7 +33,12 @@ #include #include #include +#if CC_PLATFORM == CC_PLATFORM_ANDROID #include +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY +// TODO(qgh):May be implemented in later versions +// #include +#endif #ifdef __cplusplus extern "C" { @@ -404,15 +409,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, ...) +#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(...) +#endif #endif /* @@ -467,8 +480,12 @@ extern "C" { * 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)0) +#endif #endif /* diff --git a/native/cocos/audio/android/utils/Compat.h b/native/cocos/audio/android/utils/Compat.h index 7c70936c0b..6ccae6a834 100644 --- a/native/cocos/audio/android/utils/Compat.h +++ b/native/cocos/audio/android/utils/Compat.h @@ -17,7 +17,17 @@ #ifndef COCOS_LIB_UTILS_COMPAT_H #define COCOS_LIB_UTILS_COMPAT_H + +#if CC_PLATFORM == CC_PLATFORM_ANDROID #include +#include +#include +#elif CC_PLATFORM == CC_PLATFORM_WINDOWS + +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY +#include +#include +#endif #if defined(__APPLE__) @@ -85,4 +95,13 @@ static inline ssize_t pwrite64(int fd, const void *buf, size_t nbytes, off64_t o #define OS_PATH_SEPARATOR '/' #endif +#if CC_PLATFORM == CC_PLATFORM_ANDROID +typedef SLAndroidSimpleBufferQueueItf CCSLBufferQueueItf; +#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 +#endif + #endif /* COCOS_LIB_UTILS_COMPAT_H */ diff --git a/native/cocos/audio/android/utils/Utils.cpp b/native/cocos/audio/android/utils/Utils.cpp index 378ecc400a..367048be96 100644 --- a/native/cocos/audio/android/utils/Utils.cpp +++ b/native/cocos/audio/android/utils/Utils.cpp @@ -23,7 +23,6 @@ THE SOFTWARE. ****************************************************************************/ #include "audio/android/utils/Utils.h" -#include #include "platform/BasePlatform.h" namespace cc { diff --git a/native/cocos/audio/common/utils/include/format.h b/native/cocos/audio/common/utils/include/format.h index 4756d551d9..854c16033e 100644 --- a/native/cocos/audio/common/utils/include/format.h +++ b/native/cocos/audio/common/utils/include/format.h @@ -18,7 +18,9 @@ #define COCOS_AUDIO_FORMAT_H #include +#if CC_PLATFORM == CC_PLATFORM_ANDROID #include +#endif #include "audio/android/audio.h" diff --git a/native/cocos/audio/common/utils/include/primitives.h b/native/cocos/audio/common/utils/include/primitives.h index 1e335bbd67..0901e2043d 100644 --- a/native/cocos/audio/common/utils/include/primitives.h +++ b/native/cocos/audio/common/utils/include/primitives.h @@ -24,6 +24,9 @@ #include #include #include +#if CC_PLATFORM == CC_PLATFORM_ANDROID +#include +#endif /* The memcpy_* conversion routines are designed to work in-place on same dst as src * buffers only if the types shrink on copy, with the exception of memcpy_to_i16_from_u8(). diff --git a/native/cocos/audio/common/utils/include/tinysndfile.h b/native/cocos/audio/common/utils/include/tinysndfile.h index bdf3705e2a..786302c807 100644 --- a/native/cocos/audio/common/utils/include/tinysndfile.h +++ b/native/cocos/audio/common/utils/include/tinysndfile.h @@ -25,8 +25,9 @@ #include #elif CC_PLATFORM == CC_PLATFORM_WINDOWS #include +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + #include #endif - #include #include diff --git a/native/cocos/base/Log.cpp b/native/cocos/base/Log.cpp index d00caaf722..90772e2268 100644 --- a/native/cocos/base/Log.cpp +++ b/native/cocos/base/Log.cpp @@ -47,6 +47,8 @@ #include #elif CC_PLATFORM == CC_PLATFORM_OHOS #include +#elif (CC_PLATFORM == CC_PLATFORM_OPENHARMONY) + #include #endif namespace cc { @@ -203,6 +205,29 @@ void Log::logMessage(LogType type, LogLevel level, const char *formats, ...) { default: HILOG_DEBUG(LOG_APP, typeStr, buff); } +#elif (CC_PLATFORM == CC_PLATFORM_OPENHARMONY) + ::LogLevel ohosLoglevel = ::LogLevel::LOG_DEBUG; + switch (level) { + case LogLevel::LEVEL_DEBUG: + ohosLoglevel = ::LogLevel::LOG_DEBUG; + break; + case LogLevel::INFO: + ohosLoglevel = ::LogLevel::LOG_INFO; + break; + case LogLevel::WARN: + ohosLoglevel = ::LogLevel::LOG_WARN; + break; + case LogLevel::ERR: + ohosLoglevel = ::LogLevel::LOG_ERROR; + break; + case LogLevel::FATAL: + ohosLoglevel = ::LogLevel::LOG_FATAL; + break; + default: + ohosLoglevel = ::LogLevel::LOG_INFO; + break; + } + OH_LOG_Print(LOG_APP, ohosLoglevel, LOG_DOMAIN, "HMG_LOG", "%{public}s", buff); #else fputs(buff, stdout); #endif diff --git a/native/cocos/base/TypeDef.h b/native/cocos/base/TypeDef.h index 23f89fdbc3..3a5ee80946 100644 --- a/native/cocos/base/TypeDef.h +++ b/native/cocos/base/TypeDef.h @@ -31,7 +31,7 @@ using uint = std::uint32_t; using ushort = std::uint16_t; -#if (CC_PLATFORM != CC_PLATFORM_LINUX && CC_PLATFORM != CC_PLATFORM_QNX && CC_PLATFORM != CC_PLATFORM_EMSCRIPTEN) // linux has typedef ulong +#if (CC_PLATFORM != CC_PLATFORM_LINUX && CC_PLATFORM != CC_PLATFORM_QNX && CC_PLATFORM != CC_PLATFORM_EMSCRIPTEN && CC_PLATFORM != CC_PLATFORM_OPENHARMONY) // linux and openharmony has typedef ulong using ulong = std::uint32_t; #endif using FlagBits = std::uint32_t; diff --git a/native/cocos/bindings/jswrapper/Object.h b/native/cocos/bindings/jswrapper/Object.h index 632bb87f18..f439b1b0d8 100644 --- a/native/cocos/bindings/jswrapper/Object.h +++ b/native/cocos/bindings/jswrapper/Object.h @@ -42,3 +42,8 @@ #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_CHAKRACORE #include "chakracore/Object.h" #endif + + +#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_NAPI + #include "napi/Object.h" +#endif \ No newline at end of file diff --git a/native/cocos/bindings/jswrapper/SeApi.h b/native/cocos/bindings/jswrapper/SeApi.h index e84cfa3ff9..b187a727ef 100644 --- a/native/cocos/bindings/jswrapper/SeApi.h +++ b/native/cocos/bindings/jswrapper/SeApi.h @@ -43,6 +43,10 @@ #include "chakracore/SeApi.h" #endif +#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_NAPI + #include "napi/SeApi.h" +#endif + #include "HandleObject.h" #include "Object.h" #include "State.h" diff --git a/native/cocos/bindings/jswrapper/Value.cpp b/native/cocos/bindings/jswrapper/Value.cpp index 8a1c010c0f..246224532e 100644 --- a/native/cocos/bindings/jswrapper/Value.cpp +++ b/native/cocos/bindings/jswrapper/Value.cpp @@ -30,6 +30,7 @@ #include #include #include "Object.h" +#include namespace se { diff --git a/native/cocos/bindings/jswrapper/config.h b/native/cocos/bindings/jswrapper/config.h index 72d0776d1d..c66c13a9d0 100644 --- a/native/cocos/bindings/jswrapper/config.h +++ b/native/cocos/bindings/jswrapper/config.h @@ -32,10 +32,15 @@ #define SCRIPT_ENGINE_NONE 0 #define SCRIPT_ENGINE_SM 1 #define SCRIPT_ENGINE_V8 2 +#define SCRIPT_ENGINE_NAPI 5 #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 +#endif #define SE_LOG_TO_JS_ENV 0 // print log to JavaScript environment, for example DevTools diff --git a/native/cocos/bindings/jswrapper/napi/Class.cpp b/native/cocos/bindings/jswrapper/napi/Class.cpp new file mode 100644 index 0000000000..655803f4d3 --- /dev/null +++ b/native/cocos/bindings/jswrapper/napi/Class.cpp @@ -0,0 +1,247 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "Class.h" +#include +#include "CommonHeader.h" +#include "ScriptEngine.h" +#include "Utils.h" + +namespace se { + +napi_value *Class::_exports = nullptr; +std::vector __allClasses; + +Class::Class() { + __allClasses.push_back(this); +}; + +Class::~Class() { +} + +/* static */ +Class *Class::create(const std::string &clsName, se::Object *parent, Object *parentProto, napi_callback ctor) { + Class *cls = new Class(); + if (cls != nullptr && !cls->init(clsName, parent, parentProto, ctor)) { + delete cls; + cls = nullptr; + } + return cls; +} + +Class* Class::create(const std::initializer_list &classPath, se::Object *parent, Object *parentProto, napi_callback ctor) { + se::AutoHandleScope scope; + se::Object *currentParent = parent; + se::Value tmp; + for (auto i = 0; i < classPath.size() - 1; i++) { + bool ok = currentParent->getProperty(*(classPath.begin() + i), &tmp); + CC_ASSERT(ok); // class or namespace in path is not defined + currentParent = tmp.toObject(); + } + return create(*(classPath.end() - 1), currentParent, parentProto, ctor); +} + +bool Class::init(const std::string &clsName, Object *parent, Object *parentProto, napi_callback ctor) { + _name = clsName; + _parent = parent; + if (_parent != nullptr) + _parent->incRef(); + _parentProto = parentProto; + + if (_parentProto != nullptr) + _parentProto->incRef(); + if (ctor) { + _ctorFunc = ctor; + } + + return true; +} + +napi_value Class::_defaultCtor(napi_env env, napi_callback_info info) { + LOGE("check default ctor called"); + return nullptr; +} + +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}); +} + +void Class::defineProperty(const std::initializer_list &names, napi_callback g, napi_callback s) { + for (const auto *name : names) { + defineProperty(name, g, s); + } +} + +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}); +} + +bool Class::defineStaticProperty(const char *name, const Value &v, PropertyAttribute attribute /* = PropertyAttribute::NONE */) { + //napi_value value; + //internal::seToJsValue(v, &value); + //_properties.push_back({name, nullptr, nullptr, nullptr, nullptr, value, napi_static, 0}); + 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 + _properties.push_back({name, nullptr, func, nullptr, nullptr, nullptr, napi_default_jsproperty, nullptr}); +} + +void Class::defineStaticFunction(const char* name, napi_callback func) { + _properties.push_back({name, nullptr, func, nullptr, nullptr, 0, napi_static, 0}); +} + +void Class::defineFinalizeFunction(napi_finalize func) { + assert(func != nullptr); + _finalizeFunc = func; +} + +napi_finalize Class::_getFinalizeFunction() const { + return _finalizeFunc; +} + +void Class::install() { + 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) { + inherit(ScriptEngine::getEnv(), cons, _parentProto->_getJSObject()); + } + NODE_API_CALL(status, ScriptEngine::getEnv(), + napi_create_reference(ScriptEngine::getEnv(), cons, 1, &_constructor)); + + NODE_API_CALL(status, ScriptEngine::getEnv(), + napi_set_named_property(ScriptEngine::getEnv(), _parent->_getJSObject(), _name.c_str(), cons)); + + napi_value proto; + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_get_named_property(ScriptEngine::getEnv(), cons, "prototype", &proto)); + + if (status == napi_ok) { + _proto = Object::_createJSObject(ScriptEngine::getEnv(), proto, nullptr); + _proto->root(); + } +} + +napi_status Class::inherit(napi_env env, napi_value subclass, napi_value superProto) { + napi_value global, objectClass, setProto; + napi_value argv[2]; + napi_value callbackResult = nullptr; + + napi_get_global(env, &global); + napi_status status = napi_get_named_property(env, global, "Object", &objectClass); + if (status != napi_ok) { + LOGE("ace zbclog napi_get_named_property Object %{public}d", status); + return napi_ok; + } + status = napi_get_named_property(env, objectClass, "setPrototypeOf", &setProto); + if (status != napi_ok) { + LOGE("ace zbclog napi_get_named_property setPrototypeOf %{public}d", status); + return napi_ok; + } + + status = napi_get_named_property(env, subclass, "prototype", &argv[0]); + if (status != napi_ok) { + LOGE("ace zbclog napi_get_named_property prototype arg0 %{public}d", status); + return napi_ok; + } + argv[1] = superProto; + 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; + } + + return napi_ok; +} + +napi_value Class::_createJSObjectWithClass(Class *cls) { + napi_value obj = nullptr; + napi_status status; + assert(cls); + napi_value clsCtor = cls->_getCtorFunc(); + if (!clsCtor) { + LOGE("get ctor func err"); + return nullptr; + } + se::ScriptEngine::getInstance()->_setNeedCallConstructor(false); + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_new_instance( ScriptEngine::getEnv(), clsCtor, 0, nullptr, &obj)); + se::ScriptEngine::getInstance()->_setNeedCallConstructor(true); + return obj; +} + +Object *Class::getProto() const { + //not impl + return _proto; +} + +napi_ref Class::_getCtorRef() const { + return _constructor; +} + +napi_value Class::_getCtorFunc() const { + assert(_constructor); + napi_value result = nullptr; + napi_status status; + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_get_reference_value(ScriptEngine::getEnv(), _constructor, &result)); + return result; +} + +void Class::_setCtor(Object *obj) { + assert(!_ctor.has_value()); + _ctor = obj; + if (obj != nullptr) { + obj->root(); + obj->incRef(); + } +} + +void Class::destroy() { + SAFE_DEC_REF(_parent); + SAFE_DEC_REF(_proto); + SAFE_DEC_REF(_parentProto); + if (_ctor.has_value()) { + if (_ctor.value() != nullptr) { + _ctor.value()->unroot(); + _ctor.value()->decRef(); + } + _ctor.reset(); + } +} + +void Class::cleanup() { + for (auto cls : __allClasses) { + cls->destroy(); + } + + se::ScriptEngine::getInstance()->addAfterCleanupHook([]() { + for (auto cls : __allClasses) { + delete cls; + } + __allClasses.clear(); + }); +} +}; // namespace se \ No newline at end of file diff --git a/native/cocos/bindings/jswrapper/napi/Class.h b/native/cocos/bindings/jswrapper/napi/Class.h new file mode 100644 index 0000000000..d038e02d7e --- /dev/null +++ b/native/cocos/bindings/jswrapper/napi/Class.h @@ -0,0 +1,83 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once +#include +#include "CommonHeader.h" +#include "Object.h" +#include "../Define.h" +#include "base/std/optional.h" + +namespace se { +class Class { +public: + static Class *create(const std::string &clsName, se::Object *parent, Object *parentProto, napi_callback ctor = nullptr); + static Class *create(const std::initializer_list &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 &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); + + 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; } + static void cleanup(); + // Private API used in wrapper + void _setCtor(Object *obj); // NOLINT(readability-identifier-naming) + inline const ccstd::optional &_getCtor() const { return _ctor; } // NOLINT(readability-identifier-naming) +private: + Class(); + ~Class(); + 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 _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 _properties; + napi_finalize _finalizeFunc = nullptr; +}; +}; // namespace se \ No newline at end of file diff --git a/native/cocos/bindings/jswrapper/napi/CommonHeader.h b/native/cocos/bindings/jswrapper/napi/CommonHeader.h new file mode 100644 index 0000000000..60fb084ed5 --- /dev/null +++ b/native/cocos/bindings/jswrapper/napi/CommonHeader.h @@ -0,0 +1,74 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once +#include +#include "native_common.h" + +// Empty value so that macros here are able to return NULL or void +#define NODE_API_RETVAL_NOTHING // Intentionally blank #define + +// Returns NULL on failed assertion. +// This is meant to be used inside napi_callback methods. +#define NODE_API_ASSERT(env, assertion, message) \ + NODE_API_ASSERT_BASE(env, assertion, message, NULL) + +// Returns empty on failed assertion. +// This is meant to be used inside functions with void return type. +#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) != napi_ok) { \ + assert(false); \ + } \ + } while (0) + +// Returns nullptr if the_call doesn't return napi_ok. +#define NODE_API_CALL(status, env, the_call) \ + status = the_call; \ + if (status != napi_ok) \ + LOGI("error:%d", status); \ + NODE_API_CALL_BASE(env, status, nullptr) + +// Returns empty if the_call doesn't return napi_ok. +#define NODE_API_CALL_RETURN_VOID(env, the_call) \ + NODE_API_CALL_BASE(env, the_call, NODE_API_RETVAL_NOTHING) + +#define DECLARE_NODE_API_PROPERTY(name, func) \ + { (name), nullptr, (func), nullptr, nullptr, nullptr, napi_default, nullptr } + +#define DECLARE_NODE_API_GETTER(name, func) \ + { (name), nullptr, nullptr, (func), nullptr, nullptr, napi_default, nullptr } + +void add_returned_status(napi_env env, + const char* key, + napi_value object, + char* expected_message, + napi_status expected_status, + napi_status actual_status); + +void add_last_status(napi_env env, const char* key, napi_value return_value); diff --git a/native/cocos/bindings/jswrapper/napi/HelperMacros.cpp b/native/cocos/bindings/jswrapper/napi/HelperMacros.cpp new file mode 100644 index 0000000000..a6c42a2a63 --- /dev/null +++ b/native/cocos/bindings/jswrapper/napi/HelperMacros.cpp @@ -0,0 +1,145 @@ +/**************************************************************************** + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "HelperMacros.h" +#include "../State.h" +#include "../ValueArrayPool.h" +#include "Class.h" +#include "Object.h" +#include "ScriptEngine.h" +#include "Utils.h" + +SE_HOT napi_value jsbFunctionWrapper(napi_env env, napi_callback_info info, se_function_ptr func, const char *funcName) { + napi_status status; + bool ret = false; + napi_value _this; + se::ValueArray seArgs; + seArgs.reserve(15); + size_t argc = 15; + napi_value args[15]; + NODE_API_CALL(status, env, napi_get_cb_info(env, info, &argc, args, &_this, NULL)); + se::Object *nativeThisObject = nullptr; + status = napi_unwrap(env, _this, reinterpret_cast(&nativeThisObject)); + se::internal::jsToSeArgs(argc, args, &seArgs); + se::State state(nativeThisObject, seArgs); + ret = func(state); + if (!ret) { + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", funcName, __FILE__, __LINE__); + return nullptr; + } + napi_value retVal; + if (se::internal::setReturnValue(state.rval(), retVal)) + return retVal; + return nullptr; +} + +SE_HOT void jsbFinalizeWrapper(void *thisObject, se_function_ptr func, const char *funcName) { + se::State state(reinterpret_cast(thisObject)); + bool ret = func(state); + if (!ret) { + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", funcName, __FILE__, __LINE__); + } +} + +SE_HOT napi_value jsbConstructorWrapper(napi_env env, napi_callback_info info, se_function_ptr func, se_finalize_ptr finalizeCb, se::Class *cls, const char *funcName) { + napi_status status; + bool ret = false; + napi_value _this; + se::ValueArray seArgs; + seArgs.reserve(10); + size_t argc = 10; + napi_value args[10]; + NODE_API_CALL(status, env, napi_get_cb_info(env, info, &argc, args, &_this, NULL)); + if (!se::ScriptEngine::getInstance()->_needCallConstructor()) { + return _this; + } + se::internal::jsToSeArgs(argc, args, &seArgs); + se::Object *thisObject = se::Object::_createJSObject(env, _this, cls); + thisObject->_setFinalizeCallback(finalizeCb); + se::State state(thisObject, seArgs); + ret = func(state); + if (!ret) { + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", funcName, __FILE__, __LINE__); + } + se::Value property; + bool foundCtor = false; + if (!cls->_getCtor().has_value()) { + foundCtor = thisObject->getProperty("_ctor", &property, true); + if (foundCtor) { + cls->_setCtor(property.toObject()); + } else { + cls->_setCtor(nullptr); + } + } else { + auto *ctorObj = cls->_getCtor().value(); + if (ctorObj != nullptr) { + property.setObject(ctorObj); + foundCtor = true; + } + } + + if (foundCtor) { + property.toObject()->call(seArgs, thisObject); + } + return _this; +} + +SE_HOT napi_value jsbGetterWrapper(napi_env env, napi_callback_info info, se_function_ptr func, const char *funcName) { + napi_value _this; + napi_status status; + NODE_API_CALL(status, env, + napi_get_cb_info(env, info, nullptr, nullptr, &_this, nullptr)); + se::Object *obj; + napi_unwrap(env, _this, reinterpret_cast(&obj)); + se::State state(obj); + bool ret = func(state); + if (!ret) { + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", funcName, __FILE__, __LINE__); + return nullptr; + } + napi_value retVal; + se::internal::setReturnValue(state.rval(), retVal); + return retVal; +} + +SE_HOT napi_value jsbSetterWrapper(napi_env env, napi_callback_info info, se_function_ptr func, const char *funcName) { + napi_status status; + size_t argc = 1; + napi_value args[1]; + napi_value _this; + se::Value data; + NODE_API_CALL(status, env, napi_get_cb_info(env, info, &argc, args, &_this, nullptr)); + se::internal::jsToSeValue(args[0], &data); + se::ValueArray args2; + args2.reserve(10); + args2.push_back(std::move(data)); + se::Object *nativeThisObject; + napi_unwrap(env, _this, reinterpret_cast(&nativeThisObject)); + se::State state(nativeThisObject, args2); + bool ret = func(state); + if (!ret) { + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", funcName, __FILE__, __LINE__); + } + return nullptr; +} diff --git a/native/cocos/bindings/jswrapper/napi/HelperMacros.h b/native/cocos/bindings/jswrapper/napi/HelperMacros.h new file mode 100644 index 0000000000..aef3f1ee48 --- /dev/null +++ b/native/cocos/bindings/jswrapper/napi/HelperMacros.h @@ -0,0 +1,153 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "CommonHeader.h" +#if !defined(_WIN) + #include + + #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__)) + #endif +#else + #define LOGI + #define LOGW + #define LOGE +#endif +namespace se { +class Class; +class Object; +class State; +} // namespace se +using se_function_ptr = bool (*)(se::State &state); +using se_finalize_ptr = void (*)(napi_env env, void *nativeObject, void *hint); + +napi_value jsbFunctionWrapper(napi_env, napi_callback_info, + se_function_ptr, + const char *); +void jsbFinalizeWrapper(void *thisObject, + se_function_ptr, + const char *); +napi_value jsbConstructorWrapper(napi_env, napi_callback_info, + se_function_ptr, + se_finalize_ptr finalizeCb, + se::Class *, + const char *); +napi_value jsbGetterWrapper(napi_env, napi_callback_info, + se_function_ptr, + const char *); +napi_value jsbSetterWrapper(napi_env, napi_callback_info, + se_function_ptr, + const char *); +#ifdef __GNUC__ + #define SE_UNUSED __attribute__((unused)) + #define SE_HOT __attribute__((hot)) +#else + #define SE_UNUSED + #define SE_HOT +#endif + +template +constexpr inline T *SE_THIS_OBJECT(STATE &s) { // NOLINT(readability-identifier-naming) + return reinterpret_cast(s.nativeThisObject()); +} + +#define SAFE_INC_REF(obj) \ + if (obj != nullptr) obj->incRef() +#define SAFE_DEC_REF(obj) \ + if ((obj) != nullptr) { \ + (obj)->decRef(); \ + (obj) = nullptr; \ + } +#define _SE(name) name##Registry // NOLINT(readability-identifier-naming, bugprone-reserved-identifier) + +#define SE_QUOTEME_(x) #x // NOLINT(readability-identifier-naming) +#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(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(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) \ + 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_FAST(funcName) \ + napi_value funcName##Registry(napi_env env, napi_callback_info info) { \ + napi_status status; \ + napi_value _this; \ + size_t argc = 10; \ + napi_value args[10]; \ + se::Object *nativeThisObject = nullptr; \ + NODE_API_CALL(status, env, napi_get_cb_info(env, info, &argc, args, &_this, NULL)); \ + status = napi_unwrap(env, _this, reinterpret_cast(&nativeThisObject)); \ + auto *nativeObject = nativeThisObject != nullptr ? nativeThisObject->getPrivateData() : nullptr; \ + funcName(nativeObject); \ + 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_SUB_CLS_CTOR SE_BIND_CTOR + +#define SE_DECLARE_FINALIZE_FUNC(funcName) \ + 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); \ + } + diff --git a/native/cocos/bindings/jswrapper/napi/Object.cpp b/native/cocos/bindings/jswrapper/napi/Object.cpp new file mode 100644 index 0000000000..305783fa26 --- /dev/null +++ b/native/cocos/bindings/jswrapper/napi/Object.cpp @@ -0,0 +1,738 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "Object.h" +#include +#include +#include "../MappingUtils.h" +#include "Class.h" +#include "ScriptEngine.h" +#include "Utils.h" + +#define MAX_STRING_LEN 512 +namespace se { +std::unique_ptr> __objectMap; // Currently, the value `void*` is always nullptr + +Object::Object() {} +Object::~Object() { + if (__objectMap) { + __objectMap->erase(this); + } +} + +Object* Object::createObjectWithClass(Class* cls) { + napi_value jsobj = Class::_createJSObjectWithClass(cls); + Object* obj = Object::_createJSObject(ScriptEngine::getEnv(), jsobj, cls); + return obj; +} + +bool Object::setProperty(const char* name, const Value& data) { + napi_status status; + napi_value jsVal; + internal::seToJsValue(data, &jsVal); + NODE_API_CALL(status, _env, napi_set_named_property(_env, _objRef.getValue(_env), name, jsVal)); + return status == napi_ok; +} + +bool Object::getProperty(const char* name, Value* d) { + napi_status status; + napi_value jsVal; + Value data; + NODE_API_CALL(status, _env, napi_get_named_property(_env, _objRef.getValue(_env), name, &jsVal)); + if (status == napi_ok) { + internal::jsToSeValue(jsVal, &data); + *d = data; + if (data.isUndefined()) { + return false; + } + return true; + } + return false; +} + +bool Object::isArray() const { + napi_status status; + bool ret = false; + NODE_API_CALL(status, _env, napi_is_array(_env, _objRef.getValue(_env), &ret)); + return ret; +} + +bool Object::getArrayLength(uint32_t* length) const { + napi_status status; + uint32_t len = 0; + NODE_API_CALL(status, _env, napi_get_array_length(_env, _objRef.getValue(_env), &len)); + if (length) { + *length = len; + } + return true; +} + +bool Object::getArrayElement(uint32_t index, Value* data) const { + napi_status status; + napi_value val; + NODE_API_CALL(status, _env, napi_get_element(_env, _objRef.getValue(_env), index, &val)); + internal::jsToSeValue(val, data); + return true; +} + +bool Object::setArrayElement(uint32_t index, const Value& data) { + napi_status status; + napi_value val; + internal::seToJsValue(data, &val); + NODE_API_CALL(status, _env, napi_set_element(_env, _objRef.getValue(_env), index, val)); + return true; +} + +bool Object::isTypedArray() const { + napi_status status; + bool ret = false; + NODE_API_CALL(status, _env, napi_is_typedarray(_env, _objRef.getValue(_env), &ret)); + return ret; +} + +bool Object::isProxy() const { + //return const_cast(this)->_obj.handle(__isolate)->IsProxy(); + // todo: + return false; +} + +Object *Object::createProxyTarget(se::Object *proxy) { + // SE_ASSERT(proxy->isProxy(), "parameter is not a Proxy object"); + // v8::Local jsobj = proxy->getProxyTarget().As(); + // Object *obj = Object::_createJSObject(nullptr, jsobj); + // return obj; + return nullptr; +} + +Object::TypedArrayType Object::getTypedArrayType() const { + napi_status status; + napi_typedarray_type type; + napi_value inputBuffer; + size_t byteOffset; + size_t length; + NODE_API_CALL(status, _env, napi_get_typedarray_info(_env, _objRef.getValue(_env), &type, &length, NULL, &inputBuffer, &byteOffset)); + + TypedArrayType ret = TypedArrayType::NONE; + switch (type) { + case napi_int8_array: + ret = TypedArrayType::INT8; + break; + case napi_uint8_array: + ret = TypedArrayType::UINT8; + break; + case napi_uint8_clamped_array: + ret = TypedArrayType::UINT8_CLAMPED; + break; + case napi_int16_array: + ret = TypedArrayType::INT16; + break; + case napi_uint16_array: + ret = TypedArrayType::UINT16; + break; + case napi_int32_array: + ret = TypedArrayType::INT32; + break; + case napi_uint32_array: + ret = TypedArrayType::UINT32; + break; + case napi_float32_array: + ret = TypedArrayType::FLOAT32; + break; + case napi_float64_array: + ret = TypedArrayType::FLOAT64; + break; + default: + break; + } + return ret; +} + +bool Object::getTypedArrayData(uint8_t** ptr, size_t* length) const { + napi_status status; + napi_typedarray_type type; + napi_value inputBuffer; + size_t byteOffset; + size_t byteLength; + void* data = nullptr; + NODE_API_CALL(status, _env, napi_get_typedarray_info(_env, _objRef.getValue(_env), &type, &byteLength, &data, &inputBuffer, &byteOffset)); + *ptr = (uint8_t*)(data); + if (length) { + *length = byteLength; + } + return true; +} + +bool Object::isArrayBuffer() const { + bool ret = false; + napi_status status; + NODE_API_CALL(status, _env, napi_is_arraybuffer(_env, _objRef.getValue(_env), &ret)); + return ret; +} + +bool Object::getArrayBufferData(uint8_t** ptr, size_t* length) const { + napi_status status; + size_t len = 0; + NODE_API_CALL(status, _env, napi_get_arraybuffer_info(_env, _objRef.getValue(_env), reinterpret_cast(ptr), &len)); + if (length) { + *length = len; + } + return true; +} + +Object* Object::createTypedArray(Object::TypedArrayType type, const void* data, size_t byteLength) { + napi_status status; + if (type == TypedArrayType::NONE) { + SE_LOGE("Don't pass se::Object::TypedArrayType::NONE to createTypedArray API!"); + return nullptr; + } + + if (type == TypedArrayType::UINT8_CLAMPED) { + SE_LOGE("Doesn't support to create Uint8ClampedArray with Object::createTypedArray API!"); + return nullptr; + } + napi_typedarray_type napiType; + napi_value outputBuffer; + void* outputPtr = nullptr; + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_create_arraybuffer(ScriptEngine::getEnv(), byteLength, &outputPtr, &outputBuffer)); + if (outputPtr && data && byteLength > 0) { + memcpy(outputPtr, data, byteLength); + } + size_t sizeOfEle = 0; + switch (type) { + case TypedArrayType::INT8: + napiType = napi_int8_array; + sizeOfEle = 1; + break; + case TypedArrayType::UINT8: + napiType = napi_uint8_array; + sizeOfEle = 1; + break; + case TypedArrayType::INT16: + napiType = napi_int8_array; + sizeOfEle = 2; + case TypedArrayType::UINT16: + napiType = napi_uint8_array; + sizeOfEle = 2; + break; + case TypedArrayType::INT32: + napiType = napi_int32_array; + sizeOfEle = 4; + case TypedArrayType::UINT32: + napiType = napi_uint32_array; + sizeOfEle = 4; + case TypedArrayType::FLOAT32: + napiType = napi_float32_array; + sizeOfEle = 4; + break; + case TypedArrayType::FLOAT64: + napiType = napi_float64_array; + sizeOfEle = 8; + break; + default: + assert(false); // Should never go here. + break; + } + size_t eleCounts = byteLength / sizeOfEle; + napi_value outputArray; + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_create_typedarray(ScriptEngine::getEnv(), napiType, eleCounts, outputBuffer, 0, &outputArray)); + + Object* obj = Object::_createJSObject(ScriptEngine::getEnv(), outputArray, nullptr); + return obj; +} + +Object* Object::createTypedArrayWithBuffer(TypedArrayType type, const Object *obj) { + return Object::createTypedArrayWithBuffer(type, obj, 0); +} + +Object* Object::createTypedArrayWithBuffer(TypedArrayType type, const Object *obj, size_t offset) { + size_t byteLength{0}; + uint8_t *skip{nullptr}; + + if (obj->getArrayBufferData(&skip, &byteLength)) { + return Object::createTypedArrayWithBuffer(type, obj, offset, byteLength - offset); + } + + CC_ASSERT(false); + return nullptr; +} + +Object* Object::createTypedArrayWithBuffer(TypedArrayType type, const Object *obj, size_t offset, size_t byteLength) { + if (type == TypedArrayType::NONE) { + SE_LOGE("Don't pass se::Object::TypedArrayType::NONE to createTypedArray API!"); + return nullptr; + } + + if (type == TypedArrayType::UINT8_CLAMPED) { + SE_LOGE("Doesn't support to create Uint8ClampedArray with Object::createTypedArray API!"); + return nullptr; + } + + CC_ASSERT(obj->isArrayBuffer()); + napi_status status; + napi_value outputBuffer = obj->_getJSObject(); + napi_typedarray_type napiType; + + size_t sizeOfEle = 0; + switch (type) { + case TypedArrayType::INT8: + napiType = napi_int8_array; + sizeOfEle = 1; + break; + case TypedArrayType::UINT8: + napiType = napi_uint8_array; + sizeOfEle = 1; + break; + case TypedArrayType::INT16: + napiType = napi_int8_array; + sizeOfEle = 2; + case TypedArrayType::UINT16: + napiType = napi_uint8_array; + sizeOfEle = 2; + break; + case TypedArrayType::INT32: + napiType = napi_int32_array; + sizeOfEle = 4; + case TypedArrayType::UINT32: + napiType = napi_uint32_array; + sizeOfEle = 4; + case TypedArrayType::FLOAT32: + napiType = napi_float32_array; + sizeOfEle = 4; + break; + case TypedArrayType::FLOAT64: + napiType = napi_float64_array; + sizeOfEle = 8; + break; + default: + assert(false); // Should never go here. + break; + } + size_t eleCounts = byteLength / sizeOfEle; + napi_value outputArray; + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_create_typedarray(ScriptEngine::getEnv(), napiType, eleCounts, outputBuffer, offset, &outputArray)); + + return Object::_createJSObject(ScriptEngine::getEnv(), outputArray, nullptr); +} + +Object* Object::createExternalArrayBufferObject(void *contents, size_t byteLength, BufferContentsFreeFunc freeFunc, void *freeUserData) { + napi_status status; + napi_value result; + if (freeFunc) { + struct ExternalArrayBufferCallbackParams* param = new (struct ExternalArrayBufferCallbackParams); + param->func = freeFunc; + param->contents = contents; + param->byteLength = byteLength; + param->userData = freeUserData; + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_create_external_arraybuffer( + ScriptEngine::getEnv(), contents, byteLength, [](napi_env env, void* finalize_data, void* finalize_hint) { + if (finalize_hint) { + struct ExternalArrayBufferCallbackParams* param = reinterpret_cast(finalize_hint); + param->func(param->contents, param->byteLength, param->userData); + delete param; + } + }, + reinterpret_cast(param), &result)); + } else { + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_create_external_arraybuffer( + ScriptEngine::getEnv(), contents, byteLength, nullptr, + freeUserData, &result)); + } + + Object* obj = Object::_createJSObject(ScriptEngine::getEnv(), result, nullptr); + return obj; +} + +bool Object::isFunction() const { + napi_valuetype valuetype0; + napi_status status; + NODE_API_CALL(status, _env, napi_typeof(_env, _objRef.getValue(_env), &valuetype0)); + return (valuetype0 == napi_function); +} + +bool Object::defineFunction(const char* funcName, napi_callback func) { + napi_value fn; + napi_status status; + NODE_API_CALL(status, _env, napi_create_function(_env, funcName, NAPI_AUTO_LENGTH, func, NULL, &fn)); + NODE_API_CALL(status, _env, napi_set_named_property(_env, _objRef.getValue(_env), funcName, fn)); + return true; +} + +bool Object::defineProperty(const char* name, napi_callback getter, napi_callback setter) { + napi_status status; + napi_property_descriptor properties[] = {{name, nullptr, nullptr, getter, setter, 0, napi_default, 0}}; + status = napi_define_properties(_env, _objRef.getValue(_env), sizeof(properties) / sizeof(napi_property_descriptor), properties); + if (status == napi_ok) { + return true; + } + return false; +} + +Object* Object::_createJSObject(napi_env env, napi_value js_object, Class* cls) { // NOLINT(readability-identifier-naming) + auto* ret = new Object(); + if (!ret->init(env, js_object, cls)) { + delete ret; + ret = nullptr; + } + return ret; +} + +Object* Object::createPlainObject() { + napi_value result; + napi_status status; + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_create_object(ScriptEngine::getEnv(), &result)); + Object* obj = _createJSObject(ScriptEngine::getEnv(), result, nullptr); + return obj; +} + +Object* Object::createArrayObject(size_t length) { + napi_value result; + napi_status status; + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_create_array_with_length(ScriptEngine::getEnv(), length, &result)); + Object* obj = _createJSObject(ScriptEngine::getEnv(), result, nullptr); + return obj; +} + +Object* Object::createArrayBufferObject(const void* data, size_t byteLength) { + napi_value result; + napi_status status; + void* retData; + Object* obj = nullptr; + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_create_arraybuffer(ScriptEngine::getEnv(), byteLength, &retData, &result)); + if (status == napi_ok) { + if (data) { + memcpy(retData, data, byteLength); + } + obj = _createJSObject(ScriptEngine::getEnv(), result, nullptr); + } + return obj; +} + +bool Object::getAllKeys(std::vector* allKeys) const { + napi_status status; + napi_value names; + + NODE_API_CALL(status, _env, napi_get_property_names(_env, _objRef.getValue(_env), &names)); + if (status != napi_ok) { + return false; + } + uint32_t name_len = 0; + NODE_API_CALL(status, _env, napi_get_array_length(_env, names, &name_len)); + for (uint32_t i = 0; i < name_len; i++) { + napi_value val; + NODE_API_CALL(status, _env, napi_get_element(_env, names, i, &val)); + if (status == napi_ok) { + char buffer[MAX_STRING_LEN]; + size_t result = 0; + NODE_API_CALL(status, _env, napi_get_value_string_utf8(_env, val, buffer, MAX_STRING_LEN, &result)); + if (result > 0) { + allKeys->push_back(buffer); + } + } + } + + return true; +} + +bool Object::init(napi_env env, napi_value js_object, Class* cls) { + assert(env); + _cls = cls; + _env = env; + _objRef.initWeakref(env, js_object); + + if (__objectMap) { + assert(__objectMap->find(this) == __objectMap->end()); + __objectMap->emplace(this, nullptr); + } + + napi_status status; + return true; +} + +bool Object::call(const ValueArray& args, Object* thisObject, Value* rval) { + size_t argc = 0; + std::vector argv; + argv.reserve(10); + argc = args.size(); + internal::seToJsArgs(_env, args, &argv); + napi_value return_val; + napi_status status; + assert(isFunction()); + napi_value thisObj = thisObject ? thisObject->_getJSObject() : nullptr; + status = + napi_call_function(_env, thisObj, _getJSObject(), argc, argv.data(), &return_val); + if (rval) { + internal::jsToSeValue(return_val, rval); + } + return true; +} + +void Object::_setFinalizeCallback(napi_finalize finalizeCb) { + assert(finalizeCb != nullptr); + _finalizeCb = finalizeCb; +} + +PrivateObjectBase* Object::getPrivateObject() const { + return _privateObject; +} + +void Object::setPrivateObject(PrivateObjectBase* data) { + assert(_privateData == nullptr); + #if CC_DEBUG + if (data != nullptr) { + NativePtrToObjectMap::filter(data->getRaw(), _getClass()) + .forEach([&](se::Object *seObj) { + auto *pri = seObj->getPrivateObject(); + SE_LOGE("Already exists object %s/[%s], trying to add %s/[%s]\n", pri->getName(), typeid(*pri).name(), data->getName(), typeid(*data).name()); + #if JSB_TRACK_OBJECT_CREATION + SE_LOGE(" previous object created at %s\n", it->second->_objectCreationStackFrame.c_str()); + #endif + CC_ABORT(); + }); + } + #endif + napi_status status; + if (data) { + _privateData = data->getRaw(); + _privateObject = data; + NativePtrToObjectMap::emplace(_privateData, this); + } + + //issue https://github.com/nodejs/node/issues/23999 + auto tmpThis = _objRef.getValue(_env); + //_objRef.deleteRef(); + napi_ref result = nullptr; + NODE_API_CALL(status, _env, + napi_wrap(_env, tmpThis, this, weakCallback, + (void*)this /* finalize_hint */, &result)); + //_objRef.setWeakref(_env, result); + setProperty("__native_ptr__", se::Value(static_cast(reinterpret_cast(data)))); + + return; +} + +bool Object::attachObject(Object* obj) { + assert(obj); + + Object* global = ScriptEngine::getInstance()->getGlobalObject(); + Value jsbVal; + if (!global->getProperty("jsb", &jsbVal)) { + return false; + } + Object* jsbObj = jsbVal.toObject(); + + Value func; + + if (!jsbObj->getProperty("registerNativeRef", &func)) { + return false; + } + + ValueArray args; + args.push_back(Value(this)); + args.push_back(Value(obj)); + func.toObject()->call(args, global); + return true; +} + +bool Object::detachObject(Object* obj) { + assert(obj); + + Object* global = ScriptEngine::getInstance()->getGlobalObject(); + Value jsbVal; + if (!global->getProperty("jsb", &jsbVal)) { + return false; + } + Object* jsbObj = jsbVal.toObject(); + + Value func; + + if (!jsbObj->getProperty("unregisterNativeRef", &func)) { + return false; + } + + ValueArray args; + args.push_back(Value(this)); + args.push_back(Value(obj)); + func.toObject()->call(args, global); + return true; +} + +std::string Object::toString() const { + std::string ret; + napi_status status; + if (isFunction() || isArray() || isTypedArray()) { + napi_value result; + NODE_API_CALL(status, _env, napi_coerce_to_string(_env, _objRef.getValue(_env), &result)); + char buffer[MAX_STRING_LEN]; + size_t result_t = 0; + NODE_API_CALL(status, _env, napi_get_value_string_utf8(_env, result, buffer, MAX_STRING_LEN, &result_t)); + ret = buffer; + } else if (isArrayBuffer()) { + ret = "[object ArrayBuffer]"; + } else { + ret = "[object Object]"; + } + return ret; +} + +void Object::root() { + napi_status status; + if (_rootCount == 0) { + uint32_t result = 0; + _objRef.incRef(_env); + //NODE_API_CALL(status, _env, napi_reference_ref(_env, _wrapper, &result)); + } + ++_rootCount; +} + +void Object::unroot() { + napi_status status; + if (_rootCount > 0) { + --_rootCount; + if (_rootCount == 0) { + _objRef.decRef(_env); + } + } +} + +bool Object::isRooted() const { + return _rootCount > 0; +} + +Class* Object::_getClass() const { + return _cls; +} + +Object* Object::getObjectWithPtr(void* ptr) { + Object* obj = nullptr; + auto iter = NativePtrToObjectMap::find(ptr); + if (iter != NativePtrToObjectMap::end()) { + obj = iter->second; + obj->incRef(); + } + return obj; +} + +napi_value Object::_getJSObject() const { + return _objRef.getValue(_env); +} + +void Object::weakCallback(napi_env env, void* nativeObject, void* finalizeHint /*finalize_hint*/) { + if (finalizeHint) { + if (nativeObject == nullptr) { + return; + } + void *rawPtr = reinterpret_cast(nativeObject)->_privateData; + Object* seObj = reinterpret_cast(nativeObject); + if (seObj->_onCleaingPrivateData) { //called by cleanPrivateData, not release seObj; + return; + } + if (seObj->_clearMappingInFinalizer && rawPtr != nullptr) { + auto iter = NativePtrToObjectMap::find(rawPtr); + if (iter != NativePtrToObjectMap::end()) { + NativePtrToObjectMap::erase(iter); + } else { + CC_LOG_INFO("not find ptr in NativePtrToObjectMap"); + } + } + + // TODO: remove test code before releasing. + const char* clsName = seObj->_getClass()->getName(); + CC_LOG_INFO("weakCallback class name:%s, ptr:%p", clsName, rawPtr); + + if (seObj->_finalizeCb != nullptr) { + seObj->_finalizeCb(env, nativeObject, finalizeHint); + } else { + assert(seObj->_getClass() != nullptr); + if (seObj->_getClass()->_getFinalizeFunction() != nullptr) { + seObj->_getClass()->_getFinalizeFunction()(env, nativeObject, finalizeHint); + } + } + seObj->decRef(); + } +} + +void Object::setup() { + __objectMap = std::make_unique>(); +} + +void Object::cleanup() { + void* nativeObj = nullptr; + Object* obj = nullptr; + Class* cls = nullptr; + + const auto& nativePtrToObjectMap = NativePtrToObjectMap::instance(); + for (const auto& e : nativePtrToObjectMap) { + nativeObj = e.first; + obj = e.second; + + if (obj->_finalizeCb != nullptr) { + obj->_finalizeCb(ScriptEngine::getEnv(), nativeObj, nullptr); + } else { + if (obj->_getClass() != nullptr) { + if (obj->_getClass()->_getFinalizeFunction() != nullptr) { + obj->_getClass()->_getFinalizeFunction()(ScriptEngine::getEnv(), nativeObj, nullptr); + } + } + } + obj->decRef(); + } + + NativePtrToObjectMap::clear(); + + if (__objectMap) { + for (const auto& e : *__objectMap) { + obj = e.first; + cls = obj->_getClass(); + obj->_rootCount = 0; + + } + } + + __objectMap.reset(); +} + +Object* Object::createJSONObject(const std::string& jsonStr) { + //not impl + return nullptr; +} + +void Object::clearPrivateData(bool clearMapping) { + if (_privateObject != nullptr) { + napi_status status; + void* result = nullptr; + auto tmpThis = _objRef.getValue(_env); + _onCleaingPrivateData = true; + if (clearMapping) { + NativePtrToObjectMap::erase(_privateData); + } + NODE_API_CALL(status, _env, napi_remove_wrap(_env, tmpThis, &result)); + delete _privateObject; + _privateObject = nullptr; + _privateData = nullptr; + _onCleaingPrivateData = false; + } +} + +} // namespace se diff --git a/native/cocos/bindings/jswrapper/napi/Object.h b/native/cocos/bindings/jswrapper/napi/Object.h new file mode 100644 index 0000000000..b94c1f6677 --- /dev/null +++ b/native/cocos/bindings/jswrapper/napi/Object.h @@ -0,0 +1,493 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once +#include +#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; + int _refCounts = 0; + napi_env _env = nullptr; + napi_value _obj = nullptr; + +public: + ~ObjectRef() { + deleteRef(); + } + napi_value getValue(napi_env env) const { + napi_value result; + napi_status status; + NODE_API_CALL(status, env, napi_get_reference_value(env, _ref, &result)); + assert(status == napi_ok); + assert(result != nullptr); + return result; + } + void initWeakref(napi_env env, napi_value obj) { + assert(_ref == nullptr); + _obj = obj; + _env = env; + napi_create_reference(env, obj, 0, &_ref); + } + void setWeakref(napi_env env, napi_ref ref) { + assert(_ref == nullptr); + _ref = ref; + } + void initStrongRef(napi_env env, napi_value obj) { + assert(_ref == nullptr); + _refCounts = 1; + _obj = obj; + napi_create_reference(env, obj, _refCounts, &_ref); + _env = env; + } + void incRef(napi_env env) { + assert(_refCounts == 0); + if (_refCounts == 0) { + uint32_t result = 0; + _refCounts = 1; + napi_reference_ref(env, _ref, &result); + } + } + void decRef(napi_env env) { + assert(_refCounts == 1); + uint32_t result = 0; + if (_refCounts > 0) { + _refCounts--; + if (_refCounts == 0) { + napi_reference_unref(env, _ref, &result); + } + } + } + void deleteRef() { + _refCounts = 0; + if (!_ref) { + return; + } + napi_delete_reference(_env, _ref); + _ref = nullptr; + } +}; + +class Object; + +class Object : public RefCounter { +public: + enum class TypedArrayType { + NONE, + INT8, + INT16, + INT32, + UINT8, + UINT8_CLAMPED, + UINT16, + UINT32, + FLOAT32, + FLOAT64 + }; + + using BufferContentsFreeFunc = void (*)(void *contents, size_t byteLength, void *userData); + + struct ExternalArrayBufferCallbackParams { + BufferContentsFreeFunc func{nullptr}; + void *contents{nullptr}; + size_t byteLength{0}; + void *userData{0}; + }; + + Object(); + ~Object(); + /** + * @brief Sets a property to an object. + * @param[in] name A utf-8 string containing the property's name. + * @param[in] value A value to be used as the property's value. + * @return true if the property is set successfully, otherwise false. + */ + bool setProperty(const char *name, const Value &data); + + inline bool setProperty(const std::string &name, const Value &value) { + return setProperty(name.c_str(), value); + } + + /** + * @brief Gets a property from an object. + * @param[in] name A utf-8 string containing the property's name. + * @param[out] value The property's value if object has the property, otherwise the undefined value. + * @return true if object has the property, otherwise false. + */ + bool getProperty(const char *name, Value *data); + + inline bool getProperty(const char *name, Value *data, bool cachePropertyName) { + return getProperty(name, data); + } + + inline bool getProperty(const std::string &name, Value *value) { + return getProperty(name.c_str(), value); + } + + void setPrivateObject(PrivateObjectBase *data); + PrivateObjectBase *getPrivateObject() const; + + /** + * @brief Gets an object's private data. + * @return A void* that is the object's private data, if the object has private data, otherwise nullptr. + */ + inline void *getPrivateData() const { + return _privateData; + } + + /** + * @brief Sets a pointer to private data on an object. + * @param[in] data A void* to set as the object's private data. + * @note This method will associate private data with se::Object by ccstd::unordered_map::emplace. + * It's used for search a se::Object via a void* private data. + */ + template + inline void setPrivateData(T *data) { + static_assert(!std::is_void::value, "void * is not allowed for private data"); + setPrivateObject(se::make_shared_private_object(data)); + } + /** + * @brief Use a InstrusivePtr to hold private data on the se::Object. + * + * @tparam T + * @param data A intrusive pointer object + */ + template + inline void setPrivateData(const cc::IntrusivePtr &data) { + setPrivateObject(se::ccintrusive_ptr_private_object(data)); + } + + /** + * @brief Use a std::shared_ptr to hold private data on the se::Object. + * + * @tparam T + * @param data A shared_ptr object + */ + template + inline void setPrivateData(const std::shared_ptr &data) { + setPrivateObject(se::shared_ptr_private_object(data)); + } + /** + * @brief Sets a pointer to private data on an object. + * @param[in] data A void* to set as the object's private data. + * @note This method will associate private data with se::Object by ccstd::unordered_map::emplace. + * It's used for search a se::Object via a void* private data. + */ + template + inline void setRawPrivateData(T *data, bool tryDestroyInGC = false) { + static_assert(!std::is_void::value, "void * is not allowed for private data"); + auto *privateObject = se::rawref_private_object(data); + if (tryDestroyInGC) { + privateObject->tryAllowDestroyInGC(); + } + setPrivateObject(privateObject); + } + + /** + * @brief Get the underlying private data as std::shared_ptr + * + * @tparam T + * @return std::shared_ptr + */ + template + inline std::shared_ptr getPrivateSharedPtr() const { + assert(_privateObject->isSharedPtr()); + return static_cast *>(_privateObject)->getData(); + } + + /** + * @brief Get the underlying private data as InstrusivePtr + * + * @tparam T + * @return cc::IntrusivePtr + */ + template + inline cc::IntrusivePtr getPrivateInstrusivePtr() const { + assert(_privateObject->isCCIntrusivePtr()); + return static_cast *>(_privateObject)->getData(); + } + + + template + inline T *getTypedPrivateData() const { + return reinterpret_cast(getPrivateData()); + } + + /** + * @brief Clears private data of an object. + * @param clearMapping Whether to clear the mapping of native object & se::Object. + */ + void clearPrivateData(bool clearMapping = true); + + + /** + * @brief Sets whether to clear the mapping of native object & se::Object in finalizer + */ + void setClearMappingInFinalizer(bool v) { _clearMappingInFinalizer = v; } + + /** + * @brief Tests whether an object is an array. + * @return true if object is an array, otherwise false. + */ + bool isArray() const; + + /** + * @brief Gets array length of an array object. + * @param[out] length The array length to be stored. It's set to 0 if there is an error. + * @return true if succeed, otherwise false. + */ + bool getArrayLength(uint32_t *length) const; + + /** + * @brief Gets an element from an array object by numeric index. + * @param[in] index An integer value for index. + * @param[out] data The se::Value to be stored for the element in certain index. + * @return true if succeed, otherwise false. + */ + bool getArrayElement(uint32_t index, Value *data) const; + + /** + * @brief Sets an element to an array object by numeric index. + * @param[in] index An integer value for index. + * @param[in] data The se::Value to be set to array with certain index. + * @return true if succeed, otherwise false. + */ + bool setArrayElement(uint32_t index, const Value &data); + + /** @brief Tests whether an object is a typed array. + * @return true if object is a typed array, otherwise false. + */ + bool isTypedArray() const; + + /** @brief Tests whether an object is a proxy object. + * @return true if object is a proxy object, otherwise false. + */ + bool isProxy() const; + + /** + * @brief Gets the type of a typed array object. + * @return The type of a typed array object. + */ + TypedArrayType getTypedArrayType() const; + + /** + * @brief Gets backing store of a typed array object. + * @param[out] ptr A temporary pointer to the backing store of a JavaScript Typed Array object. + * @param[out] length The byte length of a JavaScript Typed Array object. + * @return true if succeed, otherwise false. + */ + bool getTypedArrayData(uint8_t **ptr, size_t *length) const; + /** + * @brief Tests whether an object is an array buffer object. + * @return true if object is an array buffer object, otherwise false. + */ + bool isArrayBuffer() const; + + /** + * @brief Gets buffer data of an array buffer object. + * @param[out] ptr A pointer to the data buffer that serves as the backing store for a JavaScript Typed Array object. + * @param[out] length The number of bytes in a JavaScript data object. + * @return true if succeed, otherwise false. + */ + bool getArrayBufferData(uint8_t **ptr, size_t *length) const; + + /** + * @brief Creates a JavaScript Typed Array Object with specified format from an existing pointer, + if provide a null pointer,then will create a empty JavaScript Typed Array Object. + * @param[in] type The format of typed array. + * @param[in] data A pointer to the byte buffer to be used as the backing store of the Typed Array object. + * @param[in] byteLength The number of bytes pointed to by the parameter bytes. + * @return A JavaScript Typed Array Object whose backing store is the same as the one pointed data, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object *createTypedArray(TypedArrayType type, const void *data, size_t byteLength); + + static Object *createTypedArrayWithBuffer(TypedArrayType type, const Object *obj); + static Object *createTypedArrayWithBuffer(TypedArrayType type, const Object *obj, size_t offset); + static Object *createTypedArrayWithBuffer(TypedArrayType type, const Object *obj, size_t offset, size_t byteLength); + + static Object *createExternalArrayBufferObject(void *contents, size_t byteLength, BufferContentsFreeFunc freeFunc, void *freeUserData = nullptr); + /** + * @brief Tests whether an object can be called as a function. + * @return true if object can be called as a function, otherwise false. + */ + bool isFunction() const; + + /** + * @brief Defines a function with a native callback for an object. + * @param[in] funcName A utf-8 string containing the function name. + * @param[in] func The native callback triggered by JavaScript code. + * @return true if succeed, otherwise false. + */ + bool defineFunction(const char *funcName, napi_callback func); + + /** + * @brief Defines a property with native accessor callbacks for an object. + * @param[in] name A utf-8 string containing the property's name. + * @param[in] getter The native callback for getter. + * @param[in] setter The native callback for setter. + * @return true if succeed, otherwise false. + */ + bool defineProperty(const char *name, napi_callback getter, napi_callback setter); + + bool attachObject(Object *obj); + + /** + * @brief Detaches an object from current object. + * @param[in] obj The object to be detached. + * @return true if succeed, otherwise false. + * @note The attached object will not be released if current object is not garbage collected. + */ + bool detachObject(Object *obj); + + /** + * @brief Calls an object as a function. + * @param[in] args A se::Value array of arguments to pass to the function. Pass se::EmptyValueArray if argumentCount is 0. + * @param[in] thisObject The object to use as "this," or NULL to use the global object as "this." + * @param[out] rval The se::Value that results from calling object as a function, passing nullptr if return value is ignored. + * @return true if object is a function and there isn't any errors, otherwise false. + */ + bool call(const ValueArray &args, Object *thisObject, Value *rval = nullptr); + + /** + * @brief Creates a JavaScript Native Binding Object from an existing se::Class instance. + * @param[in] cls The se::Class instance which stores native callback informations. + * @return A JavaScript Native Binding Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object *createObjectWithClass(Class *cls); + + static Object *_createJSObject(napi_env env, napi_value js_object, Class *cls); + + /** + * @brief Creates a JavaScript Object like `{} or new Object()`. + * @return A JavaScript Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object *createPlainObject(); + + /** + * @brief Creates a JavaScript Array Object like `[] or new Array()`. + * @param[in] length The initical length of array. + * @return A JavaScript Array Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object *createArrayObject(size_t length); + + /** + * @brief Creates a JavaScript Array Buffer object from an existing pointer. + * @param[in] bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object. + * @param[in] byteLength The number of bytes pointed to by the parameter bytes. + * @return A Array Buffer Object whose backing store is the same as the one pointed to data, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object *createArrayBufferObject(const void *data, size_t byteLength); + /** + * Gets the Proxy Target object + * @param proxy The JavaScript Proxy object. + * @return The target JavaScript object of the parameter. + */ + static Object *createProxyTarget(se::Object *proxy); + /** + * @brief Roots an object from garbage collection. + * @note Use this method when you want to store an object in a global or on the heap, where the garbage collector will not be able to discover your reference to it. + * An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection. + */ + void root(); + + /** + * @brief Unroots an object from garbage collection. + * @note An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection. + */ + void unroot(); + + /** + * @brief Tests whether an object is rooted. + * @return true if it has been already rooted, otherwise false. + */ + bool isRooted() const; + + /** + * @brief Creates a JavaScript Object from a JSON formatted string. + * @param[in] jsonStr The utf-8 string containing the JSON string to be parsed. + * @return A JavaScript Object containing the parsed value, or nullptr if the input is invalid. + * @note The return value (non-null) has to be released manually. + */ + static Object *createJSONObject(const std::string &jsonStr); + + /** + * @brief Gets all property names of an object. + * @param[out] allKeys A string vector to store all property names. + * @return true if succeed, otherwise false. + */ + bool getAllKeys(std::vector *allKeys) const; + + /** + * @brief Gets a se::Object from an existing native object pointer. + * @param[in] ptr The native object pointer associated with the se::Object + * @return A JavaScript Native Binding Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ + static Object *getObjectWithPtr(void *ptr); + + Class * _getClass() const; // NOLINT(readability-identifier-naming) + napi_value _getJSObject() const; + void _setFinalizeCallback(napi_finalize finalizeCb); // NOLINT(readability-identifier-naming) + /** + * @brief Returns the string for describing current object. + * @return The string for describing current object. + */ + std::string toString() const; + + bool init(napi_env env, napi_value js_object, Class *cls); + +private: + static void weakCallback(napi_env env, void *nativeObject, void * /*finalize_hint*/); + static void setup(); + static void cleanup(); + +private: + ObjectRef _objRef; + napi_finalize _finalizeCb = nullptr; + bool _clearMappingInFinalizer = true; + void *_privateData = nullptr; + PrivateObjectBase *_privateObject = nullptr; + napi_env _env = nullptr; + Class * _cls = nullptr; + uint32_t _rootCount = 0; + bool _onCleaingPrivateData = false; + + friend class ScriptEngine; +}; +}; // namespace se \ No newline at end of file diff --git a/native/cocos/bindings/jswrapper/napi/ScriptEngine.cpp b/native/cocos/bindings/jswrapper/napi/ScriptEngine.cpp new file mode 100644 index 0000000000..2d321e88ed --- /dev/null +++ b/native/cocos/bindings/jswrapper/napi/ScriptEngine.cpp @@ -0,0 +1,312 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "ScriptEngine.h" +#include +#include "../MappingUtils.h" +#include "Class.h" +#include "Utils.h" +#include "CommonHeader.h" +#include +#include "base/std/container/array.h" + +namespace se { +AutoHandleScope::AutoHandleScope() { + napi_open_handle_scope(ScriptEngine::getEnv(), &_handleScope); +} + +AutoHandleScope::~AutoHandleScope() { + napi_close_handle_scope(ScriptEngine::getEnv(), _handleScope); +} + +ScriptEngine *gSriptEngineInstance = nullptr; + +ScriptEngine::ScriptEngine() {}; + +ScriptEngine::~ScriptEngine() = default; + +void ScriptEngine::setFileOperationDelegate(const FileOperationDelegate &delegate) { + _fileOperationDelegate = delegate; +} + +const ScriptEngine::FileOperationDelegate &ScriptEngine::getFileOperationDelegate() const { + return _fileOperationDelegate; +} + +ScriptEngine *ScriptEngine::getInstance() { + if (gSriptEngineInstance == nullptr) { + gSriptEngineInstance = new ScriptEngine(); + } + + return gSriptEngineInstance; +} + +void ScriptEngine::destroyInstance() { + if (gSriptEngineInstance) { + gSriptEngineInstance->cleanup(); + delete gSriptEngineInstance; + gSriptEngineInstance = nullptr; + } +} + +bool ScriptEngine::runScript(const std::string &path, Value *ret /* = nullptr */) { + assert(!path.empty()); + napi_status status; + napi_value result = nullptr; + LOGI("run script : %s", path.c_str()); + //NODE_API_CALL(status, ScriptEngine::getEnv(), napi_run_script_path(ScriptEngine::getEnv(), path.c_str(), &result)); + if (ret && result) { + internal::jsToSeValue(result, ret); + } + return false; +} + +bool ScriptEngine::evalString(const char *scriptStr, ssize_t length, Value *ret, const char *fileName) { + napi_status status; + 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); + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_run_script(ScriptEngine::getEnv(), script, &result)); + return true; +} + +bool ScriptEngine::init() { + napi_status status; + napi_value result; + + for (const auto &hook : _beforeInitHookArray) { + hook(); + } + + Object::setup(); + NativePtrToObjectMap::init(); + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_get_global(ScriptEngine::getEnv(), &result)); + _globalObj = Object::_createJSObject(ScriptEngine::getEnv(), result, nullptr); + _globalObj->root(); + _globalObj->setProperty("window", Value(_globalObj)); + _globalObj->setProperty("scriptEngineType", se::Value("napi")); + + _isValid = true; + + for (const auto &hook : _afterInitHookArray) { + hook(); + } + _afterInitHookArray.clear(); + + return _isValid; +} + +Object *ScriptEngine::getGlobalObject() const { + return _globalObj; +} + +bool ScriptEngine::start() { + bool ok = true; + if (!init()) { + return false; + } + _startTime = std::chrono::steady_clock::now(); + for (auto cb : _permRegisterCallbackArray) { + ok = cb(_globalObj); + assert(ok); + if (!ok) { + break; + } + } + + for (auto cb : _registerCallbackArray) { + ok = cb(_globalObj); + assert(ok); + if (!ok) { + break; + } + } + + // After ScriptEngine is started, _registerCallbackArray isn't needed. Therefore, clear it here. + _registerCallbackArray.clear(); + + return ok; +} + +void ScriptEngine::cleanup() { + if (!_isValid) { + return; + } + + SE_LOGD("ScriptEngine::cleanup begin ...\n"); + _isInCleanup = true; + + for (const auto &hook : _beforeCleanupHookArray) { + hook(); + } + _beforeCleanupHookArray.clear(); + + SAFE_DEC_REF(_globalObj); + Object::cleanup(); + Class::cleanup(); + garbageCollect(); + + _globalObj = nullptr; + _isValid = false; + + _registerCallbackArray.clear(); + + for (const auto &hook : _afterCleanupHookArray) { + hook(); + } + _afterCleanupHookArray.clear(); + + _isInCleanup = false; + NativePtrToObjectMap::destroy(); + SE_LOGD("ScriptEngine::cleanup end ...\n"); +} + +void ScriptEngine::addBeforeCleanupHook(const std::function &hook) { + _beforeCleanupHookArray.push_back(hook); + return; +} + +void ScriptEngine::addAfterCleanupHook(const std::function &hook) { + _afterCleanupHookArray.push_back(hook); + return; +} + +void ScriptEngine::addRegisterCallback(RegisterCallback cb) { + assert(std::find(_registerCallbackArray.begin(), _registerCallbackArray.end(), cb) == _registerCallbackArray.end()); + _registerCallbackArray.push_back(cb); +} + +napi_env ScriptEngine::getEnv() { + return getInstance()->_env; +} + +void ScriptEngine::setEnv(napi_env env) { + getInstance()->_env = env; +} + +void ScriptEngine::addPermanentRegisterCallback(RegisterCallback cb) { + if (std::find(_permRegisterCallbackArray.begin(), _permRegisterCallbackArray.end(), cb) == _permRegisterCallbackArray.end()) { + _permRegisterCallbackArray.push_back(cb); + } +} + +void ScriptEngine::setExceptionCallback(const ExceptionCallback &cb) { + //not impl + return; +} + +const std::chrono::steady_clock::time_point &ScriptEngine::getStartTime() const { + return _startTime; +} + +bool ScriptEngine::isValid() const { + return _isValid; +} + +void ScriptEngine::enableDebugger(const std::string &serverAddr, uint32_t port, bool isWait) { + //not impl + return; +} + +bool ScriptEngine::saveByteCodeToFile(const std::string &path, const std::string &pathBc) { + //not impl + return true; +} + +void ScriptEngine::clearException() { + //not impl + return; +} + +void ScriptEngine::garbageCollect() { + //not impl + return; +} + +bool ScriptEngine::isGarbageCollecting() const { + return _isGarbageCollecting; +} + +void ScriptEngine::_setGarbageCollecting(bool isGarbageCollecting) { //NOLINT(readability-identifier-naming) + _isGarbageCollecting = isGarbageCollecting; +} + +void ScriptEngine::setJSExceptionCallback(const ExceptionCallback &cb) { + //not impl + return; +} + +void ScriptEngine::addAfterInitHook(const std::function &hook) { + _afterInitHookArray.push_back(hook); + return; +} + +std::string ScriptEngine::getCurrentStackTrace() { + //not impl + return ""; +} + +void ScriptEngine::_setNeedCallConstructor(bool need) { + _isneedCallConstructor = need; +} + +bool ScriptEngine::_needCallConstructor() { + return _isneedCallConstructor; +} + +bool ScriptEngine::callFunction(Object *targetObj, const char *funcName, uint32_t argc, Value *args, Value *rval) { + Value objFunc; + if (!targetObj->getProperty(funcName, &objFunc)) { + return false; + } + + ValueArray argv; + + for (size_t i = 0; i < argc; ++i) { + argv.push_back(args[i]); + } + + objFunc.toObject()->call(argv, targetObj, rval); + + return true; +} + +void ScriptEngine::handlePromiseExceptions() { + //not impl + assert(true); + return; +} + +void ScriptEngine::mainLoopUpdate() { + // empty implementation +} + +void ScriptEngine::throwException(const std::string &errorMessage) { + napi_status status; + NODE_API_CALL_RETURN_VOID(getEnv(), napi_throw_error(getEnv(), nullptr, errorMessage.c_str())); +} +}; // namespace se diff --git a/native/cocos/bindings/jswrapper/napi/ScriptEngine.h b/native/cocos/bindings/jswrapper/napi/ScriptEngine.h new file mode 100644 index 0000000000..35835ffb43 --- /dev/null +++ b/native/cocos/bindings/jswrapper/napi/ScriptEngine.h @@ -0,0 +1,305 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include +#include +#include "../Value.h" +#include "../config.h" +#include "CommonHeader.h" + +using HandleScope = napi_handle_scope; +namespace se { +class AutoHandleScope { +public: + // 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(); + +private: + HandleScope _handleScope; +}; +using RegisterCallback = bool (*)(Object *); +using ExceptionCallback = std::function; // location, message, stack + +class ScriptEngine { +public: + /** + * Delegate class for file operation + */ + class FileOperationDelegate { + public: + FileOperationDelegate() + : onGetDataFromFile(nullptr), + onGetStringFromFile(nullptr), + onCheckFileExist(nullptr), + onGetFullPath(nullptr) {} + + /** + * @brief Tests whether delegate is valid. + */ + bool isValid() const { + return onGetDataFromFile != nullptr && onGetStringFromFile != nullptr && onCheckFileExist != nullptr && onGetFullPath != nullptr; + } + + // path, buffer, buffer size + std::function &)> onGetDataFromFile; + // path, return file string content. + std::function onGetStringFromFile; + // path + std::function onCheckFileExist; + // path, return full path + std::function onGetFullPath; + }; + ScriptEngine(); + ~ScriptEngine(); + /** + * @brief Sets the delegate for file operation. + * @param delegate[in] The delegate instance for file operation. + */ + void setFileOperationDelegate(const FileOperationDelegate &delegate); + + /** + * @brief Compile script file into v8::ScriptCompiler::CachedData and save to file. + * @param[in] path The path of script file. + * @param[in] pathBc The location where bytecode file should be written to. The path should be ends with ".bc", which indicates a bytecode file. + * @return true if succeed, otherwise false. + */ + bool saveByteCodeToFile(const std::string &path, const std::string &pathBc); + + /** + * @brief Gets the delegate for file operation. + * @return The delegate for file operation + */ + const FileOperationDelegate &getFileOperationDelegate() const; + + static ScriptEngine *getInstance(); + + /** + * @brief Destroys the instance of script engine. + */ + static void destroyInstance(); + + /** + * @brief Clears all exceptions. + */ + void clearException(); + + /** + * @brief Sets the callback function while an exception is fired in JS. + * @param[in] cb The callback function to notify that an exception is fired. + */ + void setJSExceptionCallback(const ExceptionCallback &cb); + + /** + * @brief Sets the callback function while an exception is fired. + * @param[in] cb The callback function to notify that an exception is fired. + */ + void setExceptionCallback(const ExceptionCallback &cb); + + /** + * @brief Grab a snapshot of the current JavaScript execution stack. + * @return current stack trace string + */ + std::string getCurrentStackTrace(); + /** + * @brief Executes a utf-8 string buffer which contains JavaScript code. + * @param[in] script A utf-8 string buffer, if it isn't null-terminated, parameter `length` should be assigned and > 0. + * @param[in] length The length of parameter `scriptStr`, it will be set to string length internally if passing < 0 and parameter `scriptStr` is null-terminated. + * @param[in] ret The se::Value that results from evaluating script. Passing nullptr if you don't care about the result. + * @param[in] fileName A string containing a URL for the script's source file. This is used by debuggers and when reporting exceptions. Pass NULL if you do not care to include source file information. + * @return true if succeed, otherwise false. + */ + bool evalString(const char *script, ssize_t length = -1, Value *ret = nullptr, const char *fileName = nullptr); + + /** + * @brief Adds a callback for registering a native binding module, which will not be removed by ScriptEngine::cleanup. + * @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); + + /** + * @brief Starts the script engine. + * @return true if succeed, otherwise false. + * @note This method will invoke all callbacks of native binding modules by the order of registration. + */ + bool start(); + + /** + * @brief Initializes script engine. + * @return true if succeed, otherwise false. + * @note This method will create JavaScript context and global object. + */ + bool init(); + + /** + * @brief Adds a hook function before initializing script engine. + * @param[in] hook A hook function to be invoked before initializing script engine. + * @note Multiple hook functions could be added, they will be invoked by the order of adding. + */ + void addBeforeInitHook(const std::function &hook); + + /** + * @brief Adds a hook function after initializing script engine. + * @param[in] hook A hook function to be invoked before initializing script engine. + * @note Multiple hook functions could be added, they will be invoked by the order of adding. + */ + void addAfterInitHook(const std::function &hook); + + /** + * @brief Cleanups script engine. + * @note This method will removes all objects in JavaScript VM even whose are rooted, then shutdown JavaScript VMf. + */ + void cleanup(); + + /** + * @brief Adds a hook function before cleanuping script engine. + * @param[in] hook A hook function to be invoked before cleanuping script engine. + * @note Multiple hook functions could be added, they will be invoked by the order of adding. + */ + void addBeforeCleanupHook(const std::function &hook); + + /** + * @brief Adds a hook function after cleanuping script engine. + * @param[in] hook A hook function to be invoked after cleanuping script engine. + * @note Multiple hook functions could be added, they will be invoked by the order of adding. + */ + void addAfterCleanupHook(const std::function &hook); + /** + * @brief Gets the global object of JavaScript VM. + * @return The se::Object stores the global JavaScript object. + */ + Object *getGlobalObject() const; + + static napi_env getEnv(); + static void setEnv(napi_env env); + + /** + * @brief Adds a callback for registering a native binding module. + * @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 addRegisterCallback(RegisterCallback cb); + + const std::chrono::steady_clock::time_point &getStartTime() const; + + /** + * @brief Tests whether script engine is doing garbage collection. + * @return true if it's in garbage collection, otherwise false. + */ + bool isGarbageCollecting() const; + + /** + * @brief Performs a JavaScript garbage collection. + */ + void garbageCollect(); + + /** + * @brief Tests whether script engine is being cleaned up. + * @return true if it's in cleaning up, otherwise false. + */ + bool isInCleanup() const { return _isInCleanup; } + /** + * @brief Executes a file which contains JavaScript code. + * @param[in] path Script file path. + * @param[in] ret The se::Value that results from evaluating script. Passing nullptr if you don't care about the result. + * @return true if succeed, otherwise false. + */ + bool runScript(const std::string &path, Value *ret = nullptr); + + /** + * @brief Tests whether script engine is valid. + * @return true if it's valid, otherwise false. + */ + bool isValid() const; + + /** + * @brief Enables JavaScript debugger + * @param[in] serverAddr The address of debugger server. + * @param[in] isWait Whether wait debugger attach when loading. + */ + void enableDebugger(const std::string &serverAddr, uint32_t port, bool isWait = false); + + /** + * @brief Tests whether JavaScript debugger is enabled + * @return true if JavaScript debugger is enabled, otherwise false. + */ + bool isDebuggerEnabled() const; + + /** + * @brief Main loop update trigger, it's need to invoked in main thread every frame. + */ + void mainLoopUpdate(); + + bool runByteCodeFile(const std::string &pathBc, Value *ret /* = nullptr */); + + /** + * @brief Throw JS exception + */ + 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(); + + /** + * @brief Fast version of call script function, faster than Object::call + */ + bool callFunction(Object *targetObj, const char *funcName, uint32_t argc, Value *args, Value *rval = nullptr); + + void _setGarbageCollecting(bool isGarbageCollecting); // NOLINT(readability-identifier-naming) + + void handlePromiseExceptions(); + +private: + FileOperationDelegate _fileOperationDelegate; + std::vector _registerCallbackArray; + std::vector _permRegisterCallbackArray; + + std::vector> _beforeInitHookArray; + std::vector> _afterInitHookArray; + std::vector> _beforeCleanupHookArray; + std::vector> _afterCleanupHookArray; + + Object * _globalObj = nullptr; + napi_env _env = nullptr; + + bool _isValid{false}; + bool _isGarbageCollecting{false}; + bool _isInCleanup{false}; + bool _isErrorHandleWorking{false}; + bool _isneedCallConstructor{true}; + std::chrono::steady_clock::time_point _startTime; +}; +}; // namespace se diff --git a/native/cocos/bindings/jswrapper/napi/SeApi.h b/native/cocos/bindings/jswrapper/napi/SeApi.h new file mode 100644 index 0000000000..639abd485a --- /dev/null +++ b/native/cocos/bindings/jswrapper/napi/SeApi.h @@ -0,0 +1,32 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "Class.h" +#include "HelperMacros.h" +#include "Object.h" +#include "ScriptEngine.h" +#include "Utils.h" \ No newline at end of file diff --git a/native/cocos/bindings/jswrapper/napi/Utils.cpp b/native/cocos/bindings/jswrapper/napi/Utils.cpp new file mode 100644 index 0000000000..c753fdaf77 --- /dev/null +++ b/native/cocos/bindings/jswrapper/napi/Utils.cpp @@ -0,0 +1,196 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "Utils.h" +#include "CommonHeader.h" +#include "ScriptEngine.h" +#include "Class.h" + +#define MAX_STRING_LENS 1024 + +namespace se { +namespace internal { +void jsToSeValue(const target_value& value, Value* v) { + assert(v != nullptr); + 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; + + if (!value) { + valType = napi_valuetype::napi_undefined; + }else { + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_typeof(ScriptEngine::getEnv(), value, &valType)); + } + + switch (valType) { + case napi_valuetype::napi_undefined: + v->setUndefined(); + break; + case napi_valuetype::napi_null: + v->setNull(); + break; + case napi_valuetype::napi_number: + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_get_value_double(ScriptEngine::getEnv(), value, &dRet)); + if (status == napi_ok) { + v->setDouble(dRet); + } else { + v->setUndefined(); + } + break; + case napi_valuetype::napi_bigint: + //NODE_API_CALL(status, ScriptEngine::getEnv(), napi_get_value_bigint_int64(ScriptEngine::getEnv(), value, &iRet, &lossless)); + if (lossless) { + v->setInt64(iRet); + } else { + v->setUndefined(); + } + + break; + case napi_valuetype::napi_string: + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_get_value_string_utf8(ScriptEngine::getEnv(), value, nullptr, 0, &len)); + if (status == napi_ok) { + std::string valueStr; + len += 1; + valueStr.resize(len); + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_get_value_string_utf8(ScriptEngine::getEnv(), value, const_cast(valueStr.data()), valueStr.size(), &len)); + if (valueStr.length() != len) { + valueStr.resize(len); + } + v->setString(valueStr); + } else { + v->setUndefined(); + } + break; + case napi_valuetype::napi_boolean: + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_get_value_bool(ScriptEngine::getEnv(), value, &bRet)); + if (status == napi_ok) { + v->setBoolean(bRet); + } else { + v->setUndefined(); + } + break; + case napi_valuetype::napi_object: + case napi_valuetype::napi_function: + status = napi_unwrap(ScriptEngine::getEnv(), value, &privateObjPtr); + if ((status == napi_ok) && privateObjPtr) { + nativePtr = reinterpret_cast(privateObjPtr)->getPrivateData(); + } + if (nativePtr) { + obj = Object::getObjectWithPtr(nativePtr); + } + if (obj == nullptr) { + obj = Object::_createJSObject(ScriptEngine::getEnv(), value, nullptr); + } + if (obj) { + v->setObject(obj, true); + obj->decRef(); + } else { + v->setUndefined(); + } + break; + default: + break; + } +} + +void jsToSeArgs(size_t argc, target_value* argv, ValueArray* outArr) { + assert(outArr != nullptr); + for (int i = 0; i < argc; i++) { + Value v; + jsToSeValue(argv[i], &v); + outArr->push_back(v); + } +} + +bool seToJsValue(const Value& v, target_value* outJsVal) { + assert(outJsVal != nullptr); + bool ret = false; + napi_status status = napi_ok; + switch (v.getType()) { + case Value::Type::Number: + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_create_double(ScriptEngine::getEnv(), v.toDouble(), outJsVal)); + ret = (status == napi_ok); + break; + case Value::Type::String: { + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_create_string_utf8(ScriptEngine::getEnv(), v.toString().c_str(), v.toString().length(), outJsVal)); + ret = (status == napi_ok); + } break; + case Value::Type::Boolean: + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_get_boolean(ScriptEngine::getEnv(), v.toBoolean(), outJsVal)); + ret = (status == napi_ok); + break; + case Value::Type::Object: + *outJsVal = v.toObject()->_getJSObject(); + ret = (outJsVal != nullptr); + break; + case Value::Type::Null: + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_get_null(ScriptEngine::getEnv(), outJsVal)); + ret = (status == napi_ok); + break; + case Value::Type::Undefined: + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_get_undefined(ScriptEngine::getEnv(), outJsVal)); + ret = (status == napi_ok); + break; + case Value::Type::BigInt: + //NODE_API_CALL(status, ScriptEngine::getEnv(), napi_create_bigint_int64(ScriptEngine::getEnv(), v.toInt64(), outJsVal)); + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_create_double(ScriptEngine::getEnv(), v.toDouble(), outJsVal)); + ret = (status == napi_ok); + break; + default: + assert(false); + break; + } + //LOGI("type :%d", v.getType()); + return ret; +} + +void seToJsArgs(napi_env env, const ValueArray& args, std::vector* outArr) { + assert(outArr != nullptr); + for (const auto& data : args) { + napi_value jsval; + seToJsValue(data, &jsval); + outArr->push_back(jsval); + } +} + +bool setReturnValue(const Value& data, target_value& argv) { + if (data.getType() == Value::Type::BigInt) { + // TODO: fix 'TypeError: Cannot mix BigInt and other types, use explicit conversions' for spine & dragonbones + napi_status status; + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_create_double(ScriptEngine::getEnv(), data.toDouble(), &argv)); + return true; + } + + return seToJsValue(data, &argv); +} +} // namespace internal +}; // namespace se diff --git a/native/cocos/bindings/jswrapper/napi/Utils.h b/native/cocos/bindings/jswrapper/napi/Utils.h new file mode 100644 index 0000000000..45e7bb616e --- /dev/null +++ b/native/cocos/bindings/jswrapper/napi/Utils.h @@ -0,0 +1,46 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "../config.h" +#include "Object.h" +namespace se { + +namespace internal { + +using target_value = napi_value; +struct PrivateData { + void * data; + Object *seObj; +}; + +bool setReturnValue(const Value &data, target_value &argv); +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(napi_env env, const ValueArray &args, std::vector *outArr); +} // namespace internal +} // namespace se diff --git a/native/cocos/bindings/jswrapper/napi/native_common.h b/native/cocos/bindings/jswrapper/napi/native_common.h new file mode 100644 index 0000000000..c1633d2f23 --- /dev/null +++ b/native/cocos/bindings/jswrapper/napi/native_common.h @@ -0,0 +1,115 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +#pragma once + +#ifndef FOUNDATION_ACE_NAPI_INTERFACES_KITS_NAPI_NATIVE_COMMON_H +#define FOUNDATION_ACE_NAPI_INTERFACES_KITS_NAPI_NATIVE_COMMON_H + +#define DEPRECATED __attribute__((__deprecated__)) + +#ifndef NAPI_VERSION +#define NAPI_VERSION 8 +#endif + +#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 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_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(env, theCall) NAPI_CALL_BASE(env, theCall, nullptr) + +#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_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_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_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_GETTER_SETTER(name, getter, setter) \ + { \ + (name), nullptr, nullptr, (getter), (setter), nullptr, napi_default, nullptr \ + } + +#endif /* FOUNDATION_ACE_NAPI_INTERFACES_KITS_NAPI_NATIVE_COMMON_H */ diff --git a/native/cocos/bindings/manual/jsb_audio_manual.cpp b/native/cocos/bindings/manual/jsb_audio_manual.cpp index 59145b430f..42745da90d 100644 --- a/native/cocos/bindings/manual/jsb_audio_manual.cpp +++ b/native/cocos/bindings/manual/jsb_audio_manual.cpp @@ -30,7 +30,6 @@ #include "bindings/auto/jsb_audio_auto.h" #include "cocos/bindings/manual/jsb_conversions.h" #include "cocos/bindings/manual/jsb_global.h" -#include "v8/HelperMacros.h" // NOLINTNEXTLINE(readability-identifier-naming) static bool PCMHeader_to_seval(PCMHeader& header, se::Value* ret) { diff --git a/native/cocos/bindings/manual/jsb_conversions.h b/native/cocos/bindings/manual/jsb_conversions.h index b59fc293ce..a5205d4be2 100644 --- a/native/cocos/bindings/manual/jsb_conversions.h +++ b/native/cocos/bindings/manual/jsb_conversions.h @@ -1230,8 +1230,6 @@ inline bool nativevalue_to_se(const ccstd::vector &from, se::Value &to, se::O if constexpr (!std::is_pointer::value && is_jsb_object_v) { auto *pFrom = ccnew T(from[i]); nativevalue_to_se(pFrom, tmp, ctx); - tmp.toObject()->clearPrivateData(); - tmp.toObject()->setPrivateData(pFrom); } else { nativevalue_to_se(from[i], tmp, ctx); } diff --git a/native/cocos/bindings/manual/jsb_global.cpp b/native/cocos/bindings/manual/jsb_global.cpp index bf0a051d03..5ab80561bc 100644 --- a/native/cocos/bindings/manual/jsb_global.cpp +++ b/native/cocos/bindings/manual/jsb_global.cpp @@ -92,11 +92,13 @@ static cc::network::Downloader *localDownloader() { } static void localDownloaderCreateTask(const ccstd::string &url, const std::function &callback) { +#if CC_PLATFORM != CC_PLATFORM_OPENHARMONY // TODO(qgh):May be removed later std::stringstream ss; ss << "jsb_loadimage_" << (gLocalDownloaderTaskId++); ccstd::string key = ss.str(); auto task = localDownloader()->createDataTask(url, key); gLocalDownloaderHandlers.emplace(task->identifier, callback); +#endif } bool jsb_set_extend_property(const char *ns, const char *clsName) { // NOLINT @@ -339,6 +341,8 @@ static bool JSBCore_os(se::State &s) { // NOLINT os.setString("OS X"); #elif (CC_PLATFORM == CC_PLATFORM_OHOS) os.setString("OHOS"); +#elif (CC_PLATFORM == CC_PLATFORM_OPENHARMONY) + os.setString("OpenHarmony"); #endif s.rval() = os; diff --git a/native/cocos/bindings/manual/jsb_global_init.cpp b/native/cocos/bindings/manual/jsb_global_init.cpp index 231f46270b..cd0a621464 100644 --- a/native/cocos/bindings/manual/jsb_global_init.cpp +++ b/native/cocos/bindings/manual/jsb_global_init.cpp @@ -219,6 +219,7 @@ void jsb_init_file_operation_delegate() { //NOLINT } bool jsb_enable_debugger(const ccstd::string &debuggerServerAddr, uint32_t port, bool isWaitForConnect) { //NOLINT +#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8 if (debuggerServerAddr.empty() || port == 0) { return false; } @@ -238,5 +239,6 @@ bool jsb_enable_debugger(const ccstd::string &debuggerServerAddr, uint32_t port, debuggerInfo.isWait = isWaitForConnect; se::ScriptEngine::_setDebuggerInfo(debuggerInfo); } +#endif return true; } diff --git a/native/cocos/bindings/manual/jsb_module_register.cpp b/native/cocos/bindings/manual/jsb_module_register.cpp index 30135eae54..6ca0b06713 100644 --- a/native/cocos/bindings/manual/jsb_module_register.cpp +++ b/native/cocos/bindings/manual/jsb_module_register.cpp @@ -80,6 +80,12 @@ #include "cocos/bindings/manual/JavaScriptJavaBridge.h" #endif +#if(CC_PLATFORM == CC_PLATFORM_OPENHARMONY) + #if CC_USE_WEBVIEW + #include "cocos/bindings/auto/jsb_webview_auto.h" + #endif +#endif + #if (CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) #if CC_USE_VIDEO @@ -199,7 +205,11 @@ bool jsb_register_all_modules() { se->addRegisterCallback(register_all_ar); se->addRegisterCallback(register_all_ar_manual); #endif // CC_USE_AR_MODULE - +#if (CC_PLATFORM == CC_PLATFORM_OPENHARMONY) + #if CC_USE_WEBVIEW + se->addRegisterCallback(register_all_webview); + #endif +#endif #if (CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) #if CC_USE_VIDEO diff --git a/native/cocos/bindings/manual/jsb_platform_openharmony.cpp b/native/cocos/bindings/manual/jsb_platform_openharmony.cpp new file mode 100644 index 0000000000..9dc9431a4b --- /dev/null +++ b/native/cocos/bindings/manual/jsb_platform_openharmony.cpp @@ -0,0 +1,52 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "jsb_platform.h" + +#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 + +using namespace cc; + +static std::unordered_map _fontFamilyNameMap; + +const std::unordered_map &getFontFamilyNameMap() { + return _fontFamilyNameMap; +} + +static bool JSB_loadFont(se::State &s) { + // TODO(qgh):Currently it does not support loading OpenHarmony fonts, it may be supported in the future + return true; +} +SE_BIND_FUNC(JSB_loadFont) + +bool register_platform_bindings(se::Object *obj) { + __jsbObj->defineFunction("loadFont", _SE(JSB_loadFont)); + return true; +} diff --git a/native/cocos/engine/Engine.cpp b/native/cocos/engine/Engine.cpp index 01d34363c7..8f5ec03ec9 100644 --- a/native/cocos/engine/Engine.cpp +++ b/native/cocos/engine/Engine.cpp @@ -274,7 +274,7 @@ void Engine::tick() { // iOS/macOS use its own fps limitation algorithm. // Windows for Editor should not sleep,because Editor call tick function synchronously -#if (CC_PLATFORM == CC_PLATFORM_ANDROID || (CC_PLATFORM == CC_PLATFORM_WINDOWS && !CC_EDITOR) || CC_PLATFORM == CC_PLATFORM_OHOS) || (defined(CC_SERVER_MODE) && (CC_PLATFORM == CC_PLATFORM_MAC_OSX)) +#if (CC_PLATFORM == CC_PLATFORM_ANDROID || (CC_PLATFORM == CC_PLATFORM_WINDOWS && !CC_EDITOR) || CC_PLATFORM == CC_PLATFORM_OHOS || CC_PLATFORM == CC_PLATFORM_OPENHARMONY) || (defined(CC_SERVER_MODE) && (CC_PLATFORM == CC_PLATFORM_MAC_OSX)) if (dtNS < static_cast(_prefererredNanosecondsPerFrame)) { CC_PROFILE(EngineSleep); std::this_thread::sleep_for( diff --git a/native/cocos/network/WebSocket-libwebsockets.cpp b/native/cocos/network/WebSocket-libwebsockets.cpp index d31b7ae8d1..092dfaf036 100644 --- a/native/cocos/network/WebSocket-libwebsockets.cpp +++ b/native/cocos/network/WebSocket-libwebsockets.cpp @@ -284,7 +284,7 @@ static struct lws_context *wsContext{nullptr}; static WsThreadHelper *wsHelper{nullptr}; static std::atomic_bool wsPolling{false}; -#if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) +#if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS || CC_PLATFORM == CC_PLATFORM_OPENHARMONY) static ccstd::string getFileNameForPath(const ccstd::string &filePath) { ccstd::string fileName = filePath; const size_t lastSlashIdx = fileName.find_last_of("\\/"); @@ -870,7 +870,7 @@ struct lws_vhost *WebSocketImpl::createVhost(struct lws_protocols *protocols, in int sslConnection = *sslConnectionOut; if (sslConnection != 0) { if (isCAFileExist) { -#if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) +#if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS || CC_PLATFORM == CC_PLATFORM_OPENHARMONY) // if ca file is in the apk, try to extract it to writable path ccstd::string writablePath = fileUtils->getWritablePath(); ccstd::string caFileName = getFileNameForPath(_caFilePath); diff --git a/native/cocos/platform/BasePlatform.cpp b/native/cocos/platform/BasePlatform.cpp index fc56a779c8..1ae6443ecb 100644 --- a/native/cocos/platform/BasePlatform.cpp +++ b/native/cocos/platform/BasePlatform.cpp @@ -37,6 +37,8 @@ #include "platform/linux/LinuxPlatform.h" #elif (CC_PLATFORM == CC_PLATFORM_QNX) #include "platform/qnx/QnxPlatform.h" +#elif (CC_PLATFORM == CC_PLATFORM_OPENHARMONY) + #include "platform/openharmony/OpenHarmonyPlatform.h" #endif namespace cc { @@ -67,6 +69,8 @@ BasePlatform* BasePlatform::createDefaultPlatform() { static LinuxPlatform platform; #elif (CC_PLATFORM == CC_PLATFORM_QNX) static QnxPlatform platform; +#elif (CC_PLATFORM == CC_PLATFORM_OPENHARMONY) + static OpenHarmonyPlatform platform; #endif return &platform; } diff --git a/native/cocos/platform/interfaces/modules/Device.cpp b/native/cocos/platform/interfaces/modules/Device.cpp index 070d630938..5baac986ec 100644 --- a/native/cocos/platform/interfaces/modules/Device.cpp +++ b/native/cocos/platform/interfaces/modules/Device.cpp @@ -30,9 +30,32 @@ #include "platform/interfaces/modules/INetwork.h" #include "platform/interfaces/modules/IScreen.h" #include "platform/interfaces/modules/IVibrator.h" +#include "platform/interfaces/modules/ISystemWindow.h" +#include "platform/interfaces/modules/ISystemWindowManager.h" namespace cc { +uint32_t Device::getInnerWidth() { + ISystemWindow* systemWindow = CC_GET_MAIN_SYSTEM_WINDOW(); + CC_ASSERT_NOT_NULL(systemWindow); + auto viewSize = systemWindow->getViewSize(); + return static_cast(viewSize.width); +} + +uint32_t Device::getInnerHeight() { + ISystemWindow* systemWindow = CC_GET_MAIN_SYSTEM_WINDOW(); + CC_ASSERT_NOT_NULL(systemWindow); + auto viewSize = systemWindow->getViewSize(); + return static_cast(viewSize.height); +} + +uintptr_t Device::getWindowHandle() { + ISystemWindow* systemWindow = CC_GET_MAIN_SYSTEM_WINDOW(); + CC_ASSERT_NOT_NULL(systemWindow); + auto handler = systemWindow->getWindowHandle(); + return static_cast(handler); +} + int Device::getDPI() { CC_ASSERT_NOT_NULL(CC_GET_PLATFORM_INTERFACE(IScreen)); return CC_GET_PLATFORM_INTERFACE(IScreen)->getDPI(); diff --git a/native/cocos/platform/interfaces/modules/Device.h b/native/cocos/platform/interfaces/modules/Device.h index 7fb9a6d865..ad720525b1 100644 --- a/native/cocos/platform/interfaces/modules/Device.h +++ b/native/cocos/platform/interfaces/modules/Device.h @@ -52,6 +52,9 @@ public: using Orientation = IScreen::Orientation; using MotionValue = IAccelerometer::MotionValue; + static uint32_t getInnerWidth(); + static uint32_t getInnerHeight(); + static uintptr_t getWindowHandle(); /** * Gets the DPI of device * @return The DPI of device. diff --git a/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp b/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp index 41e30e718b..7d68e2719a 100644 --- a/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp +++ b/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp @@ -44,6 +44,8 @@ #include "platform/linux/modules/CanvasRenderingContext2DDelegate.h" #elif (CC_PLATFORM == CC_PLATFORM_QNX) #include "platform/qnx/modules/CanvasRenderingContext2DDelegate.h" +#elif (CC_PLATFORM == CC_PLATFORM_OPENHARMONY) + #include "platform/openharmony/modules/CanvasRenderingContext2DDelegate.h" #endif using Vec2 = ccstd::array; @@ -293,7 +295,7 @@ void CanvasRenderingContext2D::setFont(const ccstd::string &font) { //SE_LOGD("CanvasRenderingContext2D::set_font: %s, Size: %f, isBold: %b\n", fontName.c_str(), fontSize, isBold); _delegate->updateFont(fontName, fontSize, isBold, isItalic, false, false); } -#elif CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS +#elif CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS || CC_PLATFORM == CC_PLATFORM_OPENHARMONY if (_font != font) { _font = font; ccstd::string fontName = "sans-serif"; diff --git a/native/cocos/platform/openharmony/FileUtils-OpenHarmony.cpp b/native/cocos/platform/openharmony/FileUtils-OpenHarmony.cpp new file mode 100644 index 0000000000..5420e347b0 --- /dev/null +++ b/native/cocos/platform/openharmony/FileUtils-OpenHarmony.cpp @@ -0,0 +1,285 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +#include "cocos/platform/openharmony/FileUtils-OpenHarmony.h" +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include "base/memory/Memory.h" + +#include "cocos/base/Log.h" + +#include "bindings/jswrapper/napi/HelperMacros.h" +#define ASSETS_FOLDER_WRITEABLE_PATH "/data/accounts/account_0/applications/ohos.example.xcomponent1/ohos.example.xcomponent1/writeable_path" +#include "rawfile/raw_file_manager.h" + +namespace cc { + +NativeResourceManager* FileUtilsOpenHarmony::_nativeResourceManager = nullptr; + +FileUtils *createFileUtils() { + return ccnew FileUtilsOpenHarmony(); +} + +FileUtilsOpenHarmony::FileUtilsOpenHarmony() { + init(); +} + +std::string FileUtilsOpenHarmony::_ohWritablePath; + +bool FileUtilsOpenHarmony::initResourceManager(napi_env env, napi_value param) { + _nativeResourceManager = OH_ResourceManager_InitNativeResourceManager(env, param); + return true; +} + +FileUtils::Status FileUtilsOpenHarmony::getRawFileDescriptor(const std::string &filename,RawFileDescriptor& descriptor) { + if (filename.empty()) { + return FileUtils::Status::NOT_EXISTS; + } + + std::string fullPath = fullPathForFilename(filename); + if (fullPath.empty()) { + return FileUtils::Status::NOT_EXISTS; + } + + if (nullptr == _nativeResourceManager) { + CC_LOG_ERROR("nativeResourceManager is nullptr"); + return FileUtils::Status::NOT_INITIALIZED; + } + + RawFile *rawFile = OH_ResourceManager_OpenRawFile(_nativeResourceManager, fullPath.c_str()); + if (nullptr == rawFile) { + return FileUtils::Status::OPEN_FAILED; + } + + bool result = OH_ResourceManager_GetRawFileDescriptor(rawFile, descriptor); + if (!result) { + OH_ResourceManager_CloseRawFile(rawFile); + return FileUtils::Status::OPEN_FAILED; + } + + OH_ResourceManager_CloseRawFile(rawFile); + return FileUtils::Status::OK; +} + +FileUtils::Status FileUtilsOpenHarmony::getContents(const std::string &filename, ResizableBuffer *buffer) { + if (filename.empty()) { + return FileUtils::Status::NOT_EXISTS; + } + + std::string fullPath = fullPathForFilename(filename); + if (fullPath.empty()) { + return FileUtils::Status::NOT_EXISTS; + } + + if (fullPath[0] == '/') { + return FileUtils::getContents(fullPath, buffer); + } + + if (nullptr == _nativeResourceManager) { + CC_LOG_ERROR("nativeResourceManager is nullptr"); + return FileUtils::Status::NOT_INITIALIZED; + } + + RawFile *rawFile = OH_ResourceManager_OpenRawFile(_nativeResourceManager, fullPath.c_str()); + if (nullptr == rawFile) { + return FileUtils::Status::OPEN_FAILED; + } + + auto size = OH_ResourceManager_GetRawFileSize(rawFile); + buffer->resize(size); + + assert(buffer->buffer()); + + int readsize = OH_ResourceManager_ReadRawFile(rawFile, buffer->buffer(), size); + // TODO(unknown): read error + if (readsize < size) { + if (readsize >= 0) { + buffer->resize(readsize); + } + OH_ResourceManager_CloseRawFile(rawFile); + return FileUtils::Status::READ_FAILED; + } + OH_ResourceManager_CloseRawFile(rawFile); + return FileUtils::Status::OK; +} + +FileUtilsOpenHarmony::~FileUtilsOpenHarmony() { + if(_nativeResourceManager) + OH_ResourceManager_ReleaseNativeResourceManager(_nativeResourceManager); +} + +bool FileUtilsOpenHarmony::init() { + _defaultResRootPath = ""; + return FileUtils::init(); +} + +bool FileUtilsOpenHarmony::isAbsolutePath(const std::string &strPath) const { + return !strPath.empty() && (strPath[0] == '/'); +} + +std::string FileUtilsOpenHarmony::getSuitableFOpen(const std::string &filenameUtf8) const { + return filenameUtf8; +} + +long FileUtilsOpenHarmony::getFileSize(const std::string &filepath) { + if (filepath.empty()) { + return 0; + } + + auto *fs = FileUtils::getInstance(); + + std::string fullPath = fs->fullPathForFilename(filepath); + if (fullPath.empty()) { + return 0; + } + if (nullptr == _nativeResourceManager) { + CC_LOG_ERROR("nativeResourceManager is nullptr"); + return 0; + } + + long filesize = 0; + RawFile* rawFile = OH_ResourceManager_OpenRawFile(_nativeResourceManager, fullPath.c_str()); + if(rawFile) { + filesize = OH_ResourceManager_GetRawFileSize(rawFile); + OH_ResourceManager_CloseRawFile(rawFile); + } + return filesize; +} + +std::string FileUtilsOpenHarmony::getWritablePath() const { + return _ohWritablePath; +} + +bool FileUtilsOpenHarmony::isFileExistInternal(const std::string &strFilePath) const { + if (strFilePath.empty()) { + return false; + } + std::string strPath = strFilePath; + if (!isAbsolutePath(strPath)) { // Not absolute path, add the default root path at the beginning. + strPath.insert(0, _defaultResRootPath); + } + + if (nullptr == _nativeResourceManager) { + CC_LOG_ERROR("nativeResourceManager is nullptr"); + return false; + } + + RawFile* rawFile = OH_ResourceManager_OpenRawFile(_nativeResourceManager, strPath.c_str()); + if(rawFile) { + OH_ResourceManager_CloseRawFile(rawFile); + return true; + } + return false; +} + +bool FileUtilsOpenHarmony::isDirectoryExistInternal(const std::string &dirPath) const { + if (dirPath.empty()) return false; + std::string dirPathMf = dirPath[dirPath.length() - 1] == '/' ? dirPath.substr(0, dirPath.length() - 1) : dirPath; + + if (dirPathMf[0] == '/') { + struct stat st; + return stat(dirPathMf.c_str(), &st) == 0 && S_ISDIR(st.st_mode); + } + + if (dirPathMf.find(_defaultResRootPath) == 0) { + dirPathMf = dirPathMf.substr(_defaultResRootPath.length(), dirPathMf.length()); + } + + if (nullptr == _nativeResourceManager) { + CC_LOG_ERROR("nativeResourceManager is nullptr"); + return false; + } + + RawDir* rawDir = OH_ResourceManager_OpenRawDir(_nativeResourceManager, dirPathMf.c_str()); + if(rawDir) { + OH_ResourceManager_CloseRawDir(rawDir); + return true; + } + return false; +} + +bool FileUtilsOpenHarmony::renameFile(const std::string &oldfullpath, const std::string &newfullpath) { + if (access(oldfullpath.c_str(), F_OK) != 0) { + return false; + } + if (rename(oldfullpath.c_str(), newfullpath.c_str()) != 0) { + if (access(newfullpath.c_str(), F_OK) == 0) { + remove(newfullpath.c_str()); + } + return false; + } + return true; +} + +bool FileUtilsOpenHarmony::removeFile(const std::string &filepath) { + return remove(filepath.c_str()) == 0; +} + +bool FileUtilsOpenHarmony::removeDirectory(const std::string &dirPath) { + DIR *directory = opendir(dirPath.c_str()); + if (!directory) { + return false; + } + struct dirent *dir{nullptr}; + struct stat st; + while ((dir = readdir(directory)) != NULL) { + if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0) { + continue; + } + std::string subPath = dirPath + '/' + dir->d_name; + if (lstat(subPath.c_str(), &st) == -1) { + continue; + } + if (S_ISDIR(st.st_mode)) { + if (!removeDirectory(subPath)) { + closedir(directory); + return false; + } + rmdir(subPath.c_str()); + } else if (S_ISREG(st.st_mode)) { + unlink(subPath.c_str()); + } else { + continue; + } + } + if (rmdir(dirPath.c_str()) == -1) { + closedir(directory); + return false; + } + closedir(directory); + return true; +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/openharmony/FileUtils-OpenHarmony.h b/native/cocos/platform/openharmony/FileUtils-OpenHarmony.h new file mode 100644 index 0000000000..9b84711f8a --- /dev/null +++ b/native/cocos/platform/openharmony/FileUtils-OpenHarmony.h @@ -0,0 +1,75 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +#pragma once +//clang-format off +#include +//clang-format on +#include +#include +#include +#include "base/Macros.h" +#include "cocos/platform/FileUtils.h" +#include + +class NativeResourceManager; + +namespace cc { + +class CC_DLL FileUtilsOpenHarmony : public FileUtils { +public: + FileUtilsOpenHarmony(); + ~FileUtilsOpenHarmony() override; + static bool initResourceManager(napi_env env, napi_value info); + + bool init() override; + + bool isAbsolutePath(const std::string &strPath) const override; + + std::string getWritablePath() const override; + + long getFileSize(const std::string &filepath) override; + + std::string getSuitableFOpen(const std::string &filenameUtf8) const override; + + FileUtils::Status getContents(const std::string &filename, ResizableBuffer *buffer) override; + + FileUtils::Status getRawFileDescriptor(const std::string &filename,RawFileDescriptor& descriptor); + + bool renameFile(const std::string &oldfullpath, const std::string &newfullpath) override; + bool removeFile(const std::string &filepath) override; + bool removeDirectory(const std::string &dirPath) override; + + static std::string _ohWritablePath; + +private: + bool isFileExistInternal(const std::string &strFilePath) const override; + + bool isDirectoryExistInternal(const std::string &dirPath) const override; + + friend class FileUtils; + static NativeResourceManager* _nativeResourceManager; +}; + +} // namespace cc diff --git a/native/cocos/platform/openharmony/OpenHarmonyPlatform.cpp b/native/cocos/platform/openharmony/OpenHarmonyPlatform.cpp new file mode 100644 index 0000000000..dd4ebf2665 --- /dev/null +++ b/native/cocos/platform/openharmony/OpenHarmonyPlatform.cpp @@ -0,0 +1,287 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +#include "platform/openharmony/OpenHarmonyPlatform.h" +#include "base/Macros.h" + +#include +#include + +#include "application/ApplicationManager.h" +#include "application/CocosApplication.h" +#include "platform/UniversalPlatform.h" + +#include "platform/openharmony/modules/SystemWindow.h" +#include "platform/openharmony/modules/SystemWindowManager.h" + +#include "platform/openharmony/modules/System.h" +#include "platform/empty/modules/Screen.h" +#include "platform/empty/modules/Accelerometer.h" +#include "platform/empty/modules/Battery.h" +#include "platform/empty/modules/Network.h" +#include "platform/empty/modules/Vibrator.h" + +#include +#include + +namespace { +void sendMsgToWorker(const cc::MessageType& type, OH_NativeXComponent* component, void* window) { + cc::OpenHarmonyPlatform* platform = dynamic_cast(cc::BasePlatform::getPlatform()); + CC_ASSERT(platform != nullptr); + cc::WorkerMessageData data{type, static_cast(component), window}; + platform->enqueue(data); +} + +void onSurfaceCreatedCB(OH_NativeXComponent* component, void* window) { + // It is possible that when the message is sent, the worker thread has not yet started. + //sendMsgToWorker(cc::MessageType::WM_XCOMPONENT_SURFACE_CREATED, component, window); + cc::ISystemWindowInfo info; + info.title = ""; + info.x = 0; + info.y = 0; + info.width = 0; + info.height = 0; + info.flags = 0; + info.externalHandle = window; + cc::ISystemWindowManager* windowMgr = + cc::OpenHarmonyPlatform::getInstance()->getInterface(); + windowMgr->createWindow(info); +} + +void dispatchTouchEventCB(OH_NativeXComponent* component, void* window) { + sendMsgToWorker(cc::MessageType::WM_XCOMPONENT_TOUCH_EVENT, component, window); +} + +void onSurfaceChangedCB(OH_NativeXComponent* component, void* window) { + sendMsgToWorker(cc::MessageType::WM_XCOMPONENT_SURFACE_CHANGED, component, window); +} + +void onSurfaceDestroyedCB(OH_NativeXComponent* component, void* window) { + sendMsgToWorker(cc::MessageType::WM_XCOMPONENT_SURFACE_DESTROY, component, window); +} + +} // namespace + +namespace cc { + +OpenHarmonyPlatform::OpenHarmonyPlatform() { + registerInterface(std::make_shared()); + registerInterface(std::make_shared()); + registerInterface(std::make_shared()); + registerInterface(std::make_shared()); + registerInterface(std::make_shared()); + registerInterface(std::make_shared()); + registerInterface(std::make_shared()); + + _callback.OnSurfaceCreated = onSurfaceCreatedCB; + _callback.OnSurfaceChanged = onSurfaceChangedCB; + _callback.OnSurfaceDestroyed = onSurfaceDestroyedCB; + _callback.DispatchTouchEvent = dispatchTouchEventCB; +} + +int32_t OpenHarmonyPlatform::init() { + return 0; +} + +OpenHarmonyPlatform* OpenHarmonyPlatform::getInstance() { + return dynamic_cast(BasePlatform::getPlatform()); +} + +int32_t OpenHarmonyPlatform::run(int argc, const char** argv) { + UniversalPlatform::run(argc, argv); + /* + if (_workerLoop) { + // Todo: Starting the timer in this way is inaccurate and will be fixed later. + uv_timer_init(_workerLoop, &_timerHandle); + // 1s = 1000ms = 60fps; + // 1000ms / 60fps = 16 ms/fps + uv_timer_start(&_timerHandle, &OpenHarmonyPlatform::timerCb, 16, true); + } + */ + return 0; +} + +void OpenHarmonyPlatform::setNativeXComponent(OH_NativeXComponent* component) { + _component = component; + OH_NativeXComponent_RegisterCallback(_component, &_callback); +} + +void OpenHarmonyPlatform::enqueue(const WorkerMessageData& msg) { + _messageQueue.enqueue(msg); + triggerMessageSignal(); +} + +void OpenHarmonyPlatform::triggerMessageSignal() { + if(_workerLoop != nullptr) { + // It is possible that when the message is sent, the worker thread has not yet started. + uv_async_send(&_messageSignal); + } +} + +bool OpenHarmonyPlatform::dequeue(WorkerMessageData* msg) { + return _messageQueue.dequeue(msg); +} + +// static +void OpenHarmonyPlatform::onMessageCallback(const uv_async_t* /* req */) { + void* window = nullptr; + WorkerMessageData msgData; + OpenHarmonyPlatform* platform = OpenHarmonyPlatform::getInstance(); + + while (true) { + //loop until all msg dispatch + if (!platform->dequeue(reinterpret_cast(&msgData))) { + // Queue has no data + break; + } + + if ((msgData.type >= MessageType::WM_XCOMPONENT_SURFACE_CREATED) && (msgData.type <= MessageType::WM_XCOMPONENT_SURFACE_DESTROY)) { + OH_NativeXComponent* nativexcomponet = reinterpret_cast(msgData.data); + CC_ASSERT(nativexcomponet != nullptr); + + if (msgData.type == MessageType::WM_XCOMPONENT_SURFACE_CREATED) { + platform->onSurfaceCreated(nativexcomponet, msgData.window); + } else if (msgData.type == MessageType::WM_XCOMPONENT_TOUCH_EVENT) { + platform->dispatchTouchEvent(nativexcomponet, msgData.window); + } else if (msgData.type == MessageType::WM_XCOMPONENT_SURFACE_CHANGED) { + platform->onSurfaceChanged(nativexcomponet, msgData.window); + } else if (msgData.type == MessageType::WM_XCOMPONENT_SURFACE_DESTROY) { + platform->onSurfaceDestroyed(nativexcomponet, msgData.window); + } else { + CC_ASSERT(false); + } + continue; + } + + if (msgData.type == MessageType::WM_APP_SHOW) { + platform->onShowNative(); + } else if (msgData.type == MessageType::WM_APP_HIDE) { + platform->onHideNative(); + } else if (msgData.type == MessageType::WM_APP_DESTROY) { + platform->onDestroyNative(); + } + if(msgData.type == MessageType::WM_VSYNC) { + platform->runTask(); + } + // CC_ASSERT(false); + //} + + } +} + +void OpenHarmonyPlatform::onCreateNative(napi_env env, uv_loop_t* loop) { +} + +void OpenHarmonyPlatform::onShowNative() { + WindowEvent ev; + ev.type = WindowEvent::Type::SHOW; + events::WindowEvent::broadcast(ev); +} + +void OpenHarmonyPlatform::onHideNative() { + WindowEvent ev; + ev.type = WindowEvent::Type::HIDDEN; + events::WindowEvent::broadcast(ev); +} + +void OpenHarmonyPlatform::onDestroyNative() { + onDestroy(); +} + +void OpenHarmonyPlatform::timerCb(uv_timer_t* handle) { + OpenHarmonyPlatform::getInstance()->runTask(); +} + +void OpenHarmonyPlatform::workerInit(napi_env env, uv_loop_t* loop) { + _workerLoop = loop; + if (_workerLoop) { + uv_async_init(_workerLoop, &_messageSignal, reinterpret_cast(OpenHarmonyPlatform::onMessageCallback)); + } +} + +void OpenHarmonyPlatform::requestVSync() { + //CC_LOG_ERROR("OpenHarmonyPlatform::requestVSync1"); + //OH_NativeVSync_RequestFrame(OpenHarmonyPlatform::getInstance()->_nativeVSync, OnVSync, nullptr); + if (_workerLoop) { + // // Todo: Starting the timer in this way is inaccurate and will be fixed later. + uv_timer_init(_workerLoop, &_timerHandle); + // The tick function needs to be called as quickly as possible because it is controlling the frame rate inside the engine. + uv_timer_start(&_timerHandle, &OpenHarmonyPlatform::timerCb, 0, 1); + } + //CC_LOG_ERROR("OpenHarmonyPlatform::requestVSync2"); +} + +int32_t OpenHarmonyPlatform::loop() { + return 0; +} + +void OpenHarmonyPlatform::onSurfaceCreated(OH_NativeXComponent* component, void* window) { + +} + +void OpenHarmonyPlatform::onSurfaceChanged(OH_NativeXComponent* component, void* window) { +} + +void OpenHarmonyPlatform::onSurfaceDestroyed(OH_NativeXComponent* component, void* window) { + SystemWindow* systemWindowIntf = getPlatform()->getInterface(); + systemWindowIntf->setWindowHandle(nullptr); +} + +void OpenHarmonyPlatform::dispatchTouchEvent(OH_NativeXComponent* component, void* window) { + OH_NativeXComponent_TouchEvent touchEvent; + int32_t ret = OH_NativeXComponent_GetTouchEvent(component, window, &touchEvent); + if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) { + return; + } + + TouchEvent ev; + ev.windowId = 1; + if (touchEvent.type == OH_NATIVEXCOMPONENT_DOWN) { + ev.type = cc::TouchEvent::Type::BEGAN; + } else if (touchEvent.type == OH_NATIVEXCOMPONENT_MOVE) { + ev.type = cc::TouchEvent::Type::MOVED; + } else if (touchEvent.type == OH_NATIVEXCOMPONENT_UP) { + ev.type = cc::TouchEvent::Type::ENDED; + } else if (touchEvent.type == OH_NATIVEXCOMPONENT_CANCEL) { + ev.type = cc::TouchEvent::Type::CANCELLED; + } + for(int i = 0; i < touchEvent.numPoints; ++i) { + ev.touches.emplace_back(touchEvent.touchPoints[i].x, touchEvent.touchPoints[i].y, touchEvent.touchPoints[i].id); + } + + events::Touch::broadcast(ev); +} + +ISystemWindow *OpenHarmonyPlatform::createNativeWindow(uint32_t windowId, void *externalHandle) { + SystemWindow* window = ccnew SystemWindow(windowId, externalHandle); + uint64_t width = 0; + uint64_t height = 0; + CC_ASSERT_NOT_NULL(_component); + int32_t ret = OH_NativeXComponent_GetXComponentSize(_component, externalHandle, &width, &height); + CC_ASSERT(ret == OH_NATIVEXCOMPONENT_RESULT_SUCCESS); + window->setViewSize(width, height); + return window; +} + +}; // namespace cc diff --git a/native/cocos/platform/openharmony/OpenHarmonyPlatform.h b/native/cocos/platform/openharmony/OpenHarmonyPlatform.h new file mode 100644 index 0000000000..a22eb23140 --- /dev/null +++ b/native/cocos/platform/openharmony/OpenHarmonyPlatform.h @@ -0,0 +1,82 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "platform/UniversalPlatform.h" + +#include + +#include +#include +#include +#include + +#include "platform/openharmony/WorkerMessageQueue.h" + +namespace cc { +class OpenHarmonyPlatform : public UniversalPlatform { +public: + OpenHarmonyPlatform(); + int32_t init() override; + static OpenHarmonyPlatform* getInstance(); + + void onCreateNative(napi_env env, uv_loop_t* loop); + void onShowNative(); + void onHideNative(); + void onDestroyNative(); + + void workerInit(napi_env env, uv_loop_t* loop); + + void setNativeXComponent(OH_NativeXComponent* component); + + int32_t run(int argc, const char** argv) override; + int32_t loop() override; + + void requestVSync(); + + void enqueue(const WorkerMessageData& data); + bool dequeue(WorkerMessageData* data); + + void triggerMessageSignal(); + ISystemWindow *createNativeWindow(uint32_t windowId, void *externalHandle) override; +public: + // Callback, called by ACE XComponent + void onSurfaceCreated(OH_NativeXComponent* component, void* window); + void onSurfaceChanged(OH_NativeXComponent* component, void* window); + void onSurfaceDestroyed(OH_NativeXComponent* component, void* window); + void dispatchTouchEvent(OH_NativeXComponent* component, void* window); + + static void onMessageCallback(const uv_async_t* req); + static void timerCb(uv_timer_t* handle); + + OH_NativeXComponent* _component{nullptr}; + OH_NativeXComponent_Callback _callback; + uv_timer_t _timerHandle; + uv_loop_t* _workerLoop{nullptr}; + uv_async_t _messageSignal{}; + WorkerMessageQueue _messageQueue; +}; +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/openharmony/WorkerMessageQueue.cpp b/native/cocos/platform/openharmony/WorkerMessageQueue.cpp new file mode 100644 index 0000000000..7dfc9aa31a --- /dev/null +++ b/native/cocos/platform/openharmony/WorkerMessageQueue.cpp @@ -0,0 +1,49 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "platform/openharmony/WorkerMessageQueue.h" + +namespace cc { + +void WorkerMessageQueue::enqueue(const WorkerMessageData& data) { + std::lock_guard lck(_mutex); + _queue.push(data); +} + +bool WorkerMessageQueue::dequeue(WorkerMessageData *data) { + std::lock_guard lck(_mutex); + if (empty()) { + return false; + } + *data = _queue.front(); + _queue.pop(); + return true; +} + +bool WorkerMessageQueue::empty() const { + return _queue.empty(); +} + +} // namespace cc diff --git a/native/cocos/platform/openharmony/WorkerMessageQueue.h b/native/cocos/platform/openharmony/WorkerMessageQueue.h new file mode 100644 index 0000000000..ec0743e131 --- /dev/null +++ b/native/cocos/platform/openharmony/WorkerMessageQueue.h @@ -0,0 +1,67 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include + +#include +#include + + +namespace cc { + +enum class MessageType { + WM_XCOMPONENT_SURFACE_CREATED = 0, + WM_XCOMPONENT_TOUCH_EVENT, + WM_XCOMPONENT_SURFACE_CHANGED, + WM_XCOMPONENT_SURFACE_DESTROY, + WM_APP_SHOW, + WM_APP_HIDE, + WM_APP_DESTROY, + WM_VSYNC, +}; + +struct WorkerMessageData { + MessageType type; + void* data; + void* window; +}; + +class WorkerMessageQueue final { +public: + void enqueue(const WorkerMessageData& data); + bool dequeue(WorkerMessageData *data); + bool empty() const; + size_t size() const { + return _queue.size(); + } + +private: + std::mutex _mutex; + std::queue _queue; +}; + +} // namespace cc diff --git a/native/cocos/platform/openharmony/modules/Accelerometer.cpp b/native/cocos/platform/openharmony/modules/Accelerometer.cpp new file mode 100644 index 0000000000..f1d7acd6d0 --- /dev/null +++ b/native/cocos/platform/openharmony/modules/Accelerometer.cpp @@ -0,0 +1,62 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "platform/openharmony/modules/Accelerometer.h" +#include "platform/openharmony/napi/NapiHelper.h" +namespace cc { + +void Accelerometer::setAccelerometerEnabled(bool isEnabled) { + //setAccelerometerEnabledJNI(isEnabled); +} + +void Accelerometer::setAccelerometerInterval(float interval) { + //setAccelerometerIntervalJNI(interval); +} + +const Accelerometer::MotionValue &Accelerometer::getDeviceMotionValue() { + + ccstd::vector v; + NapiHelper::napiCallFunction >("getDeviceMotionValue", &v); + static MotionValue motionValue; + if (!v.empty()) { + + motionValue.accelerationIncludingGravityX = v[0]; + motionValue.accelerationIncludingGravityY = v[1]; + motionValue.accelerationIncludingGravityZ = v[2]; + + motionValue.accelerationX = v[3]; + motionValue.accelerationY = v[4]; + motionValue.accelerationZ = v[5]; + + motionValue.rotationRateAlpha = v[6]; + motionValue.rotationRateBeta = v[7]; + motionValue.rotationRateGamma = v[8]; + } else { + memset(&motionValue, 0, sizeof(motionValue)); + } + return motionValue; +} + +} // namespace cc diff --git a/native/cocos/platform/openharmony/modules/Accelerometer.h b/native/cocos/platform/openharmony/modules/Accelerometer.h new file mode 100644 index 0000000000..419b723696 --- /dev/null +++ b/native/cocos/platform/openharmony/modules/Accelerometer.h @@ -0,0 +1,50 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IAccelerometer.h" + +namespace cc { + +class Accelerometer : public IAccelerometer { +public: + /** + * To enable or disable accelerometer. + */ + void setAccelerometerEnabled(bool isEnabled) override; + + /** + * Sets the interval of accelerometer. + */ + void setAccelerometerInterval(float interval) override; + + /** + * Gets the motion value of current device. + */ + const MotionValue &getDeviceMotionValue() override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/openharmony/modules/Battery.cpp b/native/cocos/platform/openharmony/modules/Battery.cpp new file mode 100644 index 0000000000..aac590a90f --- /dev/null +++ b/native/cocos/platform/openharmony/modules/Battery.cpp @@ -0,0 +1,37 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "platform/openharmony/modules/Battery.h" +#include "platform/openharmony/napi/NapiHelper.h" + +namespace cc { + +float Battery::getBatteryLevel() const { + int32_t value; + NapiHelper::napiCallFunction("getBatteryLevel", &value); + return value; +} + +} // namespace cc diff --git a/native/cocos/platform/openharmony/modules/Battery.h b/native/cocos/platform/openharmony/modules/Battery.h new file mode 100644 index 0000000000..8f0373c8f1 --- /dev/null +++ b/native/cocos/platform/openharmony/modules/Battery.h @@ -0,0 +1,37 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IBattery.h" + +namespace cc { + +class Battery : public IBattery { +public: + float getBatteryLevel() const override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.cpp b/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.cpp new file mode 100644 index 0000000000..953aa8ccbd --- /dev/null +++ b/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.cpp @@ -0,0 +1,335 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. \ + ****************************************************************************/ + +#include "platform/openharmony/modules/CanvasRenderingContext2DDelegate.h" +#include "platform/openharmony/OpenHarmonyPlatform.h" +#include +#include +#include +#include +#include + + +namespace cc { +class CanvasRenderingContext2DDelegate::ScopedTypography { +public: + ScopedTypography(OH_Drawing_Typography* typography) :_typegraphy(typography) {} + ~ScopedTypography() { + if(_typegraphy) { + OH_Drawing_DestroyTypography(_typegraphy); + } + } + OH_Drawing_Typography* get() { + return _typegraphy; + } +private: + OH_Drawing_Typography* _typegraphy{nullptr}; +}; + +CanvasRenderingContext2DDelegate::CanvasRenderingContext2DDelegate() { + _typographyStyle = OH_Drawing_CreateTypographyStyle(); + OH_Drawing_SetTypographyTextDirection(_typographyStyle, TEXT_DIRECTION_LTR); + OH_Drawing_SetTypographyTextAlign(_typographyStyle, TEXT_ALIGN_LEFT); + + _fontCollection = OH_Drawing_CreateFontCollection(); + _typographyCreate = OH_Drawing_CreateTypographyHandler(_typographyStyle, _fontCollection); + _textStyle = OH_Drawing_CreateTextStyle(); +} + +CanvasRenderingContext2DDelegate::~CanvasRenderingContext2DDelegate() { + if(_typographyStyle) { + OH_Drawing_DestroyTypographyStyle(_typographyStyle); + _typographyStyle = nullptr; + } + + if(_fontCollection) { + OH_Drawing_DestroyFontCollection(_fontCollection); + } + + if(_typographyCreate) { + OH_Drawing_DestroyTypographyHandler(_typographyCreate); + _typographyCreate = nullptr; + } + + if(_textStyle) { + OH_Drawing_DestroyTextStyle(_textStyle); + _textStyle = nullptr; + } + + if(_canvas) { + OH_Drawing_CanvasDestroy(_canvas); + _canvas = nullptr; + } + + if(_bitmap) { + OH_Drawing_BitmapDestroy(_bitmap); + _bitmap = nullptr; + } +} + +void CanvasRenderingContext2DDelegate::recreateBuffer(float w, float h) { + _bufferWidth = w; + _bufferHeight = h; + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + + if(_canvas) { + OH_Drawing_CanvasDestroy(_canvas); + _canvas = nullptr; + } + if(_bitmap) { + OH_Drawing_BitmapDestroy(_bitmap); + _bitmap = nullptr; + } + + _bufferSize = static_cast(_bufferWidth * _bufferHeight * 4); + auto *data = static_cast(malloc(sizeof(uint8_t) * _bufferSize)); + memset(data, 0x00, _bufferSize); + _imageData.fastSet(data, _bufferSize); + + _bitmap = OH_Drawing_BitmapCreate(); + OH_Drawing_BitmapBuild(_bitmap, _bufferWidth, _bufferHeight, &_format); + _canvas = OH_Drawing_CanvasCreate(); + OH_Drawing_CanvasBind(_canvas, _bitmap); +} + +void CanvasRenderingContext2DDelegate::beginPath() { +} + +void CanvasRenderingContext2DDelegate::closePath() { +} + +void CanvasRenderingContext2DDelegate::moveTo(float x, float y) { + //MoveToEx(_DC, static_cast(x), static_cast(-(y - _bufferHeight - _fontSize)), nullptr); + _x = x; + _y = y; +} + +void CanvasRenderingContext2DDelegate::lineTo(float x, float y) { +} + +void CanvasRenderingContext2DDelegate::stroke() { +} + +void CanvasRenderingContext2DDelegate::saveContext() { +} + +void CanvasRenderingContext2DDelegate::restoreContext() { +} + +void CanvasRenderingContext2DDelegate::clearRect(float x, float y, float w, float h) { + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + + if (_imageData.isNull()) { + return; + } + + recreateBuffer(w, h); +} + +void CanvasRenderingContext2DDelegate::fillRect(float x, float y, float w, float h) { + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { + return; + } + uint8_t r = static_cast(_fillStyle[0]); + uint8_t g = static_cast(_fillStyle[1]); + uint8_t b = static_cast(_fillStyle[2]); + uint8_t a = static_cast(_fillStyle[3]); + + // OH_Drawing_Path* path = OH_Drawing_PathCreate(); + // OH_Drawing_PathMoveTo(path, x, y); + // OH_Drawing_PathLineTo(path, x + w, y); + // OH_Drawing_PathLineTo(path, x + w, y + h); + // OH_Drawing_PathLineTo(path, x, y + h); + // OH_Drawing_PathLineTo(path, x, y); + // OH_Drawing_PathClose(path); + OH_Drawing_CanvasClear(_canvas, OH_Drawing_ColorSetArgb(a, r, g, b)); +} + +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); + drawText(text, (int)offsetPoint[0], (int)offsetPoint[1]); +} + +void CanvasRenderingContext2DDelegate::strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const { +} + +CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::measureText(const ccstd::string &text) { + auto typography = createTypography(text); + return ccstd::array{static_cast(OH_Drawing_TypographyGetMaxIntrinsicWidth(typography->get())), + static_cast(OH_Drawing_TypographyGetHeight(typography->get()))}; +} + +void CanvasRenderingContext2DDelegate::updateFont(const ccstd::string &fontName, + float fontSize, + bool bold, + bool italic, + bool oblique, + bool /* smallCaps */) { + _fontName = fontName; + _fontSize = static_cast(fontSize); + ccstd::string fontPath; + if (!_fontName.empty()) { + const char* fontFamilies[1]; + fontFamilies[0] = fontName.c_str(); + OH_Drawing_SetTextStyleFontFamilies(_textStyle, 1, fontFamilies); + OH_Drawing_SetTextStyleLocale(_textStyle, "en"); + } + 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); +} + +void CanvasRenderingContext2DDelegate::setTextAlign(TextAlign align) { + _textAlign = align; +} + +void CanvasRenderingContext2DDelegate::setTextBaseline(TextBaseline baseline) { + _textBaseLine = baseline; +} + +void CanvasRenderingContext2DDelegate::setFillStyle(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { + _fillStyle = {r / 255.0F, g / 255.0F, b / 255.0F, a / 255.0F}; + OH_Drawing_SetTextStyleColor(_textStyle, OH_Drawing_ColorSetArgb(a, r, g, b)); +} + +void CanvasRenderingContext2DDelegate::setStrokeStyle(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { +_strokeStyle = {r / 255.0F, g / 255.0F, b / 255.0F, a / 255.0F}; +} + +void CanvasRenderingContext2DDelegate::setLineWidth(float lineWidth) { + _lineWidth = lineWidth; +} + +const cc::Data &CanvasRenderingContext2DDelegate::getDataRef() const { + void* bitmapAddr = OH_Drawing_BitmapGetPixels(_bitmap); + memcpy(_imageData.getBytes(), bitmapAddr, _bufferSize); + return _imageData; +} + +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); + return 0; +} + +CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::sizeWithText(const wchar_t *pszText, int nLen) { + return ccstd::array{0.0F, 0.0F}; +} + +void CanvasRenderingContext2DDelegate::prepareBitmap(int nWidth, int nHeight) { +} + +void CanvasRenderingContext2DDelegate::deleteBitmap() { +} + +void CanvasRenderingContext2DDelegate::fillTextureData() { +} + +ccstd::array CanvasRenderingContext2DDelegate::convertDrawPoint(Point point, const ccstd::string &text) { + auto typography = createTypography(text); + 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) { + point[0] -= textSize[0]; + } + double alphabeticBaseLine = OH_Drawing_TypographyGetAlphabeticBaseline(typography->get()); + if (_textBaseLine == TextBaseline::TOP) { + //point[1] += -alphabeticBaseLine; + } else if (_textBaseLine == TextBaseline::MIDDLE) { + point[1] += -textSize[1] / 2.0f; + } else if (_textBaseLine == TextBaseline::BOTTOM) { + point[1] += -textSize[1]; + } else if (_textBaseLine == TextBaseline::ALPHABETIC) { + //GetTextMetrics(_DC, &_tm); + //point[1] -= _tm.tmAscent; + point[1] -= alphabeticBaseLine; + } + return point; +} + +std::unique_ptr CanvasRenderingContext2DDelegate::createTypography(const ccstd::string &text) { + OH_Drawing_TypographyHandlerPushTextStyle(_typographyCreate, _textStyle); + OH_Drawing_TypographyHandlerAddText(_typographyCreate, text.c_str()); + OH_Drawing_TypographyHandlerPopTextStyle(_typographyCreate); + OH_Drawing_Typography* typography = OH_Drawing_CreateTypography(_typographyCreate); + OH_Drawing_TypographyLayout(typography, _bufferWidth); + return std::make_unique(typography); +} + + +void CanvasRenderingContext2DDelegate::fill() { +} + +void CanvasRenderingContext2DDelegate::setLineCap(const ccstd::string &lineCap) { +} + +void CanvasRenderingContext2DDelegate::setLineJoin(const ccstd::string &lineJoin) { +} + +void CanvasRenderingContext2DDelegate::fillImageData(const Data & /* imageData */, + float /* imageWidth */, + float /* imageHeight */, + float /* offsetX */, + float /* offsetY */) { +} + +void CanvasRenderingContext2DDelegate::strokeText(const ccstd::string & /* text */, + float /* x */, + float /* y */, + float /* maxWidth */) { +} + +void CanvasRenderingContext2DDelegate::rect(float /* x */, + float /* y */, + float /* w */, + float /* h */) { +} + +void CanvasRenderingContext2DDelegate::updateData() { + +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.h b/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.h new file mode 100644 index 0000000000..479fd1b9b4 --- /dev/null +++ b/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.h @@ -0,0 +1,136 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h" + +#include +#include +#include +#include + +#include +#include +#include + +#include "base/csscolorparser.h" +#include "cocos/bindings/manual/jsb_platform.h" +#include "math/Math.h" +#include "platform/FileUtils.h" + +namespace cc { + +class CanvasRenderingContext2DDelegate : public ICanvasRenderingContext2D::Delegate { +public: + using Point = ccstd::array; + using Vec2 = ccstd::array; + using Size = ccstd::array; + using Color4F = ccstd::array; + using TextAlign = ICanvasRenderingContext2D::TextAlign; + using TextBaseline = ICanvasRenderingContext2D::TextBaseline; + + CanvasRenderingContext2DDelegate(); + ~CanvasRenderingContext2DDelegate() override; + + void recreateBuffer(float w, float h) override; + void beginPath() override; + void closePath() override; + void moveTo(float x, float y) override; + void lineTo(float x, float y) override; + void stroke() override; + void saveContext() override; + void restoreContext() override; + 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; + 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; + void setTextBaseline(TextBaseline baseline) override; + void setFillStyle(uint8_t r, uint8_t g, uint8_t b, uint8_t a) override; + void setStrokeStyle(uint8_t r, uint8_t g, uint8_t b, uint8_t a) override; + void setLineWidth(float lineWidth) override; + const cc::Data &getDataRef() const override; + void fill() override; + 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; +private: + static wchar_t * utf8ToUtf16(const ccstd::string &str, int *pRetLen = nullptr); + void removeCustomFont(); + int drawText(const ccstd::string &text, int x, int y); + Size sizeWithText(const wchar_t *pszText, int nLen); + void prepareBitmap(int nWidth, int nHeight); + void deleteBitmap(); + void fillTextureData(); + ccstd::array convertDrawPoint(Point point, const ccstd::string &text); + + class ScopedTypography; + std::unique_ptr createTypography(const ccstd::string &text); +public: + int _screen{0}; + +private: + + int32_t _x{0}; + int32_t _y{0}; + int32_t _lineCap{0}; + int32_t _lineJoin{0}; + +private: + OH_Drawing_Bitmap* _bitmap{nullptr}; + OH_Drawing_BitmapFormat _format {COLOR_FORMAT_RGBA_8888, ALPHA_FORMAT_OPAQUE}; + OH_Drawing_Canvas* _canvas{nullptr}; + OH_Drawing_TypographyStyle* _typographyStyle{nullptr}; + OH_Drawing_TypographyCreate* _typographyCreate{nullptr}; + OH_Drawing_FontCollection* _fontCollection{nullptr}; + OH_Drawing_TextStyle* _textStyle{nullptr}; + cc::Data _imageData; + ccstd::string _curFontPath; + int _savedDC{0}; + float _lineWidth{0.0F}; + float _bufferWidth{0.0F}; + float _bufferHeight{0.0F}; + int32_t _bufferSize{0}; + + ccstd::string _fontName; + int _fontSize{0}; + Size _textSize; + TextAlign _textAlign{TextAlign::CENTER}; + TextBaseline _textBaseLine{TextBaseline::TOP}; + Color4F _fillStyle{0}; + Color4F _strokeStyle{0}; +}; + +} // namespace cc diff --git a/native/cocos/platform/openharmony/modules/Screen.cpp b/native/cocos/platform/openharmony/modules/Screen.cpp new file mode 100644 index 0000000000..994b04287e --- /dev/null +++ b/native/cocos/platform/openharmony/modules/Screen.cpp @@ -0,0 +1,85 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "platform/openharmony/modules/Screen.h" +#include "platform/openharmony/napi/NapiHelper.h" + +namespace cc { + +int Screen::getDPI() const { + float value; + NapiHelper::napiCallFunction("getDPI", &value); + return value; +} + +float Screen::getDevicePixelRatio() const { + // float value; + // NapiHelper::napiCallFunction("getPixelRation", &value); + // return value; + // TODO(qgh):openharmony does support this interface, but returning a value of 1.5 will cause the entire page to zoom in. + return 1; +} + +Screen::Orientation Screen::getDeviceOrientation() const { + int32_t value = 0; + NapiHelper::napiCallFunction("getDeviceOrientation", &value); + if(value == 0) { + return Orientation::PORTRAIT; + } else if(value == 1) { + return Orientation::LANDSCAPE_LEFT; + } else if(value == 2) { + return Orientation::PORTRAIT_UPSIDE_DOWN; + } else if(value == 3) { + return Orientation::LANDSCAPE_RIGHT; + } + CC_ASSERT(false); + return Orientation::PORTRAIT; +} + +void Screen::setKeepScreenOn(bool value) { + CC_UNUSED_PARAM(value); +} + +Vec4 Screen::getSafeAreaEdge() const { + return cc::Vec4(); +} + +bool Screen::isDisplayStats() { + se::AutoHandleScope hs; + se::Value ret; + char commandBuf[100] = "cc.profiler.isShowingStats();"; + se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret); + return ret.toBoolean(); +} + +void Screen::setDisplayStats(bool isShow) { + se::AutoHandleScope hs; + char commandBuf[100] = {0}; + sprintf(commandBuf, isShow ? "cc.profiler.showStats();" : "cc.profiler.hideStats();"); + se::ScriptEngine::getInstance()->evalString(commandBuf); +} + + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/openharmony/modules/Screen.h b/native/cocos/platform/openharmony/modules/Screen.h new file mode 100644 index 0000000000..1277231d5d --- /dev/null +++ b/native/cocos/platform/openharmony/modules/Screen.h @@ -0,0 +1,51 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/IScreen.h" + +namespace cc { + +class Screen : public IScreen { +public: + int getDPI() const override; + float getDevicePixelRatio() const override; + void setKeepScreenOn(bool value) override; + Orientation getDeviceOrientation() const override; + Vec4 getSafeAreaEdge() const override; + /** + @brief Get current display stats. + @return bool, is displaying stats or not. + */ + bool isDisplayStats() override; + + /** + @brief set display stats information. + */ + void setDisplayStats(bool isShow) override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/openharmony/modules/System.cpp b/native/cocos/platform/openharmony/modules/System.cpp new file mode 100644 index 0000000000..ac58b35b50 --- /dev/null +++ b/native/cocos/platform/openharmony/modules/System.cpp @@ -0,0 +1,106 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "platform/openharmony/modules/System.h" +#include +#include "platform/openharmony/napi/NapiHelper.h" + +namespace cc { +System::System() = default; +System::~System() = default; + +System::OSType System::getOSType() const { + return OSType::OHOS; +} + +std::string System::getDeviceModel() const { + return ""; +} + +System::LanguageType System::getCurrentLanguage() const { + ccstd::string languageStr = getCurrentLanguageCode(); // NOLINT + if (languageStr == "en") { + return ISystem::LanguageType::ENGLISH; + } else if (languageStr == "zh") { + return ISystem::LanguageType::CHINESE; + } else if (languageStr == "fr") { + return ISystem::LanguageType::FRENCH; + } else if (languageStr == "it") { + return ISystem::LanguageType::ITALIAN; + } else if (languageStr == "de") { + return ISystem::LanguageType::GERMAN; + } else if (languageStr == "es") { + return ISystem::LanguageType::SPANISH; + } else if (languageStr == "du") { + return ISystem::LanguageType::DUTCH; + } else if (languageStr == "ru") { + return ISystem::LanguageType::RUSSIAN; + } else if (languageStr == "ko") { + return ISystem::LanguageType::KOREAN; + } else if (languageStr == "ja") { + return ISystem::LanguageType::JAPANESE; + } else if (languageStr == "hu") { + return ISystem::LanguageType::HUNGARIAN; + } else if (languageStr == "pt") { + return ISystem::LanguageType::PORTUGUESE; + } else if (languageStr == "ar") { + return ISystem::LanguageType::ARABIC; + } else if (languageStr == "no") { + return ISystem::LanguageType::NORWEGIAN; + } else if (languageStr == "pl") { + return ISystem::LanguageType::POLISH; + } else if (languageStr == "tr") { + return ISystem::LanguageType::TURKISH; + } else if (languageStr == "uk") { + return ISystem::LanguageType::UKRAINIAN; + } else if (languageStr == "ro") { + return ISystem::LanguageType::ROMANIAN; + } else if (languageStr == "bg") { + return ISystem::LanguageType::BULGARIAN; + } + return ISystem::LanguageType::ENGLISH; +} + +std::string System::getCurrentLanguageCode() const { + std::string str; + NapiHelper::napiCallFunction("getSystemLanguage", &str); + std::string::size_type pos = str.find('-'); + if(pos != std::string::npos) { + str = str.substr(0, pos); + } + return str; +} + +std::string System::getSystemVersion() const { + std::string str; + NapiHelper::napiCallFunction("getOSFullName", &str); + return str; +} + +bool System::openURL(const std::string& url) { + return false; +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/openharmony/modules/System.h b/native/cocos/platform/openharmony/modules/System.h new file mode 100644 index 0000000000..b1b5ab36a2 --- /dev/null +++ b/native/cocos/platform/openharmony/modules/System.h @@ -0,0 +1,67 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "platform/interfaces/modules/ISystem.h" + +class ANativeWindow; + +namespace cc { + +class System : public ISystem { +public: + System(); + ~System() override; + + OSType getOSType() const override; + /** + @brief Get target device model. + */ + std::string getDeviceModel() const override; + /** + @brief Get current language config. + @return Current language config. + */ + LanguageType getCurrentLanguage() const override; + /** + @brief Get current language iso 639-1 code. + @return Current language iso 639-1 code. + */ + std::string getCurrentLanguageCode() const override; + /** + @brief Get system version. + @return system version. + */ + std::string getSystemVersion() const override; + /** + @brief Open url in default browser. + @param String with url to open. + @return True if the resource located by the URL was successfully opened; otherwise false. + */ + bool openURL(const std::string& url) override; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/openharmony/modules/SystemWindow.cpp b/native/cocos/platform/openharmony/modules/SystemWindow.cpp new file mode 100644 index 0000000000..22ef3c10a1 --- /dev/null +++ b/native/cocos/platform/openharmony/modules/SystemWindow.cpp @@ -0,0 +1,89 @@ +/**************************************************************************** + Copyright (c) 2021-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "platform/openharmony/modules/SystemWindow.h" +#include "base/Log.h" +#include "base/Macros.h" +#include "platform/openharmony/OpenHarmonyPlatform.h" + +namespace cc { + +SystemWindow::SystemWindow(uint32_t windowId, void *externalHandle) +: _windowId(windowId) { + if (externalHandle) { + _windowHandle = reinterpret_cast(externalHandle); + } +} + +SystemWindow::~SystemWindow() { + _windowHandle = 0; + _windowId = 0; +} + +bool SystemWindow::createWindow(const char* title, + int x, int y, int w, + int h, int flags) { + CC_UNUSED_PARAM(title); + CC_UNUSED_PARAM(x); + CC_UNUSED_PARAM(y); + CC_UNUSED_PARAM(flags); + + _width = w; + _height = h; + return true; +} + + +void SystemWindow::setCursorEnabled(bool value) { +} + +void SystemWindow::copyTextToClipboard(const std::string& text) { + //copyTextToClipboardJNI(text); +} + +uint32_t SystemWindow::getWindowId() const { + return _windowId; +} + +uintptr_t SystemWindow::getWindowHandle() const { + return reinterpret_cast(_windowHandle); +} + +void SystemWindow::setWindowHandle(void* window) { + _windowHandle = window; +} + +void SystemWindow::setViewSize(uint32_t width, uint32_t height) { + _width = width; + _height = height; +} + +SystemWindow::Size SystemWindow::getViewSize() const { + return Size{static_cast(_width), + static_cast(_height)}; +} + + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/openharmony/modules/SystemWindow.h b/native/cocos/platform/openharmony/modules/SystemWindow.h new file mode 100644 index 0000000000..91fe8d7973 --- /dev/null +++ b/native/cocos/platform/openharmony/modules/SystemWindow.h @@ -0,0 +1,63 @@ +/**************************************************************************** + Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include + +#include "platform/interfaces/modules/ISystemWindow.h" +#include + +namespace cc { + +class SystemWindow : public ISystemWindow { +public: + explicit SystemWindow(uint32_t windowId, void* externalHandle); + ~SystemWindow() override; + + bool createWindow(const char* title, + int x, int y, int w, + int h, int flags) override; + + uint32_t getWindowId() const override; + uintptr_t getWindowHandle() const override; + void setWindowHandle(void* window); + Size getViewSize() const override; + void setViewSize(uint32_t width, uint32_t height) override; + + /** + @brief enable/disable(lock) the cursor, default is enabled + */ + void setCursorEnabled(bool value) override; + void copyTextToClipboard(const std::string& text) override; +private: + void* _windowHandle{nullptr}; + uint32_t _windowId{0}; + std::string _id{""}; + uint64_t _width{0}; + uint64_t _height{0}; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/openharmony/modules/SystemWindowManager.cpp b/native/cocos/platform/openharmony/modules/SystemWindowManager.cpp new file mode 100644 index 0000000000..61514aba27 --- /dev/null +++ b/native/cocos/platform/openharmony/modules/SystemWindowManager.cpp @@ -0,0 +1,63 @@ +/**************************************************************************** + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "SystemWindowManager.h" +#include "platform/BasePlatform.h" +#include "platform/SDLHelper.h" +#include "platform/interfaces/modules/ISystemWindowManager.h" +#include "platform/openharmony/modules/SystemWindow.h" + +namespace cc { + +int SystemWindowManager::init() { + return 0; +} + +void SystemWindowManager::processEvent() { +} + +ISystemWindow *SystemWindowManager::createWindow(const ISystemWindowInfo &info) { + ISystemWindow *window = BasePlatform::getPlatform()->createNativeWindow(_nextWindowId, info.externalHandle); + if (window) { + if (!info.externalHandle) { + window->createWindow(info.title.c_str(), info.x, info.y, info.width, info.height, info.flags); + } + _windows[_nextWindowId] = std::shared_ptr(window); + _nextWindowId++; + } + return window; +} + +ISystemWindow *SystemWindowManager::getWindow(uint32_t windowId) const { + if (windowId == 0) { + return nullptr; + } + + auto iter = _windows.find(windowId); + if (iter != _windows.end()) + return iter->second.get(); + return nullptr; +} + +} // namespace cc diff --git a/native/cocos/platform/openharmony/modules/SystemWindowManager.h b/native/cocos/platform/openharmony/modules/SystemWindowManager.h new file mode 100644 index 0000000000..de9cf73c47 --- /dev/null +++ b/native/cocos/platform/openharmony/modules/SystemWindowManager.h @@ -0,0 +1,50 @@ +/**************************************************************************** + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "base/std/container/unordered_map.h" +#include "platform/interfaces/modules/ISystemWindowManager.h" + +namespace cc { + +class ISystemWindow; + +class SystemWindowManager : public ISystemWindowManager { +public: + SystemWindowManager() = default; + + int init() override; + void processEvent() override; + + ISystemWindow *createWindow(const ISystemWindowInfo &info) override; + ISystemWindow *getWindow(uint32_t windowId) const override; + const SystemWindowMap &getWindows() const override { return _windows; } + +private: + uint32_t _nextWindowId{1}; // start from 1, 0 means an invalid ID + + SystemWindowMap _windows; +}; +} // namespace cc diff --git a/native/cocos/platform/openharmony/napi/NapiHelper.cpp b/native/cocos/platform/openharmony/napi/NapiHelper.cpp new file mode 100644 index 0000000000..fa7f458a16 --- /dev/null +++ b/native/cocos/platform/openharmony/napi/NapiHelper.cpp @@ -0,0 +1,330 @@ + +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +#include "platform/openharmony/napi/NapiHelper.h" +#include "platform/openharmony/OpenHarmonyPlatform.h" +#include "bindings/jswrapper/napi/HelperMacros.h" +#include "platform/openharmony/modules/SystemWindow.h" +#include "platform/openharmony/FileUtils-OpenHarmony.h" +#include "bindings/jswrapper/SeApi.h" +#include "ui/edit-box/EditBox-openharmony.h" +#include "ui/webview/WebViewImpl-openharmony.h" + +namespace cc { +const int32_t kMaxStringLen = 512; + +// Must be the same as the value called by js +enum ContextType { + APP_LIFECYCLE = 0, + JS_PAGE_LIFECYCLE, + XCOMPONENT_CONTEXT, + XCOMPONENT_REGISTER_LIFECYCLE_CALLBACK, + NATIVE_RENDER_API, + WORKER_INIT, + ENGINE_UTILS, + EDITBOX_UTILS, + WEBVIEW_UTILS, + UV_ASYNC_SEND, +}; +NapiHelper::PostMessage2UIThreadCb NapiHelper::_postMsg2UIThreadCb; +NapiHelper::PostSyncMessage2UIThreadCb NapiHelper::_postSyncMsg2UIThreadCb; + +static bool js_set_PostMessage2UIThreadCallback(se::State& s) { + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + do { + if (args[0].isObject() && args[0].toObject()->isFunction()) { + //se::Value jsThis(s.thisObject()); + se::Value jsFunc(args[0]); + //jsThis.toObject()->attachObject(jsFunc.toObject()); + auto * thisObj = s.thisObject(); + NapiHelper::_postMsg2UIThreadCb = [=](const std::string larg0, const se::Value& larg1) -> void { + se::ScriptEngine::getInstance()->clearException(); + se::AutoHandleScope hs; + CC_UNUSED bool ok = true; + se::ValueArray args; + args.resize(2); + ok &= nativevalue_to_se(larg0, args[0], nullptr /*ctx*/); + CC_ASSERT(ok); + args[1] = larg1; + //ok &= nativevalue_to_se(larg1, args[1], nullptr /*ctx*/); + se::Value rval; + se::Object* funcObj = jsFunc.toObject(); + bool succeed = funcObj->call(args, thisObj, &rval); + if (!succeed) { + se::ScriptEngine::getInstance()->clearException(); + } + }; + } + } while(false); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_set_PostMessage2UIThreadCallback); + +static bool js_set_PostSyncMessage2UIThreadCallback(se::State& s) { + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc == 1) { + do { + if (args[0].isObject() && args[0].toObject()->isFunction()) { + //se::Value jsThis(s.thisObject()); + se::Value jsFunc(args[0]); + //jsThis.toObject()->attachObject(jsFunc.toObject()); + auto * thisObj = s.thisObject(); + NapiHelper::_postSyncMsg2UIThreadCb = [=](const std::string larg0, const se::Value& larg1, se::Value* res) -> void { + se::ScriptEngine::getInstance()->clearException(); + se::AutoHandleScope hs; + CC_UNUSED bool ok = true; + se::ValueArray args; + args.resize(2); + ok &= nativevalue_to_se(larg0, args[0], nullptr /*ctx*/); + CC_ASSERT(ok); + args[1] = larg1; + //ok &= nativevalue_to_se(larg1, args[1], nullptr /*ctx*/); + //se::Value rval; + se::Object* funcObj = jsFunc.toObject(); + bool succeed = funcObj->call(args, thisObj, res); + if (!succeed) { + se::ScriptEngine::getInstance()->clearException(); + } + }; + } + } while(false); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(js_set_PostSyncMessage2UIThreadCallback); + +// NAPI Interface +napi_value NapiHelper::getContext(napi_env env, napi_callback_info info) { + napi_status status; + napi_value exports; + size_t argc = 1; + napi_value args[1]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + + if (argc != 1) { + napi_throw_type_error(env, NULL, "Wrong number of arguments"); + return nullptr; + } + + napi_valuetype valuetype; + status = napi_typeof(env, args[0], &valuetype); + if (status != napi_ok) { + return nullptr; + } + if (valuetype != napi_number) { + napi_throw_type_error(env, NULL, "Wrong arguments"); + return nullptr; + } + + int64_t value; + NAPI_CALL(env, napi_get_value_int64(env, args[0], &value)); + NAPI_CALL(env, napi_create_object(env, &exports)); + switch (value) { + case APP_LIFECYCLE: { + // Register app lifecycle + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("onCreate", NapiHelper::napiOnCreate), + DECLARE_NAPI_FUNCTION("onShow", NapiHelper::napiOnShow), + DECLARE_NAPI_FUNCTION("onHide", NapiHelper::napiOnHide), + DECLARE_NAPI_FUNCTION("onDestroy", NapiHelper::napiOnDestroy), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + } + break; + case JS_PAGE_LIFECYCLE: { + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("onPageShow", NapiHelper::napiOnPageShow), + DECLARE_NAPI_FUNCTION("onPageHide", NapiHelper::napiOnPageHide), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + } break; + case XCOMPONENT_REGISTER_LIFECYCLE_CALLBACK: { + } break; + case NATIVE_RENDER_API: { + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("nativeEngineInit", NapiHelper::napiNativeEngineInit), + DECLARE_NAPI_FUNCTION("nativeEngineStart", NapiHelper::napiNativeEngineStart), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + } break; + case WORKER_INIT: { + se::ScriptEngine::setEnv(env); + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("workerInit", NapiHelper::napiWorkerInit), + DECLARE_NAPI_FUNCTION("setPostMessageFunction", _SE(js_set_PostMessage2UIThreadCallback)), + DECLARE_NAPI_FUNCTION("setPostSyncMessageFunction", _SE(js_set_PostSyncMessage2UIThreadCallback)), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + } break; + case ENGINE_UTILS: { + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("resourceManagerInit", NapiHelper::napiResourceManagerInit), + DECLARE_NAPI_FUNCTION("writablePathInit", NapiHelper::napiWritablePathInit), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + } + case EDITBOX_UTILS: { + std::vector desc; + OpenHarmonyEditBox::GetInterfaces(desc); + NAPI_CALL(env, napi_define_properties(env, exports, desc.size(), desc.data())); + } + + case WEBVIEW_UTILS: { + std::vector desc; + OpenHarmonyWebView::GetInterfaces(desc); + NAPI_CALL(env, napi_define_properties(env, exports, desc.size(), desc.data())); + } break; + case UV_ASYNC_SEND: { + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("send", NapiHelper::napiASend), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + } break; + default: + LOGE("unknown type"); + } + return exports; +} + + +// NAPI Interface +bool NapiHelper::exportFunctions(napi_env env, napi_value exports) { + napi_status status; + // Application/SDK etc. Init + // XComponent Init: + napi_value exportInstance = nullptr; + OH_NativeXComponent* nativeXComponent = nullptr; + int32_t ret; + + char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {}; + uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1; + + status = napi_get_named_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance); + if (status != napi_ok) { + return false; + } + + status = napi_unwrap(env, exportInstance, reinterpret_cast(&nativeXComponent)); + if (status != napi_ok) { + LOGE("napi_unwrap %d", status); + return false; + } + + ret = OH_NativeXComponent_GetXComponentId(nativeXComponent, idStr, &idSize); + if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) { + return false; + } + + OpenHarmonyPlatform::getInstance()->setNativeXComponent(nativeXComponent); + return true; +} + +napi_value NapiHelper::napiOnCreate(napi_env env, napi_callback_info info) { + // uv_loop_t* loop = nullptr; + // NAPI_CALL(env, napi_get_uv_event_loop(env, &loop)); + // OpenHarmonyPlatform::getInstance()->onCreateNative(env, loop); + return nullptr; +} + +napi_value NapiHelper::napiOnShow(napi_env env, napi_callback_info info) { + cc::WorkerMessageData data{cc::MessageType::WM_APP_SHOW, nullptr, nullptr}; + OpenHarmonyPlatform::getInstance()->enqueue(data); + return nullptr; +} + +napi_value NapiHelper::napiOnHide(napi_env env, napi_callback_info info) { + cc::WorkerMessageData data{cc::MessageType::WM_APP_HIDE, nullptr, nullptr}; + OpenHarmonyPlatform::getInstance()->enqueue(data); + return nullptr; +} + +napi_value NapiHelper::napiOnDestroy(napi_env env, napi_callback_info info) { + cc::WorkerMessageData data{cc::MessageType::WM_APP_DESTROY, nullptr, nullptr}; + OpenHarmonyPlatform::getInstance()->enqueue(data); + return nullptr; +} + +napi_value NapiHelper::napiOnPageShow(napi_env env, napi_callback_info info) { + return nullptr; +} + +napi_value NapiHelper::napiOnPageHide(napi_env env, napi_callback_info info) { + return nullptr; +} + +napi_value NapiHelper::napiNativeEngineInit(napi_env env, napi_callback_info info) { + se::ScriptEngine::setEnv(env); + OpenHarmonyPlatform::getInstance()->run(0, nullptr); + return nullptr; +} + +napi_value NapiHelper::napiNativeEngineStart(napi_env env, napi_callback_info info) { + OpenHarmonyPlatform::getInstance()->requestVSync(); + return nullptr; +} + +napi_value NapiHelper::napiWorkerInit(napi_env env, napi_callback_info info) { + uv_loop_t* loop = nullptr; + NAPI_CALL(env, napi_get_uv_event_loop(env, &loop)); + OpenHarmonyPlatform::getInstance()->workerInit(env, loop); + return nullptr; +} + +napi_value NapiHelper::napiResourceManagerInit(napi_env env, napi_callback_info info) { + size_t argc = 1; + napi_value args[1]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + FileUtilsOpenHarmony::initResourceManager(env, args[0]); + return nullptr; +} + +napi_value NapiHelper::napiWritablePathInit(napi_env env, napi_callback_info info) { + size_t argc = 1; + napi_value args[1]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + + napi_status status; + char buffer[kMaxStringLen]; + size_t result = 0; + NODE_API_CALL(status, env, napi_get_value_string_utf8(env, args[0], buffer, kMaxStringLen, &result)); + FileUtilsOpenHarmony::_ohWritablePath = std::string(buffer); + return nullptr; +} + +napi_value NapiHelper::napiASend(napi_env env, napi_callback_info info) { + OpenHarmonyPlatform::getInstance()->triggerMessageSignal(); + return nullptr; +} +} diff --git a/native/cocos/platform/openharmony/napi/NapiHelper.h b/native/cocos/platform/openharmony/napi/NapiHelper.h new file mode 100644 index 0000000000..af20e1f270 --- /dev/null +++ b/native/cocos/platform/openharmony/napi/NapiHelper.h @@ -0,0 +1,115 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include +#include "cocos/bindings/jswrapper/SeApi.h" +#include "cocos/bindings/manual/jsb_conversions.h" + +namespace cc { + +class NapiHelper { +public: + + static napi_value getContext(napi_env env, napi_callback_info info); + // APP Lifecycle + static napi_value napiOnCreate(napi_env env, napi_callback_info info); + static napi_value napiOnShow(napi_env env, napi_callback_info info); + static napi_value napiOnHide(napi_env env, napi_callback_info info); + static napi_value napiOnDestroy(napi_env env, napi_callback_info info); + + // JS Page : Lifecycle + static napi_value napiOnPageShow(napi_env env, napi_callback_info info); + static napi_value napiOnPageHide(napi_env env, napi_callback_info info); + + // Worker Func + static napi_value napiWorkerInit(napi_env env, napi_callback_info info); + static napi_value napiASend(napi_env env, napi_callback_info info); + static napi_value napiNativeEngineInit(napi_env env, napi_callback_info info); + static napi_value napiNativeEngineStart(napi_env env, napi_callback_info info); + + static napi_value napiWritablePathInit(napi_env env, napi_callback_info info); + static napi_value napiResourceManagerInit(napi_env env, napi_callback_info info); + + template + static napi_value napiCallFunction(const std::string& functionName, ReturnType* value) { + if (!se::ScriptEngine::getInstance()->isValid()) { + return nullptr; + } + se::Value tickVal; + se::AutoHandleScope scope; + if (tickVal.isUndefined()) { + se::ScriptEngine::getInstance()->getGlobalObject()->getProperty(functionName, &tickVal); + } + se::Value rval; + se::ValueArray tickArgsValArr(1); + if (!tickVal.isUndefined()) { + tickVal.toObject()->call(tickArgsValArr, nullptr, &rval); + } + if(rval.isNullOrUndefined()) { + return nullptr; + } + bool ok = true; + ok &= sevalue_to_native(rval, value, nullptr); + SE_PRECONDITION2(ok, nullptr, "Error processing arguments"); + return nullptr; + } + static napi_value napiSetPostMessageFunction(napi_env env, napi_callback_info info); + // Napi export + static bool exportFunctions(napi_env env, napi_value exports); + + template + static void postMessageToUIThread(const std::string& type, ParamType param) { + if (!_postMsg2UIThreadCb) { + return; + } + CC_UNUSED bool ok = true; + se::Value value; + ok &= nativevalue_to_se(param, value, nullptr /*ctx*/); + _postMsg2UIThreadCb(type, value); + } + + template + static void postSyncMessageToUIThread(const std::string& type, ParamType param, ResType* res) { + if (!_postSyncMsg2UIThreadCb) { + return; + } + CC_UNUSED bool ok = true; + se::Value value; + ok &= nativevalue_to_se(param, value, nullptr /*ctx*/); + se::Value seOut; + _postSyncMsg2UIThreadCb(type, value, &seOut); + sevalue_to_native(seOut, res, nullptr); + } + +public: + using PostMessage2UIThreadCb = std::function; + static PostMessage2UIThreadCb _postMsg2UIThreadCb; + using PostSyncMessage2UIThreadCb = std::function; + static PostSyncMessage2UIThreadCb _postSyncMsg2UIThreadCb; +}; + +} diff --git a/native/cocos/platform/openharmony/napi/NapiInit.cpp b/native/cocos/platform/openharmony/napi/NapiInit.cpp new file mode 100644 index 0000000000..367ec238b3 --- /dev/null +++ b/native/cocos/platform/openharmony/napi/NapiInit.cpp @@ -0,0 +1,63 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +#include +#include "bindings/jswrapper/SeApi.h" +#include "platform/openharmony/napi/NapiHelper.h" + +const char kLibname[] = "cocos"; +/* + * function for module exports + */ +static napi_value init(napi_env env, napi_value exports) { + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("getContext", cc::NapiHelper::getContext), + }; + + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + bool ret = cc::NapiHelper::exportFunctions(env, exports); + if (!ret) { + LOGE("Init failed"); + } + return exports; +} + +/* + * Napi Module define + */ +static napi_module cocos2dModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = init, // called by ACE XComponent + .nm_modname = kLibname, + .nm_priv = ((void*)0), + .reserved = {0}, +}; +/* + * Module register function + */ +extern "C" __attribute__((constructor)) void RegisterModule(void) { + napi_module_register(&cocos2dModule); +} diff --git a/native/cocos/ui/edit-box/EditBox-openharmony.cpp b/native/cocos/ui/edit-box/EditBox-openharmony.cpp new file mode 100644 index 0000000000..53ae208e0a --- /dev/null +++ b/native/cocos/ui/edit-box/EditBox-openharmony.cpp @@ -0,0 +1,113 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "EditBox.h" +#include "EditBox-openharmony.h" + +#include "cocos/application/ApplicationManager.h" +#include "platform/openharmony/napi/NapiHelper.h" +#include "cocos/bindings/jswrapper/SeApi.h" + +namespace cc { + +/************************************************************************* + Global variables and functions. +************************************************************************/ + +namespace { +se::Value g_textInputCallback; + +void getTextInputCallback() { + if (!g_textInputCallback.isUndefined()) + return; + + auto global = se::ScriptEngine::getInstance()->getGlobalObject(); + se::Value jsbVal; + if (global->getProperty("jsb", &jsbVal) && jsbVal.isObject()) { + jsbVal.toObject()->getProperty("onTextInput", &g_textInputCallback); + // free globle se::Value before ScriptEngine clean up + se::ScriptEngine::getInstance()->addBeforeCleanupHook([]() { + g_textInputCallback.setUndefined(); + }); + } +} + +void callJSFunc(const ccstd::string &type, const ccstd::string &text) { + getTextInputCallback(); + + se::AutoHandleScope scope; + se::ValueArray args; + args.push_back(se::Value(type)); + args.push_back(se::Value(text)); + g_textInputCallback.toObject()->call(args, nullptr); +} + +} // namespace + +/************************************************************************* +Implementation of EditBox. +************************************************************************/ +void EditBox::show(const EditBox::ShowInfo &showInfo) { + NapiHelper::postMessageToUIThread("showEditBox", showInfo.defaultValue.c_str()); +} + +void EditBox::hide() { + NapiHelper::postMessageToUIThread("hideEditBox", ""); +} + +bool EditBox::complete() { + callJSFunc("complete", ""); + return true; +} + +void OpenHarmonyEditBox::GetInterfaces(std::vector &descriptors) { +#if CC_USE_EDITBOX + descriptors = { + DECLARE_NAPI_FUNCTION("onTextChange", OpenHarmonyEditBox::napiOnTextChange), + DECLARE_NAPI_FUNCTION("onComplete", OpenHarmonyEditBox::napiOnComplete), + }; +#endif +} + +napi_value OpenHarmonyEditBox::napiOnComplete(napi_env env, napi_callback_info info) { + EditBox::complete(); + return nullptr; +} + +napi_value OpenHarmonyEditBox::napiOnTextChange(napi_env env, napi_callback_info info) { + size_t argc = 1; + napi_value args[1]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + napi_status status; + char buffer[512]; + size_t result = 0; + NODE_API_CALL(status, env, napi_get_value_string_utf8(env, args[0], buffer, 512, &result)); + callJSFunc("input", std::string(buffer)); + return nullptr; +} + +} // namespace cc + + diff --git a/native/cocos/ui/edit-box/EditBox-openharmony.h b/native/cocos/ui/edit-box/EditBox-openharmony.h new file mode 100644 index 0000000000..79d8d2a4a9 --- /dev/null +++ b/native/cocos/ui/edit-box/EditBox-openharmony.h @@ -0,0 +1,50 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "EditBox.h" +#include "cocos/application/ApplicationManager.h" +#include "platform/openharmony/napi/NapiHelper.h" +#include "cocos/bindings/jswrapper/SeApi.h" + +namespace cc { + +class OpenHarmonyEditBox : public EditBox { +public: + static void GetInterfaces(std::vector& descriptors); + + static napi_value napiOnComplete(napi_env env, napi_callback_info info); + static napi_value napiOnTextChange(napi_env env, napi_callback_info info); + + static napi_value show(const std::string& inputMessage); + static napi_value hide(); +private: + static napi_ref showEditBoxFunction; + static napi_ref hideEditBoxFunction; + +}; + +} // namespace cc + + diff --git a/native/cocos/ui/videoplayer/VideoPlayer.h b/native/cocos/ui/videoplayer/VideoPlayer.h index 893a8c0836..a3db31a3c9 100644 --- a/native/cocos/ui/videoplayer/VideoPlayer.h +++ b/native/cocos/ui/videoplayer/VideoPlayer.h @@ -61,7 +61,8 @@ public: COMPLETED, META_LOADED, CLICKED, - READY_TO_PLAY + READY_TO_PLAY, + UPDATE, }; VideoPlayer(); diff --git a/native/cocos/ui/webview/WebView-inl.h b/native/cocos/ui/webview/WebView-inl.h index f813f9f530..321f0c6e9c 100644 --- a/native/cocos/ui/webview/WebView-inl.h +++ b/native/cocos/ui/webview/WebView-inl.h @@ -29,7 +29,7 @@ #if CC_PLATFORM == CC_PLATFORM_IOS #include "WebViewImpl-ios.h" -#elif CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS +#elif CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS || CC_PLATFORM == CC_PLATFORM_OPENHARMONY #include "WebViewImpl-java.h" #else static_assert(false, "WebView only supported on iOS & Android"); diff --git a/native/cocos/ui/webview/WebViewImpl-openharmony.cpp b/native/cocos/ui/webview/WebViewImpl-openharmony.cpp new file mode 100644 index 0000000000..6915a40ee7 --- /dev/null +++ b/native/cocos/ui/webview/WebViewImpl-openharmony.cpp @@ -0,0 +1,333 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include +#include "base/std/container/string.h" +#include "base/std/container/unordered_map.h" + +#include "WebView-inl.h" + +#include "platform/FileUtils.h" +#include "platform/openharmony/napi/NapiHelper.h" +#include "WebViewImpl-openharmony.h" +#include "cocos/base/Log.h" + +static const ccstd::string S_DEFAULT_BASE_URL = "file:///openharmony_asset/"; +static const ccstd::string S_SD_ROOT_BASE_URL = "file://"; + +static ccstd::string getFixedBaseUrl(const ccstd::string &baseUrl) { + ccstd::string fixedBaseUrl; + if (baseUrl.empty()) { + fixedBaseUrl = S_DEFAULT_BASE_URL; + } else if (baseUrl.find(S_SD_ROOT_BASE_URL) != ccstd::string::npos) { + fixedBaseUrl = baseUrl; + } else if (baseUrl.c_str()[0] != '/') { + if (baseUrl.find("assets/") == 0) { + fixedBaseUrl = S_DEFAULT_BASE_URL + baseUrl.c_str()[7]; + } else { + fixedBaseUrl = S_DEFAULT_BASE_URL + baseUrl; + } + } else { + fixedBaseUrl = S_SD_ROOT_BASE_URL + baseUrl; + } + + if (fixedBaseUrl.c_str()[fixedBaseUrl.length() - 1] != '/') { + fixedBaseUrl += "/"; + } + + return fixedBaseUrl; +} + +ccstd::string getUrlStringByFileName(const ccstd::string &fileName) { + // LOGD("error: %s,%d",__func__,__LINE__); + const ccstd::string basePath(S_DEFAULT_BASE_URL); + ccstd::string fullPath = cc::FileUtils::getInstance()->fullPathForFilename(fileName); + const ccstd::string assetsPath("assets/"); + + ccstd::string urlString; + if (fullPath.find(assetsPath) != ccstd::string::npos) { + urlString = fullPath.replace(fullPath.find_first_of(assetsPath), assetsPath.length(), + basePath); + } else { + urlString = fullPath; + } + + return urlString; +} + +namespace cc { +static int32_t kWebViewTag = 0; +static ccstd::unordered_map sWebViewImpls; + +WebViewImpl::WebViewImpl(WebView *webView) : _viewTag(-1), + _webView(webView) { + _viewTag = kWebViewTag++; + NapiHelper::postMessageToUIThread("createWebView", _viewTag); + sWebViewImpls[_viewTag] = this; +} + +WebViewImpl::~WebViewImpl() { + destroy(); +} + +void WebViewImpl::destroy() { + if (_viewTag != -1) { + NapiHelper::postMessageToUIThread("removeWebView", _viewTag); + auto iter = sWebViewImpls.find(_viewTag); + if (iter != sWebViewImpls.end()) { + sWebViewImpls.erase(iter); + } + _viewTag = -1; + } +} + +void WebViewImpl::loadData(const Data &data, const ccstd::string &mimeType, + const ccstd::string &encoding, const ccstd::string &baseURL) { + ccstd::string dataString(reinterpret_cast(data.getBytes()), + static_cast(data.getSize())); + ccstd::unordered_map vals; + vals.insert(std::make_pair("tag", _viewTag)); + vals.insert(std::make_pair("contents", cc::Value(dataString))); + vals.insert(std::make_pair("mimeType", mimeType)); + vals.insert(std::make_pair("encoding", encoding)); + vals.insert(std::make_pair("baseUrl", baseURL)); + NapiHelper::postMessageToUIThread("loadData", vals); +} + +void WebViewImpl::loadHTMLString(const ccstd::string &string, const ccstd::string &baseURL) { + ccstd::unordered_map vals; + vals.insert(std::make_pair("tag", _viewTag)); + vals.insert(std::make_pair("contents", cc::Value(string))); + vals.insert(std::make_pair("baseUrl", baseURL)); + NapiHelper::postMessageToUIThread("loadHTMLString", vals); +} + +void WebViewImpl::loadURL(const ccstd::string &url) { + ccstd::unordered_map vals; + vals.insert(std::make_pair("tag", _viewTag)); + vals.insert(std::make_pair("url", url)); + NapiHelper::postMessageToUIThread("loadUrl", vals); +} + +void WebViewImpl::loadFile(const ccstd::string &fileName) { + auto fullPath = getUrlStringByFileName(fileName); + ccstd::unordered_map vals; + vals.insert(std::make_pair("tag", _viewTag)); + vals.insert(std::make_pair("url", fullPath)); + NapiHelper::postMessageToUIThread("loadUrl", vals); +} + +void WebViewImpl::stopLoading() { + NapiHelper::postMessageToUIThread("stopLoading", _viewTag); +} + +void WebViewImpl::reload() { + NapiHelper::postMessageToUIThread("reload", _viewTag); +} + +bool WebViewImpl::canGoBack() { + // TODO(qgh):OpenHarmony does not support this interface. + return true; +} + +bool WebViewImpl::canGoForward() { + // TODO(qgh):OpenHarmony does not support this interface. + return true; +} + +void WebViewImpl::goBack() { + NapiHelper::postMessageToUIThread("goBack", _viewTag); +} + +void WebViewImpl::goForward() { + NapiHelper::postMessageToUIThread("goForward", _viewTag); +} + +void WebViewImpl::setJavascriptInterfaceScheme(const ccstd::string &scheme) { + // TODO(qgh):OpenHarmony does not support this interface. +} + +void WebViewImpl::evaluateJS(const ccstd::string &js) { + ccstd::unordered_map vals; + vals.insert(std::make_pair("tag", _viewTag)); + vals.insert(std::make_pair("jsContents", js)); + NapiHelper::postMessageToUIThread("evaluateJS", vals); +} + +void WebViewImpl::setScalesPageToFit(bool scalesPageToFit) { + NapiHelper::postMessageToUIThread("setScalesPageToFit", _viewTag); +} + +bool WebViewImpl::shouldStartLoading(int viewTag, const ccstd::string &url) { + bool allowLoad = true; + auto it = sWebViewImpls.find(viewTag); + if (it != sWebViewImpls.end()) { + auto webView = it->second->_webView; + if (webView->_onShouldStartLoading) { + allowLoad = webView->_onShouldStartLoading(webView, url); + } + } + return allowLoad; +} + +void WebViewImpl::didFinishLoading(int viewTag, const ccstd::string &url) { + auto it = sWebViewImpls.find(viewTag); + if (it != sWebViewImpls.end()) { + auto webView = it->second->_webView; + if (webView->_onDidFinishLoading) { + webView->_onDidFinishLoading(webView, url); + } + } +} + +void WebViewImpl::didFailLoading(int viewTag, const ccstd::string &url) { + auto it = sWebViewImpls.find(viewTag); + if (it != sWebViewImpls.end()) { + auto webView = it->second->_webView; + if (webView->_onDidFailLoading) { + webView->_onDidFailLoading(webView, url); + } + } +} + +void WebViewImpl::onJsCallback(int viewTag, const ccstd::string &message) { + auto it = sWebViewImpls.find(viewTag); + if (it != sWebViewImpls.end()) { + auto webView = it->second->_webView; + if (webView->_onJSCallback) { + webView->_onJSCallback(webView, message); + } + } +} + +void WebViewImpl::setVisible(bool visible) { + ccstd::unordered_map vals; + vals.insert(std::make_pair("tag", _viewTag)); + vals.insert(std::make_pair("visible", visible)); + NapiHelper::postMessageToUIThread("setVisible", vals); +} + +void WebViewImpl::setFrame(float x, float y, float width, float height) { + //cc::Rect rect(x, y, width, height); + ccstd::unordered_map vals; + vals.insert(std::make_pair("tag", _viewTag)); + vals.insert(std::make_pair("x", x)); + vals.insert(std::make_pair("y", y)); + vals.insert(std::make_pair("w", width)); + vals.insert(std::make_pair("h", height)); + NapiHelper::postMessageToUIThread("setWebViewRect", vals); +} + +void WebViewImpl::setBounces(bool bounces) { + // empty function as this was mainly a fix for iOS +} + +void WebViewImpl::setBackgroundTransparent(bool isTransparent) { + // TODO(qgh):OpenHarmony is not supported at this time +} + +void OpenHarmonyWebView::GetInterfaces(std::vector &descriptors) { + descriptors = { + DECLARE_NAPI_FUNCTION("shouldStartLoading", OpenHarmonyWebView::napiShouldStartLoading), + DECLARE_NAPI_FUNCTION("finishLoading", OpenHarmonyWebView::napiFinishLoading), + DECLARE_NAPI_FUNCTION("failLoading", OpenHarmonyWebView::napiFailLoading), + DECLARE_NAPI_FUNCTION("jsCallback", OpenHarmonyWebView::napiJsCallback), + }; +} + +napi_value OpenHarmonyWebView::napiShouldStartLoading(napi_env env, napi_callback_info info) { + size_t argc = 2; + napi_value args[2]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + + se::ValueArray seArgs; + seArgs.reserve(2); + se::internal::jsToSeArgs(argc, args, &seArgs); + + int32_t viewTag; + sevalue_to_native(seArgs[0], &viewTag, nullptr); + + std::string url; + sevalue_to_native(seArgs[1], &url, nullptr); + WebViewImpl::shouldStartLoading(viewTag, url); + return nullptr; +} + +napi_value OpenHarmonyWebView::napiFinishLoading(napi_env env, napi_callback_info info) { + size_t argc = 2; + napi_value args[2]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + + se::ValueArray seArgs; + seArgs.reserve(2); + se::internal::jsToSeArgs(argc, args, &seArgs); + + int32_t viewTag; + sevalue_to_native(seArgs[0], &viewTag, nullptr); + + std::string url; + sevalue_to_native(seArgs[1], &url, nullptr); + WebViewImpl::didFinishLoading(viewTag, url); + return nullptr; +} + +napi_value OpenHarmonyWebView::napiFailLoading(napi_env env, napi_callback_info info) { + size_t argc = 2; + napi_value args[2]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + + se::ValueArray seArgs; + seArgs.reserve(2); + se::internal::jsToSeArgs(argc, args, &seArgs); + + int32_t viewTag; + sevalue_to_native(seArgs[0], &viewTag, nullptr); + + std::string url; + sevalue_to_native(seArgs[1], &url, nullptr); + WebViewImpl::didFailLoading(viewTag, url); + return nullptr; +} + +napi_value OpenHarmonyWebView::napiJsCallback(napi_env env, napi_callback_info info) { + size_t argc = 2; + napi_value args[2]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + + se::ValueArray seArgs; + seArgs.reserve(2); + se::internal::jsToSeArgs(argc, args, &seArgs); + + int32_t viewTag; + sevalue_to_native(seArgs[0], &viewTag, nullptr); + + std::string url; + sevalue_to_native(seArgs[1], &url, nullptr); + WebViewImpl::onJsCallback(viewTag, url); + return nullptr; +} + + +} //namespace cc diff --git a/native/cocos/ui/webview/WebViewImpl-openharmony.h b/native/cocos/ui/webview/WebViewImpl-openharmony.h new file mode 100644 index 0000000000..f12c94e50f --- /dev/null +++ b/native/cocos/ui/webview/WebViewImpl-openharmony.h @@ -0,0 +1,43 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "platform/openharmony/napi/NapiHelper.h" +#include "cocos/bindings/jswrapper/SeApi.h" +#include "ui/webview/WebViewImpl-java.h" + +namespace cc { + +class OpenHarmonyWebView { +public: + static void GetInterfaces(std::vector& descriptors); + static napi_value napiShouldStartLoading(napi_env env, napi_callback_info info); + static napi_value napiFinishLoading(napi_env env, napi_callback_info info); + static napi_value napiFailLoading(napi_env env, napi_callback_info info); + static napi_value napiJsCallback(napi_env env, napi_callback_info info); +}; + +} //namespace cc diff --git a/native/external-config.json b/native/external-config.json index f01551f391..5ca4373b9d 100644 --- a/native/external-config.json +++ b/native/external-config.json @@ -3,6 +3,6 @@ "type": "github", "owner": "cocos-creator", "name": "engine-native-external", - "checkout": "develop-13" + "checkout": "develop-14" } } diff --git a/native/utils/clear-platform.js b/native/utils/clear-platform.js index e009b41e80..b034dd2113 100644 --- a/native/utils/clear-platform.js +++ b/native/utils/clear-platform.js @@ -8,8 +8,8 @@ const fs = require('fs-extra'); let externalDir = path.join(__dirname, "../external"); let failed = false; -let macUsefulDirs = ['android', 'cmake', 'emscripten', 'ios', 'ios-m1-simulator', 'mac', 'ohos', 'sources']; -let winUsefulDirs = ['android', 'cmake', 'emscripten', 'ohos', 'sources', 'win64']; +let macUsefulDirs = ['android', 'cmake', 'emscripten', 'ios', 'ios-m1-simulator', 'mac', 'ohos', 'sources', 'openharmony']; +let winUsefulDirs = ['android', 'cmake', 'emscripten', 'ohos', 'sources', 'win64', 'openharmony']; let linuxUsefulDirs = ['android', 'cmake', 'emscripten', 'linux', 'ohos', 'sources']; let allDirs = []; diff --git a/pal/env/native/env.ts b/pal/env/native/env.ts index 2b5becea2f..4ebb47a82b 100644 --- a/pal/env/native/env.ts +++ b/pal/env/native/env.ts @@ -37,29 +37,35 @@ export function findCanvas (): { frame: HTMLDivElement, container: HTMLDivElemen } export function loadJsFile (path: string): Promise { - if (PREVIEW) { - // NOTE: in native preview (simulator), we need to request script with url http://x.x.x.x:xxxx/plugins/xxx.js - // so that the editor preview server would resolve the plugin script and return the code. - // here we use window.eval() function to execute the code of plugin script. - return new Promise((resolve, reject) => { - const sourceURL = window.location.href + path; - const xhr = new XMLHttpRequest(); - xhr.onload = () => { - if (xhr.status !== 200) { - reject(new Error(`load js file failed: ${sourceURL}, error status: ${xhr.status}`)); - return; - } - // eslint-disable-next-line no-eval - window.eval(`${xhr.response as string}\n//# sourceURL=${sourceURL}`); - resolve(); - }; - xhr.onerror = () => { - reject(new Error(`load js file failed: ${sourceURL}`)); - }; - xhr.open('GET', sourceURL, true); - xhr.send(null); - }); + if (window.oh) { + // TODO(qgh):OpenHarmony does not currently support dynamic require expressions + window.oh.loadModule(path); + return Promise.resolve(); + } else { + if (PREVIEW) { + // NOTE: in native preview (simulator), we need to request script with url http://x.x.x.x:xxxx/plugins/xxx.js + // so that the editor preview server would resolve the plugin script and return the code. + // here we use window.eval() function to execute the code of plugin script. + return new Promise((resolve, reject) => { + const sourceURL = window.location.href + path; + const xhr = new XMLHttpRequest(); + xhr.onload = () => { + if (xhr.status !== 200) { + reject(new Error(`load js file failed: ${sourceURL}, error status: ${xhr.status}`)); + return; + } + // eslint-disable-next-line no-eval + window.eval(`${xhr.response as string}\n//# sourceURL=${sourceURL}`); + resolve(); + }; + xhr.onerror = () => { + reject(new Error(`load js file failed: ${sourceURL}`)); + }; + xhr.open('GET', sourceURL, true); + xhr.send(null); + }); + } + // eslint-disable-next-line import/no-dynamic-require + return require(`${path}`); } - // eslint-disable-next-line import/no-dynamic-require - return require(`${path}`); } diff --git a/pal/screen-adapter/native/screen-adapter.ts b/pal/screen-adapter/native/screen-adapter.ts index 0525afc465..2ca644b907 100644 --- a/pal/screen-adapter/native/screen-adapter.ts +++ b/pal/screen-adapter/native/screen-adapter.ts @@ -54,8 +54,13 @@ class ScreenAdapter extends EventTarget { public get windowSize (): Size { const dpr = this.devicePixelRatio; // NOTE: fix precision issue on Metal render end. - const roundWidth = Math.round(jsb.window.innerWidth); - const roundHeight = Math.round(jsb.window.innerHeight); + // @ts-expect-error interface for OH only + const width = globalThis.oh ? jsb.device.getInnerWidth() : jsb.window.innerWidth; + // @ts-expect-error interface for OH only + const height = globalThis.oh ? jsb.device.getInnerHeight() : jsb.window.innerHeight; + // NOTE: fix precision issue on Metal render end. + const roundWidth = Math.round(width); + const roundHeight = Math.round(height); return new Size(roundWidth * dpr, roundHeight * dpr); } public set windowSize (size: Size) { diff --git a/platforms/native/builtin/index.js b/platforms/native/builtin/index.js index 9b84dfd320..6bce9d28ed 100644 --- a/platforms/native/builtin/index.js +++ b/platforms/native/builtin/index.js @@ -115,19 +115,24 @@ function createTimeoutInfo (prevFuncArgs, isRepeat) { return info.id; } -jsbWindow.setTimeout = function (cb) { - return createTimeoutInfo(arguments, false); -}; +if (!window.oh) { + // In openharmony, the setTimeout function will conflict with the timer of the worker thread and cause a crash, + // so you need to use the default timer + jsbWindow.setTimeout = function (cb) { + return createTimeoutInfo(arguments, false); + }; -jsbWindow.clearTimeout = function (id) { - delete _timeoutInfos[id]; -}; + jsbWindow.clearTimeout = function (id) { + delete _timeoutInfos[id]; + }; -jsbWindow.setInterval = function (cb) { - return createTimeoutInfo(arguments, true); -}; + jsbWindow.setInterval = function (cb) { + return createTimeoutInfo(arguments, true); + }; + + jsbWindow.clearInterval = jsbWindow.clearTimeout; +} -jsbWindow.clearInterval = jsbWindow.clearTimeout; jsbWindow.alert = console.error.bind(console); // File utils (Temporary, won't be accessible) diff --git a/platforms/native/engine/index.js b/platforms/native/engine/index.js index 1987139121..2ac7d0e4ce 100644 --- a/platforms/native/engine/index.js +++ b/platforms/native/engine/index.js @@ -27,7 +27,10 @@ require('./jsb-assets-manager.js'); require('./jsb-game.js'); require('./jsb-gfx.js'); require('./jsb-loader.js'); -require('./jsb-videoplayer.js'); +if(window.oh) + require('./jsb-videoplayer-openharmony.js'); +else + require('./jsb-videoplayer.js'); require('./jsb-webview.js'); require('./jsb-editbox.js'); require('./jsb-editor-support.js'); diff --git a/platforms/native/engine/jsb-gfx.js b/platforms/native/engine/jsb-gfx.js index daf9394964..43c13b9ce4 100644 --- a/platforms/native/engine/jsb-gfx.js +++ b/platforms/native/engine/jsb-gfx.js @@ -57,7 +57,8 @@ deviceProto.copyTexImagesToTexture = function (texImages, texture, regions) { const oldDeviceCreateSwapchainFunc = deviceProto.createSwapchain; deviceProto.createSwapchain = function (info) { - info.windowHandle = jsbWindow.windowHandler; + // In openharmony, we need to get the window handle through the jsb interface + info.windowHandle = window.oh ? jsb.device.getWindowHandle() : jsbWindow.windowHandler; return oldDeviceCreateSwapchainFunc.call(this, info); }; diff --git a/platforms/native/engine/jsb-loader.js b/platforms/native/engine/jsb-loader.js index 717dfba131..d08ccaf68d 100644 --- a/platforms/native/engine/jsb-loader.js +++ b/platforms/native/engine/jsb-loader.js @@ -55,7 +55,10 @@ function downloadScript (url, options, onComplete) { if (loadedScripts[url]) return onComplete && onComplete(); download(url, (src, options, onComplete) => { - if (__EDITOR__) { + if (window.oh) { + // TODO(qgh):OpenHarmony does not currently support dynamic require expressions + window.oh.loadModule(src); + } else if (__EDITOR__) { // in editor mode,require is from electron,__require is from engine globalThis.__require(src); } else { diff --git a/platforms/native/engine/jsb-videoplayer-openharmony.js b/platforms/native/engine/jsb-videoplayer-openharmony.js new file mode 100644 index 0000000000..86c35f0c3b --- /dev/null +++ b/platforms/native/engine/jsb-videoplayer-openharmony.js @@ -0,0 +1,421 @@ +/**************************************************************************** + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +'use strict'; + +if (cc.internal.VideoPlayer) { + + const { EventType } = cc.internal.VideoPlayer; + + let vec3 = cc.Vec3; + let mat4 = cc.Mat4; + let _mat4_temp = new mat4(); + + let _topLeft = new vec3(); + let _bottomRight = new vec3(); + let kWebViewTag = 0; + let videoPlayers = []; + const VideoEvent = { + PLAYING: 0, + PAUSED: 1, + STOPPED: 2, + COMPLETED: 3, + META_LOADED: 4, + CLICKED: 5, + READY_TO_PLAY:6, + UPDATE:7, + QUIT_FULLSCREEN:1000 + }; + + cc.internal.VideoPlayerImplManager.getImpl = function(componenet) { + return new VideoPlayerImplOpenHarmony(componenet); + }; + window.oh.onVideoEvent = (tag, ev, args) => { + videoPlayers.forEach(player => { + if (player.index == tag) { + player.dispatchEvent(ev, args); + } + }); + }; + class VideoPlayer { + constructor() { + this._events = {}; + this._currentTime = 0; + this._duration = 0; + this._videoIndex = kWebViewTag++; + this._matViewProj_temp = new mat4(); + window.oh.postMessage("createVideo", this._videoIndex); + videoPlayers.push(this); + } + get index() { + return this._videoIndex; + } + play() { + window.oh.postMessage("startVideo", this._videoIndex); + } + setURL(url) { + window.oh.postMessage("setVideoUrl", {tag:this._videoIndex, url:url}); + } + pause() { + window.oh.postMessage("pauseVideo", this._videoIndex); + } + setVisible(visible) { + window.oh.postMessage("setVideoVisible", {tag:this._videoIndex, visible:visible}); + } + resume() { + window.oh.postMessage("resumeVideo", this._videoIndex); + } + currentTime() { + window.oh.postSyncMessage("currentTime", this._videoIndex).then((result) => { + this._currentTime = result; + }); + return this._currentTime; + } + stop() { + window.oh.postMessage("stopVideo", this._videoIndex); + } + seekTo(val) { + window.oh.postMessage("seekVideoTo", {tag:this._videoIndex, time:val}); + } + duration() { + window.oh.postSyncMessage("getVideoDuration", this._videoIndex).then((result) => { + this._duration = result; + }); + return this._duration; + } + destroy() { + window.oh.postMessage("removeVideo", this._videoIndex); + } + setFullScreenEnabled(enable) { + window.oh.postMessage("setFullScreenEnabled", {tag:this._videoIndex, fullScreen:enable}); + } + setKeepAspectRatioEnabled(enable) { + cc.warn('The platform does not support'); + } + setFrame(x, y, w, h){ + window.oh.postMessage("setVideoRect", {tag:this._videoIndex, x:x, y:y, w:w, h:h}); + } + + eventTypeToEventName(ev) { + let evString; + switch (ev) { + case VideoEvent.PLAYING: + evString = "play"; + break; + case VideoEvent.PAUSED: + evString = "pause"; + break; + case VideoEvent.STOPPED: + evString = "stoped"; + break; + case VideoEvent.COMPLETED: + evString = "ended"; + break; + case VideoEvent.META_LOADED: + evString = "loadedmetadata"; + break; + case VideoEvent.CLICKED: + evString = "click"; + break; + case VideoEvent.READY_TO_PLAY: + evString = "suspend"; + break; + case VideoEvent.UPDATE: + evString = "update"; + break; + case VideoEvent.QUIT_FULLSCREEN: + evString = "suspend"; + break; + default: + evString = "none"; + break; + } + return evString; + } + + dispatchEvent(type, args) { + let eventName = this.eventTypeToEventName(type); + const listeners = this._events[eventName]; + + if (listeners) { + for (let i = 0; i < listeners.length; i++) { + listeners[i](args); + } + } + } + + addEventListener(name, listener) { + if (!this._events[name]) { + this._events[name] = []; + } + this._events[name].push(listener); + } + + removeEventListener(name, listener) { + const listeners = this._events[name]; + + if (listeners && listeners.length > 0) { + for (let i = listeners.length; i--; i > 0) { + if (listeners[i] === listener) { + listeners.splice(i, 1); + break; + } + } + } + } + } + + class VideoPlayerImplOpenHarmony extends cc.internal.VideoPlayerImpl { + + constructor(componenet) { + super(componenet); + this._matViewProj_temp = new mat4(); + } + + syncClip(clip) { + this.removeVideoPlayer(); + if (!clip) { + return; + } + this.createVideoPlayer(clip._nativeAsset); + } + + syncURL(url) { + this.removeVideoPlayer(); + if (!url) { + return; + } + this.createVideoPlayer(url); + } + + onCanplay () { + if (this._loaded) { + return; + } + this._loaded = true; + this.video.setVisible(this._visible); + this.dispatchEvent(EventType.READY_TO_PLAY); + this.delayedPlay(); + } + + _bindEvent() { + this.video.addEventListener('loadedmetadata', this.onLoadedMetadata.bind(this)); + this.video.addEventListener('suspend', this.onCanPlay.bind(this)); + this.video.addEventListener('play', this.onPlay.bind(this)); + this.video.addEventListener('pause', this.onPause.bind(this)); + this.video.addEventListener('stoped', this.onStoped.bind(this)); + this.video.addEventListener('click', this.onClick.bind(this)); + this.video.addEventListener('ended', this.onEnded.bind(this)); + } + + onLoadedMetadata() { + this._loadedMeta = true; + this._forceUpdate = true; + if (this._visible) { + this.enable(); + } else { + this.disable(); + } + this.dispatchEvent(EventType.META_LOADED); + this.delayedFullScreen(); + this.delayedPlay(); + } + + createVideoPlayer(url) { + this._video = new VideoPlayer(); + this._bindEvent(); + this._video.setVisible(this._visible); + this._video.setURL(url); + this._forceUpdate = true; + } + + removeVideoPlayer() { + let video = this.video; + if (video) { + video.stop(); + video.setVisible(false); + video.destroy(); + this._playing = false; + this._loaded = false; + this._loadedMeta = false; + this._ignorePause = false; + this._cachedCurrentTime = 0; + this._video = null; + } + } + + getDuration () { + if (!this.video) { + return -1; + } + return this.video.duration(); + } + + syncPlaybackRate() { + cc.warn('The platform does not support'); + } + + syncVolume() { + cc.warn('The platform does not support'); + } + + syncMute() { + cc.warn('The platform does not support'); + } + + syncLoop() { + cc.warn('The platform does not support'); + } + + syncStayOnBottom() { + cc.warn('The platform does not support'); + } + + getCurrentTime() { + if (this.video) { + this._cachedCurrentTime = this.video.currentTime(); + return this._cachedCurrentTime; + } + return -1; + } + + seekTo (val) { + let video = this._video; + if (!video) return; + video.seekTo(val); + this._cachedCurrentTime = val; + } + + disable(noPause) { + if (this.video) { + if (!noPause) { + this.video.pause(); + } + this.video.setVisible(false); + this._visible = false; + } + } + + enable() { + if (this.video) { + this.video.setVisible(true); + this._visible = true; + } + } + + canPlay () { + this.video.play(); + this.syncCurrentTime(); + } + + resume() { + if (this.video) { + this.video.resume(); + this.syncCurrentTime(); + this._playing = true; + } + } + + pause() { + if (this.video) { + this._cachedCurrentTime = this.video.currentTime(); + this.video.pause(); + } + } + + stop() { + if (this.video) { + this._ignorePause = true; + this.video.seekTo(0); + this._cachedCurrentTime = 0; + this.video.stop(); + } + } + + canFullScreen(enabled) { + if (this.video) { + this.video.setFullScreenEnabled(enabled); + } + } + + syncKeepAspectRatio(enabled) { + if (this.video) { + this.video.setKeepAspectRatioEnabled(enabled); + } + } + + syncMatrix() { + if (!this._video || !this._component || !this._uiTrans) return; + + const camera = this.UICamera; + if (!camera) { + return; + } + + this._component.node.getWorldMatrix(_mat4_temp); + const { width, height } = this._uiTrans.contentSize; + if (!this._forceUpdate && + camera.matViewProj.equals(this._matViewProj_temp) && + this._m00 === _mat4_temp.m00 && this._m01 === _mat4_temp.m01 && + this._m04 === _mat4_temp.m04 && this._m05 === _mat4_temp.m05 && + this._m12 === _mat4_temp.m12 && this._m13 === _mat4_temp.m13 && + this._w === width && this._h === height) { + return; + } + + this._matViewProj_temp.set(camera.matViewProj); + // update matrix cache + this._m00 = _mat4_temp.m00; + this._m01 = _mat4_temp.m01; + this._m04 = _mat4_temp.m04; + this._m05 = _mat4_temp.m05; + this._m12 = _mat4_temp.m12; + this._m13 = _mat4_temp.m13; + this._w = width; + this._h = height; + + let canvas_width = cc.game.canvas.width; + let canvas_height = cc.game.canvas.height; + + let ap = this._uiTrans.anchorPoint; + // Vectors in node space + vec3.set(_topLeft, -ap.x * this._w, (1.0 - ap.y) * this._h, 0); + vec3.set(_bottomRight, (1 - ap.x) * this._w, -ap.y * this._h, 0); + // Convert to world space + vec3.transformMat4(_topLeft, _topLeft, _mat4_temp); + vec3.transformMat4(_bottomRight, _bottomRight, _mat4_temp); + // need update camera data + camera.update(); + // Convert to Screen space + camera.worldToScreen(_topLeft, _topLeft); + camera.worldToScreen(_bottomRight, _bottomRight); + + let finalWidth = _bottomRight.x - _topLeft.x; + let finalHeight = _topLeft.y - _bottomRight.y; + this._video.setFrame(_topLeft.x, canvas_height - _topLeft.y, finalWidth, finalHeight); + this._forceUpdate = false; + } + } +} diff --git a/scripts/build-engine/package-lock.json b/scripts/build-engine/package-lock.json index e3232c5058..fc42763921 100644 --- a/scripts/build-engine/package-lock.json +++ b/scripts/build-engine/package-lock.json @@ -1,6 +1,6 @@ { "name": "@cocos/build-engine", - "version": "4.4.1-alpha.10", + "version": "4.4.1-oh.0", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/scripts/build-engine/package.json b/scripts/build-engine/package.json index ce1dcf7e70..f672b46f1c 100644 --- a/scripts/build-engine/package.json +++ b/scripts/build-engine/package.json @@ -1,6 +1,6 @@ { "name": "@cocos/build-engine", - "version": "4.4.1-alpha.10", + "version": "4.4.1-oh.0", "description": "", "repository": { "type": "git", diff --git a/scripts/build-engine/src/constant-manager.ts b/scripts/build-engine/src/constant-manager.ts index 9b72c42db8..d30868a72a 100644 --- a/scripts/build-engine/src/constant-manager.ts +++ b/scripts/build-engine/src/constant-manager.ts @@ -15,6 +15,10 @@ export interface ConstantOptions { mode: ModeType; platform: PlatformType; flags: Partial>; + /** + * @experimental + */ + forceJitValue?: boolean; } export type BuildTimeConstants = Record; export type CCEnvConstants = Record; @@ -99,6 +103,9 @@ export class ConstantManager { const info = config[key]; jsonObj[key] = info.value as ValueType; } + if (typeof options.forceJitValue !== 'undefined') { + jsonObj['SUPPORT_JIT'] = options.forceJitValue; + } return jsonObj as BuildTimeConstants; } @@ -122,6 +129,7 @@ export class ConstantManager { mode, platform, flags, + forceJitValue, }: ConstantOptions): string { const config = this._getConfig(); // init helper @@ -157,6 +165,10 @@ export class ConstantManager { info.value = this._evalExpression(info.value, config); } } + if (typeof forceJitValue !== 'undefined') { + const info = config['SUPPORT_JIT']; + info.value = forceJitValue; + } // generate export content for (const key in config) { diff --git a/scripts/build-engine/src/index.ts b/scripts/build-engine/src/index.ts index bd9c5817f4..9915db17da 100644 --- a/scripts/build-engine/src/index.ts +++ b/scripts/build-engine/src/index.ts @@ -170,6 +170,11 @@ namespace build { * Generate cocos/native-binding/decorators.ts for native platforms */ generateDecoratorsForJSB?: boolean; + + /** + * Whether force SUPPORT_JIT to the specified value. + */ + forceJitValue?: boolean, } export interface Result { @@ -270,6 +275,9 @@ async function doBuild({ ...intrinsicFlags, ...options.buildTimeConstants, }; + if (typeof options.forceJitValue !== undefined) { + buildTimeConstants['SUPPORT_JIT'] = options.forceJitValue as boolean; + } const moduleOverrides = Object.entries(statsQuery.evaluateModuleOverrides({ mode: options.mode, @@ -284,8 +292,10 @@ async function doBuild({ // HACK: get platform, mode, flags from build time constants const flags: Record = {}; - ['SERVER_MODE', 'NOT_PACK_PHYSX_LIBS', 'DEBUG', 'NET_MODE', 'WEBGPU'].forEach((key) => { - flags[key] = buildTimeConstants[key]; + ['SERVER_MODE', 'NOT_PACK_PHYSX_LIBS', 'DEBUG', 'NET_MODE', 'WEBGPU', 'SUPPORT_JIT'].forEach((key) => { + if (key !== 'SUPPORT_JIT' || typeof buildTimeConstants['SUPPORT_JIT'] !== 'undefined') { + flags[key] = buildTimeConstants[key]; + } }); // Wether use webgpu const useWebGPU = flags['WEBGPU']; @@ -316,6 +326,7 @@ async function doBuild({ platform, mode, flags, + forceJitValue: options.forceJitValue, }); console.debug(`Module source "internal-constants":\n${vmInternalConstants}`); rpVirtualOptions['internal:constants'] = vmInternalConstants; diff --git a/scripts/native-pack-tool/package.json b/scripts/native-pack-tool/package.json index 05a59e27ae..1d9c41c389 100644 --- a/scripts/native-pack-tool/package.json +++ b/scripts/native-pack-tool/package.json @@ -17,6 +17,7 @@ "iconv-lite": "^0.4.24", "xxtea-node": "^1.1.4", "yargs": "^17.5.1", - "zlib": "^1.0.5" + "zlib": "^1.0.5", + "json5":"^2.2.1" } } diff --git a/scripts/native-pack-tool/source/index.ts b/scripts/native-pack-tool/source/index.ts index c94499657d..6d4e265365 100644 --- a/scripts/native-pack-tool/source/index.ts +++ b/scripts/native-pack-tool/source/index.ts @@ -3,6 +3,7 @@ import { nativePackToolMg } from './base/manager'; import { MacPackTool } from './platforms/mac'; import { WindowsPackTool } from './platforms/windows'; import { AndroidPackTool } from './platforms/android'; +import { OpenHarmonyPackTool } from './platforms/openharmony'; import { OHOSPackTool } from './platforms/ohos'; import { IOSPackTool } from './platforms/ios'; import { HuaweiAGCPackTool } from './platforms/huawei-agc'; @@ -11,6 +12,7 @@ nativePackToolMg.register('ios', new IOSPackTool()); nativePackToolMg.register('mac', new MacPackTool()); nativePackToolMg.register('windows', new WindowsPackTool()); nativePackToolMg.register('android', new AndroidPackTool()); +nativePackToolMg.register('openharmony', new OpenHarmonyPackTool()); nativePackToolMg.register('ohos', new OHOSPackTool()); nativePackToolMg.register('huawei-agc', new HuaweiAGCPackTool()); diff --git a/scripts/native-pack-tool/source/platforms/openharmony.ts b/scripts/native-pack-tool/source/platforms/openharmony.ts new file mode 100644 index 0000000000..abfe594c7d --- /dev/null +++ b/scripts/native-pack-tool/source/platforms/openharmony.ts @@ -0,0 +1,217 @@ + +import { CocosParams, NativePackTool } from "../base/default"; +import * as ps from 'path'; +import * as fs from 'fs-extra'; +import { cchelper, Paths } from "../utils"; +import { randomBytes } from "crypto"; +import { outputJSONSync } from 'fs-extra'; +import * as JSON5 from "json5" + +export interface IOrientation { + landscapeLeft: boolean; + landscapeRight: boolean; + portrait: boolean; + upsideDown: boolean; +} + +export interface OHOSParam { + sdkPath: string; + ndkPath: string; + orientation: IOrientation; + packageName: string; +} + +export class OpenHarmonyPackTool extends NativePackTool { + params!: CocosParams; + + initEnv() { + this.setEnv('OHOS_SDK_HOME', this.params.platformParams.sdkPath); + } + + async create() { + await this.copyCommonTemplate(); + await this.copyPlatformTemplate(); + await this.generateCMakeConfig(); + + const ohosProjDir = this.paths.platformTemplateDirInPrj; + const platformParams = this.params.platformParams; + const assetsDir = this.paths.buildAssetsDir; + // local.properties + await cchelper.replaceInFile([ + { reg: '^sdk\\.dir.*', text: `sdk.dir=${platformParams.sdkPath}` }, + ], ps.join(ohosProjDir, 'local.properties')); + + // entry/build-profile.json5 + const buildCfgFile = ps.join(ohosProjDir, 'entry/build-profile.json5'); + await cchelper.replaceInFile([ + { reg: '={DRES_DIR}', text: `=${cchelper.fixPath(this.paths.buildDir!)}` }, + { reg: '={DCOMMON_DIR}', text: `=${cchelper.fixPath(process.env.COMMON_DIR || '')}` }, + { reg: /"compileSdkVersion": *,/, text: `"compileSdkVersion": ${platformParams.apiLevel},}` }, + ], buildCfgFile); + + //write abi + try { + const abiFilters = (platformParams.appABIs && platformParams.appABIs.length > 0) ? platformParams.appABIs : ['armeabi-v7a']; + let buildCfgContent = fs.readFileSync(buildCfgFile); + let buildCfgJson = JSON5.parse(buildCfgContent.toString()); + buildCfgJson.buildOption.externalNativeOptions.abiFilters = abiFilters; + + fs.writeFileSync(buildCfgFile, JSON5.stringify(buildCfgJson, null, 2)); + } catch (e) { + console.log(`rewrite buildCfgJson err: ${e}`); + } + + const moduleFile = ps.join(ohosProjDir, 'entry/src/main/module.json5'); + let moduleJSON = this.readJSON5Sync(moduleFile); + const cfg = platformParams.orientation; + if (cfg.landscapeLeft && cfg.landscapeRight && cfg.portrait) { + moduleJSON.module.abilities[0].orientation = 'auto_rotation'; + } + else if (cfg.landscapeRight && !cfg.landscapeLeft) { + moduleJSON.module.abilities[0].orientation = 'landscape'; + } + else if (!cfg.landscapeRight && cfg.landscapeLeft) { + moduleJSON.module.abilities[0].orientation = 'landscape_inverted'; + } + else if (cfg.landscapeRight && cfg.landscapeLeft) { + moduleJSON.module.abilities[0].orientation = 'auto_rotation_landscape'; + } + else if (cfg.portrait) { + moduleJSON.module.abilities[0].orientation = 'portrait'; + } + outputJSONSync(moduleFile, moduleJSON, { spaces: 2 }); + + // copy jsb-adapter to entry/src/main/ets/cocos/jsb-adapter + const mainDir = ps.join(ohosProjDir, 'entry/src/main'); + await cchelper.copyFileSync("", ps.join(assetsDir, 'jsb-adapter/engine-adapter.js'), "", ps.join(mainDir, 'ets/cocos/jsb-adapter/engine-adapter.js')); + await cchelper.copyFileSync("", ps.join(assetsDir, 'jsb-adapter/web-adapter.js'), "", ps.join(mainDir, 'ets/cocos/jsb-adapter/web-adapter.js')); + + const cfgFile = ps.join(ohosProjDir, 'AppScope/app.json5'); + let configJSON = this.readJSON5Sync(cfgFile); + configJSON.app.bundleName = platformParams.packageName; + outputJSONSync(cfgFile, configJSON, { spaces: 2 }); + + const stringJSONPath = ps.join(ohosProjDir, 'entry/src/main/resources/base/element/string.json'); + const stringJSON = fs.readJSONSync(stringJSONPath); + stringJSON.string.find((item: any) => item.name === 'MainAbility_label').value = this.params.projectName; + outputJSONSync(stringJSONPath, stringJSON, { spaces: 2 }); + + const packageJsonPath = ps.join(ohosProjDir, 'package.json'); + const packageJson = fs.readJSONSync(packageJsonPath); + packageJson.name = this.params.projectName; + fs.writeJSONSync(packageJsonPath, packageJson, { + spaces: 4, + }); + + return true; + } + + async make() { + this.initEnv(); + const ohosProjDir = this.paths.platformTemplateDirInPrj; + if (!fs.existsSync(ps.join(ohosProjDir, 'node_modules'))) { + console.debug(`Start install project ${ohosProjDir}`); + //set OpenHarmony npm repo + await cchelper.runCmd('npm', ['config', 'set', '@ohos:registry=https://repo.harmonyos.com/npm/'], false, ohosProjDir); + // install + await cchelper.runCmd('npm', ['i'], false, ohosProjDir); + } + console.debug(`Start buildOhosHap in ${ohosProjDir}`); + + // npm run buildOhosHap + await cchelper.runCmd('npm', ['run', 'build'], false, ohosProjDir); + return true; + } + // --------------- run ------------------// + async run(): Promise { + this.initEnv(); + const sdkPath = process.env['OHOS_SDK_HOME']; + if (!sdkPath) { + return false; + } + const hdc = this.findHDCTool(sdkPath); + const hdcCwd = ps.dirname(hdc); + const hdcExe = "hdc_std"; + const projectDir = this.paths.platformTemplateDirInPrj; + const packageName = this.params.platformParams.packageName; + let configJson = this.readJSON5Sync(ps.join(projectDir, 'entry/src/main/module.json5')); + //const moduleId = configJson.module.package + configJson.module.abilities[0].name; + const ability = configJson.module.abilities[0].name; + const moduleName = configJson.module.name; + const hapFile = this.selectHapFile(projectDir); + console.debug(`Start run hap ${hapFile} ...`); + console.debug(`${hdc} uninstall ${packageName}`); + await cchelper.runCmd( + hdcExe, ['uninstall', packageName], false, hdcCwd); + console.debug(`${hdc} install -r ${hapFile}`); + await cchelper.runCmd( + hdcExe,['install', '-r', hapFile], false, hdcCwd); + console.debug(`${hdc} shell aa start -a ${ability} -b ${packageName}`); + await cchelper.runCmd( + hdcExe, ['shell', 'aa', 'start', '-a', ability, '-b', packageName, '-m', moduleName], false, hdcCwd); + return true; + } + + findHDCTool(sdkPath: string): string { + const versionList = fs.readdirSync(ps.join(sdkPath, 'toolchains')); + if (!versionList.length) { + throw new Error('Please install hdc_std tool fist, doc: https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/subsystems/subsys-toolchain-hdc-guide.md') + } + return ps.join(sdkPath, 'toolchains', versionList[0], 'hdc_std'); + } + + private readJSON5Sync(json5FilePath: string): any { + let json5FileContent = fs.readFileSync(json5FilePath); + return JSON5.parse(json5FileContent.toString()); + } + + private selectHapFile(projectDir: string): string { + const outputDir = ps.join(projectDir, 'entry/build/default/outputs/default'); + if (!fs.existsSync(outputDir)) { + throw new Error(`directory ${outputDir} does not exist!`); + } + const hapFiles = fs.readdirSync(outputDir).filter(x => x.endsWith(`.hap`)); + if (hapFiles.length === 0) { + throw new Error(`no hap found in ${outputDir}`); + } else if (hapFiles.length === 1) { + return ps.join(outputDir, hapFiles[0]); + } + // first use signed hap + const opt1 = hapFiles.filter( + x => x.endsWith('-signed.hap')); + const opt2 = hapFiles.filter(x => x.endsWith('-unsigned.hap')); + const hapName = opt1.length > 0 ? opt1[0] : + (opt2.length > 0 ? opt2[0] : hapFiles[0]); + return ps.join(outputDir, hapName); + } + + get hdcPath(): string | null { + if (this.params.platformParams.sdkPath) { + return ps.join(this.params.platformParams.sdkPath, 'toolchains/hdc'); + } + return null; + } + + randString(n: number): string { + if (n <= 0) { + return ''; + } + let rs = ''; + try { + rs = randomBytes(Math.ceil(n / 2)).toString('hex').slice(0, n); + } catch (ex) { + rs = ''; + const r = n % 8; + const q = (n - r) / 8; + let i: number = 0; + for (; i < q; i++) { + rs += Math.random().toString(16).slice(2); + } + if (r > 0) { + rs += Math.random().toString(16).slice(2, i); + } + } + return rs; + } +} + diff --git a/scripts/native-pack-tool/source/utils.ts b/scripts/native-pack-tool/source/utils.ts index e9cea4daa8..585898ec54 100644 --- a/scripts/native-pack-tool/source/utils.ts +++ b/scripts/native-pack-tool/source/utils.ts @@ -277,7 +277,7 @@ export class cchelper { await cpRAsync(srcRoot, from, copyTo); } - static async replaceInFile(patterns: { reg: string, text: string }[], filepath: string) { + static async replaceInFile(patterns: { reg: string | RegExp, text: string }[], filepath: string) { filepath = this.replaceEnvVariables(filepath); if (!fs.existsSync(filepath)) { console.log(`While replace template content, file ${filepath}`); diff --git a/templates/cmake/openharmony.cmake b/templates/cmake/openharmony.cmake new file mode 100644 index 0000000000..762f0192e9 --- /dev/null +++ b/templates/cmake/openharmony.cmake @@ -0,0 +1,18 @@ +macro(cc_openharmony_before_target target_name) + list(APPEND CC_COMMON_SOURCES + ${COCOS_X_PATH}/cocos/platform/openharmony/napi/NapiInit.cpp + ) + set(CC_ALL_SOURCES ${CC_COMMON_SOURCES} ${CC_PROJ_SOURCES}) + cc_common_before_target(${target_name}) +endmacro() + +macro(cc_openharmony_after_target target_name) + + target_link_libraries(${target_name} + ${ENGINE_NAME} + ) + target_include_directories(${target_name} PRIVATE + ${CC_PROJECT_DIR}/../common/Classes + ) + cc_common_after_target(${target_name}) +endmacro() \ No newline at end of file diff --git a/templates/openharmony/.gitignore b/templates/openharmony/.gitignore new file mode 100644 index 0000000000..e5b4043b0c --- /dev/null +++ b/templates/openharmony/.gitignore @@ -0,0 +1,6 @@ +/node_modules +/local.properties +/.idea +**/build +/.hvigor +log.txt \ No newline at end of file diff --git a/templates/openharmony/AppScope/app.json5 b/templates/openharmony/AppScope/app.json5 new file mode 100644 index 0000000000..3438095bfb --- /dev/null +++ b/templates/openharmony/AppScope/app.json5 @@ -0,0 +1,11 @@ +{ + "app": { + "bundleName": "com.example.openharmonydemo", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:app_icon", + "label": "$string:app_name", + "distributedNotificationEnabled": true + } +} diff --git a/templates/openharmony/AppScope/resources/base/element/string.json b/templates/openharmony/AppScope/resources/base/element/string.json new file mode 100644 index 0000000000..3eb436c973 --- /dev/null +++ b/templates/openharmony/AppScope/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "app_name", + "value": "OpenHarmonyApp" + } + ] +} diff --git a/templates/openharmony/AppScope/resources/base/media/app_icon.png b/templates/openharmony/AppScope/resources/base/media/app_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..2b6f32ae038cca6190392754a2a90ba4dff00204 GIT binary patch literal 9915 zcmV;sCPdkZP)PyA07*naRCr$PeF=D6Wx4}gTj@n2vVU?1wm96 zv54&Df^u23F7yfowXDTnC`f5p%2iPo^}6F$9G)9)O1!Tj+VnoPA+jJ83iU8a zPJ$uKkED-j{}6Cf`%mjT(S4)#}X5tiA{;*BDEoUs4Oc@U<{^d z0;b7F`t#opE4(S2bokvv&el$dE4Fie9cUEExZwvOkV zM?YU zgn=fWfZ@^}{2(~(mQa$`RHdX^0FXp; zqcUT!+1Dp#bYI4)#xN=q?>Rfrbh?fSzMWg>>ZheTtckW$;G->B9twv@y)#Jy1Nw!8Uh*le@<$m zc`!&N6g4DgQac}f>!nSf15mV?q#gil+EHfCo4>I!p8SMXDwP;xs^3QKK_KYnh5=?6 zFcp<3*dwxHER)Llp0N?cOC?2B)$HiVFSfq;+#&#)CDblD@{X5&CtlaO=gxaD*3x>S zn0!ffvH4_#zYD0zMN3QqD~u!eo+A<3_BzyoZ7?HI4oLYkEsdBIF8}52Z|X4CHVEmF z;fJ>UOyBni@Z4*3HP#n7o2 zqUYO7!L$-gRds{lQh}*x#O?!vgAfX-!`rs5=->J}*#thvE*zb{Yg3}__>MXIZZtHl zsO_7`9&jUoaY?U_~8zOu>vbHz4`5JE1qXff=@w@lOYY9YIcPeg3ce zjgOD-;3G_QbY0ZiHR}dVD`^tv{y-Ee*uGOhND^4FfYOXEj4u2fQlI=R!2R(~2|4{8M0f>1~q*s}TJp&i?9)PjZKG}29IpWAX}fQ z0pWA_YS@UWdQ9YQ%K0oN_B$98a~B}-%k|iD{ePj@)dQB-IGdWXgsxTphWKB83azOX z5`p02gntT+&?QNd@|n!N*}HS@{1=%dMJ?ATm>X(wc_5`%r!6PL)dd7k zL+IS+@4sjT+W+%E5PtJzWIlKddM~~aEU$}d8{N`0F!SaM5!>_|=#5FC3AXNfB)zJ| z-n|+@^*&~rMt9s0aIp7Nmfk(25vHs{86Cptac5xgtjn?YISV1@ z#$c!+NW}uQWGA-$`~5H?F`&eAkuVkEE%mHC2jLwrLytDQLGZaMy90(Y~XJO~(FM&L!!6X^d447dV%E(UitUL?q&^8#6MlkN8dY*5$ zYedk4nua9FQf_SQ3Dz@j!9Ubccs?a8ta_(!vda@!YtnYLMo{ESmA6nB+rEE4^kge$ zFa0#+u@NgBZ3SI)oL0p4W%pow-vyA!9zX)qbm$QU;l8)fbMsk{vqLaLltJ~!3H-74 zED$DR5-U!OzszRMKe%636g&4*izSKq%zN`7nqGIfb34Ux(3!CqYhIRAg8nL={9|eh%HYp9^N{AiGj7=mbQ~Q__g( z0l_suE0t0e02~w)%rw&jBDm9|T6%+`5EW8(6!}AsMBkM^gb|aFc;o@J-}3Jc>Gyau zbQ7H-*j4F`3IIJ80E{R|q@n%OZIR+` z1wv9FWkxXcg=;Z-{3(#L8cfAR&sCpAXxnC(RCoz&y>yI<4017#;>>y2cJW$K{WGXo zWA#LmCg>XUsEXv1YtjDG@4$#r8rxf2E;l3w2Fq?6F)fYo17KCag#7xgkjsh(Dyip7 z@oP0hUHKb7PF5hLhmra45)3R|4mnqVo(LoU>z`xBs*7MWwpc#Ab(3I8;CCc`S2DvG zUUV6Tk2|wsknQ#;4ubHGS|7U=ZBO0=J=Q9&PsRU9Cbiaqnud&OE&=cSP-CT4!~G=#Ul2s0cldo5*P zt1<-{R|Ak`Y`1CLAGszX=pIRD%v-$K=Kc(p~u>|yeO$544!!fl;Hui zZ2U3wM5`4$1mAE<9#iEKCYZzw7XVc#s5TI;>2OO!JsM$oFVyGLx9olt_nHG~ya>HH zgr+|}fsR$@TNFXk>6WdUK=24UjocweqwnmSz{W*zX7?>~=Z9#A(iR~F9UHDe;+b{O z;_XmUgV_G9yCG*rG4s3ULrb&?+vB?bWQMxB9kHImgv1!vfbMw)fcI@tOZd$EtH-#NxjEjWZeO zpBD#6R*FJPbYc62>tLuc(Ogd%Q>q=?bVMNV$JWuk=3IpGTd?H^kMsJ%tYx1;X#48` zxvX|4UVsx8iO#%R}0s9_c*?@`{_dL``m%36%? zwE%3K3N#)NI1nbF%P?mGa#DvLl@b5dFVK1OB`|o$g`G*=C9U|}2wNI3zoG$EC@7fr zD&Gdu5=pLPWw*=0934r)RssEI{utv2ydTnp1}I`>j~S8CdCS>|{^NI|*T<7Su3oFI z?(#CS1ru3}&v`F)oU|@)hwf-?99aB%wI>K!jdXHO3Zx0W4RtCSQjcRS|vV zujsh#beN$S80Xv?3BOtz;hhgEs45;y_(Chs*CN-fRJ!kO&OSV z-RTIwvB~8Mdp)9Q0Ko$>ZiHvf-QN`lxar<;X~%^7HNtrugH)J6>YQ(&>CrV%2Kz+* zo_Ie$g6z9az~HIh2P>9@hryM^fZ3p+^RA_czW5Z31|j`5Db8ltdhCN$TcFg#w(~Y{ z`a{VId+f<4h6zDv06}l)(Blf)*L)u>)b7%hbUOq-84a+9!PLPWFW#!?27s@6aLaXo zlsgwj1Oh=SpB}-^<@cfC=_e3>^e*TvGa!v;P-@>7eP`Y;(h64RsXh6TH=je-?We$0 zDdpe}J$DHZ+$~KZ{hlS*x#XK*+%2_Y1DX;t4UGWnBv*`vpmUF`=?_n$Yt;oXV$H!# zU(*A^1Ayg*R@x?m_}vp+RMQAqhLlNRVEF^Q_|bX!i7;bLT&nucSchWw{$NGoeNq4C z07MncSbG5)pZ__GsQsXRFY9ds!LzM7^nHFc^7GygmZu`Jl`$nek_@1n00)4yQby#} z7twwF=>SFOF2M+*=?ec(vP#GTKufW%x$}4&V5O@p{qsA!9^G)>$sz-5KqP6oF$`Y0 z8u|P0Kso1U!c--wL;dLa_Q_zS2~L@8vh;O*8sPw7&OC<~ zL>v^%`(;RiXvwJ@+~AF2@X}k6JN9Ep-nbmn8)*zJ`JRwCSr(FSbAMDp`})h!`1glk zL=&EzkH@136uPMaVOj=x_+ytN^{;0NgKYJpaRADJugSeQs!z=N&SEI3UYJU_T#u-$ zpUE+Nk46XpbkYC31h-yUUj`dV)b2-0dx1^pJO#qq{K7}>XwQwGNBGTv zv`AnqS{F5WG(eJhDk7*QeaaePQP9w(cOv(}k3yO-VZH`n%m6|*O;xzRZR3?_`uk5{ zMD5OIHx5<0MWX_J^;79&^M3wX|$#S8*t`K0Xt>AFy5PsDj34e}&Gwzv>7OgB%sV=NPQe{MT>4vnwH)zhZim_6;Qkf5|sP^I@f&)Odl6TlB%77yH_JjvIDshq>lP3MvlD@Qoh8Syedj3 z8hzDNA9_|T1}hb;0*yCPpRz_&yr7QRbGZ?=YrnJN%go8ah@ zqQ0$lk>Ko$mi1X&mqY?VX$?Rn*%kc!sF zRv_`m+o4C3JQncNTpd7EPIA})0>IV)YeOIh33^;lhq{$k$l^uKyY_?1S3Z-!{|rOt>mek9)T5%88H>jf4moMzr0!i zV6QQ#rxsy*%}!T?GJ0hj-~_;)ZXXj>(FmUyFmANu{0K5foQ=^X*9rhEF9@2Tq2|YK zMDtVMhtcRvKR7&|@{fU*&cE3}0FBi)*7Q6Qdz^r{Z1^HJ<23@!gASk%WjUfA>FJW}aw?x^o+@&nK z57fTR=(zLv3ikwP)8y1ttvDV;O+kK<2~!TE@6?A;N_1PzS04W7QcGzQ1(6+_F!TOX zVXD-sXz(o)j3_k@c%o-t*ceDnmKUU@So^Gf%0`&q-j|D+A`n*PDRUjH@BaNMf@R$nGmo0_Hp1Vy`47igQ0zR#}rcr;!kY{dfUKFqxTB*>W& zUO&hjdn!VkHzB;4>cw{3d}XpHu@MywXz$tE6$exTPwyq_1j6e1$se)^Bd4wszO`L- z;s6L^9Q)fNNN)TpjA%=_`=OS{wM#XE_oI#?JO3mM9`il00(okd|8GBb`SDF28&D9| zbLU54wl`zwqHBSYimoe9b4;B1EaPR zS7R&%+_VE$8Z*`$11UemSH)EJ)O7$KWawRCbFiBl%xI2p$xcm-VEBk@kv{AUun7wQ z@8r|(^iQKgjfNPW#Q0H1L2qe5_m@vb__Y^cMk~!@KK7|sR$PU4kKI-5P>;x z@~;bN6y_d<;nVKnn`!XN@>W2*CzG@wgqB}ig~q?#1tTCIR6Wn)a4BmV>l$q|oPzQg zIPM-y%z7VK$xaA5XwcrEne6OL26li1gDj;A#5Zn4+YOh%h_`U}x*`*Gx6xGG(Dv@x zBTS}1jM>pYUSg zm)*<@7DMUX8c087@d&c}6^-x!P^KVpgkOcd4;*lH+jS-BD&|n^c`t@Pw?VjS_6ijn z0J|rX0d4CSBQ)@LM>AG%tTAb2t{OFYf#A}gL!t99^dI*V|H2QNc-k##KL$2m0>aj= zpR@=tAtQ0$-ALYY4U9z6lKyH<12u|EU>pFGYQpW^dyOzV7gVMo@ifx{f^0xBk5cD> z7(C-K;RUHyz1MDn;;rF=h8q968j0V2!%EE2ZVAE0tU`(PYDAEIpvO`mPo$7J=nM>h zrm>N^>R@08GoYP`-|ZHaumpK5gRZ5YORA2BH9)Cjr!&Xm3K#-wHq(Q5q{SPQggI>WW0H!~ zsHiPGtRngI^AUaZAs7*AOR01r?;ao+Xj}uwuS22j5Mh9OWU&1t-WkW&5Rk(1ZOO?6 z75zc&%P&RjsSPk_$&zJw#e6%Q0+;goY1#pV1AwksmJzlJGIs95l75$KH5HAZv@UfO z8zx4-eK!gpJREGZ26LMP>@WjPBb3f{Gg@^08HQ7~OasPbm|IO?kP7vbfh?kZ!zZDn z-UJjYs`QQfZ34mb{1TM09mvl=7K2}21J)t>frKzv|EMHM#d*nq(I}&J<+W&fbTy1b zyAUXQ`h(`BevPQ4B3iq8tZb;m4fXJ6P0!`1XfYI0qXa!5grVt2v#IF)niv%GnH?yo0m+W;5s62_9#Ja`ljDLO-kTZ_VkZ=q z8-w06AE|5Bi#dA`l@ z_`%0u>{H87n!PVrflA)GSdrtMcrN)GjD(8j^>-q1&vh`GC`o8Vjt)xp-!@1a0?n}i zO0b0!fSLVFk~_*>5gz`p)Sh<{5Q++x9fdaM-AG-v4n`ynR^7Eh~+0Al-AM1TFC zX!!F6$YTS1I~wo~a~vjk^cCl$RBo`sF#qdsYqZX`QFLrv5A=crbq8V z%bKslXiQi@yEYHlbxi{VfFv8> zN5uX<_KFo!d#(`*U$m|CZb$UDcO&}e^^nK<#0p9Rf|fDy<*oFBhcx$~vLE;&GDm$C zMl%6RbzVv>R3@HrFULVW*5o%n{s5AzFLP}K?pAoO017Ferbcits8lSz%;L%R$3x-B zLX+MB#zfb?KPl?Jx!*=OydMu$IW2hkD59gx5Q^_U2BR0sDIgvWIMzeg2EB=_kj*^7V)4YvNUZS!{wgM4o0=FzU`47P zjhGAw+8rxBh>7s-xF?<^zFC+ z!%pGuq)j(`TkIgZp>TlyW{Sy={^>C!Z$A&9T~YWVZY#gzrQ%)Ly#eTwEX(QC;7u&l z5Id!*x#d1n^iU>^2#97qZJ0 zuPTrZyXz~G`UFvITRGCZ^;8B#_D*&rUj&%gy4X6~nsO&2)j>^@WKgSVgsehN4puG z#&2ymCmfSS-K9hc3spAR2F86^_KdLR!GczwoH1k0V|4=#?hl00Qhv4IntZ z*zXdeU!2LfYTlMOM&M#!+i@Pnn%>=VYd%9|rUUImHPC`xv8_?F?`9j@0{ z*_WZyTAJHBHZdl3h%L;x^7?pkj{;GCNRN01uBLK;?gGKV^MQ-|ygjc$)MV+2*Jf1H z2KV>0GMpKPKG3`Q9|u8HLWD**hQ_rZ91b5JZBA~am(AFf(O?zzwvkTu5MGV&N`H{w z?VV81(^`}4pOb$oASk4#7d9wE+qW&sXGQ~GWoYBTUo_beYrZ}bjb3J&MhT9Wd2;0r z;K}J|#BNJ(l#Pjdpl({Kr4d1WKGW9-m?+7Ls%A!pR-|_J)_j?#EnfU}wvEln2h~vc zL=FO&>WW!gerDw*6>b$S+Y}e2 zS2@RFg#FG%4Z9L_UVvc^rlvYu@q;Oux1Gs~Ea$VC2ZwjOHRV^DJ3-({l7?8*_2Gut zWqhfr)vO&9HUL_{+9ybPZhsyAh?%9ag!v;&~$b8Jd?RSwX^qH0E5oAW(Ur^%W~8@qVhKz z1gNU|E;Z6{p&E*u%p@ts4-pZj{jLgI&?=piUYgleK$OjkKdx|yf%T(D-X`g1s@NP# zD2b;OT*f4c>d+E{q3gLqF1J3D8e3T^<({*SE6>$rQ(LbF*w+z~F0_F@vl|*>C(5D7 zB3Y3SWs=lnU(nOI9q@9F+R463O2PREyTefXNXge^MTLJ+{1^8(bv>hL+TX^Dx8E@KUK* t_={OAK0Prp@rL7qyxddG(ALs|{{b2*2vZrNCnf*@002ovPDHLkV1lTm%^Uy# literal 0 HcmV?d00001 diff --git a/templates/openharmony/CMakeLists.txt b/templates/openharmony/CMakeLists.txt new file mode 100644 index 0000000000..ede723465a --- /dev/null +++ b/templates/openharmony/CMakeLists.txt @@ -0,0 +1,19 @@ +# the minimum version of CMake. + +cmake_minimum_required(VERSION 3.8) +set(CC_LIB_NAME cocos) +set(CC_PROJ_SOURCES) +set(CC_COMMON_SOURCES) +set(CC_ALL_SOURCES) + +option(APP_NAME "Project Name" "test-cases") +project(${APP_NAME} CXX) + +set(CMAKE_CXX_FLAGS_DEBUG "-Werror=return-type") + + +include(${COMMON_DIR}/CMakeLists.txt) + +cc_openharmony_before_target(${CC_LIB_NAME}) +add_library(${CC_LIB_NAME} SHARED ${CC_ALL_SOURCES}) +cc_openharmony_after_target(${CC_LIB_NAME}) \ No newline at end of file diff --git a/templates/openharmony/build-profile.json5 b/templates/openharmony/build-profile.json5 new file mode 100644 index 0000000000..cfb7fe59f2 --- /dev/null +++ b/templates/openharmony/build-profile.json5 @@ -0,0 +1,26 @@ +{ + "app": { + "compileSdkVersion": 9, + "compatibleSdkVersion": 9, + "products": [ + { + "name": "default", + "signingConfig": "default", + } + ] + }, + "modules": [ + { + "name": "entry", + "srcPath": "./entry", + "targets": [ + { + "name": "default", + "applyToProducts": [ + "default" + ] + } + ] + } + ] +} diff --git a/templates/openharmony/entry/.gitignore b/templates/openharmony/entry/.gitignore new file mode 100644 index 0000000000..5a6ba80fa3 --- /dev/null +++ b/templates/openharmony/entry/.gitignore @@ -0,0 +1,4 @@ +/node_modules +/.preview +/build +/.cxx \ No newline at end of file diff --git a/templates/openharmony/entry/build-profile.json5 b/templates/openharmony/entry/build-profile.json5 new file mode 100644 index 0000000000..f3d96460c6 --- /dev/null +++ b/templates/openharmony/entry/build-profile.json5 @@ -0,0 +1,22 @@ +{ + "apiType": 'stageMode', + "buildOption": { + "externalNativeOptions": { + "path": "../CMakeLists.txt", + "arguments": "-v -DOHOS_STL=c++_shared -DRES_DIR={DRES_DIR} -DCOMMON_DIR={DCOMMON_DIR} -DOPENHARMONY=1", + "abiFilters": [ + "armeabi-v7a", + "arm64-v8a" + ], + "cppFlags": "", + } + }, + "targets": [ + { + "name": "default" + }, + { + "name": "ohosTest", + } + ] +} diff --git a/templates/openharmony/entry/hvigorfile.js b/templates/openharmony/entry/hvigorfile.js new file mode 100644 index 0000000000..d7720ee6a7 --- /dev/null +++ b/templates/openharmony/entry/hvigorfile.js @@ -0,0 +1,2 @@ +// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently. +module.exports = require('@ohos/hvigor-ohos-plugin').hapTasks diff --git a/templates/openharmony/entry/package-lock.json b/templates/openharmony/entry/package-lock.json new file mode 100644 index 0000000000..15bc7145be --- /dev/null +++ b/templates/openharmony/entry/package-lock.json @@ -0,0 +1,5 @@ +{ + "name": "entry", + "version": "1.0.0", + "lockfileVersion": 1 +} diff --git a/templates/openharmony/entry/package.json b/templates/openharmony/entry/package.json new file mode 100644 index 0000000000..dba669833f --- /dev/null +++ b/templates/openharmony/entry/package.json @@ -0,0 +1,14 @@ +{ + "license":"ISC", + "devDependencies":{}, + "name":"entry", + "ohos":{ + "org":"huawei", + "directoryLevel":"module", + "buildTool":"hvigor" + }, + "description":"example description", + "repository":{}, + "version":"1.0.0", + "dependencies":{} +} diff --git a/templates/openharmony/entry/src/main/cpp/README.md b/templates/openharmony/entry/src/main/cpp/README.md new file mode 100644 index 0000000000..991b84a80d --- /dev/null +++ b/templates/openharmony/entry/src/main/cpp/README.md @@ -0,0 +1 @@ +Need a cpp folder to fix the IDE can't compile native code for verion 3.0.0.992 \ No newline at end of file diff --git a/templates/openharmony/entry/src/main/ets/Application/GameAbilityStage.ts b/templates/openharmony/entry/src/main/ets/Application/GameAbilityStage.ts new file mode 100644 index 0000000000..5900fc1e1c --- /dev/null +++ b/templates/openharmony/entry/src/main/ets/Application/GameAbilityStage.ts @@ -0,0 +1,30 @@ +/**************************************************************************** + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +import AbilityStage from "@ohos.application.AbilityStage" + +export default class GameAbilityStage extends AbilityStage { + onCreate() { + } +} \ No newline at end of file diff --git a/templates/openharmony/entry/src/main/ets/MainAbility/MainAbility.ts b/templates/openharmony/entry/src/main/ets/MainAbility/MainAbility.ts new file mode 100644 index 0000000000..0481f5a036 --- /dev/null +++ b/templates/openharmony/entry/src/main/ets/MainAbility/MainAbility.ts @@ -0,0 +1,67 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +import Ability from '@ohos.application.Ability' +import nativerender from "libcocos.so"; +import { ContextType } from "../common/Constants" +import resourceManager from '@ohos.resourceManager'; + +const nativeContext = nativerender.getContext(ContextType.ENGINE_UTILS); +const nativeAppLifecycle = nativerender.getContext(ContextType.APP_LIFECYCLE); + +export default class MainAbility extends Ability { + onCreate(want, launchParam) { + globalThis.abilityWant = want; + nativeAppLifecycle.onCreate(); + nativeContext.resourceManagerInit(this.context.resourceManager); + } + + onDestroy() { + nativeAppLifecycle.onDestroy(); + } + + onWindowStageCreate(windowStage) { + // Main window is created, set main page for this ability + windowStage.loadContent("pages/index", (err, data) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + }); + nativeContext.writablePathInit(this.context.cacheDir); + } + + onWindowStageDestroy() { + } + + onForeground() { + // Ability has brought to foreground + nativeAppLifecycle.onShow(); + } + + onBackground() { + // Ability has back to background + nativeAppLifecycle.onHide(); + } +}; diff --git a/templates/openharmony/entry/src/main/ets/cocos/WorkerManager.ets b/templates/openharmony/entry/src/main/ets/cocos/WorkerManager.ets new file mode 100644 index 0000000000..989b7cfd70 --- /dev/null +++ b/templates/openharmony/entry/src/main/ets/cocos/WorkerManager.ets @@ -0,0 +1,54 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +import worker from '@ohos.worker'; +import {Constants} from '../common/Constants' + +export class WorkerManager { + private static instance: WorkerManager; + private cocosWorker: any; + + private constructor() { + this.cocosWorker = new worker.Worker("/entry/ets/workers/cocos_worker.ts", {type:"classic", name: "CocosWorker"}); + this.cocosWorker.onerror = function (e) { + var msg = e.message; + var filename = e.filename; + var lineno = e.lineno; + var colno = e.colno; + console.error(`on Error ${msg} ${filename} ${lineno} ${colno}`); + } + } + + public static getInstance(): WorkerManager { + if (AppStorage.Get(Constants.APP_KEY_WORKER_MANAGER) == null) { + AppStorage.SetOrCreate(Constants.APP_KEY_WORKER_MANAGER, new WorkerManager); + } + return AppStorage.Get(Constants.APP_KEY_WORKER_MANAGER); + } + public getWorker(): any { + return this.cocosWorker; + } +} + diff --git a/templates/openharmony/entry/src/main/ets/cocos/game.ts b/templates/openharmony/entry/src/main/ets/cocos/game.ts new file mode 100644 index 0000000000..841a5941f4 --- /dev/null +++ b/templates/openharmony/entry/src/main/ets/cocos/game.ts @@ -0,0 +1,110 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +import importMap from './src/<%= importMapUrl%>' +const commonJSModuleMap: Record = { + '/src/<%= applicationUrl%>'() { require('./src/<%= applicationUrl%>'); }, +<% if (chunkBundleUrl) { %> + '/src/chunks/<%= chunkBundleUrl%>'() { require('./src/chunks/<%= chunkBundleUrl%>') }, +<% } %> +<% for (var i = 0; i < ccUrls.length; i++) {%> + '/src/cocos-js/<%=ccUrls[i]%>' () { require('./src/cocos-js/<%=ccUrls[i]%>'); }, +<% } %> +<% for (var j = 0; j < bundleJsList.length; j++) {%> + 'assets/<%=bundleJsList[j]%>' () { require('./assets/<%=bundleJsList[j]%>'); }, +<% } %> +} +export function loadModule (name: string) { + const moduleExecutor = commonJSModuleMap[name]; + moduleExecutor?.(); +} +declare const require: any; +declare const System: any; + +// fix undefined console.time and console.timeEnd +const startTimeList = {}; +// @ts-ignore +console.time = function (tag) { + // @ts-ignore + startTimeList[tag] = Date.now(); +}; +// @ts-ignore +console.timeEnd = function (tag) { + // @ts-ignore + console.log(tag + ' ' + (Date.now() - startTimeList[tag])); + delete startTimeList[tag]; +}; + +// @ts-ignore +//const onTouch = () => new Promise(resolve => jsb.onTouchStart = function () { +// log('promise onTouch') +// resolve(); +//}) + +const onTouch = () => new Promise(resolve => resolve()) + +export function launchEngine (): Promise { + return new Promise((resolve, reject) => { + // @ts-ignore + window.global = window; + const systemReady = require('./jsb-adapter/sys-ability-polyfill.js'); + systemReady().then(() => { + // @ts-ignore + window.oh.loadModule = loadModule; + try { + require("./jsb-adapter/web-adapter.js"); + } catch (e) { + console.error('error in builtin ', e.stack, e.message); + } + + require("./src/<%= systemBundleUrl%>"); + System.warmup({ + importMap, + importMapUrl: './src/<%= importMapUrl%>', + defaultHandler: (urlNoSchema: string) => { + console.info('urlNoSchema ', urlNoSchema); + loadModule(urlNoSchema); + }, + }); + System.import('./src/<%= applicationUrl%>').then(({ Application }) => { + return new Application(); + }).then((application) => { + System.import('cc').then((cc) => { + require('./jsb-adapter/engine-adapter.js'); + cc.macro.CLEANUP_IMAGE_CACHE = false; + return application.init(cc); + }).then(() => { + return application.start(); + }).catch(e => { + console.log('error in importing cc ' + e.stack) + }); + }).catch((e: any) => { + console.error('imported failed', e.message, e.stack) + reject(e); + }) + }); + }) +} + + diff --git a/templates/openharmony/entry/src/main/ets/cocos/jsb-adapter/sys-ability-polyfill.js b/templates/openharmony/entry/src/main/ets/cocos/jsb-adapter/sys-ability-polyfill.js new file mode 100644 index 0000000000..37bcd9ff00 --- /dev/null +++ b/templates/openharmony/entry/src/main/ets/cocos/jsb-adapter/sys-ability-polyfill.js @@ -0,0 +1,168 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +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'; + +window.oh = {}; + +module.exports = function systemReady () { + return new Promise(resolve => { + if (typeof XMLHttpRequest === 'undefined') { + window.XMLHttpRequest = function () {} + } + display.getDefaultDisplay((err, data) => { + window.oh.display = data; + // TODO: impl device in js. + //https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-display-0000001281001106 + }); + resolve(); + }) + +} + +window.getSystemLanguage = function () { + return i18n.getSystemLanguage(); +} + +window.getOSFullName = function () { + return deviceInfo.osFullName; +} + +window.getBatteryLevel = function () { + return batteryInfo.batterySOC; +} + +window.getDPI = function () { + var displayClass = display.getDefaultDisplaySync(); + return displayClass.densityDPI; +} + +window.getPixelRation = function () { + var displayClass = display.getDefaultDisplaySync(); + return displayClass.densityPixels; +} + +window.getDeviceOrientation = function () { + var displayClass = display.getDefaultDisplaySync(); + return displayClass.rotation; +} + +function radiansToDegrees(radians) { + var pi = Math.PI; + return radians * (180/pi); +} + + +let sDeviceMotionValues = []; +try { + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function (data) { + sDeviceMotionValues[0] = data.x; + sDeviceMotionValues[1] = data.y; + sDeviceMotionValues[2] = data.z; + }, + { interval: 10000000000 } + ); +} catch (err) { + sDeviceMotionValues[0] = 0; + sDeviceMotionValues[1] = 0; + sDeviceMotionValues[2] = 0; +} + +try { + // TODO(qgh):Must pass values, macros have been renamed and can cause problems with linear sensors + //sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER,function(data){ + sensor.on(258,function(data){ + sDeviceMotionValues[3] = data.x; + sDeviceMotionValues[4] = data.y; + sDeviceMotionValues[5] = data.z; + }, + {interval: 10000000000} + ); +} catch (err) { + sDeviceMotionValues[3] = 0; + sDeviceMotionValues[4] = 0; + sDeviceMotionValues[5] = 0; +} +try { + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE,function(data){ + sDeviceMotionValues[6] = radiansToDegrees(data.x); + sDeviceMotionValues[7] = radiansToDegrees(data.y); + sDeviceMotionValues[8] = radiansToDegrees(data.z); + }, + {interval: 10000000000} + ); +} catch (err) { + sDeviceMotionValues[6] = 0; + sDeviceMotionValues[7] = 0; + sDeviceMotionValues[8] = 0; +} +// Keep this, in the master branch, this interface has been replaced. +//try { +// sensor.on(sensor.SensorId.ACCELEROMETER, function (data) { +// sDeviceMotionValues[0] = data.x; +// sDeviceMotionValues[1] = data.y; +// sDeviceMotionValues[2] = data.z; +// }, +// { interval: 10000000000 } +// ); +//} 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: 10000000000} +// ); +//} catch (err) { +// sDeviceMotionValues[3] = 0; +// sDeviceMotionValues[4] = 0; +// sDeviceMotionValues[5] = 0; +//} +//try { +// sensor.on(sensor.SensorId.GYROSCOPE,function(data){ +// sDeviceMotionValues[6] = data.x; +// sDeviceMotionValues[7] = data.y; +// sDeviceMotionValues[8] = data.z; +// }, +// {interval: 10000000000} +// ); +//} catch (err) { +// sDeviceMotionValues[7] = 0; +// sDeviceMotionValues[8] = 0; +// sDeviceMotionValues[9] = 0; +//} + +window.getDeviceMotionValue = function () { + return sDeviceMotionValues; +} diff --git a/templates/openharmony/entry/src/main/ets/common/Constants.ts b/templates/openharmony/entry/src/main/ets/common/Constants.ts new file mode 100644 index 0000000000..5fba78be9f --- /dev/null +++ b/templates/openharmony/entry/src/main/ets/common/Constants.ts @@ -0,0 +1,40 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +export enum ContextType { + APP_LIFECYCLE = 0, + JSPAGE_LIFECYCLE, + XCOMPONENT_CONTEXT, + XCOMPONENT_REGISTER_LIFECYCLE_CALLBACK, + NATIVE_RENDER_API, + WORKER_INIT, + ENGINE_UTILS, + EDITBOX_UTILS, + WEBVIEW_UTILS, + UV_ASYNC_SEND, +} + +export class Constants { + static readonly APP_KEY_WORKER_MANAGER = "app_key_worker_manager"; +} \ No newline at end of file diff --git a/templates/openharmony/entry/src/main/ets/common/PortProxy.ts b/templates/openharmony/entry/src/main/ets/common/PortProxy.ts new file mode 100644 index 0000000000..f1b420974b --- /dev/null +++ b/templates/openharmony/entry/src/main/ets/common/PortProxy.ts @@ -0,0 +1,75 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +import worker from '@ohos.worker'; +import {DedicatedWorkerGlobalScope} from '@ohos.worker'; +import * as wk from '@ohos.worker'; + +export class PortProxy { + private autoId: number = 0; + public actionHandleMap = {} + private port :DedicatedWorkerGlobalScope = null; + + public _messageHandle?:(e:wk.MessageEvent) => void; + + constructor (port) { + this.port = port; + this.port.onmessage = this.onMessage.bind(this); + } + + public onMessage(e) { + let data = e['data']; + if(data.type != "syncResult" && this._messageHandle) { + this._messageHandle(e); + } else if(data.type == "syncResult") { + const {id, response} = data.data; + if (!this.actionHandleMap[id]) { + return; + } + this.actionHandleMap[id].call(this, response) + delete this.actionHandleMap[id]; + } + } + public postReturnMessage(e:any, res: any) { + if(e.type == "sync" && res != null && res != undefined) { + this.port.postMessage({type:"syncResult", data:{id:e.data.cbId, response:res}}); + } + } + public postMessage(msgName: string, msgData:any) { + this.port.postMessage({type:"async", data:{name:msgName, param:msgData}}); + } + + public postSyncMessage(msgName: string, msgData:any) { + const id = this.autoId++; + return new Promise((resolve, reject) => { + const message = { + type:"sync", data:{cbId:id, name:msgName, param:msgData} + } + this.port.postMessage(message); + this.actionHandleMap[id] = (response) => { + resolve(response) + } + }) + } +} \ No newline at end of file diff --git a/templates/openharmony/entry/src/main/ets/components/CocosVideoPlayer.ets b/templates/openharmony/entry/src/main/ets/components/CocosVideoPlayer.ets new file mode 100644 index 0000000000..86d2703a62 --- /dev/null +++ b/templates/openharmony/entry/src/main/ets/components/CocosVideoPlayer.ets @@ -0,0 +1,113 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +import { WorkerManager } from '../cocos/WorkerManager' +import { PortProxy } from '../common/PortProxy' + +enum EventType { + PLAYING = 0, + PAUSED, + STOPPED, + COMPLETED, + META_LOADED, + CLICKED, + READY_TO_PLAY, + UPDATE, + QUIT_FULLSCREEN = 1000 +}; + +@Observed +export class VideoInfo { + public x: number = 0; + public y: number = 0; + public w: number = 0; + public h: number = 0; + // url + public url: string = "" + public viewTag: string = '' + public visible: boolean = true + + public duration: number = 0; + public currentTime: number = 0; + public isFullScreen: boolean = false; + public currentProgressRate:number | string | PlaybackSpeed; + + /** + * https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/arkui-ts/ts-media-components-video.md#videocontroller + * + */ + public controller: VideoController = new VideoController() + + constructor(x: number, y: number, w: number, h: number, viewTag: string) { + this.x = x; + this.y = y; + this.w = w; + this.h = h; + this.viewTag = viewTag + } +} + + +@Component +export struct CocosVideoPlayer { + @ObjectLink videoInfo: VideoInfo; + public workPort: PortProxy; + build() { + Video({ src: this.videoInfo.url, controller: this.videoInfo.controller, currentProgressRate:this.videoInfo.currentProgressRate }) + .position({ x: this.videoInfo.x, y: this.videoInfo.y }) + .width(this.videoInfo.w) + .height(this.videoInfo.h) + .controls(false) + .autoPlay(true) + .onStart(() => { + this.workPort.postMessage("onVideoEvent",{videoTag:this.videoInfo.viewTag, videoEvent:EventType.PLAYING}); + }) + .onPause(() => { + this.workPort.postMessage("onVideoEvent",{videoTag:this.videoInfo.viewTag, videoEvent:EventType.PAUSED}); + }) + .onFinish(() => { + this.workPort.postMessage("onVideoEvent",{videoTag:this.videoInfo.viewTag, videoEvent:EventType.COMPLETED}); + }) + .onPrepared((event: { + duration: number; + }) => { + this.videoInfo.duration = event.duration; + this.workPort.postMessage("onVideoEvent",{videoTag:this.videoInfo.viewTag, videoEvent:EventType.READY_TO_PLAY, args:event.duration}); + }) + .onUpdate((event?: { + time: number; + }) => { + this.videoInfo.currentTime = event.time + this.workPort.postMessage("onVideoEvent",{videoTag:this.videoInfo.viewTag, videoEvent:EventType.UPDATE, args:event.time}); + }) + .onFullscreenChange((event?: { + fullscreen: boolean; + }) => { + if (!event.fullscreen) { + this.workPort.postMessage("onVideoEvent",{videoTag:this.videoInfo.viewTag, videoEvent:EventType.QUIT_FULLSCREEN}); + } + this.videoInfo.isFullScreen = event.fullscreen + }) + } +} \ No newline at end of file diff --git a/templates/openharmony/entry/src/main/ets/components/CocosWebview.ets b/templates/openharmony/entry/src/main/ets/components/CocosWebview.ets new file mode 100644 index 0000000000..909f6e82df --- /dev/null +++ b/templates/openharmony/entry/src/main/ets/components/CocosWebview.ets @@ -0,0 +1,78 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +import { WorkerManager } from '../cocos/WorkerManager' +import { PortProxy } from '../common/PortProxy' +@Observed +export class WebViewInfo { + // position + public x: number = 0; + public y: number = 0; + // size + public w: number = 0; + public h: number = 0; + // url + public url: string = '' + // tag + public viewTag: string = '' + // Whether to display + public visible: boolean = true + /* + * doc : https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md#webcontroller + */ + public controller: WebController = new WebController() + + constructor(x: number, y: number, w: number, h: number, viewTag: string) { + this.x = x; + this.y = y; + this.w = w; + this.h = h; + this.viewTag = viewTag + } +} + +@Component +export struct CocosWebView { + @ObjectLink viewInfo: WebViewInfo; + public workPort: PortProxy; + build() { + Web({ src: this.viewInfo.url, controller: this.viewInfo.controller }) + .position({ x: this.viewInfo.x, y: this.viewInfo.y }) + .width(this.viewInfo.w) + .height(this.viewInfo.h) + .border({ width: 1 }) + .onPageBegin((event) => { + this.workPort.postMessage("onPageBegin", {viewTag:this.viewInfo.viewTag, url:event.url}); + }) + .onPageEnd((event) => { + this.workPort.postMessage("onPageEnd", {viewTag:this.viewInfo.viewTag, url:event.url}) + }) + .onErrorReceive((event) => { + this.workPort.postMessage("onErrorReceive", {viewTag:this.viewInfo.viewTag, url:this.viewInfo.url}) + }) + .onHttpErrorReceive((event) => { + this.workPort.postMessage("onErrorReceive", {viewTag:this.viewInfo.viewTag, url:this.viewInfo.url}) + }) + } +} \ No newline at end of file diff --git a/templates/openharmony/entry/src/main/ets/components/EditBoxDialog.ets b/templates/openharmony/entry/src/main/ets/components/EditBoxDialog.ets new file mode 100644 index 0000000000..643c053212 --- /dev/null +++ b/templates/openharmony/entry/src/main/ets/components/EditBoxDialog.ets @@ -0,0 +1,68 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +@CustomDialog +export struct EditBoxDialog { + private showMessage: string = '' + private inputMessage: string = '' + onTextChange: (msg: string) => void + accept: (msg: string) => void + controller: CustomDialogController + cancel: () => void + confirm: () => void + + build() { + Column() { + Row() { + TextInput({ text: this.showMessage }) + .backgroundColor('#ffffff') + .layoutWeight(1) + .onChange((value) => { + if (this.onTextChange) { + this.onTextChange(value); + } + this.inputMessage = value; + }) + .onSubmit((value) => { + if (this.accept) { + this.accept(this.inputMessage); + } + this.controller.close(); + }) + Blank(8).width(16) + Button('完成').onClick(() => { + if (this.accept) { + this.accept(this.inputMessage); + } + this.controller.close(); + }) + }.padding({ left: 8, right: 8, top: 8, bottom: 8 }) + .backgroundColor(Color.Gray) + + } + .width('100%') + + .justifyContent(FlexAlign.End) + } +} diff --git a/templates/openharmony/entry/src/main/ets/pages/index.ets b/templates/openharmony/entry/src/main/ets/pages/index.ets new file mode 100644 index 0000000000..1f975f4def --- /dev/null +++ b/templates/openharmony/entry/src/main/ets/pages/index.ets @@ -0,0 +1,288 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +import nativerender from "libcocos.so"; + +import { WorkerManager } from '../cocos/WorkerManager' +import { ContextType } from "../common/Constants" +import featureAbility from '@ohos.ability.featureAbility' +import { EditBoxDialog } from '../components/EditBoxDialog' +import { WebViewInfo, CocosWebView } from '../components/CocosWebView' +import { VideoInfo, CocosVideoPlayer } from '../components/CocosVideoPlayer' + +import {PortProxy} from '../common/PortProxy' +const nativePageLifecycle = nativerender.getContext(ContextType.JSPAGE_LIFECYCLE); +const engineUtils = nativerender.getContext(ContextType.ENGINE_UTILS); + +@Entry +@Component +struct Index { + @State showMessage: string = '' + @State webViewArray: WebViewInfo[] = []; + @State videoArray:VideoInfo[] = []; + //private index: number = 0; + private webViewIndexMap: Map = new Map; + private videoIndexMap: Map = new Map; + + private workPort : PortProxy = new PortProxy(WorkerManager.getInstance().getWorker()); + dialogController: CustomDialogController = new CustomDialogController({ + builder: EditBoxDialog({ + showMessage: this.showMessage, + onTextChange: (msg: string) => { + this.showMessage = msg; + this.workPort.postMessage('onTextInput', msg) + }, + accept: (msg: string) => { + this.showMessage = msg; + this.workPort.postMessage('onComplete', msg) + }, + }), + cancel: () => { + this.workPort.postMessage('onComplete', this.showMessage) + }, + autoCancel: true, + alignment: DialogAlignment.Bottom, + customStyle: true, + }) + + aboutToAppear(): void { + console.log('[LIFECYCLE-Index] cocos aboutToAppear'); + this.workPort._messageHandle = (e) => { + //let data = e['data']; + var data = e.data; + var msg = data.data; + var result; + switch (msg.name) { + // EditBox + case "showEditBox": { + this.showMessage = msg.param + this.dialogController.open() + break; + } + case "hideEditBox": { + this.showMessage = '' + this.dialogController.close() + break; + } + // WebView + case "createWebView": { + this.webViewArray.push(new WebViewInfo(0, 0, 0, 0, msg.param)) + this.webViewIndexMap.set(msg.param, this.webViewArray.length - 1); + break; + } + case "removeWebView": { + if (this.webViewArray.length > 0) { + this.webViewArray.splice(this.webViewIndexMap.get(msg.param), 1) + } + break; + } + case "loadUrl": { + var web = msg.param; + var index = this.webViewIndexMap.get(web.tag); + this.webViewArray[index].controller.loadUrl({url: web.url}); + break; + } + case "loadHTMLString": { + var web = msg.param; + var index = this.webViewIndexMap.get(web.tag); + this.webViewArray[index].controller.loadData({data: web.contents, mimeType:"text/html",encoding:"UTF-8", baseUrl:web.baseUrl}); + break; + } + case "loadData": { + var web = msg.param; + var index = this.webViewIndexMap.get(web.tag); + this.webViewArray[index].controller.loadData({data: web.contents, mimeType:web.mimeType,encoding:web.encoding, baseUrl:web.baseUrl}); + break; + } + case "evaluateJS": { + var web = msg.param; + var index = this.webViewIndexMap.get(web.tag) + this.webViewArray[index].controller.runJavaScript({ + script: web.jsContents + }); + break; + } + case "reload": { + var index = this.webViewIndexMap.get(msg.param); + this.webViewArray[index].controller.refresh(); + break; + } + case "stopLoading": { + var index = this.webViewIndexMap.get(msg.param); + this.webViewArray[index].controller.stop(); + break; + } + case "canGoForward": { + var index = this.webViewIndexMap.get(msg.param); + result = this.webViewArray[index].controller.accessForward(); + break; + } + case "canGoBack": { + var index = this.webViewIndexMap.get(msg.param); + result = this.webViewArray[index].controller.accessBackward(); + break; + } + case "goForward": { + var index = this.webViewIndexMap.get(msg.param); + this.webViewArray[index].controller.forward(); + break; + } + case "goBack": { + var index = this.webViewIndexMap.get(msg.param); + this.webViewArray[index].controller.backward(); + break; + } + case "setWebViewRect": { + var web = msg.param; + var index = this.webViewIndexMap.get(web.tag); + this.webViewArray[index].x = px2vp(web.x); + this.webViewArray[index].y = px2vp(web.y); + this.webViewArray[index].w = px2vp(web.w); + this.webViewArray[index].h = px2vp(web.h); + } + case "setVisible": + var web = msg.param; + var index = this.webViewIndexMap.get(web.tag); + this.webViewArray[index].visible = web.visible; + break; + // video + case "createVideo": + this.videoArray.push(new VideoInfo(0, 0, 0, 0, msg.param)) + this.videoIndexMap.set(msg.param, this.videoArray.length - 1); + break; + case "removeVideo": + if (this.videoArray.length > 0) { + this.videoArray.splice(this.videoIndexMap.get(msg.param), 1) + } + break; + case "setVideoUrl": + var video = msg.param; + var index = this.videoIndexMap.get(video.tag); + this.videoArray[index].url = video.url; + break; + case "setVideoRect": { + var video = msg.param; + var index = this.videoIndexMap.get(video.tag); + this.videoArray[index].x = px2vp(video.x); + this.videoArray[index].y = px2vp(video.y); + this.videoArray[index].w = px2vp(video.w); + this.videoArray[index].h = px2vp(video.h); + break; + } + case "startVideo": { + var index = this.videoIndexMap.get(msg.param); + this.videoArray[index].controller.start(); + break; + } + case "pauseVideo" : { + var index = this.videoIndexMap.get(msg.param); + this.videoArray[index].controller.pause(); + break; + } + case "stopVideo" : { + var index = this.videoIndexMap.get(msg.param); + this.videoArray[index].controller.stop(); + break; + } + case "resumeVideo": { + var index = this.videoIndexMap.get(msg.param); + this.videoArray[index].controller.start(); + break; + } + case "getVideoDuration": { + var index = this.videoIndexMap.get(msg.param); + result = this.videoArray[index].duration; + break; + } + case "seekVideoTo" : { + var video = msg.param; + var index = this.videoIndexMap.get(video.tag); + this.videoArray[index].controller.setCurrentTime(video.time); + break; + } + case "setVideoVisible" : { + var video = msg.param; + var index = this.videoIndexMap.get(video.tag); + this.videoArray[index].visible = video.visible; + break; + } + case "setFullScreenEnabled": { + var video = msg.param; + var index = this.videoIndexMap.get(video.tag); + this.videoArray[index].isFullScreen = video.fullScreen; + break; + } + case "currentTime": { + var index = this.videoIndexMap.get(msg.param); + result = this.videoArray[index].currentTime; + } + default: { + + } + } + if (result != null || result != undefined) { + this.workPort.postReturnMessage(data, result); + } + } + } + + aboutToDisappear(): void { + console.log('[LIFECYCLE-Index] cocos aboutToDisappear'); +// this.cocosWorker.postMessage({type: "JSPageLifecycle", data: "aboutToAppear"}); +// nativePageLifecycle.aboutToDisappear(); + } + + onPageShow(): void { + console.log('[LIFECYCLE-Page] cocos onPageShow'); + nativePageLifecycle.onPageShow(); + } + + onPageHide(): void { + console.log('[LIFECYCLE-Page] cocos onPageHide'); + nativePageLifecycle.onPageHide(); + } + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + XComponent({ id: 'xcomponentId', type: 'surface', libraryname: 'cocos'}) + .onLoad((context) => { + // Set the cache directory in the ts layer. + this.workPort.postMessage("onXCLoad", "XComponent"); + }) + .onDestroy(() => { + console.log('cocos onDestroy') + }) + + ForEach(this.webViewArray, (item: WebViewInfo, index: number) => { + CocosWebView({ viewInfo: this.webViewArray[index], workPort: this.workPort}) + }, item => item.viewTag) + + ForEach(this.videoArray, (item: VideoInfo, index: number) => { + CocosVideoPlayer({ videoInfo: this.videoArray[index], workPort: this.workPort}) + }, item => item.viewTag) + } + .width('100%') + .height('100%') + } +} diff --git a/templates/openharmony/entry/src/main/ets/workers/cocos_worker.ts b/templates/openharmony/entry/src/main/ets/workers/cocos_worker.ts new file mode 100644 index 0000000000..4b2c9e9782 --- /dev/null +++ b/templates/openharmony/entry/src/main/ets/workers/cocos_worker.ts @@ -0,0 +1,98 @@ +/**************************************************************************** + Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +import worker from '@ohos.worker'; +import nativerender from "libcocos.so"; +import { ContextType } from "../common/Constants" +import { launchEngine } from '../cocos/game' +import {PortProxy} from '../common/PortProxy.ts' + +const nativeContext = nativerender.getContext(ContextType.WORKER_INIT); +nativeContext.workerInit() + +const nativeEditBox = nativerender.getContext(ContextType.EDITBOX_UTILS); +const nativeWebView = nativerender.getContext(ContextType.WEBVIEW_UTILS); + +let uiPort = new PortProxy(worker.parentPort); +nativeContext.postMessage = function(msgType: string, msgData:string) { + uiPort.postMessage(msgType, msgData); +} + +nativeContext.postSyncMessage = async function(msgType: string, msgData:string) { + const result = await uiPort.postSyncMessage(msgType, msgData); + return result; +} + +// The purpose of this is to avoid being GC +nativeContext.setPostMessageFunction.call(nativeContext, nativeContext.postMessage) +nativeContext.setPostSyncMessageFunction.call(nativeContext, nativeContext.postSyncMessage) + +var renderContext: any = undefined; +uiPort._messageHandle = function(e) { + var data = e.data; + var msg = data.data; + switch(msg.name) { + case "onXCLoad": + const renderContext = nativerender.getContext(ContextType.NATIVE_RENDER_API); + renderContext.nativeEngineInit(); + launchEngine().then(() => { + console.info('launch CC engine finished'); + }).catch(e => { + console.error('launch CC engine failed'); + }); + // @ts-ignore + window.oh.postMessage = nativeContext.postMessage; + // @ts-ignore + window.oh.postSyncMessage = nativeContext.postSyncMessage; + renderContext.nativeEngineStart(); + break; + case "onTextInput": + nativeEditBox.onTextChange(msg.param); + break; + case "onComplete": + nativeEditBox.onComplete(msg.param); + break; + case "onPageBegin": + nativeWebView.shouldStartLoading(msg.param.viewTag, msg.param.url); + break; + case "onPageEnd": + nativeWebView.finishLoading(msg.param.viewTag, msg.param.url); + break; + case "onErrorReceive": + nativeWebView.failLoading(msg.param.viewTag, msg.param.url); + break; + case "onVideoEvent": + // @ts-ignore + if(window.oh && typeof window.oh.onVideoEvent === "function") { + // @ts-ignore + window.oh.onVideoEvent(msg.param.videoTag, msg.param.videoEvent, msg.param.args); + } + break; + default: + console.error("cocos worker: message type unknown"); + break; + } +} + diff --git a/templates/openharmony/entry/src/main/module.json5 b/templates/openharmony/entry/src/main/module.json5 new file mode 100644 index 0000000000..fa8974335e --- /dev/null +++ b/templates/openharmony/entry/src/main/module.json5 @@ -0,0 +1,65 @@ +{ + "module": { + "name": "entry", + "type": "entry", + "srcEntrance": "./ets/Application/GameAbilityStage.ts", + "description": "$string:entry_desc", + "mainElement": "MainAbility", + "deviceTypes": [ + "default", + "tablet" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "uiSyntax": "ets", + "abilities": [ + { + "name": "MainAbility", + "srcEntrance": "./ets/MainAbility/MainAbility.ts", + "description": "$string:MainAbility_desc", + "orientation": "portrait", + "icon": "$media:icon", + "label": "$string:MainAbility_label", + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:white", + "visible": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ] + } + ], + "requestPermissions": [ + { + "name": 'ohos.permission.INTERNET' + }, + { + "name": "ohos.permission.ACCELEROMETER", + "reason": "$string:permissions_label", + "usedScene": { + "abilities": [ + "MainAbility" + ], + "when": "inuse" + } + }, + { + "name": "ohos.permission.GYROSCOPE", + "reason": "$string:permissions_label", + "usedScene": { + "abilities": [ + "MainAbility" + ], + "when": "inuse" + } + } + ] + } +} \ No newline at end of file diff --git a/templates/openharmony/entry/src/main/resources/base/element/color.json b/templates/openharmony/entry/src/main/resources/base/element/color.json new file mode 100644 index 0000000000..1bbc9aa961 --- /dev/null +++ b/templates/openharmony/entry/src/main/resources/base/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "white", + "value": "#FFFFFF" + } + ] +} \ No newline at end of file diff --git a/templates/openharmony/entry/src/main/resources/base/element/string.json b/templates/openharmony/entry/src/main/resources/base/element/string.json new file mode 100644 index 0000000000..2b38941145 --- /dev/null +++ b/templates/openharmony/entry/src/main/resources/base/element/string.json @@ -0,0 +1,20 @@ +{ + "string": [ + { + "name": "entry_desc", + "value": "description" + }, + { + "name": "MainAbility_label", + "value": "label" + }, + { + "name": "MainAbility_desc", + "value": "description" + }, + { + "name": "permissions_label", + "value": "label" + } + ] +} \ No newline at end of file diff --git a/templates/openharmony/entry/src/main/resources/base/media/icon.png b/templates/openharmony/entry/src/main/resources/base/media/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..2b6f32ae038cca6190392754a2a90ba4dff00204 GIT binary patch literal 9915 zcmV;sCPdkZP)PyA07*naRCr$PeF=D6Wx4}gTj@n2vVU?1wm96 zv54&Df^u23F7yfowXDTnC`f5p%2iPo^}6F$9G)9)O1!Tj+VnoPA+jJ83iU8a zPJ$uKkED-j{}6Cf`%mjT(S4)#}X5tiA{;*BDEoUs4Oc@U<{^d z0;b7F`t#opE4(S2bokvv&el$dE4Fie9cUEExZwvOkV zM?YU zgn=fWfZ@^}{2(~(mQa$`RHdX^0FXp; zqcUT!+1Dp#bYI4)#xN=q?>Rfrbh?fSzMWg>>ZheTtckW$;G->B9twv@y)#Jy1Nw!8Uh*le@<$m zc`!&N6g4DgQac}f>!nSf15mV?q#gil+EHfCo4>I!p8SMXDwP;xs^3QKK_KYnh5=?6 zFcp<3*dwxHER)Llp0N?cOC?2B)$HiVFSfq;+#&#)CDblD@{X5&CtlaO=gxaD*3x>S zn0!ffvH4_#zYD0zMN3QqD~u!eo+A<3_BzyoZ7?HI4oLYkEsdBIF8}52Z|X4CHVEmF z;fJ>UOyBni@Z4*3HP#n7o2 zqUYO7!L$-gRds{lQh}*x#O?!vgAfX-!`rs5=->J}*#thvE*zb{Yg3}__>MXIZZtHl zsO_7`9&jUoaY?U_~8zOu>vbHz4`5JE1qXff=@w@lOYY9YIcPeg3ce zjgOD-;3G_QbY0ZiHR}dVD`^tv{y-Ee*uGOhND^4FfYOXEj4u2fQlI=R!2R(~2|4{8M0f>1~q*s}TJp&i?9)PjZKG}29IpWAX}fQ z0pWA_YS@UWdQ9YQ%K0oN_B$98a~B}-%k|iD{ePj@)dQB-IGdWXgsxTphWKB83azOX z5`p02gntT+&?QNd@|n!N*}HS@{1=%dMJ?ATm>X(wc_5`%r!6PL)dd7k zL+IS+@4sjT+W+%E5PtJzWIlKddM~~aEU$}d8{N`0F!SaM5!>_|=#5FC3AXNfB)zJ| z-n|+@^*&~rMt9s0aIp7Nmfk(25vHs{86Cptac5xgtjn?YISV1@ z#$c!+NW}uQWGA-$`~5H?F`&eAkuVkEE%mHC2jLwrLytDQLGZaMy90(Y~XJO~(FM&L!!6X^d447dV%E(UitUL?q&^8#6MlkN8dY*5$ zYedk4nua9FQf_SQ3Dz@j!9Ubccs?a8ta_(!vda@!YtnYLMo{ESmA6nB+rEE4^kge$ zFa0#+u@NgBZ3SI)oL0p4W%pow-vyA!9zX)qbm$QU;l8)fbMsk{vqLaLltJ~!3H-74 zED$DR5-U!OzszRMKe%636g&4*izSKq%zN`7nqGIfb34Ux(3!CqYhIRAg8nL={9|eh%HYp9^N{AiGj7=mbQ~Q__g( z0l_suE0t0e02~w)%rw&jBDm9|T6%+`5EW8(6!}AsMBkM^gb|aFc;o@J-}3Jc>Gyau zbQ7H-*j4F`3IIJ80E{R|q@n%OZIR+` z1wv9FWkxXcg=;Z-{3(#L8cfAR&sCpAXxnC(RCoz&y>yI<4017#;>>y2cJW$K{WGXo zWA#LmCg>XUsEXv1YtjDG@4$#r8rxf2E;l3w2Fq?6F)fYo17KCag#7xgkjsh(Dyip7 z@oP0hUHKb7PF5hLhmra45)3R|4mnqVo(LoU>z`xBs*7MWwpc#Ab(3I8;CCc`S2DvG zUUV6Tk2|wsknQ#;4ubHGS|7U=ZBO0=J=Q9&PsRU9Cbiaqnud&OE&=cSP-CT4!~G=#Ul2s0cldo5*P zt1<-{R|Ak`Y`1CLAGszX=pIRD%v-$K=Kc(p~u>|yeO$544!!fl;Hui zZ2U3wM5`4$1mAE<9#iEKCYZzw7XVc#s5TI;>2OO!JsM$oFVyGLx9olt_nHG~ya>HH zgr+|}fsR$@TNFXk>6WdUK=24UjocweqwnmSz{W*zX7?>~=Z9#A(iR~F9UHDe;+b{O z;_XmUgV_G9yCG*rG4s3ULrb&?+vB?bWQMxB9kHImgv1!vfbMw)fcI@tOZd$EtH-#NxjEjWZeO zpBD#6R*FJPbYc62>tLuc(Ogd%Q>q=?bVMNV$JWuk=3IpGTd?H^kMsJ%tYx1;X#48` zxvX|4UVsx8iO#%R}0s9_c*?@`{_dL``m%36%? zwE%3K3N#)NI1nbF%P?mGa#DvLl@b5dFVK1OB`|o$g`G*=C9U|}2wNI3zoG$EC@7fr zD&Gdu5=pLPWw*=0934r)RssEI{utv2ydTnp1}I`>j~S8CdCS>|{^NI|*T<7Su3oFI z?(#CS1ru3}&v`F)oU|@)hwf-?99aB%wI>K!jdXHO3Zx0W4RtCSQjcRS|vV zujsh#beN$S80Xv?3BOtz;hhgEs45;y_(Chs*CN-fRJ!kO&OSV z-RTIwvB~8Mdp)9Q0Ko$>ZiHvf-QN`lxar<;X~%^7HNtrugH)J6>YQ(&>CrV%2Kz+* zo_Ie$g6z9az~HIh2P>9@hryM^fZ3p+^RA_czW5Z31|j`5Db8ltdhCN$TcFg#w(~Y{ z`a{VId+f<4h6zDv06}l)(Blf)*L)u>)b7%hbUOq-84a+9!PLPWFW#!?27s@6aLaXo zlsgwj1Oh=SpB}-^<@cfC=_e3>^e*TvGa!v;P-@>7eP`Y;(h64RsXh6TH=je-?We$0 zDdpe}J$DHZ+$~KZ{hlS*x#XK*+%2_Y1DX;t4UGWnBv*`vpmUF`=?_n$Yt;oXV$H!# zU(*A^1Ayg*R@x?m_}vp+RMQAqhLlNRVEF^Q_|bX!i7;bLT&nucSchWw{$NGoeNq4C z07MncSbG5)pZ__GsQsXRFY9ds!LzM7^nHFc^7GygmZu`Jl`$nek_@1n00)4yQby#} z7twwF=>SFOF2M+*=?ec(vP#GTKufW%x$}4&V5O@p{qsA!9^G)>$sz-5KqP6oF$`Y0 z8u|P0Kso1U!c--wL;dLa_Q_zS2~L@8vh;O*8sPw7&OC<~ zL>v^%`(;RiXvwJ@+~AF2@X}k6JN9Ep-nbmn8)*zJ`JRwCSr(FSbAMDp`})h!`1glk zL=&EzkH@136uPMaVOj=x_+ytN^{;0NgKYJpaRADJugSeQs!z=N&SEI3UYJU_T#u-$ zpUE+Nk46XpbkYC31h-yUUj`dV)b2-0dx1^pJO#qq{K7}>XwQwGNBGTv zv`AnqS{F5WG(eJhDk7*QeaaePQP9w(cOv(}k3yO-VZH`n%m6|*O;xzRZR3?_`uk5{ zMD5OIHx5<0MWX_J^;79&^M3wX|$#S8*t`K0Xt>AFy5PsDj34e}&Gwzv>7OgB%sV=NPQe{MT>4vnwH)zhZim_6;Qkf5|sP^I@f&)Odl6TlB%77yH_JjvIDshq>lP3MvlD@Qoh8Syedj3 z8hzDNA9_|T1}hb;0*yCPpRz_&yr7QRbGZ?=YrnJN%go8ah@ zqQ0$lk>Ko$mi1X&mqY?VX$?Rn*%kc!sF zRv_`m+o4C3JQncNTpd7EPIA})0>IV)YeOIh33^;lhq{$k$l^uKyY_?1S3Z-!{|rOt>mek9)T5%88H>jf4moMzr0!i zV6QQ#rxsy*%}!T?GJ0hj-~_;)ZXXj>(FmUyFmANu{0K5foQ=^X*9rhEF9@2Tq2|YK zMDtVMhtcRvKR7&|@{fU*&cE3}0FBi)*7Q6Qdz^r{Z1^HJ<23@!gASk%WjUfA>FJW}aw?x^o+@&nK z57fTR=(zLv3ikwP)8y1ttvDV;O+kK<2~!TE@6?A;N_1PzS04W7QcGzQ1(6+_F!TOX zVXD-sXz(o)j3_k@c%o-t*ceDnmKUU@So^Gf%0`&q-j|D+A`n*PDRUjH@BaNMf@R$nGmo0_Hp1Vy`47igQ0zR#}rcr;!kY{dfUKFqxTB*>W& zUO&hjdn!VkHzB;4>cw{3d}XpHu@MywXz$tE6$exTPwyq_1j6e1$se)^Bd4wszO`L- z;s6L^9Q)fNNN)TpjA%=_`=OS{wM#XE_oI#?JO3mM9`il00(okd|8GBb`SDF28&D9| zbLU54wl`zwqHBSYimoe9b4;B1EaPR zS7R&%+_VE$8Z*`$11UemSH)EJ)O7$KWawRCbFiBl%xI2p$xcm-VEBk@kv{AUun7wQ z@8r|(^iQKgjfNPW#Q0H1L2qe5_m@vb__Y^cMk~!@KK7|sR$PU4kKI-5P>;x z@~;bN6y_d<;nVKnn`!XN@>W2*CzG@wgqB}ig~q?#1tTCIR6Wn)a4BmV>l$q|oPzQg zIPM-y%z7VK$xaA5XwcrEne6OL26li1gDj;A#5Zn4+YOh%h_`U}x*`*Gx6xGG(Dv@x zBTS}1jM>pYUSg zm)*<@7DMUX8c087@d&c}6^-x!P^KVpgkOcd4;*lH+jS-BD&|n^c`t@Pw?VjS_6ijn z0J|rX0d4CSBQ)@LM>AG%tTAb2t{OFYf#A}gL!t99^dI*V|H2QNc-k##KL$2m0>aj= zpR@=tAtQ0$-ALYY4U9z6lKyH<12u|EU>pFGYQpW^dyOzV7gVMo@ifx{f^0xBk5cD> z7(C-K;RUHyz1MDn;;rF=h8q968j0V2!%EE2ZVAE0tU`(PYDAEIpvO`mPo$7J=nM>h zrm>N^>R@08GoYP`-|ZHaumpK5gRZ5YORA2BH9)Cjr!&Xm3K#-wHq(Q5q{SPQggI>WW0H!~ zsHiPGtRngI^AUaZAs7*AOR01r?;ao+Xj}uwuS22j5Mh9OWU&1t-WkW&5Rk(1ZOO?6 z75zc&%P&RjsSPk_$&zJw#e6%Q0+;goY1#pV1AwksmJzlJGIs95l75$KH5HAZv@UfO z8zx4-eK!gpJREGZ26LMP>@WjPBb3f{Gg@^08HQ7~OasPbm|IO?kP7vbfh?kZ!zZDn z-UJjYs`QQfZ34mb{1TM09mvl=7K2}21J)t>frKzv|EMHM#d*nq(I}&J<+W&fbTy1b zyAUXQ`h(`BevPQ4B3iq8tZb;m4fXJ6P0!`1XfYI0qXa!5grVt2v#IF)niv%GnH?yo0m+W;5s62_9#Ja`ljDLO-kTZ_VkZ=q z8-w06AE|5Bi#dA`l@ z_`%0u>{H87n!PVrflA)GSdrtMcrN)GjD(8j^>-q1&vh`GC`o8Vjt)xp-!@1a0?n}i zO0b0!fSLVFk~_*>5gz`p)Sh<{5Q++x9fdaM-AG-v4n`ynR^7Eh~+0Al-AM1TFC zX!!F6$YTS1I~wo~a~vjk^cCl$RBo`sF#qdsYqZX`QFLrv5A=crbq8V z%bKslXiQi@yEYHlbxi{VfFv8> zN5uX<_KFo!d#(`*U$m|CZb$UDcO&}e^^nK<#0p9Rf|fDy<*oFBhcx$~vLE;&GDm$C zMl%6RbzVv>R3@HrFULVW*5o%n{s5AzFLP}K?pAoO017Ferbcits8lSz%;L%R$3x-B zLX+MB#zfb?KPl?Jx!*=OydMu$IW2hkD59gx5Q^_U2BR0sDIgvWIMzeg2EB=_kj*^7V)4YvNUZS!{wgM4o0=FzU`47P zjhGAw+8rxBh>7s-xF?<^zFC+ z!%pGuq)j(`TkIgZp>TlyW{Sy={^>C!Z$A&9T~YWVZY#gzrQ%)Ly#eTwEX(QC;7u&l z5Id!*x#d1n^iU>^2#97qZJ0 zuPTrZyXz~G`UFvITRGCZ^;8B#_D*&rUj&%gy4X6~nsO&2)j>^@WKgSVgsehN4puG z#&2ymCmfSS-K9hc3spAR2F86^_KdLR!GczwoH1k0V|4=#?hl00Qhv4IntZ z*zXdeU!2LfYTlMOM&M#!+i@Pnn%>=VYd%9|rUUImHPC`xv8_?F?`9j@0{ z*_WZyTAJHBHZdl3h%L;x^7?pkj{;GCNRN01uBLK;?gGKV^MQ-|ygjc$)MV+2*Jf1H z2KV>0GMpKPKG3`Q9|u8HLWD**hQ_rZ91b5JZBA~am(AFf(O?zzwvkTu5MGV&N`H{w z?VV81(^`}4pOb$oASk4#7d9wE+qW&sXGQ~GWoYBTUo_beYrZ}bjb3J&MhT9Wd2;0r z;K}J|#BNJ(l#Pjdpl({Kr4d1WKGW9-m?+7Ls%A!pR-|_J)_j?#EnfU}wvEln2h~vc zL=FO&>WW!gerDw*6>b$S+Y}e2 zS2@RFg#FG%4Z9L_UVvc^rlvYu@q;Oux1Gs~Ea$VC2ZwjOHRV^DJ3-({l7?8*_2Gut zWqhfr)vO&9HUL_{+9ybPZhsyAh?%9ag!v;&~$b8Jd?RSwX^qH0E5oAW(Ur^%W~8@qVhKz z1gNU|E;Z6{p&E*u%p@ts4-pZj{jLgI&?=piUYgleK$OjkKdx|yf%T(D-X`g1s@NP# zD2b;OT*f4c>d+E{q3gLqF1J3D8e3T^<({*SE6>$rQ(LbF*w+z~F0_F@vl|*>C(5D7 zB3Y3SWs=lnU(nOI9q@9F+R463O2PREyTefXNXge^MTLJ+{1^8(bv>hL+TX^Dx8E@KUK* t_={OAK0Prp@rL7qyxddG(ALs|{{b2*2vZrNCnf*@002ovPDHLkV1lTm%^Uy# literal 0 HcmV?d00001 diff --git a/templates/openharmony/entry/src/main/resources/base/profile/main_pages.json b/templates/openharmony/entry/src/main/resources/base/profile/main_pages.json new file mode 100644 index 0000000000..feec276e10 --- /dev/null +++ b/templates/openharmony/entry/src/main/resources/base/profile/main_pages.json @@ -0,0 +1,5 @@ +{ + "src": [ + "pages/index" + ] +} diff --git a/templates/openharmony/entry/src/main/resources/rawfile/.keep b/templates/openharmony/entry/src/main/resources/rawfile/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/templates/openharmony/hvigorfile.js b/templates/openharmony/hvigorfile.js new file mode 100644 index 0000000000..5f2735e3de --- /dev/null +++ b/templates/openharmony/hvigorfile.js @@ -0,0 +1,2 @@ +// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently. +module.exports = require('@ohos/hvigor-ohos-plugin').appTasks \ No newline at end of file diff --git a/templates/openharmony/package-lock.json b/templates/openharmony/package-lock.json new file mode 100644 index 0000000000..97d30687f9 --- /dev/null +++ b/templates/openharmony/package-lock.json @@ -0,0 +1,1212 @@ +{ + "name": "myapplication", + "version": "1.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@ohos/hos-sdkmanager-common": { + "version": "1.0.4", + "resolved": "https://repo.harmonyos.com/npm/@ohos/hos-sdkmanager-common/-/@ohos/hos-sdkmanager-common-1.0.4.tgz", + "integrity": "sha512-LWrfF8Js+u54BcEAdyjzsA81iGBA4LPvQdQ1ig/pX6mvTieUPSvtjtAzdI8nnGVmJRLrHwAMHEO/syd9d8UAFw==", + "requires": { + "@ohos/sdkmanager-common": "^1.1.8" + } + }, + "@ohos/hvigor": { + "version": "1.1.6", + "resolved": "https://repo.harmonyos.com/npm/@ohos/hvigor/-/@ohos/hvigor-1.1.6.tgz", + "integrity": "sha512-/n7cSH3Tc1p5CEgELeJof2MLBYbu96Enmkga8PA1BFoBZnPF+SirHwJyynhtUtOJQOyFkBFQOXmwzq5o2Pdvug==", + "requires": { + "@ohos/hvigor-base": "1.1.6", + "fs-extra": "10.0.0", + "interpret": "1.4.0", + "liftoff": "4.0.0", + "mute-stdout": "1.0.0", + "pretty-hrtime": "1.0.0", + "v8flags": "3.2.0", + "yargs": "7.1.2" + } + }, + "@ohos/hvigor-base": { + "version": "1.1.6", + "resolved": "https://repo.harmonyos.com/npm/@ohos/hvigor-base/-/@ohos/hvigor-base-1.1.6.tgz", + "integrity": "sha512-VU1jdgb+86RZ6fsea1kKP3Dx77DAQmSwGQoFEpjRVPP6aLXpRfM8aLS8DNlpMVEw1dFVQhOOsZ22thcbxinSOA==", + "requires": { + "json5": "2.2.0", + "log4js": "6.4.1", + "once": "1.4.0", + "pretty-hrtime": "1.0.0" + } + }, + "@ohos/hvigor-ohos-plugin": { + "version": "1.1.6", + "resolved": "https://repo.harmonyos.com/npm/@ohos/hvigor-ohos-plugin/-/@ohos/hvigor-ohos-plugin-1.1.6.tgz", + "integrity": "sha512-Bnm1932VypATJf/Cp+sTzsX/oHFojAW7dAbEgfQpwQsyXmQbwXEf0zGnbrjVD0WKtxVVpO+znhpZvrDhOiUXlg==", + "requires": { + "@ohos/hos-sdkmanager-common": "1.0.4", + "@ohos/hvigor-base": "1.1.6", + "@ohos/sdkmanager-common": "1.1.8", + "adm-zip": "0.5.9", + "ajv": "8.10.0", + "execa": "5.1.1", + "fast-xml-parser": "4.0.3", + "fs-extra": "10.0.0", + "glob": "7.2.0", + "iconv-lite": "0.6.3", + "json5": "2.2.0", + "lodash": "4.17.21", + "pretty-hrtime": "1.0.3", + "resolve-package-path": "4.0.3" + }, + "dependencies": { + "pretty-hrtime": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/pretty-hrtime/-/pretty-hrtime-1.0.3.tgz", + "integrity": "sha512-66hKPCr+72mlfiSjlEB1+45IjXSqvVAIy6mocupoww4tBFE9R9IhwwUGoI4G++Tc9Aq+2rxOt0RFU6gPcrte0A==" + } + } + }, + "@ohos/hypium": { + "version": "1.0.1", + "resolved": "https://repo.harmonyos.com/npm/@ohos/hypium/-/@ohos/hypium-1.0.1.tgz", + "integrity": "sha512-HaztFbgwYZCdVlayXirBlmJaNTXUO65qRgYnUmrhWGEzG7wFU2fyFbeXgQeYMVWFXgeezFOoHAPoS96TEE7TIQ==" + }, + "@ohos/sdkmanager-common": { + "version": "1.1.8", + "resolved": "https://repo.harmonyos.com/npm/@ohos/sdkmanager-common/-/@ohos/sdkmanager-common-1.1.8.tgz", + "integrity": "sha512-mxq69+6Zg/ybeQGnOtkBzOTbNBkEdiYehRKWsAD/je53v1W+ahauLqe90pNZEiBuVYugzb6z2EaJtAXYZtE8gQ==" + }, + "adm-zip": { + "version": "0.5.9", + "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.9.tgz", + "integrity": "sha512-s+3fXLkeeLjZ2kLjCBwQufpI5fuN+kIGBxu6530nVQZGVol0d7Y/M88/xw9HGGUcJjKf8LutN3VPRUBq6N7Ajg==" + }, + "ajv": { + "version": "8.10.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.10.0.tgz", + "integrity": "sha512-bzqAEZOjkrUMl2afH8dknrq5KEk2SrwdBROR+vH1EKVQTqaUbJVPdc/gEdggTMM0Se+s+Ja4ju4TlNcStKl2Hw==", + "requires": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + } + }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha512-TIGnTpdo+E3+pCyAluZvtED5p5wCqLdezCyhPZzKPcxvFplEt4i+W7OONCKgeZFT3+y5NZZfOOS/Bdcanm1MYA==" + }, + "array-each": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/array-each/-/array-each-1.0.1.tgz", + "integrity": "sha512-zHjL5SZa68hkKHBFBK6DJCTtr9sfTCPCaph/L7tMSLcTFgy+zX7E+6q5UArbtOtMBCtxdICpfTCspRse+ywyXA==" + }, + "array-slice": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/array-slice/-/array-slice-1.1.0.tgz", + "integrity": "sha512-B1qMD3RBP7O8o0H2KbrXDyB0IccejMF15+87Lvlor12ONPRHP6gTjXMNkt/d3ZuOGbAe66hFmaCfECI24Ufp6w==" + }, + "balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "requires": { + "fill-range": "^7.0.1" + } + }, + "call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "requires": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + } + }, + "camelcase": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-3.0.0.tgz", + "integrity": "sha512-4nhGqUkc4BqbBBB4Q6zLuD7lzzrHYrjKGeYaEji/3tFR5VdJu9v+LilhGIVe8wxEJPPOeWo7eg8dwY13TZ1BNg==" + }, + "cliui": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz", + "integrity": "sha512-0yayqDxWQbqk3ojkYqUKqaAQ6AfNKeKWRNA8kR0WXzAsdHpP4BIaOmMAG87JGuO6qcobyW4GjxHd9PmhEd+T9w==", + "requires": { + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wrap-ansi": "^2.0.0" + } + }, + "code-point-at": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz", + "integrity": "sha512-RpAVKQA5T63xEj6/giIbUEtZwJ4UFIc3ZtvEkiaUERylqe8xb5IvqcgOurZLahv93CLKfxcw5YI+DZcUBRyLXA==" + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==" + }, + "cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "requires": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "dependencies": { + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "requires": { + "isexe": "^2.0.0" + } + } + } + }, + "date-format": { + "version": "4.0.11", + "resolved": "https://registry.npmjs.org/date-format/-/date-format-4.0.11.tgz", + "integrity": "sha512-VS20KRyorrbMCQmpdl2hg5KaOUsda1RbnsJg461FfrcyCUg+pkd0b40BSW4niQyTheww4DBXQnS7HwSrKkipLw==" + }, + "debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "requires": { + "ms": "2.1.2" + } + }, + "decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==" + }, + "define-properties": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.4.tgz", + "integrity": "sha512-uckOqKcfaVvtBdsVkdPv3XjveQJsNQqmhXgRi8uhvWWuPYZCNlzT8qAyblUgNoXdHdjMTzAqeGjAoli8f+bzPA==", + "requires": { + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + } + }, + "detect-file": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/detect-file/-/detect-file-1.0.0.tgz", + "integrity": "sha512-DtCOLG98P007x7wiiOmfI0fi3eIKyWiLTGJ2MDnVi/E04lWGbf+JzrRHMm0rgIIZJGtHpKpbVgLWHrv8xXpc3Q==" + }, + "error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "requires": { + "is-arrayish": "^0.2.1" + } + }, + "execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "requires": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + } + }, + "expand-tilde": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/expand-tilde/-/expand-tilde-2.0.2.tgz", + "integrity": "sha512-A5EmesHW6rfnZ9ysHQjPdJRni0SRar0tjtG5MNtm9n5TUvsYU8oozprtRD4AqHxcZWWlVuAmQo2nWKfN9oyjTw==", + "requires": { + "homedir-polyfill": "^1.0.1" + } + }, + "extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" + }, + "fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" + }, + "fast-xml-parser": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.0.3.tgz", + "integrity": "sha512-xhQbg3a/EYNHwK0cxIG1nZmVkHX/0tWihamn5pU4Mhd9KEVE2ga8ZJiqEUgB2sApElvAATOdMTLjgqIpvYDUkQ==", + "requires": { + "strnum": "^1.0.5" + } + }, + "fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "requires": { + "to-regex-range": "^5.0.1" + } + }, + "find-up": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-1.1.2.tgz", + "integrity": "sha512-jvElSjyuo4EMQGoTwo1uJU5pQMwTW5lS1x05zzfJuTIyLR3zwO27LYrxNg+dlvKpGOuGy/MzBdXh80g0ve5+HA==", + "requires": { + "path-exists": "^2.0.0", + "pinkie-promise": "^2.0.0" + } + }, + "findup-sync": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-5.0.0.tgz", + "integrity": "sha512-MzwXju70AuyflbgeOhzvQWAvvQdo1XL0A9bVvlXsYcFEBM87WR4OakL4OfZq+QRmr+duJubio+UtNQCPsVESzQ==", + "requires": { + "detect-file": "^1.0.0", + "is-glob": "^4.0.3", + "micromatch": "^4.0.4", + "resolve-dir": "^1.0.1" + } + }, + "fined": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fined/-/fined-2.0.0.tgz", + "integrity": "sha512-OFRzsL6ZMHz5s0JrsEr+TpdGNCtrVtnuG3x1yzGNiQHT0yaDnXAj8V/lWcpJVrnoDpcwXcASxAZYbuXda2Y82A==", + "requires": { + "expand-tilde": "^2.0.2", + "is-plain-object": "^5.0.0", + "object.defaults": "^1.1.0", + "object.pick": "^1.3.0", + "parse-filepath": "^1.0.2" + } + }, + "flagged-respawn": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/flagged-respawn/-/flagged-respawn-2.0.0.tgz", + "integrity": "sha512-Gq/a6YCi8zexmGHMuJwahTGzXlAZAOsbCVKduWXC6TlLCjjFRlExMJc4GC2NYPYZ0r/brw9P7CpRgQmlPVeOoA==" + }, + "flatted": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.6.tgz", + "integrity": "sha512-0sQoMh9s0BYsm+12Huy/rkKxVu4R1+r96YX5cG44rHV0pQ6iC3Q+mkoMFaGWObMFYQxCVT+ssG1ksneA2MI9KQ==" + }, + "for-in": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", + "integrity": "sha512-7EwmXrOjyL+ChxMhmG5lnW9MPt1aIeZEwKhQzoBUdTV0N3zuwWDZYVJatDvZ2OyzPUvdIAZDsCetk3coyMfcnQ==" + }, + "for-own": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/for-own/-/for-own-1.0.0.tgz", + "integrity": "sha512-0OABksIGrxKK8K4kynWkQ7y1zounQxP+CWnyclVwj81KW3vlLlGUx57DKGcP/LH216GzqnstnPocF16Nxs0Ycg==", + "requires": { + "for-in": "^1.0.1" + } + }, + "fs-extra": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.0.0.tgz", + "integrity": "sha512-C5owb14u9eJwizKGdchcDUQeFtlSHHthBk8pbX9Vc1PFZrLombudjDnNns88aYslCyF6IY5SUw3Roz6xShcEIQ==", + "requires": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==" + }, + "function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + }, + "get-caller-file": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-1.0.3.tgz", + "integrity": "sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w==" + }, + "get-intrinsic": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.2.tgz", + "integrity": "sha512-Jfm3OyCxHh9DJyc28qGk+JmfkpO41A4XkneDSujN9MDXrm4oDKdHvndhZ2dN94+ERNfkYJWDclW6k2L/ZGHjXA==", + "requires": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.3" + } + }, + "get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==" + }, + "glob": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz", + "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==", + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "global-modules": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-1.0.0.tgz", + "integrity": "sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg==", + "requires": { + "global-prefix": "^1.0.1", + "is-windows": "^1.0.1", + "resolve-dir": "^1.0.0" + } + }, + "global-prefix": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/global-prefix/-/global-prefix-1.0.2.tgz", + "integrity": "sha512-5lsx1NUDHtSjfg0eHlmYvZKv8/nVqX4ckFbM+FrGcQ+04KWcWFo9P5MxPZYSzUvyzmdTbI7Eix8Q4IbELDqzKg==", + "requires": { + "expand-tilde": "^2.0.2", + "homedir-polyfill": "^1.0.1", + "ini": "^1.3.4", + "is-windows": "^1.0.1", + "which": "^1.2.14" + } + }, + "graceful-fs": { + "version": "4.2.10", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.10.tgz", + "integrity": "sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==" + }, + "has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "requires": { + "function-bind": "^1.1.1" + } + }, + "has-property-descriptors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.0.tgz", + "integrity": "sha512-62DVLZGoiEBDHQyqG4w9xCuZ7eJEwNmJRWw2VY84Oedb7WFcA27fiEVe8oUQx9hAUJ4ekurquucTGwsyO1XGdQ==", + "requires": { + "get-intrinsic": "^1.1.1" + } + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==" + }, + "homedir-polyfill": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/homedir-polyfill/-/homedir-polyfill-1.0.3.tgz", + "integrity": "sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA==", + "requires": { + "parse-passwd": "^1.0.0" + } + }, + "hosted-git-info": { + "version": "2.8.9", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.9.tgz", + "integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==" + }, + "human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==" + }, + "iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "requires": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + } + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==" + }, + "interpret": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.4.0.tgz", + "integrity": "sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA==" + }, + "invert-kv": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-1.0.0.tgz", + "integrity": "sha512-xgs2NH9AE66ucSq4cNG1nhSFghr5l6tdL15Pk+jl46bmmBapgoaY/AacXyaDznAqmGL99TiLSQgO/XazFSKYeQ==" + }, + "is-absolute": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-absolute/-/is-absolute-1.0.0.tgz", + "integrity": "sha512-dOWoqflvcydARa360Gvv18DZ/gRuHKi2NU/wU5X1ZFzdYfH29nkiNZsF3mp4OJ3H4yo9Mx8A/uAGNzpzPN3yBA==", + "requires": { + "is-relative": "^1.0.0", + "is-windows": "^1.0.1" + } + }, + "is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==" + }, + "is-core-module": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.9.0.tgz", + "integrity": "sha512-+5FPy5PnwmO3lvfMb0AsoPaBG+5KHUI0wYFXOtYPnVVVspTFUuMZNfNaNVRt3FZadstu2c8x23vykRW/NBoU6A==", + "requires": { + "has": "^1.0.3" + } + }, + "is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==" + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", + "integrity": "sha512-1pqUqRjkhPJ9miNq9SwMfdvi6lBJcd6eFxvfaivQhaH3SgisfiuudvFntdKOmxuee/77l+FPjKrQjWvmPjWrRw==", + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "requires": { + "is-extglob": "^2.1.1" + } + }, + "is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==" + }, + "is-plain-object": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz", + "integrity": "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==" + }, + "is-relative": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-relative/-/is-relative-1.0.0.tgz", + "integrity": "sha512-Kw/ReK0iqwKeu0MITLFuj0jbPAmEiOsIwyIXvvbfa6QfmN9pkD1M+8pdk7Rl/dTKbH34/XBFMbgD4iMJhLQbGA==", + "requires": { + "is-unc-path": "^1.0.0" + } + }, + "is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==" + }, + "is-unc-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-unc-path/-/is-unc-path-1.0.0.tgz", + "integrity": "sha512-mrGpVd0fs7WWLfVsStvgF6iEJnbjDFZh9/emhRDcGWTduTfNHd9CHeUwH3gYIjdbwo4On6hunkztwOaAw0yllQ==", + "requires": { + "unc-path-regex": "^0.1.2" + } + }, + "is-utf8": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz", + "integrity": "sha512-rMYPYvCzsXywIsldgLaSoPlw5PfoB/ssr7hY4pLfcodrA5M/eArza1a9VmTiNIBNMjOGr1Ow9mTyU2o69U6U9Q==" + }, + "is-windows": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", + "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==" + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==" + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==" + }, + "json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==" + }, + "json5": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.0.tgz", + "integrity": "sha512-f+8cldu7X/y7RAJurMEJmdoKXGB/X550w2Nr3tTbezL6RwEE/iMcm+tZnXeoZtKuOq6ft8+CqzEkrIgx1fPoQA==", + "requires": { + "minimist": "^1.2.5" + } + }, + "jsonfile": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", + "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", + "requires": { + "graceful-fs": "^4.1.6", + "universalify": "^2.0.0" + } + }, + "kind-of": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==" + }, + "lcid": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/lcid/-/lcid-1.0.0.tgz", + "integrity": "sha512-YiGkH6EnGrDGqLMITnGjXtGmNtjoXw9SVUzcaos8RBi7Ps0VBylkq+vOcY9QE5poLasPCR849ucFUkl0UzUyOw==", + "requires": { + "invert-kv": "^1.0.0" + } + }, + "liftoff": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/liftoff/-/liftoff-4.0.0.tgz", + "integrity": "sha512-rMGwYF8q7g2XhG2ulBmmJgWv25qBsqRbDn5gH0+wnuyeFt7QBJlHJmtg5qEdn4pN6WVAUMgXnIxytMFRX9c1aA==", + "requires": { + "extend": "^3.0.2", + "findup-sync": "^5.0.0", + "fined": "^2.0.0", + "flagged-respawn": "^2.0.0", + "is-plain-object": "^5.0.0", + "object.map": "^1.0.1", + "rechoir": "^0.8.0", + "resolve": "^1.20.0" + } + }, + "load-json-file": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", + "integrity": "sha512-cy7ZdNRXdablkXYNI049pthVeXFurRyb9+hA/dZzerZ0pGTx42z+y+ssxBaVV2l70t1muq5IdKhn4UtcoGUY9A==", + "requires": { + "graceful-fs": "^4.1.2", + "parse-json": "^2.2.0", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0", + "strip-bom": "^2.0.0" + } + }, + "lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + }, + "log4js": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/log4js/-/log4js-6.4.1.tgz", + "integrity": "sha512-iUiYnXqAmNKiIZ1XSAitQ4TmNs8CdZYTAWINARF3LjnsLN8tY5m0vRwd6uuWj/yNY0YHxeZodnbmxKFUOM2rMg==", + "requires": { + "date-format": "^4.0.3", + "debug": "^4.3.3", + "flatted": "^3.2.4", + "rfdc": "^1.3.0", + "streamroller": "^3.0.2" + } + }, + "make-iterator": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/make-iterator/-/make-iterator-1.0.1.tgz", + "integrity": "sha512-pxiuXh0iVEq7VM7KMIhs5gxsfxCux2URptUQaXo4iZZJxBAzTPOLE2BumO5dbfVYq/hBJFBR/a1mFDmOx5AGmw==", + "requires": { + "kind-of": "^6.0.2" + } + }, + "map-cache": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz", + "integrity": "sha512-8y/eV9QQZCiyn1SprXSrCmqJN0yNRATe+PO8ztwqrvrbdRLA3eYJF0yaR0YayLWkMbsQSKWS9N2gPcGEc4UsZg==" + }, + "merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==" + }, + "micromatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", + "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "requires": { + "braces": "^3.0.2", + "picomatch": "^2.3.1" + } + }, + "mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==" + }, + "minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz", + "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==" + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "mute-stdout": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/mute-stdout/-/mute-stdout-1.0.0.tgz", + "integrity": "sha512-MaSQenn0f9oxIjtCufclpV00MuYTiHaXPbdcfPIM+quMqoa8cXywjHHx4LhhIAZlXqPWMdcUpYviajfmHtHRJw==" + }, + "normalize-package-data": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", + "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", + "requires": { + "hosted-git-info": "^2.1.4", + "resolve": "^1.10.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" + } + }, + "npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "requires": { + "path-key": "^3.0.0" + } + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha512-4jbtZXNAsfZbAHiiqjLPBiCl16dES1zI4Hpzzxw61Tk+loF+sBDBKx1ICKKKwIqQ7M0mFn1TmkN7euSncWgHiQ==" + }, + "object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==" + }, + "object.assign": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", + "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", + "requires": { + "call-bind": "^1.0.0", + "define-properties": "^1.1.3", + "has-symbols": "^1.0.1", + "object-keys": "^1.1.1" + } + }, + "object.defaults": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/object.defaults/-/object.defaults-1.1.0.tgz", + "integrity": "sha512-c/K0mw/F11k4dEUBMW8naXUuBuhxRCfG7W+yFy8EcijU/rSmazOUd1XAEEe6bC0OuXY4HUKjTJv7xbxIMqdxrA==", + "requires": { + "array-each": "^1.0.1", + "array-slice": "^1.0.0", + "for-own": "^1.0.0", + "isobject": "^3.0.0" + } + }, + "object.map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/object.map/-/object.map-1.0.1.tgz", + "integrity": "sha512-3+mAJu2PLfnSVGHwIWubpOFLscJANBKuB/6A4CxBstc4aqwQY0FWcsppuy4jU5GSB95yES5JHSI+33AWuS4k6w==", + "requires": { + "for-own": "^1.0.0", + "make-iterator": "^1.0.0" + } + }, + "object.pick": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/object.pick/-/object.pick-1.3.0.tgz", + "integrity": "sha512-tqa/UMy/CCoYmj+H5qc07qvSL9dqcs/WZENZ1JbtWBlATP+iVOe778gE6MSijnyCnORzDuX6hU+LA4SZ09YjFQ==", + "requires": { + "isobject": "^3.0.1" + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "requires": { + "wrappy": "1" + } + }, + "onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "requires": { + "mimic-fn": "^2.1.0" + } + }, + "os-locale": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-1.4.0.tgz", + "integrity": "sha512-PRT7ZORmwu2MEFt4/fv3Q+mEfN4zetKxufQrkShY2oGvUms9r8otu5HfdyIFHkYXjO7laNsoVGmM2MANfuTA8g==", + "requires": { + "lcid": "^1.0.0" + } + }, + "parse-filepath": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/parse-filepath/-/parse-filepath-1.0.2.tgz", + "integrity": "sha512-FwdRXKCohSVeXqwtYonZTXtbGJKrn+HNyWDYVcp5yuJlesTwNH4rsmRZ+GrKAPJ5bLpRxESMeS+Rl0VCHRvB2Q==", + "requires": { + "is-absolute": "^1.0.0", + "map-cache": "^0.2.0", + "path-root": "^0.1.1" + } + }, + "parse-json": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-2.2.0.tgz", + "integrity": "sha512-QR/GGaKCkhwk1ePQNYDRKYZ3mwU9ypsKhB0XyFnLQdomyEqk3e8wpW3V5Jp88zbxK4n5ST1nqo+g9juTpownhQ==", + "requires": { + "error-ex": "^1.2.0" + } + }, + "parse-passwd": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/parse-passwd/-/parse-passwd-1.0.0.tgz", + "integrity": "sha512-1Y1A//QUXEZK7YKz+rD9WydcE1+EuPr6ZBgKecAB8tmoW6UFv0NREVJe1p+jRxtThkcbbKkfwIbWJe/IeE6m2Q==" + }, + "path-exists": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-2.1.0.tgz", + "integrity": "sha512-yTltuKuhtNeFJKa1PiRzfLAU5182q1y4Eb4XCJ3PBqyzEDkAZRzBrKKBct682ls9reBVHf9udYLN5Nd+K1B9BQ==", + "requires": { + "pinkie-promise": "^2.0.0" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==" + }, + "path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==" + }, + "path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==" + }, + "path-root": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/path-root/-/path-root-0.1.1.tgz", + "integrity": "sha512-QLcPegTHF11axjfojBIoDygmS2E3Lf+8+jI6wOVmNVenrKSo3mFdSGiIgdSHenczw3wPtlVMQaFVwGmM7BJdtg==", + "requires": { + "path-root-regex": "^0.1.0" + } + }, + "path-root-regex": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/path-root-regex/-/path-root-regex-0.1.2.tgz", + "integrity": "sha512-4GlJ6rZDhQZFE0DPVKh0e9jmZ5egZfxTkp7bcRDuPlJXbAwhxcl2dINPUAsjLdejqaLsCeg8axcLjIbvBjN4pQ==" + }, + "path-type": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-1.1.0.tgz", + "integrity": "sha512-S4eENJz1pkiQn9Znv33Q+deTOKmbl+jj1Fl+qiP/vYezj+S8x+J3Uo0ISrx/QoEvIlOaDWJhPaRd1flJ9HXZqg==", + "requires": { + "graceful-fs": "^4.1.2", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" + } + }, + "picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==" + }, + "pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==" + }, + "pinkie": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", + "integrity": "sha512-MnUuEycAemtSaeFSjXKW/aroV7akBbY+Sv+RkyqFjgAe73F+MR0TBWKBRDkmfWq/HiFmdavfZ1G7h4SPZXaCSg==" + }, + "pinkie-promise": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", + "integrity": "sha512-0Gni6D4UcLTbv9c57DfxDGdr41XfgUjqWZu492f0cIGr16zDU06BWP/RAEvOuo7CQ0CNjHaLlM59YJJFm3NWlw==", + "requires": { + "pinkie": "^2.0.0" + } + }, + "pretty-hrtime": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/pretty-hrtime/-/pretty-hrtime-1.0.0.tgz", + "integrity": "sha512-CU2l5CYUAptUYq/671ajexQfXuxJFwwg0n243Kdkx8bTjeenedsWgu8TGHPm03vLfNtk3aTXgySKPp3Usykudw==" + }, + "punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==" + }, + "read-pkg": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-1.1.0.tgz", + "integrity": "sha512-7BGwRHqt4s/uVbuyoeejRn4YmFnYZiFl4AuaeXHlgZf3sONF0SOGlxs2Pw8g6hCKupo08RafIO5YXFNOKTfwsQ==", + "requires": { + "load-json-file": "^1.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^1.0.0" + } + }, + "read-pkg-up": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-1.0.1.tgz", + "integrity": "sha512-WD9MTlNtI55IwYUS27iHh9tK3YoIVhxis8yKhLpTqWtml739uXc9NWTpxoHkfZf3+DkCCsXox94/VWZniuZm6A==", + "requires": { + "find-up": "^1.0.0", + "read-pkg": "^1.0.0" + } + }, + "rechoir": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.8.0.tgz", + "integrity": "sha512-/vxpCXddiX8NGfGO/mTafwjq4aFa/71pvamip0++IQk3zG8cbCj0fifNPrjjF1XMXUne91jL9OoxmdykoEtifQ==", + "requires": { + "resolve": "^1.20.0" + } + }, + "require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==" + }, + "require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==" + }, + "require-main-filename": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-1.0.1.tgz", + "integrity": "sha512-IqSUtOVP4ksd1C/ej5zeEh/BIP2ajqpn8c5x+q99gvcIG/Qf0cud5raVnE/Dwd0ua9TXYDoDc0RE5hBSdz22Ug==" + }, + "resolve": { + "version": "1.22.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.1.tgz", + "integrity": "sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==", + "requires": { + "is-core-module": "^2.9.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + } + }, + "resolve-dir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/resolve-dir/-/resolve-dir-1.0.1.tgz", + "integrity": "sha512-R7uiTjECzvOsWSfdM0QKFNBVFcK27aHOUwdvK53BcW8zqnGdYp0Fbj82cy54+2A4P2tFM22J5kRfe1R+lM/1yg==", + "requires": { + "expand-tilde": "^2.0.0", + "global-modules": "^1.0.0" + } + }, + "resolve-package-path": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/resolve-package-path/-/resolve-package-path-4.0.3.tgz", + "integrity": "sha512-SRpNAPW4kewOaNUt8VPqhJ0UMxawMwzJD8V7m1cJfdSTK9ieZwS6K7Dabsm4bmLFM96Z5Y/UznrpG5kt1im8yA==", + "requires": { + "path-root": "^0.1.1" + } + }, + "rfdc": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.3.0.tgz", + "integrity": "sha512-V2hovdzFbOi77/WajaSMXk2OLm+xNIeQdMMuB7icj7bk6zi2F8GGAxigcnDFpJHbNyNcgyJDiP+8nOrY5cZGrA==" + }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" + }, + "set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==" + }, + "shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "requires": { + "shebang-regex": "^3.0.0" + } + }, + "shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==" + }, + "signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" + }, + "spdx-correct": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.1.tgz", + "integrity": "sha512-cOYcUWwhCuHCXi49RhFRCyJEK3iPj1Ziz9DpViV3tbZOwXD49QzIN3MpOLJNxh2qwq2lJJZaKMVw9qNi4jTC0w==", + "requires": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-exceptions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz", + "integrity": "sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A==" + }, + "spdx-expression-parse": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", + "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", + "requires": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-license-ids": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.11.tgz", + "integrity": "sha512-Ctl2BrFiM0X3MANYgj3CkygxhRmr9mi6xhejbdO960nF6EDJApTYpn0BQnDKlnNBULKiCN1n3w9EBkHK8ZWg+g==" + }, + "streamroller": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/streamroller/-/streamroller-3.1.1.tgz", + "integrity": "sha512-iPhtd9unZ6zKdWgMeYGfSBuqCngyJy1B/GPi/lTpwGpa3bajuX30GjUVd0/Tn/Xhg0mr4DOSENozz9Y06qyonQ==", + "requires": { + "date-format": "^4.0.10", + "debug": "^4.3.4", + "fs-extra": "^10.1.0" + }, + "dependencies": { + "fs-extra": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", + "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==", + "requires": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + } + } + } + }, + "string-width": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", + "integrity": "sha512-0XsVpQLnVCXHJfyEs8tC0zpTVIr5PKKsQtkT29IwupnPTjtPmQ3xT/4yCREF9hYkV/3M3kzcUTSAZT6a6h81tw==", + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha512-VhumSSbBqDTP8p2ZLKj40UjBCV4+v8bUSEpUb4KjRgWk9pbqGF4REFj6KEagidb2f/M6AzC0EmFyDNGaw9OCzg==", + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "strip-bom": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-2.0.0.tgz", + "integrity": "sha512-kwrX1y7czp1E69n2ajbG65mIo9dqvJ+8aBQXOGVxqwvNbsXdFM6Lq37dLAY3mknUwru8CfcCbfOLL/gMo+fi3g==", + "requires": { + "is-utf8": "^0.2.0" + } + }, + "strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==" + }, + "strnum": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-1.0.5.tgz", + "integrity": "sha512-J8bbNyKKXl5qYcR36TIO8W3mVGVHrmmxsd5PAItGkmyzwJvybiw2IVq5nqd0i4LSNSkB/sx9VHllbfFdr9k1JA==" + }, + "supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==" + }, + "to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "requires": { + "is-number": "^7.0.0" + } + }, + "unc-path-regex": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/unc-path-regex/-/unc-path-regex-0.1.2.tgz", + "integrity": "sha512-eXL4nmJT7oCpkZsHZUOJo8hcX3GbsiDOa0Qu9F646fi8dT3XuSVopVqAcEiVzSKKH7UoDti23wNX3qGFxcW5Qg==" + }, + "universalify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz", + "integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==" + }, + "uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "requires": { + "punycode": "^2.1.0" + } + }, + "v8flags": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/v8flags/-/v8flags-3.2.0.tgz", + "integrity": "sha512-mH8etigqMfiGWdeXpaaqGfs6BndypxusHHcv2qSHyZkGEznCd/qAXCWWRzeowtL54147cktFOC4P5y+kl8d8Jg==", + "requires": { + "homedir-polyfill": "^1.0.1" + } + }, + "validate-npm-package-license": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", + "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", + "requires": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "requires": { + "isexe": "^2.0.0" + } + }, + "which-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-1.0.0.tgz", + "integrity": "sha512-F6+WgncZi/mJDrammbTuHe1q0R5hOXv/mBaiNA2TCNT/LTHusX0V+CJnj9XT8ki5ln2UZyyddDgHfCzyrOH7MQ==" + }, + "wrap-ansi": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", + "integrity": "sha512-vAaEaDM946gbNpH5pLVNR+vX2ht6n0Bt3GXwVB1AuAqZosOvHNF3P7wDnh8KLkSqgUh0uh77le7Owgoz+Z9XBw==", + "requires": { + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" + }, + "y18n": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-3.2.2.tgz", + "integrity": "sha512-uGZHXkHnhF0XeeAPgnKfPv1bgKAYyVvmNL1xlKsPYZPaIHxGti2hHqvOCQv71XMsLxu1QjergkqogUnms5D3YQ==" + }, + "yargs": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-7.1.2.tgz", + "integrity": "sha512-ZEjj/dQYQy0Zx0lgLMLR8QuaqTihnxirir7EwUHp1Axq4e3+k8jXU5K0VLbNvedv1f4EWtBonDIZm0NUr+jCcA==", + "requires": { + "camelcase": "^3.0.0", + "cliui": "^3.2.0", + "decamelize": "^1.1.1", + "get-caller-file": "^1.0.1", + "os-locale": "^1.4.0", + "read-pkg-up": "^1.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^1.0.1", + "set-blocking": "^2.0.0", + "string-width": "^1.0.2", + "which-module": "^1.0.0", + "y18n": "^3.2.1", + "yargs-parser": "^5.0.1" + } + }, + "yargs-parser": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-5.0.1.tgz", + "integrity": "sha512-wpav5XYiddjXxirPoCTUPbqM0PXvJ9hiBMvuJgInvo4/lAOTZzUprArw17q2O1P2+GHhbBr18/iQwjL5Z9BqfA==", + "requires": { + "camelcase": "^3.0.0", + "object.assign": "^4.1.0" + } + } + } +} diff --git a/templates/openharmony/package.json b/templates/openharmony/package.json new file mode 100644 index 0000000000..bd27e7414a --- /dev/null +++ b/templates/openharmony/package.json @@ -0,0 +1,21 @@ +{ + "license": "ISC", + "devDependencies": {}, + "name": "myapplication", + "ohos": { + "org": "huawei", + "directoryLevel": "project", + "buildTool": "hvigor" + }, + "scripts": { + "build": "hvigor assembleHap" + }, + "description": "example description", + "repository": {}, + "version": "1.0.0", + "dependencies": { + "@ohos/hypium": "1.0.1", + "@ohos/hvigor-ohos-plugin": "1.1.6", + "@ohos/hvigor": "1.1.6" + } +}