From aca253cc09ac18cd16267b076accb1c4c01e0973 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=86=B0=E5=86=B0=E5=86=B0?= <418776654@qq.com> Date: Wed, 16 Apr 2025 09:47:20 +0800 Subject: [PATCH 1/2] ohos code optimization MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 冰冰冰 <418776654@qq.com> --- .gitmodules | 12 + CMakeLists.txt | 8 + cmake/Modules/BuildModules.cmake | 6 - cmake/Modules/CocosBuildHelpers.cmake | 4 +- cocos/CMakeLists.txt | 5 +- cocos/audio/CMakeLists.txt | 16 +- cocos/audio/ohos/AudioDecoder.cpp | 20 +- cocos/audio/ohos/AudioDecoder.h | 6 +- cocos/audio/ohos/AudioDecoderMp3.cpp | 76 --- cocos/audio/ohos/AudioDecoderMp3.h | 41 -- cocos/audio/ohos/AudioDecoderOH.cpp | 317 +++++++++++ cocos/audio/ohos/AudioDecoderOH.h | 96 ++++ cocos/audio/ohos/AudioDecoderOgg.cpp | 101 ---- cocos/audio/ohos/AudioDecoderOgg.h | 44 -- cocos/audio/ohos/AudioDecoderProvider.cpp | 32 +- cocos/audio/ohos/AudioDecoderProvider.h | 5 +- cocos/audio/ohos/AudioDecoderSLES.cpp | 292 ---------- cocos/audio/ohos/AudioDecoderSLES.h | 96 ---- cocos/audio/ohos/AudioEngine-inl.cpp | 19 +- cocos/audio/ohos/AudioPlayerProvider.cpp | 85 ++- cocos/audio/ohos/AudioPlayerProvider.h | 8 +- cocos/audio/ohos/BigAudioPlayer.cpp | 149 +++++ cocos/audio/ohos/BigAudioPlayer.h | 80 +++ cocos/audio/ohos/BigAudioService.cpp | 153 +++++ cocos/audio/ohos/BigAudioService.h | 45 ++ cocos/audio/ohos/OpenSLHelper.h | 4 - cocos/audio/ohos/PcmAudioPlayer.cpp | 2 +- cocos/audio/ohos/PcmAudioService.cpp | 13 +- cocos/audio/ohos/SimpleAudioEngine.cpp | 2 +- cocos/audio/ohos/Track.h | 2 + cocos/audio/ohos/UrlAudioPlayer.cpp | 336 ----------- cocos/audio/ohos/UrlAudioPlayer.h | 125 ---- cocos/audio/ohos/mp3reader.cpp | 497 ---------------- cocos/audio/ohos/mp3reader.h | 33 -- cocos/base/CCUserDefault-ohos.cpp | 537 ++++++++++++++++++ cocos/base/CCUserDefault.cpp | 2 +- cocos/base/CMakeLists.txt | 9 +- cocos/platform/CCApplicationProtocol.h | 2 +- cocos/platform/CCDevice.h | 5 + cocos/platform/CMakeLists.txt | 1 - cocos/platform/ohos/CCApplication-ohos.cpp | 2 +- cocos/platform/ohos/CCDevice-ohos.cpp | 130 ++++- cocos/platform/ohos/CCFileUtils-ohos.cpp | 10 +- cocos/platform/ohos/CCFileUtils-ohos.h | 2 +- cocos/platform/ohos/CCTextBitmap.cpp | 32 +- cocos/platform/ohos/CCTextBitmap.h | 4 +- .../ohos/napi/helper/Js_Cocos2dxHelper.cpp | 26 - .../ohos/napi/helper/Js_Cocos2dxHelper.h | 5 - .../platform/ohos/napi/modules/RawFileUtils.h | 24 +- .../platform/ohos/napi/modules/SensorNapi.cpp | 63 -- cocos/platform/ohos/napi/modules/SensorNapi.h | 14 - cocos/platform/ohos/napi/plugin_manager.cpp | 9 - .../ohos/napi/render/plugin_render.cpp | 7 +- .../js-bindings/manual/ScriptingCore.cpp | 2 +- .../scripting/js-bindings/script/jsb_boot.js | 2 +- .../lua-bindings/script/framework/device.lua | 2 +- tests/cpp-tests/CMakeLists.txt | 40 +- tests/cpp-tests/proj.ohos | 1 + tests/cpp-tests/proj.ohos/.gitignore | 15 - tests/cpp-tests/proj.ohos/AppScope/app.json5 | 11 - .../resources/base/element/string.json | 8 - .../resources/base/media/app_icon.png | Bin 6790 -> 0 bytes tests/cpp-tests/proj.ohos/build-profile.json5 | 45 -- tests/cpp-tests/proj.ohos/entry/.gitignore | 6 - .../proj.ohos/entry/build-profile.json5 | 40 -- tests/cpp-tests/proj.ohos/entry/hvigorfile.ts | 6 - .../proj.ohos/entry/obfuscation-rules.txt | 18 - .../proj.ohos/entry/oh-package.json5 | 13 - .../entry/src/main/cpp/CMakeLists.txt | 87 --- .../proj.ohos/entry/src/main/cpp/main.cpp | 31 - .../entry/src/main/cpp/napi_init.cpp | 37 -- .../src/main/cpp/types/libentry/index.d.ts | 30 - .../main/cpp/types/libentry/oh-package.json5 | 6 - .../src/main/ets/MainAbility/MainAbility.ts | 80 --- .../src/main/ets/components/CocosEditBox.ets | 82 --- .../main/ets/components/CocosVideoPlayer.ets | 39 -- .../src/main/ets/components/CocosWebview.ets | 43 -- .../main/ets/components/TextInputDialog.ets | 33 -- .../entry/src/main/ets/pages/Index.ets | 158 ------ .../entry/src/main/ets/workers/CocosWorker.ts | 79 --- .../src/main/ets/workers/WorkerManager.ts | 34 -- .../proj.ohos/entry/src/main/module.json5 | 71 --- .../main/resources/base/element/color.json | 8 - .../main/resources/base/element/string.json | 20 - .../src/main/resources/base/media/icon.png | Bin 6790 -> 0 bytes .../resources/base/profile/main_pages.json | 5 - .../proj.ohos/hvigor/hvigor-config.json5 | 5 - tests/cpp-tests/proj.ohos/hvigorfile.ts | 6 - .../libSysCapabilities/BuildProfile.ets | 17 - .../libSysCapabilities/build-profile.json5 | 27 - .../libSysCapabilities/hvigorfile.ts | 6 - .../proj.ohos/libSysCapabilities/index.ts | 15 - .../libSysCapabilities/obfuscation-rules.txt | 18 - .../libSysCapabilities/oh-package.json5 | 10 - .../src/main/ets/common/Constants.ts | 22 - .../src/main/ets/common/GlobalContext.ts | 25 - .../main/ets/components/dialog/DialogMsg.ts | 47 -- .../ets/components/dialog/DialogWorker.ts | 29 - .../ets/components/editbox/CocosEditBox.ts | 111 ---- .../ets/components/editbox/EditBoxMsg.ets | 194 ------- .../ets/components/videoplayer/VideoPlayer.ts | 79 --- .../components/videoplayer/VideoPlayerMsg.ets | 145 ----- .../main/ets/components/webview/WebView.ts | 114 ---- .../ets/components/webview/WebViewMsg.ets | 245 -------- .../src/main/ets/entity/Result.ts | 16 - .../main/ets/entity/TextInputDialogEntity.ts | 7 - .../src/main/ets/entity/WorkerMsgEntity.ts | 141 ----- .../src/main/ets/napi/NapiHelper.ts | 118 ---- .../src/main/ets/preferences/Preferences.ts | 218 ------- .../main/ets/system/appJump/JumpManager.ts | 19 - .../main/ets/system/appJump/JumpManagerMsg.ts | 31 - .../system/application/ApplicationManager.ts | 54 -- .../src/main/ets/system/device/DeviceUtils.ts | 164 ------ .../ets/system/sensor/AccelerometerUtils.ts | 55 -- .../src/main/ets/utils/Logger.ts | 27 - .../src/main/ets/utils/StringUtils.ts | 8 - .../src/main/ets/utils/WorkerMsgUtils.ets | 42 -- .../libSysCapabilities/src/main/module.json5 | 11 - tests/cpp-tests/proj.ohos/oh-package.json5 | 11 - tests/js-tests/project/proj.ohos | 1 + tests/js-tests/project/proj.ohos/.gitignore | 13 - .../project/proj.ohos/AppScope/app.json5 | 11 - .../resources/base/element/string.json | 8 - .../resources/base/media/app_icon.png | Bin 6790 -> 0 bytes .../project/proj.ohos/build-profile.json5 | 45 -- .../project/proj.ohos/entry/.gitignore | 6 - .../proj.ohos/entry/build-profile.json5 | 22 - .../project/proj.ohos/entry/hvigorfile.ts | 2 - .../project/proj.ohos/entry/oh-package.json5 | 13 - .../entry/src/main/cpp/CMakeLists.txt | 155 ----- .../proj.ohos/entry/src/main/cpp/main.cpp | 36 -- .../entry/src/main/cpp/napi_init.cpp | 39 -- .../src/main/cpp/types/libentry/index.d.ts | 30 - .../main/cpp/types/libentry/oh-package.json5 | 6 - .../src/main/ets/MainAbility/MainAbility.ts | 80 --- .../src/main/ets/components/CocosEditBox.ets | 82 --- .../main/ets/components/CocosVideoPlayer.ets | 39 -- .../src/main/ets/components/CocosWebview.ets | 43 -- .../main/ets/components/TextInputDialog.ets | 33 -- .../entry/src/main/ets/pages/Index.ets | 158 ------ .../entry/src/main/ets/workers/CocosWorker.ts | 79 --- .../src/main/ets/workers/WorkerManager.ts | 34 -- .../proj.ohos/entry/src/main/module.json5 | 82 --- .../main/resources/base/element/color.json | 8 - .../main/resources/base/element/string.json | 20 - .../src/main/resources/base/media/icon.png | Bin 6790 -> 0 bytes .../resources/base/profile/main_pages.json | 5 - .../main/resources/en_US/element/string.json | 16 - .../main/resources/zh_CN/element/string.json | 16 - .../proj.ohos/hvigor/hvigor-config.json5 | 5 - .../js-tests/project/proj.ohos/hvigorfile.ts | 2 - .../libSysCapabilities/BuildProfile.ets | 17 - .../libSysCapabilities/build-profile.json5 | 10 - .../libSysCapabilities/hvigorfile.ts | 2 - .../proj.ohos/libSysCapabilities/index.ts | 15 - .../libSysCapabilities/oh-package.json5 | 14 - .../src/main/ets/common/Constants.ts | 22 - .../src/main/ets/common/GlobalContext.ts | 25 - .../main/ets/components/dialog/DialogMsg.ts | 47 -- .../ets/components/dialog/DialogWorker.ts | 29 - .../ets/components/editbox/CocosEditBox.ts | 111 ---- .../ets/components/editbox/EditBoxMsg.ets | 194 ------- .../ets/components/videoplayer/VideoPlayer.ts | 79 --- .../components/videoplayer/VideoPlayerMsg.ets | 145 ----- .../main/ets/components/webview/WebView.ts | 114 ---- .../ets/components/webview/WebViewMsg.ets | 245 -------- .../src/main/ets/entity/Result.ts | 16 - .../main/ets/entity/TextInputDialogEntity.ts | 7 - .../src/main/ets/entity/WorkerMsgEntity.ts | 141 ----- .../src/main/ets/napi/NapiHelper.ts | 118 ---- .../src/main/ets/preferences/Preferences.ts | 218 ------- .../main/ets/system/appJump/JumpManager.ts | 19 - .../main/ets/system/appJump/JumpManagerMsg.ts | 31 - .../system/application/ApplicationManager.ts | 54 -- .../src/main/ets/system/device/DeviceUtils.ts | 164 ------ .../ets/system/sensor/AccelerometerUtils.ts | 55 -- .../src/main/ets/utils/Logger.ts | 27 - .../src/main/ets/utils/StringUtils.ts | 8 - .../src/main/ets/utils/WorkerMsgUtils.ets | 42 -- .../libSysCapabilities/src/main/module.json5 | 10 - .../project/proj.ohos/oh-package.json5 | 10 - tests/lua-tests/project/CMakeLists.txt | 66 ++- tests/lua-tests/project/proj.ohos | 1 + tests/lua-tests/project/proj.ohos/.gitignore | 14 - .../project/proj.ohos/AppScope/app.json5 | 11 - .../resources/base/element/string.json | 8 - .../resources/base/media/app_icon.png | Bin 6790 -> 0 bytes .../project/proj.ohos/build-profile.json5 | 45 -- .../project/proj.ohos/entry/.gitignore | 6 - .../proj.ohos/entry/build-profile.json5 | 40 -- .../project/proj.ohos/entry/hvigorfile.ts | 6 - .../proj.ohos/entry/obfuscation-rules.txt | 18 - .../proj.ohos/entry/oh-package-lock.json5 | 25 - .../project/proj.ohos/entry/oh-package.json5 | 13 - .../entry/src/main/cpp/CMakeLists.txt | 79 --- .../proj.ohos/entry/src/main/cpp/main.cpp | 31 - .../entry/src/main/cpp/napi_init.cpp | 37 -- .../src/main/cpp/types/libentry/index.d.ts | 30 - .../main/cpp/types/libentry/oh-package.json5 | 6 - .../src/main/ets/MainAbility/MainAbility.ts | 80 --- .../src/main/ets/components/CocosEditBox.ets | 82 --- .../main/ets/components/CocosVideoPlayer.ets | 39 -- .../src/main/ets/components/CocosWebview.ets | 43 -- .../main/ets/components/TextInputDialog.ets | 33 -- .../entry/src/main/ets/pages/Index.ets | 157 ----- .../entry/src/main/ets/workers/CocosWorker.ts | 79 --- .../src/main/ets/workers/WorkerManager.ts | 34 -- .../proj.ohos/entry/src/main/module.json5 | 68 --- .../main/resources/base/element/color.json | 8 - .../main/resources/base/element/string.json | 20 - .../src/main/resources/base/media/icon.png | Bin 6790 -> 0 bytes .../resources/base/profile/main_pages.json | 5 - .../proj.ohos/hvigor/hvigor-config.json5 | 5 - .../lua-tests/project/proj.ohos/hvigorfile.ts | 6 - .../libSysCapabilities/BuildProfile.ets | 17 - .../libSysCapabilities/build-profile.json5 | 27 - .../merge_profile/default/module.json | 25 - .../libSysCapabilities/hvigorfile.ts | 6 - .../proj.ohos/libSysCapabilities/index.ts | 15 - .../libSysCapabilities/obfuscation-rules.txt | 18 - .../libSysCapabilities/oh-package.json5 | 11 - .../src/main/ets/common/Constants.ts | 22 - .../src/main/ets/common/GlobalContext.ts | 25 - .../main/ets/components/dialog/DialogMsg.ts | 47 -- .../ets/components/dialog/DialogWorker.ts | 29 - .../ets/components/editbox/CocosEditBox.ts | 111 ---- .../ets/components/editbox/EditBoxMsg.ets | 194 ------- .../ets/components/videoplayer/VideoPlayer.ts | 79 --- .../components/videoplayer/VideoPlayerMsg.ets | 145 ----- .../main/ets/components/webview/WebView.ts | 114 ---- .../ets/components/webview/WebViewMsg.ets | 246 -------- .../src/main/ets/entity/Result.ts | 16 - .../main/ets/entity/TextInputDialogEntity.ts | 7 - .../src/main/ets/entity/WorkerMsgEntity.ts | 141 ----- .../src/main/ets/napi/NapiHelper.ts | 119 ---- .../src/main/ets/preferences/Preferences.ts | 218 ------- .../main/ets/system/appJump/JumpManager.ts | 19 - .../main/ets/system/appJump/JumpManagerMsg.ts | 31 - .../system/application/ApplicationManager.ts | 55 -- .../src/main/ets/system/device/DeviceUtils.ts | 164 ------ .../ets/system/sensor/AccelerometerUtils.ts | 55 -- .../src/main/ets/utils/Logger.ts | 27 - .../src/main/ets/utils/StringUtils.ts | 8 - .../src/main/ets/utils/WorkerMsgUtils.ets | 42 -- .../libSysCapabilities/src/main/module.json5 | 10 - .../project/proj.ohos/oh-package.json5 | 10 - tests/lua-tests/src/controller.lua | 7 +- 247 files changed, 1790 insertions(+), 11146 deletions(-) delete mode 100644 cocos/audio/ohos/AudioDecoderMp3.cpp delete mode 100644 cocos/audio/ohos/AudioDecoderMp3.h create mode 100644 cocos/audio/ohos/AudioDecoderOH.cpp create mode 100644 cocos/audio/ohos/AudioDecoderOH.h delete mode 100644 cocos/audio/ohos/AudioDecoderOgg.cpp delete mode 100644 cocos/audio/ohos/AudioDecoderOgg.h delete mode 100644 cocos/audio/ohos/AudioDecoderSLES.cpp delete mode 100644 cocos/audio/ohos/AudioDecoderSLES.h create mode 100644 cocos/audio/ohos/BigAudioPlayer.cpp create mode 100644 cocos/audio/ohos/BigAudioPlayer.h create mode 100644 cocos/audio/ohos/BigAudioService.cpp create mode 100644 cocos/audio/ohos/BigAudioService.h delete mode 100644 cocos/audio/ohos/UrlAudioPlayer.cpp delete mode 100644 cocos/audio/ohos/UrlAudioPlayer.h delete mode 100644 cocos/audio/ohos/mp3reader.cpp delete mode 100644 cocos/audio/ohos/mp3reader.h create mode 100644 cocos/base/CCUserDefault-ohos.cpp delete mode 100644 cocos/platform/ohos/napi/modules/SensorNapi.cpp delete mode 100644 cocos/platform/ohos/napi/modules/SensorNapi.h create mode 160000 tests/cpp-tests/proj.ohos delete mode 100644 tests/cpp-tests/proj.ohos/.gitignore delete mode 100644 tests/cpp-tests/proj.ohos/AppScope/app.json5 delete mode 100644 tests/cpp-tests/proj.ohos/AppScope/resources/base/element/string.json delete mode 100644 tests/cpp-tests/proj.ohos/AppScope/resources/base/media/app_icon.png delete mode 100644 tests/cpp-tests/proj.ohos/build-profile.json5 delete mode 100644 tests/cpp-tests/proj.ohos/entry/.gitignore delete mode 100644 tests/cpp-tests/proj.ohos/entry/build-profile.json5 delete mode 100644 tests/cpp-tests/proj.ohos/entry/hvigorfile.ts delete mode 100644 tests/cpp-tests/proj.ohos/entry/obfuscation-rules.txt delete mode 100644 tests/cpp-tests/proj.ohos/entry/oh-package.json5 delete mode 100644 tests/cpp-tests/proj.ohos/entry/src/main/cpp/CMakeLists.txt delete mode 100644 tests/cpp-tests/proj.ohos/entry/src/main/cpp/main.cpp delete mode 100644 tests/cpp-tests/proj.ohos/entry/src/main/cpp/napi_init.cpp delete mode 100644 tests/cpp-tests/proj.ohos/entry/src/main/cpp/types/libentry/index.d.ts delete mode 100644 tests/cpp-tests/proj.ohos/entry/src/main/cpp/types/libentry/oh-package.json5 delete mode 100644 tests/cpp-tests/proj.ohos/entry/src/main/ets/MainAbility/MainAbility.ts delete mode 100644 tests/cpp-tests/proj.ohos/entry/src/main/ets/components/CocosEditBox.ets delete mode 100644 tests/cpp-tests/proj.ohos/entry/src/main/ets/components/CocosVideoPlayer.ets delete mode 100644 tests/cpp-tests/proj.ohos/entry/src/main/ets/components/CocosWebview.ets delete mode 100644 tests/cpp-tests/proj.ohos/entry/src/main/ets/components/TextInputDialog.ets delete mode 100644 tests/cpp-tests/proj.ohos/entry/src/main/ets/pages/Index.ets delete mode 100644 tests/cpp-tests/proj.ohos/entry/src/main/ets/workers/CocosWorker.ts delete mode 100644 tests/cpp-tests/proj.ohos/entry/src/main/ets/workers/WorkerManager.ts delete mode 100644 tests/cpp-tests/proj.ohos/entry/src/main/module.json5 delete mode 100644 tests/cpp-tests/proj.ohos/entry/src/main/resources/base/element/color.json delete mode 100644 tests/cpp-tests/proj.ohos/entry/src/main/resources/base/element/string.json delete mode 100644 tests/cpp-tests/proj.ohos/entry/src/main/resources/base/media/icon.png delete mode 100644 tests/cpp-tests/proj.ohos/entry/src/main/resources/base/profile/main_pages.json delete mode 100644 tests/cpp-tests/proj.ohos/hvigor/hvigor-config.json5 delete mode 100644 tests/cpp-tests/proj.ohos/hvigorfile.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/BuildProfile.ets delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/build-profile.json5 delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/hvigorfile.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/index.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/obfuscation-rules.txt delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/oh-package.json5 delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/common/Constants.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/common/GlobalContext.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/components/dialog/DialogMsg.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/components/dialog/DialogWorker.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/components/editbox/CocosEditBox.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/components/editbox/EditBoxMsg.ets delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayer.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayerMsg.ets delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebView.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebViewMsg.ets delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/entity/Result.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/entity/TextInputDialogEntity.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/entity/WorkerMsgEntity.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/napi/NapiHelper.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/preferences/Preferences.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManager.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManagerMsg.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/system/application/ApplicationManager.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/system/device/DeviceUtils.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/system/sensor/AccelerometerUtils.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/utils/Logger.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/utils/StringUtils.ts delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/utils/WorkerMsgUtils.ets delete mode 100644 tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/module.json5 delete mode 100644 tests/cpp-tests/proj.ohos/oh-package.json5 create mode 160000 tests/js-tests/project/proj.ohos delete mode 100644 tests/js-tests/project/proj.ohos/.gitignore delete mode 100644 tests/js-tests/project/proj.ohos/AppScope/app.json5 delete mode 100644 tests/js-tests/project/proj.ohos/AppScope/resources/base/element/string.json delete mode 100644 tests/js-tests/project/proj.ohos/AppScope/resources/base/media/app_icon.png delete mode 100644 tests/js-tests/project/proj.ohos/build-profile.json5 delete mode 100644 tests/js-tests/project/proj.ohos/entry/.gitignore delete mode 100644 tests/js-tests/project/proj.ohos/entry/build-profile.json5 delete mode 100644 tests/js-tests/project/proj.ohos/entry/hvigorfile.ts delete mode 100644 tests/js-tests/project/proj.ohos/entry/oh-package.json5 delete mode 100644 tests/js-tests/project/proj.ohos/entry/src/main/cpp/CMakeLists.txt delete mode 100644 tests/js-tests/project/proj.ohos/entry/src/main/cpp/main.cpp delete mode 100644 tests/js-tests/project/proj.ohos/entry/src/main/cpp/napi_init.cpp delete mode 100644 tests/js-tests/project/proj.ohos/entry/src/main/cpp/types/libentry/index.d.ts delete mode 100644 tests/js-tests/project/proj.ohos/entry/src/main/cpp/types/libentry/oh-package.json5 delete mode 100644 tests/js-tests/project/proj.ohos/entry/src/main/ets/MainAbility/MainAbility.ts delete mode 100644 tests/js-tests/project/proj.ohos/entry/src/main/ets/components/CocosEditBox.ets delete mode 100644 tests/js-tests/project/proj.ohos/entry/src/main/ets/components/CocosVideoPlayer.ets delete mode 100644 tests/js-tests/project/proj.ohos/entry/src/main/ets/components/CocosWebview.ets delete mode 100644 tests/js-tests/project/proj.ohos/entry/src/main/ets/components/TextInputDialog.ets delete mode 100644 tests/js-tests/project/proj.ohos/entry/src/main/ets/pages/Index.ets delete mode 100644 tests/js-tests/project/proj.ohos/entry/src/main/ets/workers/CocosWorker.ts delete mode 100644 tests/js-tests/project/proj.ohos/entry/src/main/ets/workers/WorkerManager.ts delete mode 100644 tests/js-tests/project/proj.ohos/entry/src/main/module.json5 delete mode 100644 tests/js-tests/project/proj.ohos/entry/src/main/resources/base/element/color.json delete mode 100644 tests/js-tests/project/proj.ohos/entry/src/main/resources/base/element/string.json delete mode 100644 tests/js-tests/project/proj.ohos/entry/src/main/resources/base/media/icon.png delete mode 100644 tests/js-tests/project/proj.ohos/entry/src/main/resources/base/profile/main_pages.json delete mode 100644 tests/js-tests/project/proj.ohos/entry/src/main/resources/en_US/element/string.json delete mode 100644 tests/js-tests/project/proj.ohos/entry/src/main/resources/zh_CN/element/string.json delete mode 100644 tests/js-tests/project/proj.ohos/hvigor/hvigor-config.json5 delete mode 100644 tests/js-tests/project/proj.ohos/hvigorfile.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/BuildProfile.ets delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/build-profile.json5 delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/hvigorfile.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/index.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/oh-package.json5 delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/common/Constants.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/common/GlobalContext.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/dialog/DialogMsg.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/dialog/DialogWorker.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/editbox/CocosEditBox.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/editbox/EditBoxMsg.ets delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayer.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayerMsg.ets delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebView.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebViewMsg.ets delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/Result.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/TextInputDialogEntity.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/WorkerMsgEntity.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/napi/NapiHelper.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/preferences/Preferences.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManager.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManagerMsg.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/application/ApplicationManager.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/device/DeviceUtils.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/sensor/AccelerometerUtils.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/Logger.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/StringUtils.ts delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/WorkerMsgUtils.ets delete mode 100644 tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/module.json5 delete mode 100644 tests/js-tests/project/proj.ohos/oh-package.json5 create mode 160000 tests/lua-tests/project/proj.ohos delete mode 100644 tests/lua-tests/project/proj.ohos/.gitignore delete mode 100644 tests/lua-tests/project/proj.ohos/AppScope/app.json5 delete mode 100644 tests/lua-tests/project/proj.ohos/AppScope/resources/base/element/string.json delete mode 100644 tests/lua-tests/project/proj.ohos/AppScope/resources/base/media/app_icon.png delete mode 100644 tests/lua-tests/project/proj.ohos/build-profile.json5 delete mode 100644 tests/lua-tests/project/proj.ohos/entry/.gitignore delete mode 100644 tests/lua-tests/project/proj.ohos/entry/build-profile.json5 delete mode 100644 tests/lua-tests/project/proj.ohos/entry/hvigorfile.ts delete mode 100644 tests/lua-tests/project/proj.ohos/entry/obfuscation-rules.txt delete mode 100644 tests/lua-tests/project/proj.ohos/entry/oh-package-lock.json5 delete mode 100644 tests/lua-tests/project/proj.ohos/entry/oh-package.json5 delete mode 100644 tests/lua-tests/project/proj.ohos/entry/src/main/cpp/CMakeLists.txt delete mode 100644 tests/lua-tests/project/proj.ohos/entry/src/main/cpp/main.cpp delete mode 100644 tests/lua-tests/project/proj.ohos/entry/src/main/cpp/napi_init.cpp delete mode 100644 tests/lua-tests/project/proj.ohos/entry/src/main/cpp/types/libentry/index.d.ts delete mode 100644 tests/lua-tests/project/proj.ohos/entry/src/main/cpp/types/libentry/oh-package.json5 delete mode 100644 tests/lua-tests/project/proj.ohos/entry/src/main/ets/MainAbility/MainAbility.ts delete mode 100644 tests/lua-tests/project/proj.ohos/entry/src/main/ets/components/CocosEditBox.ets delete mode 100644 tests/lua-tests/project/proj.ohos/entry/src/main/ets/components/CocosVideoPlayer.ets delete mode 100644 tests/lua-tests/project/proj.ohos/entry/src/main/ets/components/CocosWebview.ets delete mode 100644 tests/lua-tests/project/proj.ohos/entry/src/main/ets/components/TextInputDialog.ets delete mode 100644 tests/lua-tests/project/proj.ohos/entry/src/main/ets/pages/Index.ets delete mode 100644 tests/lua-tests/project/proj.ohos/entry/src/main/ets/workers/CocosWorker.ts delete mode 100644 tests/lua-tests/project/proj.ohos/entry/src/main/ets/workers/WorkerManager.ts delete mode 100644 tests/lua-tests/project/proj.ohos/entry/src/main/module.json5 delete mode 100644 tests/lua-tests/project/proj.ohos/entry/src/main/resources/base/element/color.json delete mode 100644 tests/lua-tests/project/proj.ohos/entry/src/main/resources/base/element/string.json delete mode 100644 tests/lua-tests/project/proj.ohos/entry/src/main/resources/base/media/icon.png delete mode 100644 tests/lua-tests/project/proj.ohos/entry/src/main/resources/base/profile/main_pages.json delete mode 100644 tests/lua-tests/project/proj.ohos/hvigor/hvigor-config.json5 delete mode 100644 tests/lua-tests/project/proj.ohos/hvigorfile.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/BuildProfile.ets delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/build-profile.json5 delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/build/default/intermediates/merge_profile/default/module.json delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/hvigorfile.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/index.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/obfuscation-rules.txt delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/oh-package.json5 delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/common/Constants.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/common/GlobalContext.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/dialog/DialogMsg.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/dialog/DialogWorker.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/editbox/CocosEditBox.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/editbox/EditBoxMsg.ets delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayer.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayerMsg.ets delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebView.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebViewMsg.ets delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/Result.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/TextInputDialogEntity.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/WorkerMsgEntity.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/napi/NapiHelper.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/preferences/Preferences.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManager.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManagerMsg.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/application/ApplicationManager.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/device/DeviceUtils.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/sensor/AccelerometerUtils.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/Logger.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/StringUtils.ts delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/WorkerMsgUtils.ets delete mode 100644 tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/module.json5 delete mode 100644 tests/lua-tests/project/proj.ohos/oh-package.json5 diff --git a/.gitmodules b/.gitmodules index 1046d0a4f6c9..bdcd7de42588 100644 --- a/.gitmodules +++ b/.gitmodules @@ -13,3 +13,15 @@ [submodule "web"] path = web url = git://github.com/cocos2d/cocos2d-html5.git +[submodule "tests/cpp-tests/proj.ohos"] + path = tests/cpp-tests/proj.ohos + url = git@github.com:cocos2d/cocos2d-x-tests-harmonyos-next-project.git + branch = cpp-tests +[submodule "tests/js-tests/project/proj.ohos"] + path = tests/js-tests/project/proj.ohos + url = git@github.com:cocos2d/cocos2d-x-tests-harmonyos-next-project.git + branch = js-tests +[submodule "tests/lua-tests/project/proj.ohos"] + path = tests/lua-tests/project/proj.ohos + url = git@github.com:cocos2d/cocos2d-x-tests-harmonyos-next-project.git + branch = lua-tests diff --git a/CMakeLists.txt b/CMakeLists.txt index 9b70b46c18f5..3f3350da9822 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -90,6 +90,14 @@ include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/external ) +if(OHOS) + include_directories( + ${CMAKE_CURRENT_SOURCE_DIR}/external/opengles/api + ${CMAKE_CURRENT_SOURCE_DIR}/external/bullet/include + ${CMAKE_CURRENT_SOURCE_DIR}/external/bullet/include/bullet + ) +endif() + if(USE_PREBUILT_LIBS) include(CocosUsePrebuiltLibs) endif() diff --git a/cmake/Modules/BuildModules.cmake b/cmake/Modules/BuildModules.cmake index 003500e50776..60509ddee593 100644 --- a/cmake/Modules/BuildModules.cmake +++ b/cmake/Modules/BuildModules.cmake @@ -33,12 +33,6 @@ macro (BuildModules) endif(LINUX OR MACOSX OR WINDOWS) if(OHOS) - add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/external/ohos-specific/pvmp3dec) - set(PVMP3DEC_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/external/ohos-specific/pvmp3dec/include) - set(PVMP3DEC_LIBRARIES pvmp3dec) - add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/external/ohos-specific/tremolo) - set(TREMOLO_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/external/ohos-specific/tremolo) - set(TREMOLO_LIBRARIES tremolo) add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/external/openssl) add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/external/websockets) endif(OHOS) diff --git a/cmake/Modules/CocosBuildHelpers.cmake b/cmake/Modules/CocosBuildHelpers.cmake index 342491bf856b..a1112dff7a18 100644 --- a/cmake/Modules/CocosBuildHelpers.cmake +++ b/cmake/Modules/CocosBuildHelpers.cmake @@ -114,7 +114,7 @@ endfunction() #IOS = iOS #MACOSX = MacOS X #LINUX = Linux -#OHOS = Ohos +#OHOS = HarmonyOS Next OS if (${CMAKE_SYSTEM_NAME} MATCHES "Windows") if(WINRT) @@ -141,7 +141,7 @@ elseif (${CMAKE_SYSTEM_NAME} MATCHES "Darwin") set(SYSTEM_STRING "Mac OSX") endif() elseif(OHOS) - set(SYSTEM_STRING "OHOS") + set(SYSTEM_STRING "HarmonyOS Next") endif() if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") diff --git a/cocos/CMakeLists.txt b/cocos/CMakeLists.txt index bd17e35f7cf8..f000b13a05dc 100644 --- a/cocos/CMakeLists.txt +++ b/cocos/CMakeLists.txt @@ -92,7 +92,8 @@ add_library(cocos2dInternal ${COCOS_SRC}) # use all platform related system libs if (OHOS) - target_link_libraries(cocos2dInternal ${Drawing-lib} ${libace-lib} ${GLES-lib} ${libnapi-lib} ${libuv-lib} ${rawfile-lib} ${EGL-lib} ${hilog-lib} libohaudio.so libavplayer.so libnative_window.so libnative_buffer.so) + target_link_libraries(cocos2dInternal ${Drawing-lib} ${libace-lib} ${GLES-lib} ${libnapi-lib} ${libuv-lib} ${rawfile-lib} ${EGL-lib} ${hilog-lib} libohaudio.so libavplayer.so libnative_window.so libnative_buffer.so libnative_display_manager.so libohsensor.so + libnative_media_codecbase.so libnative_media_core.so libnative_media_acodec.so libnative_media_avdemuxer.so libnative_media_avsource.so) endif() set_target_properties(cocos2dInternal @@ -208,8 +209,6 @@ if(USE_RECAST) endif() if(OHOS) - cocos_use_pkg(cocos2dInternal PVMP3DEC) - cocos_use_pkg(cocos2dInternal TREMOLO) target_link_libraries(cocos2dInternal ext_ssl ext_crypto diff --git a/cocos/audio/CMakeLists.txt b/cocos/audio/CMakeLists.txt index 4d6884f655d4..584f869c4f33 100644 --- a/cocos/audio/CMakeLists.txt +++ b/cocos/audio/CMakeLists.txt @@ -42,7 +42,6 @@ elseif(OHOS) audio/ohos/AudioResamplerPublic.h audio/ohos/AudioMixer.h audio/ohos/tinysndfile.h - audio/ohos/mp3reader.h audio/ohos/AudioMixerOps.h audio/ohos/cutils/bitops.h audio/ohos/cutils/log.h @@ -51,7 +50,6 @@ elseif(OHOS) audio/ohos/utils/Utils.h audio/ohos/utils/Errors.h audio/ohos/utils/Compat.h - audio/ohos/AudioDecoderOgg.h audio/ohos/Track.h audio/ohos/OpenSLHelper.h audio/ohos/PcmAudioPlayer.h @@ -65,9 +63,9 @@ elseif(OHOS) audio/ohos/ICallerThreadUtils.h audio/ohos/AudioDecoderWav.h audio/ohos/AudioDecoderProvider.h - audio/ohos/UrlAudioPlayer.h - audio/ohos/AudioDecoderSLES.h - audio/ohos/AudioDecoderMp3.h + audio/ohos/AudioDecoderOH.h + audio/ohos/BigAudioPlayer.h + audio/ohos/BigAudioService.h audio/ohos/PcmData.h audio/ohos/AudioMixerController.h audio/ohos/AudioResamplerCubic.h @@ -84,10 +82,8 @@ elseif(OHOS) audio/ohos/AssetFd.cpp audio/ohos/AudioDecoder.cpp audio/ohos/AudioDecoderProvider.cpp - audio/ohos/AudioDecoderSLES.cpp - audio/ohos/AudioDecoderOgg.cpp - audio/ohos/AudioDecoderMp3.cpp audio/ohos/AudioDecoderWav.cpp + audio/ohos/AudioDecoderOH.cpp audio/ohos/AudioPlayerProvider.cpp audio/ohos/AudioResampler.cpp audio/ohos/AudioResamplerCubic.cpp @@ -95,10 +91,10 @@ elseif(OHOS) audio/ohos/PcmAudioPlayer.cpp audio/ohos/PcmData.cpp audio/ohos/PcmAudioService.cpp - audio/ohos/UrlAudioPlayer.cpp + audio/ohos/BigAudioPlayer.cpp + audio/ohos/BigAudioService.cpp audio/ohos/AudioMixerController.cpp audio/ohos/AudioMixer.cpp - audio/ohos/mp3reader.cpp audio/ohos/tinysndfile.cpp audio/ohos/Track.cpp audio/ohos/audio_utils/RefCounted.cpp diff --git a/cocos/audio/ohos/AudioDecoder.cpp b/cocos/audio/ohos/AudioDecoder.cpp index a1f7017d818f..c4daa496b18b 100644 --- a/cocos/audio/ohos/AudioDecoder.cpp +++ b/cocos/audio/ohos/AudioDecoder.cpp @@ -75,9 +75,10 @@ AudioDecoder::~AudioDecoder() { ALOGV("~AudioDecoder() %p", this); } -bool AudioDecoder::init(const std::string &url, int sampleRate) { +bool AudioDecoder::init(const std::string &url, int sampleRate, AudioPlayerProvider::AudioFileInfo fileInfo) { _url = url; _sampleRate = sampleRate; + _fileInfo = fileInfo; return true; } @@ -121,6 +122,23 @@ bool AudioDecoder::start() { return ret; } +bool AudioDecoder::asyncStart() { + auto oldTime = clockNow(); + auto nowTime = oldTime; + bool ret; + do { + ret = decodeToPcm(); + if (!ret) { + ALOGE("decodeToPcm (%s) failed!", _url.c_str()); + break; + } + nowTime = clockNow(); + ALOGD("Decoding (%s) to pcm data wasted %fms", _url.c_str(), intervalInMS(oldTime, nowTime)); + } while (false); + ALOGV_IF(!ret, "%s returns false, decode (%s)", __FUNCTION__, _url.c_str()); + return ret; +} + bool AudioDecoder::resample() { if (_result.sampleRate == _sampleRate) { ALOGI("No need to resample since the sample rate (%d) of the decoded pcm data is the same as the device output sample rate", diff --git a/cocos/audio/ohos/AudioDecoder.h b/cocos/audio/ohos/AudioDecoder.h index ddb4cd55becf..07696ec0c99f 100644 --- a/cocos/audio/ohos/AudioDecoder.h +++ b/cocos/audio/ohos/AudioDecoder.h @@ -27,6 +27,7 @@ THE SOFTWARE. #include "OpenSLHelper.h" #include "PcmData.h" #include "base/CCData.h" +#include "AudioPlayerProvider.h" namespace cocos2d { namespace experimental { @@ -36,10 +37,12 @@ class AudioDecoder { AudioDecoder(); virtual ~AudioDecoder(); - virtual bool init(const std::string &url, int sampleRate); + virtual bool init(const std::string &url, int sampleRate, AudioPlayerProvider::AudioFileInfo fileInfo); bool start(); + bool asyncStart(); + inline PcmData getResult() { return _result; }; protected: @@ -52,6 +55,7 @@ class AudioDecoder { static int fileClose(void *datasource); static long fileTell(void *datasource); // NOLINT + AudioPlayerProvider::AudioFileInfo _fileInfo; std::string _url; PcmData _result; int _sampleRate; diff --git a/cocos/audio/ohos/AudioDecoderMp3.cpp b/cocos/audio/ohos/AudioDecoderMp3.cpp deleted file mode 100644 index 990113f6e84a..000000000000 --- a/cocos/audio/ohos/AudioDecoderMp3.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. -Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -http://www.cocos2d-x.org - -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. -****************************************************************************/ -#define LOG_TAG "AudioDecoderMp3" - -#include "AudioDecoderMp3.h" -#include "mp3reader.h" -#include "platform/CCFileUtils.h" - -namespace cocos2d { namespace experimental { - -AudioDecoderMp3::AudioDecoderMp3() { - ALOGV("Create AudioDecoderMp3"); -} - -AudioDecoderMp3::~AudioDecoderMp3() { -} - -bool AudioDecoderMp3::decodeToPcm() { - _fileData = FileUtils::getInstance()->getDataFromFile(_url); - if (_fileData.isNull()) { - return false; - } - - mp3_callbacks callbacks; - callbacks.read = AudioDecoder::fileRead; - callbacks.seek = AudioDecoder::fileSeek; - callbacks.close = AudioDecoder::fileClose; - callbacks.tell = AudioDecoder::fileTell; - - int numChannels = 0; - int sampleRate = 0; - int numFrames = 0; - - if (EXIT_SUCCESS == decodeMP3(&callbacks, this, *_result.pcmBuffer, &numChannels, &sampleRate, &numFrames) && numChannels > 0 && sampleRate > 0 && numFrames > 0) { - _result.numChannels = numChannels; - _result.sampleRate = sampleRate; - _result.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; - _result.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; - _result.channelMask = numChannels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT); - _result.endianness = SL_BYTEORDER_LITTLEENDIAN; - _result.numFrames = numFrames; - _result.duration = 1.0f * numFrames / sampleRate; - - std::string info = _result.toString(); - ALOGI("Original audio info: %s, total size: %d", info.c_str(), (int)_result.pcmBuffer->size()); - return true; - } - - ALOGE("Decode MP3 (%s) failed, channels: %d, rate: %d, frames: %d", _url.c_str(), numChannels, sampleRate, numFrames); - return false; -} - -} // namespace cocos2d { namespace experimental -} \ No newline at end of file diff --git a/cocos/audio/ohos/AudioDecoderMp3.h b/cocos/audio/ohos/AudioDecoderMp3.h deleted file mode 100644 index 13d2cf54e2f7..000000000000 --- a/cocos/audio/ohos/AudioDecoderMp3.h +++ /dev/null @@ -1,41 +0,0 @@ -/**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. -Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -http://www.cocos2d-x.org - -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 "AudioDecoder.h" - -namespace cocos2d { namespace experimental { - -class AudioDecoderMp3 : public AudioDecoder { -protected: - AudioDecoderMp3(); - virtual ~AudioDecoderMp3(); - - virtual bool decodeToPcm() override; - - friend class AudioDecoderProvider; -}; - -}} // namespace cocos2d { namespace experimental \ No newline at end of file diff --git a/cocos/audio/ohos/AudioDecoderOH.cpp b/cocos/audio/ohos/AudioDecoderOH.cpp new file mode 100644 index 000000000000..9fc52a31cb48 --- /dev/null +++ b/cocos/audio/ohos/AudioDecoderOH.cpp @@ -0,0 +1,317 @@ +#include "AudioDecoderOH.h" + +namespace cocos2d { namespace experimental { + +static void OnError(OH_AVCodec *codec, int32_t errorCode, void *userData) { + ALOGV("AudioDecoderOH OH_AVCodecOnError errorCode=%{public}d", errorCode); +} + +static void OnOutputFormatChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData) { +} + +static void OnInputBufferAvailable(OH_AVCodec *codec, uint32_t index, OH_AVBuffer *buffer, void *userData) { + if (userData == nullptr) { + return; + } + ADecBufferSignal *signal = static_cast(userData); + unique_lock lock(signal->inMutex_); + signal->inBufferQueue_.emplace(index, buffer); + signal->inCond_.notify_all(); +} + +static void OnOutputBufferAvailable(OH_AVCodec *codec, uint32_t index, OH_AVBuffer *buffer, void *userData) { + if (userData == nullptr) { + return; + } + ADecBufferSignal *signal = static_cast(userData); + unique_lock lock(signal->outMutex_); + signal->outBufferQueue_.emplace(index, buffer); + signal->outCond_.notify_all(); +} + +AudioDecoderOH::AudioDecoderOH(): demuxer_(nullptr), audioDec_(nullptr), signal_(nullptr) { +} + +AudioDecoderOH::~AudioDecoderOH() { + Release(); +} + +bool AudioDecoderOH::decodeToPcm() { + + if (!demuxer()) { + return false; + } + + if (info->audioCodecMime == "audio/raw") { + while (true) { + size_t bufSize = 4096; + OH_AVBuffer * buffer = OH_AVBuffer_Create(bufSize); + int32_t ret = OH_AVDemuxer_ReadSampleBuffer(demuxer_, audioTrackIndex_, buffer); + if (ret != AV_ERR_OK) { + break; + } + OH_AVCodecBufferAttr attr = {0, 0, 0, AVCODEC_BUFFER_FLAGS_NONE}; + ret = OH_AVBuffer_GetBufferAttr(buffer, &attr); + char* source = (char*)OH_AVBuffer_GetAddr(buffer); + _result.pcmBuffer->insert(_result.pcmBuffer->end(), source, source + attr.size); + if (attr.flags & AVCODEC_BUFFER_FLAGS_EOS) { + break; + } + } + return true; + } + + audioDec_ = OH_AudioCodec_CreateByMime(info->audioCodecMime.c_str(), false); + if (audioDec_ == nullptr) { + ALOGE("AudioDecoderOH Create AudioCodec Failed"); + return false; + } + + decFormat = OH_AVFormat_Create(); + OH_AVFormat_SetIntValue(decFormat, OH_MD_KEY_AUDIO_SAMPLE_FORMAT, SAMPLE_S16LE); + OH_AVFormat_SetIntValue(decFormat, OH_MD_KEY_AUD_CHANNEL_COUNT, info->audioChannelCount); + OH_AVFormat_SetIntValue(decFormat, OH_MD_KEY_AUD_SAMPLE_RATE, info->audioSampleRate); + OH_AVFormat_SetLongValue(decFormat, OH_MD_KEY_CHANNEL_LAYOUT, info->audioChannelLayout); + if (info->audioCodecMime == OH_AVCODEC_MIMETYPE_AUDIO_VORBIS) { + OH_AVFormat_SetBuffer(decFormat, OH_MD_KEY_CODEC_CONFIG, info->extra_addr, info->extra_size); + } + + int32_t ret = OH_AudioCodec_Configure(audioDec_, decFormat); + if (ret != AV_ERR_OK) { + ALOGE("AudioDecoderOH Configure AudioCodec Failed"); + return false; + } + + signal_ = new ADecBufferSignal(); + OH_AVCodecCallback cb_ = {&OnError, &OnOutputFormatChanged, &OnInputBufferAvailable, &OnOutputBufferAvailable}; + OH_AudioCodec_RegisterCallback(audioDec_, cb_, signal_); + + { + int ret = OH_AudioCodec_Prepare(audioDec_); + if (ret != AV_ERR_OK) { + ALOGE("AudioDecoderOH Prepare AudioCodec Failed"); + return false; + } + } + + ret = OH_AudioCodec_Start(audioDec_); + if (ret != AV_ERR_OK) { + ALOGE("AudioDecoderOH Start AudioCodec Failed"); + return false; + } + + isRunning_.store(true); + inputLoop_ = make_unique(&AudioDecoderOH::InputFunc, this); + outputLoop_ = make_unique(&AudioDecoderOH::OutputFunc, this); + + unique_lock lock(signal_->startMutex_); + signal_->startCond_.wait(lock, [this]() { return (!(isRunning_.load())); }); + + return true; +} + +void AudioDecoderOH::getDemuxerResult() { + if (info == nullptr) { + return; + } + _result.numChannels = info->audioChannelCount; + _result.sampleRate = info->audioSampleRate; + _result.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; + _result.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; + _result.channelMask = info->audioChannelCount == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT); + _result.endianness = SL_BYTEORDER_LITTLEENDIAN; + _result.duration = info->duration / 1000000.0f; + _result.numFrames = _result.duration * info->audioSampleRate; +} + +bool AudioDecoderOH::demuxer() { + + if (info != nullptr) { + return true; + } + + info = new AudioSampleInfo(); + + int64_t offset = _fileInfo.start; + int fd = _fileInfo.assetFd->getFd(); + if (fd < 0) { + ALOGE("AudioDecoderOH Failed to open file descriptor for '%{public}s'", _url.c_str()); + return false; + } + long fileSize = _fileInfo.length; + source_ = OH_AVSource_CreateWithFD(fd, offset, fileSize); + if (source_ == nullptr) { + ALOGE("AudioDecoderOH demuxer create source failed"); + return false; + } + demuxer_ = OH_AVDemuxer_CreateWithSource(source_); + if (demuxer_ == nullptr) { + ALOGE("AudioDecoderOH demuxer create demuxer failed"); + return false; + } + + OH_AVFormat *sourceFormat = OH_AVSource_GetSourceFormat(source_); + if (sourceFormat == nullptr) { + ALOGE("AudioDecoderOH demuxer get source format failed"); + return false; + } + int32_t trackCount = 0; + OH_AVFormat_GetIntValue(sourceFormat, OH_MD_KEY_TRACK_COUNT, &trackCount); + OH_AVFormat_GetLongValue(sourceFormat, OH_MD_KEY_DURATION, &info->duration); + OH_AVFormat_Destroy(sourceFormat); + + for (uint32_t index = 0; index < (static_cast(trackCount)); index++) { + trackFormat = OH_AVSource_GetTrackFormat(source_, index); + if (trackFormat == nullptr) { + ALOGE("AudioDecoderOH demuxer get track format failed"); + return false; + } + audioTrackIndex_ = index; + if(OH_AVDemuxer_SelectTrackByID(demuxer_, audioTrackIndex_) != AV_ERR_OK){ + ALOGE("AudioDecoderOH select audio track failed: %d", audioTrackIndex_); + return false; + } + OH_AVFormat_GetIntValue(trackFormat, OH_MD_KEY_AUD_CHANNEL_COUNT, &info->audioChannelCount); + OH_AVFormat_GetLongValue(trackFormat, OH_MD_KEY_CHANNEL_LAYOUT, &info->audioChannelLayout); + OH_AVFormat_GetIntValue(trackFormat, OH_MD_KEY_AUD_SAMPLE_RATE, &info->audioSampleRate); + char *audioCodecMime; + OH_AVFormat_GetStringValue(trackFormat, + OH_MD_KEY_CODEC_MIME, const_cast(&audioCodecMime)); + info->audioCodecMime = audioCodecMime; + if (info->audioCodecMime == OH_AVCODEC_MIMETYPE_AUDIO_VORBIS) { + OH_AVFormat_GetBuffer(trackFormat, OH_MD_KEY_CODEC_CONFIG, &info->extra_addr, &info->extra_size); + } + } + + getDemuxerResult(); + return true; +} + +void AudioDecoderOH::InputFunc() { + + while (isRunning_.load()) { + if (!isRunning_.load()) { + break; + } + std::unique_lock lock(signal_->inMutex_); + bool condRet = signal_->inCond_.wait_for( + lock, 5s, [this]() { return (!signal_->inBufferQueue_.empty() || !isRunning_.load()); }); + if (!isRunning_.load()) { + break; + } + if (signal_->inBufferQueue_.empty()) { + continue; + } + auto bufferInfo = signal_->inBufferQueue_.front(); + signal_->inBufferQueue_.pop(); + lock.unlock(); + auto buffer = reinterpret_cast(bufferInfo.buffer); + + int32_t ret = OH_AVDemuxer_ReadSampleBuffer(demuxer_, audioTrackIndex_, buffer); + ret = OH_AVBuffer_GetBufferAttr(buffer, &bufferInfo.attr); + ret = OH_AVBuffer_SetBufferAttr(buffer, &bufferInfo.attr); + ret = OH_AudioCodec_PushInputBuffer(audioDec_, bufferInfo.bufferIndex); + if (ret != AV_ERR_OK) { + ALOGV("InputFunc Fatal error, exit! ret=%{public}d", ret); + break; + } + if (bufferInfo.attr.flags & AVCODEC_BUFFER_FLAGS_EOS) { + break; + } + } + ALOGV("InputFunc stop, exit"); +} + +void AudioDecoderOH::OutputFunc() { + while (isRunning_.load()) { + if (!isRunning_.load()) { + break; + } + std::unique_lock lock(signal_->outMutex_); + bool condRet = signal_->outCond_.wait_for( + lock, 5s, [this]() { return (!signal_->outBufferQueue_.empty() || !isRunning_.load()); }); + if (!isRunning_.load()) { + break; + } + if (signal_->outBufferQueue_.empty()) { + continue; + } + auto bufferInfo = signal_->outBufferQueue_.front(); + signal_->outBufferQueue_.pop(); + char* source = (char*)OH_AVBuffer_GetAddr(reinterpret_cast(bufferInfo.buffer)); + _result.pcmBuffer->insert(_result.pcmBuffer->end(), source, source + bufferInfo.attr.size); + + int32_t ret = OH_AudioCodec_FreeOutputBuffer(audioDec_, bufferInfo.bufferIndex); + if (ret != AV_ERR_OK) { + ALOGV("InputFunc Fatal error, exit! ret=%{public}d", ret); + break; + } + + if (bufferInfo.attr.flags & AVCODEC_BUFFER_FLAGS_EOS) { + break; + } + + lock.unlock(); + } + isRunning_.store(false); + signal_->startCond_.notify_all(); + ALOGV("OutputFunc stop, exit"); +} + +void AudioDecoderOH::Release() { + isRunning_.store(false); + if (inputLoop_ != nullptr && inputLoop_->joinable()) { + { + unique_lock lock(signal_->inMutex_); + signal_->inCond_.notify_all(); + } + inputLoop_->join(); + inputLoop_ = nullptr; + } + + if (outputLoop_ != nullptr && outputLoop_->joinable()) { + { + unique_lock lock(signal_->outMutex_); + signal_->outCond_.notify_all(); + } + outputLoop_->join(); + outputLoop_ = nullptr; + while (!signal_->outBufferQueue_.empty()) { + signal_->outBufferQueue_.pop(); + } + } + if (audioDec_ != nullptr) { + OH_AudioCodec_Flush(audioDec_); + OH_AudioCodec_Stop(audioDec_); + OH_AudioCodec_Destroy(audioDec_); + audioDec_ = nullptr; + } + + if (demuxer_ != nullptr) { + OH_AVDemuxer_Destroy(demuxer_); + demuxer_ = nullptr; + } + if (source_ != nullptr) { + OH_AVSource_Destroy(source_); + source_ = nullptr; + } + + if (trackFormat != nullptr) { + OH_AVFormat_Destroy(trackFormat); + trackFormat = nullptr; + } + if (decFormat != nullptr) { + OH_AVFormat_Destroy(decFormat); + decFormat = nullptr; + } + if (signal_) { + delete signal_; + signal_ = nullptr; + } + if (info != nullptr) { + delete info; + info = nullptr; + } +} +}} + diff --git a/cocos/audio/ohos/AudioDecoderOH.h b/cocos/audio/ohos/AudioDecoderOH.h new file mode 100644 index 000000000000..a9cf2d389349 --- /dev/null +++ b/cocos/audio/ohos/AudioDecoderOH.h @@ -0,0 +1,96 @@ +#ifndef PROJ_OHOS_AUDIODECODEROH_H +#define PROJ_OHOS_AUDIODECODEROH_H + +#include "AudioDecoder.h" + +#include +#include +#include +#include +#include +#include +#include "BigAudioPlayer.h" +#include "platform/CCFileUtils.h" +#include +#include +#include +#include + +#include +#include + +using namespace std; + +namespace cocos2d { namespace experimental { + +struct AudioSampleInfo { + int32_t audioSampleRate = 0; + int32_t audioChannelCount = 0; + int64_t audioChannelLayout = 0; + std::string audioCodecMime = ""; + uint8_t *extra_addr; + size_t extra_size; + // microseconds + int64_t duration = 0; +}; + +struct CodecBufferInfo { + uint32_t bufferIndex = 0; + uintptr_t *buffer = nullptr; + uint8_t *bufferAddr = nullptr; + OH_AVCodecBufferAttr attr = {0, 0, 0, AVCODEC_BUFFER_FLAGS_NONE}; + + explicit CodecBufferInfo(uint8_t *addr) : bufferAddr(addr){}; + CodecBufferInfo(uint8_t *addr, int32_t bufferSize) + : bufferAddr(addr), attr({0, bufferSize, 0, AVCODEC_BUFFER_FLAGS_NONE}){}; + CodecBufferInfo(uint32_t argBufferIndex, OH_AVBuffer *argBuffer) + : bufferIndex(argBufferIndex), buffer(reinterpret_cast(argBuffer)) + { + OH_AVBuffer_GetBufferAttr(argBuffer, &attr); + }; +}; + +class ADecBufferSignal { +public: + std::mutex inMutex_; + std::mutex outMutex_; + std::mutex startMutex_; + std::condition_variable inCond_; + std::condition_variable outCond_; + std::condition_variable startCond_; + std::queue inBufferQueue_; + std::queue outBufferQueue_; +}; + +class AudioDecoderOH : public AudioDecoder { +public: + bool demuxer(); + +protected: + AudioDecoderOH(); + virtual ~AudioDecoderOH(); + + virtual bool decodeToPcm() override; + void getDemuxerResult(); + void Release(); + void InputFunc(); + void OutputFunc(); + + friend class AudioDecoderProvider; + +private: + std::atomic isRunning_{false}; + std::unique_ptr inputLoop_; + std::unique_ptr outputLoop_; + OH_AVCodec *audioDec_; + ADecBufferSignal *signal_; + OH_AVSource *source_; + OH_AVDemuxer *demuxer_; + struct OH_AVCodecCallback cb_; + uint32_t audioTrackIndex_ = 0; + OH_AVFormat *trackFormat = nullptr; + OH_AVFormat *decFormat = nullptr; + AudioSampleInfo *info = nullptr; +}; +}} +#endif //PROJ_OHOS_AUDIODECODEROH_H \ No newline at end of file diff --git a/cocos/audio/ohos/AudioDecoderOgg.cpp b/cocos/audio/ohos/AudioDecoderOgg.cpp deleted file mode 100644 index 8db15350bf57..000000000000 --- a/cocos/audio/ohos/AudioDecoderOgg.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. -Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -http://www.cocos2d-x.org - -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. -****************************************************************************/ -#define LOG_TAG "AudioDecoderOgg" - -#include "AudioDecoderOgg.h" -#include "platform/CCFileUtils.h" - -namespace cocos2d { namespace experimental { - -AudioDecoderOgg::AudioDecoderOgg() { - ALOGV("Create AudioDecoderOgg"); -} - -AudioDecoderOgg::~AudioDecoderOgg() { -} - -int AudioDecoderOgg::fseek64Wrap(void *datasource, ogg_int64_t off, int whence) { - return AudioDecoder::fileSeek(datasource, (long)off, whence); -} - -bool AudioDecoderOgg::decodeToPcm() { - _fileData = FileUtils::getInstance()->getDataFromFile(_url); - if (_fileData.isNull()) { - return false; - } - - ov_callbacks callbacks; - callbacks.read_func = AudioDecoder::fileRead; - callbacks.seek_func = AudioDecoderOgg::fseek64Wrap; - callbacks.close_func = AudioDecoder::fileClose; - callbacks.tell_func = AudioDecoder::fileTell; - - _fileCurrPos = 0; - - OggVorbis_File vf; - int ret = ov_open_callbacks(this, &vf, NULL, 0, callbacks); - if (ret != 0) { - ALOGE("Open file error, file: %s, ov_open_callbacks return %d", _url.c_str(), ret); - return false; - } - // header - auto vi = ov_info(&vf, -1); - - uint32_t pcmSamples = (uint32_t)ov_pcm_total(&vf, -1); - - uint32_t bufferSize = pcmSamples * vi->channels * sizeof(short); - char *pcmBuffer = (char *)malloc(bufferSize); - memset(pcmBuffer, 0, bufferSize); - - int currentSection = 0; - long curPos = 0; - long readBytes = 0; - - do { - readBytes = ov_read(&vf, pcmBuffer + curPos, 4096, ¤tSection); - curPos += readBytes; - } while (readBytes > 0); - - if (curPos > 0) { - _result.pcmBuffer->insert(_result.pcmBuffer->end(), pcmBuffer, pcmBuffer + bufferSize); - _result.numChannels = vi->channels; - _result.sampleRate = vi->rate; - _result.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; - _result.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; - _result.channelMask = vi->channels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT); - _result.endianness = SL_BYTEORDER_LITTLEENDIAN; - _result.numFrames = pcmSamples; - _result.duration = 1.0f * pcmSamples / vi->rate; - } else { - ALOGE("ov_read returns 0 byte!"); - } - - ov_clear(&vf); - free(pcmBuffer); - - return (curPos > 0); -} - -}} // namespace cocos2d { namespace experimental \ No newline at end of file diff --git a/cocos/audio/ohos/AudioDecoderOgg.h b/cocos/audio/ohos/AudioDecoderOgg.h deleted file mode 100644 index 75b8e5afcf64..000000000000 --- a/cocos/audio/ohos/AudioDecoderOgg.h +++ /dev/null @@ -1,44 +0,0 @@ -/**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. -Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -http://www.cocos2d-x.org - -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 "AudioDecoder.h" - -#include "Tremolo/ivorbisfile.h" - -namespace cocos2d { namespace experimental { - -class AudioDecoderOgg : public AudioDecoder { -protected: - AudioDecoderOgg(); - virtual ~AudioDecoderOgg(); - - static int fseek64Wrap(void *datasource, ogg_int64_t off, int whence); - virtual bool decodeToPcm() override; - - friend class AudioDecoderProvider; -}; - -}} // namespace cocos2d { namespace experimental \ No newline at end of file diff --git a/cocos/audio/ohos/AudioDecoderProvider.cpp b/cocos/audio/ohos/AudioDecoderProvider.cpp index eff65c9ec8eb..d7cb20a818a1 100644 --- a/cocos/audio/ohos/AudioDecoderProvider.cpp +++ b/cocos/audio/ohos/AudioDecoderProvider.cpp @@ -26,43 +26,29 @@ #define LOG_TAG "AudioDecoderProvider" #include "AudioDecoderProvider.h" -#include "AudioDecoderMp3.h" -#include "AudioDecoderOgg.h" -#include "AudioDecoderSLES.h" #include "AudioDecoderWav.h" +#include "AudioDecoderOH.h" #include "platform/CCFileUtils.h" namespace cocos2d { namespace experimental { -cocos2d::experimental::AudioDecoder *AudioDecoderProvider::createAudioDecoder(SLEngineItf engineItf, const std::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback) { +cocos2d::experimental::AudioDecoder *AudioDecoderProvider::createAudioDecoder(const std::string &url, int sampleRate, AudioPlayerProvider::AudioFileInfo fileInfo) { AudioDecoder *decoder = nullptr; std::string extension = FileUtils::getInstance()->getFileExtension(url); ALOGE("url:%s, extension:%s, sampleRate:%d", url.c_str(), extension.c_str(), sampleRate); - if (extension == ".ogg") { - decoder = new AudioDecoderOgg(); - if (!decoder->init(url, sampleRate)) { - delete decoder; - decoder = nullptr; - } - } else if (extension == ".mp3") { - decoder = new AudioDecoderMp3(); - if (!decoder->init(url, sampleRate)) { + if (extension == ".wav" && fileInfo.smallFile) { + decoder = new AudioDecoderWav(); + if (!decoder->init(url, sampleRate, fileInfo)) { delete decoder; decoder = nullptr; } - } else if (extension == ".wav") { - decoder = new AudioDecoderWav(); - if (!decoder->init(url, sampleRate)) { + } + else { + decoder = new AudioDecoderOH(); + if (!decoder->init(url, sampleRate, fileInfo)) { delete decoder; decoder = nullptr; } - } else { - auto slesDecoder = new AudioDecoderSLES(); - if (slesDecoder->init(engineItf, url, bufferSizeInFrames, sampleRate, fdGetterCallback)) { - decoder = slesDecoder; - } else { - delete slesDecoder; - } } return decoder; diff --git a/cocos/audio/ohos/AudioDecoderProvider.h b/cocos/audio/ohos/AudioDecoderProvider.h index 1a650ce2fad8..6e6d9a892480 100644 --- a/cocos/audio/ohos/AudioDecoderProvider.h +++ b/cocos/audio/ohos/AudioDecoderProvider.h @@ -25,7 +25,8 @@ THE SOFTWARE. #pragma once -#include "OpenSLHelper.h" +#include +#include "AudioPlayerProvider.h" namespace cocos2d { namespace experimental { @@ -33,7 +34,7 @@ class AudioDecoder; class AudioDecoderProvider { public: - static AudioDecoder *createAudioDecoder(SLEngineItf engineItf, const std::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback); + static AudioDecoder *createAudioDecoder(const std::string &url, int sampleRate, AudioPlayerProvider::AudioFileInfo fileInfo); static void destroyAudioDecoder(AudioDecoder **decoder); }; diff --git a/cocos/audio/ohos/AudioDecoderSLES.cpp b/cocos/audio/ohos/AudioDecoderSLES.cpp deleted file mode 100644 index 42274ee9505f..000000000000 --- a/cocos/audio/ohos/AudioDecoderSLES.cpp +++ /dev/null @@ -1,292 +0,0 @@ -/**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. -Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -http://www.cocos2d-x.org - -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. -****************************************************************************/ - -#define LOG_TAG "AudioDecoderSLES" - -#include "AudioDecoderSLES.h" -#include "platform/CCFileUtils.h" - -#include -#include - -namespace cocos2d { namespace experimental { - -/* Explicitly requesting SL_IID_ANDROIDSIMPLEBUFFERQUEUE and SL_IID_PREFETCHSTATUS -* on the UrlAudioPlayer object for decoding, SL_IID_METADATAEXTRACTION for retrieving the -* format of the decoded audio */ -#define NUM_EXPLICIT_INTERFACES_FOR_PLAYER 3 - -/* Size of the decode buffer queue */ -#define NB_BUFFERS_IN_QUEUE 4 - -/* size of the struct to retrieve the PCM format metadata values: the values we're interested in - * are SLuint32, but it is saved in the data field of a SLMetadataInfo, hence the larger size. - * Nate that this size is queried and displayed at l.452 for demonstration/test purposes. - * */ -#define PCM_METADATA_VALUE_SIZE 32 - -/* used to detect errors likely to have occurred when the OpenSL ES framework fails to open - * a resource, for instance because a file URI is invalid, or an HTTP server doesn't respond. - */ -#define PREFETCHEVENT_ERROR_CANDIDATE (SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE) - -//----------------------------------------------------------------- - -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; // NOLINT(readability-identifier-naming) - -static void checkMetaData(int index, const char *key) { - if (index != -1) { - ALOGV("Key %s is at index %d", key, index); - } else { - ALOGV("Unable to find key %s", key); - } -} - -class SLAudioDecoderCallbackProxy { -public: - //----------------------------------------------------------------- - /* Callback for "prefetch" events, here used to detect audio resource opening errors */ - static void prefetchEventCallback(SLPrefetchStatusItf caller, void *context, SLuint32 event) { - auto *thiz = reinterpret_cast(context); - thiz->prefetchCallback(caller, event); - } - - static void decPlayCallback(CCSLBufferQueueItf queueItf, void *context) { - auto *thiz = reinterpret_cast(context); - thiz->decodeToPcmCallback(queueItf); - } - - static void decProgressCallback(SLPlayItf caller, void *context, SLuint32 event) { - auto *thiz = reinterpret_cast(context); - thiz->decodeProgressCallback(caller, event); - } -}; - -AudioDecoderSLES::AudioDecoderSLES() -: _engineItf(nullptr), _playObj(nullptr), _formatQueried(false), _prefetchError(false), _counter(0), _numChannelsKeyIndex(-1), _sampleRateKeyIndex(-1), _bitsPerSampleKeyIndex(-1), _containerSizeKeyIndex(-1), _channelMaskKeyIndex(-1), _endiannessKeyIndex(-1), _eos(false), _bufferSizeInFrames(-1), _assetFd(0), _fdGetterCallback(nullptr), _isDecodingCallbackInvoked(false) { - ALOGV("Create AudioDecoderSLES"); -} - -AudioDecoderSLES::~AudioDecoderSLES() { - { - std::lock_guard lk(__SLPlayerMutex); - SL_DESTROY_OBJ(_playObj); - } - ALOGV("After destroying SL play object"); - if (_assetFd > 0) { - ALOGV("Closing assetFd: %d", _assetFd); - ::close(_assetFd); - _assetFd = 0; - } - free(_pcmData); -} - -bool AudioDecoderSLES::init(SLEngineItf engineItf, const std::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback) { - if (AudioDecoder::init(url, sampleRate)) { - _engineItf = engineItf; - _bufferSizeInFrames = bufferSizeInFrames; - _fdGetterCallback = fdGetterCallback; - - BUFFER_SIZE_IN_BYTES = toBufferSizeInBytes(bufferSizeInFrames, 2, 2); - _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; - } - - return false; -} - -bool AudioDecoderSLES::decodeToPcm() { - // 当前oh不支持,直接返回true - return true; -} - -//----------------------------------------------------------------- -void AudioDecoderSLES::signalEos() { - std::unique_lock autoLock(_eosLock); - _eos = true; - _eosCondition.notify_one(); -} - -void AudioDecoderSLES::queryAudioInfo() { - if (_formatQueried) { - return; - } - - SLresult result; - /* Get duration in callback where we use the callback context for the SLPlayItf*/ - SLmillisecond durationInMsec = SL_TIME_UNKNOWN; - result = (*_decContext.playItf)->GetDuration(_decContext.playItf, &durationInMsec); - SL_RETURN_IF_FAILED(result, "decodeProgressCallback,GetDuration failed"); - - if (durationInMsec == SL_TIME_UNKNOWN) { - ALOGV("Content duration is unknown (in dec callback)"); - } else { - ALOGV("Content duration is %dms (in dec callback)", (int)durationInMsec); - _result.duration = durationInMsec / 1000.0F; - } - - /* used to query metadata values */ - SLMetadataInfo pcmMetaData; - - result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _sampleRateKeyIndex, PCM_METADATA_VALUE_SIZE, &pcmMetaData); - - SL_RETURN_IF_FAILED(result, "%s GetValue _sampleRateKeyIndex failed", __FUNCTION__); - // Note: here we could verify the following: - // pcmMetaData->encoding == SL_CHARACTERENCODING_BINARY - // pcmMetaData->size == sizeof(SLuint32) - // but the call was successful for the PCM format keys, so those conditions are implied - - _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 = *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 = *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 = *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 = *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 = *reinterpret_cast(pcmMetaData.data); - - _formatQueried = true; -} - -void AudioDecoderSLES::prefetchCallback(SLPrefetchStatusItf caller, SLuint32 event) { - SLpermille level = 0; - SLresult result; - result = (*caller)->GetFillLevel(caller, &level); - SL_RETURN_IF_FAILED(result, "GetFillLevel failed"); - - SLuint32 status; - //ALOGV("PrefetchEventCallback: received event %u", event); - result = (*caller)->GetPrefetchStatus(caller, &status); - - SL_RETURN_IF_FAILED(result, "GetPrefetchStatus failed"); - - if ((PREFETCHEVENT_ERROR_CANDIDATE == (event & PREFETCHEVENT_ERROR_CANDIDATE)) && (level == 0) && (status == SL_PREFETCHSTATUS_UNDERFLOW)) { - ALOGV("PrefetchEventCallback: Error while prefetching data, exiting"); - _prefetchError = true; - signalEos(); - } -} - -/* 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) { - queryAudioInfo(); - - for (int i = 0; i < NB_BUFFERS_IN_QUEUE; ++i) { - _result.pcmBuffer->insert(_result.pcmBuffer->end(), _decContext.pData, - _decContext.pData + BUFFER_SIZE_IN_BYTES); - - /* Increase data pointer by buffer size */ - _decContext.pData += BUFFER_SIZE_IN_BYTES; - } - } - signalEos(); - } -} - -//----------------------------------------------------------------- -/* Callback for decoding buffer queue events */ -void AudioDecoderSLES::decodeToPcmCallback(CCSLBufferQueueItf queueItf) { - _isDecodingCallbackInvoked = true; - ALOGV("%s ...", __FUNCTION__); - _counter++; - SLresult result; - // IDEA: ?? - if (_counter % 1000 == 0) { - SLmillisecond msec; - result = (*_decContext.playItf)->GetPosition(_decContext.playItf, &msec); - SL_RETURN_IF_FAILED(result, "%s, GetPosition failed", __FUNCTION__); - ALOGV("%s called (iteration %d): current position=%d ms", __FUNCTION__, _counter, (int)msec); - } - - _result.pcmBuffer->insert(_result.pcmBuffer->end(), _decContext.pData, - _decContext.pData + BUFFER_SIZE_IN_BYTES); - - result = (*queueItf)->Enqueue(queueItf, _decContext.pData, BUFFER_SIZE_IN_BYTES); - SL_RETURN_IF_FAILED(result, "%s, Enqueue failed", __FUNCTION__); - - /* Increase data pointer by buffer size */ - _decContext.pData += BUFFER_SIZE_IN_BYTES; - - if (_decContext.pData >= _decContext.pDataBase + (NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES)) { - _decContext.pData = _decContext.pDataBase; - } - - // Note: adding a sleep here or any sync point is a way to slow down the decoding, or - // synchronize it with some other event, as the OpenSL ES framework will block until the - // buffer queue callback return to proceed with the decoding. - -#if 0 - /* Example: buffer queue state display */ - SLAndroidSimpleBufferQueueState decQueueState; - result =(*queueItf)->GetState(queueItf, &decQueueState); - SL_RETURN_IF_FAILED(result, "decQueueState.GetState failed"); - - ALOGV("DecBufferQueueCallback now has _decContext.pData=%p, _decContext.pDataBase=%p, queue: " - "count=%u playIndex=%u, count: %d", - _decContext.pData, _decContext.pDataBase, decQueueState.count, decQueueState.index, _counter); -#endif - -#if 0 - /* Example: display position in callback where we use the callback context for the SLPlayItf*/ - SLmillisecond posMsec = SL_TIME_UNKNOWN; - result = (*_decContext.playItf)->GetPosition(_decContext.playItf, &posMsec); - SL_RETURN_IF_FAILED(result, "decodeToPcmCallback,GetPosition2 failed"); - - if (posMsec == SL_TIME_UNKNOWN) { - ALOGV("Content position is unknown (in dec callback)"); - } else { - ALOGV("Content position is %ums (in dec callback)", - posMsec); - } -#endif - - queryAudioInfo(); -} - -}} // namespace cocos2d { namespace experimental \ No newline at end of file diff --git a/cocos/audio/ohos/AudioDecoderSLES.h b/cocos/audio/ohos/AudioDecoderSLES.h deleted file mode 100644 index 5fb5ae868c90..000000000000 --- a/cocos/audio/ohos/AudioDecoderSLES.h +++ /dev/null @@ -1,96 +0,0 @@ -/**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. -Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -http://www.cocos2d-x.org - -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 -#include -#include "AudioDecoder.h" -#include "utils/Compat.h" - -namespace cocos2d { namespace experimental { - -class AudioDecoderSLES : public AudioDecoder { -protected: - AudioDecoderSLES(); - ~AudioDecoderSLES() override; - - bool init(SLEngineItf engineItf, const std::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback); - bool decodeToPcm() override; - -private: - void queryAudioInfo(); - - void signalEos(); - void decodeToPcmCallback(CCSLBufferQueueItf queueItf); - void prefetchCallback(SLPrefetchStatusItf caller, SLuint32 event); - void decodeProgressCallback(SLPlayItf caller, SLuint32 event); - - SLEngineItf _engineItf; - SLObjectItf _playObj; - /* Local storage for decoded audio data */ - char *_pcmData; - - /* we only want to query / display the PCM format once */ - bool _formatQueried; - /* Used to signal prefetching failures */ - bool _prefetchError; - - /* to display the number of decode iterations */ - int _counter; - - /* metadata key index for the PCM format information we want to retrieve */ - int _numChannelsKeyIndex; - int _sampleRateKeyIndex; - int _bitsPerSampleKeyIndex; - int _containerSizeKeyIndex; - int _channelMaskKeyIndex; - int _endiannessKeyIndex; - - /* to signal to the test app the end of the stream to decode has been reached */ - bool _eos; - std::mutex _eosLock; - std::condition_variable _eosCondition; - - /* Structure for passing information to callback function */ - typedef struct CallbackCntxt_ { //NOLINT(modernize-use-using, readability-identifier-naming) - SLPlayItf playItf; - SLMetadataExtractionItf metaItf; - SLuint32 size; - SLint8 *pDataBase; // Base address of local audio data storage - SLint8 *pData; // Current address of local audio data storage - } CallbackCntxt; - - CallbackCntxt _decContext; - int _bufferSizeInFrames; - int _assetFd; - FdGetterCallback _fdGetterCallback; - bool _isDecodingCallbackInvoked; - - friend class SLAudioDecoderCallbackProxy; - friend class AudioDecoderProvider; -}; - -}}// namespace cocos2d { namespace experimental \ No newline at end of file diff --git a/cocos/audio/ohos/AudioEngine-inl.cpp b/cocos/audio/ohos/AudioEngine-inl.cpp index 5bdd16faf7b1..42b59d3ee9a7 100644 --- a/cocos/audio/ohos/AudioEngine-inl.cpp +++ b/cocos/audio/ohos/AudioEngine-inl.cpp @@ -39,7 +39,7 @@ #include "AudioPlayerProvider.h" #include "IAudioPlayer.h" #include "ICallerThreadUtils.h" -#include "UrlAudioPlayer.h" +#include "BigAudioPlayer.h" #include "cutils/log.h" #include "base/CCDirector.h" #include "base/CCScheduler.h" @@ -55,7 +55,7 @@ AudioEngineImpl *gAudioImpl = nullptr; int outputSampleRate = 48000; // TODO(hack) : There is currently a bug in the opensles module, -// so openharmony must configure a fixed size, otherwise the callback will be suspended +// so HarmonyOS Next must configure a fixed size, otherwise the callback will be suspended int bufferSizeInFrames = 2048; @@ -67,7 +67,7 @@ void getAudioInfo() { class CallerThreadUtils : public ICallerThreadUtils { public: void performFunctionInCallerThread(const std::function &func) override { - cocos2d::Director::sharedDirector()->getScheduler()->performFunctionInCocosThread(func); + cocos2d::Director::getInstance()->getScheduler()->performFunctionInCocosThread(func); }; @@ -88,9 +88,9 @@ static CallerThreadUtils gCallerThreadUtils; static int fdGetter(const std::string &url, off_t *start, off_t *length) { int fd = -1; - RawFileDescriptor descriptor; + RawFileDescriptor64 descriptor; FileUtilsOhos *utils = dynamic_cast(FileUtils::getInstance()); - utils->getRawFileDescriptor(url, descriptor); + utils->getRawFileDescriptor(url, &descriptor); fd = descriptor.fd; if (fd <= 0) { @@ -116,6 +116,7 @@ AudioEngineImpl::AudioEngineImpl() } AudioEngineImpl::~AudioEngineImpl() { + stopAll(); if (_audioPlayerProvider != nullptr) { delete _audioPlayerProvider; _audioPlayerProvider = nullptr; @@ -186,7 +187,7 @@ void AudioEngineImpl::onEnterBackground(EventCustom* event) { // pause UrlAudioPlayers which are playing. for (auto&& e : _audioPlayers) { auto player = e.second; - if (dynamic_cast(player) != nullptr + if (dynamic_cast(player) != nullptr && player->getState() == IAudioPlayer::State::PLAYING) { _urlAudioPlayersNeedResume.emplace(e.first, player); player->pause(); @@ -458,7 +459,8 @@ PCMHeader AudioEngineImpl::getPCMHeader(const char *url) { return header; } - AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(_engineEngine, fileFullPath, bufferSizeInFrames, outputSampleRate, fdGetter); + auto info = AudioPlayerProvider::getFileInfo(fileFullPath); + AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(fileFullPath, bufferSizeInFrames, info); if (decoder == nullptr) { ALOGD("decode %{public}s failed, the file formate might not support", url); @@ -493,7 +495,8 @@ std::vector AudioEngineImpl::getOriginalPCMBuffer(const char *url, uint if (_audioPlayerProvider->getPcmData(url, data)) { ALOGD("file %{public}s pcm data already cached", url); } else { - AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(_engineEngine, fileFullPath, bufferSizeInFrames, outputSampleRate, fdGetter); + auto info = AudioPlayerProvider::getFileInfo(fileFullPath); + AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(fileFullPath, bufferSizeInFrames, info); if (decoder == nullptr) { ALOGD("decode %{public}s failed, the file formate might not support", url); return pcmData; diff --git a/cocos/audio/ohos/AudioPlayerProvider.cpp b/cocos/audio/ohos/AudioPlayerProvider.cpp index dfd7dc3ed996..034ac2e7b6d2 100644 --- a/cocos/audio/ohos/AudioPlayerProvider.cpp +++ b/cocos/audio/ohos/AudioPlayerProvider.cpp @@ -35,13 +35,14 @@ THE SOFTWARE. #include #include "platform/ohos/CCFileUtils-ohos.h" #include "AudioDecoder.h" +#include "AudioDecoderOH.h" #include "AudioDecoderProvider.h" #include "AudioMixerController.h" #include "AudioPlayerProvider.h" #include "ICallerThreadUtils.h" #include "PcmAudioPlayer.h" #include "PcmAudioService.h" -#include "UrlAudioPlayer.h" +#include "BigAudioPlayer.h" #include "utils/Utils.h" #include "CCThreadPool.h" @@ -53,11 +54,6 @@ THE SOFTWARE. namespace cocos2d { namespace experimental { -static int getSystemAPILevel() { - // TODO(qgh): On the openharmony platform, pcm streaming must be used - return std::numeric_limits::max(); -} - struct AudioFileIndicator { std::string extension; int smallSizeIndicator; @@ -75,19 +71,16 @@ AudioPlayerProvider::AudioPlayerProvider(SLEngineItf engineItf, int deviceSample ICallerThreadUtils *callerThreadUtils) : _engineItf(engineItf), _deviceSampleRate(deviceSampleRate), _fdGetterCallback(fdGetterCallback), _callerThreadUtils(callerThreadUtils), _pcmAudioService(nullptr), _mixController(nullptr), _threadPool(LegacyThreadPool::newCachedThreadPool(1, 8, 5, 2, 2)) { ALOGI("deviceSampleRate: %d", _deviceSampleRate); - if (getSystemAPILevel() >= 17) { - _mixController = new AudioMixerController(_deviceSampleRate, 2); - _pcmAudioService = new PcmAudioService(); - _pcmAudioService->init(_mixController, CHANNEL_NUMBERS, deviceSampleRate, &_bufferSizeInFrames); - _mixController->init(_bufferSizeInFrames); - } + _mixController = new AudioMixerController(_deviceSampleRate, 2); + _pcmAudioService = new PcmAudioService(); + _pcmAudioService->init(_mixController, CHANNEL_NUMBERS, deviceSampleRate, &_bufferSizeInFrames); + _mixController->init(_bufferSizeInFrames); ALOG_ASSERT(callerThreadUtils != nullptr, "Caller thread utils parameter should not be nullptr!"); } AudioPlayerProvider::~AudioPlayerProvider() { ALOGV("~AudioPlayerProvider()"); - UrlAudioPlayer::stopAll(); SL_SAFE_DELETE(_pcmAudioService); SL_SAFE_DELETE(_mixController); @@ -95,16 +88,6 @@ AudioPlayerProvider::~AudioPlayerProvider() { } IAudioPlayer *AudioPlayerProvider::getAudioPlayer(const std::string &audioFilePath) { - // Pcm data decoding by OpenSLES API only supports in API level 17 and later. - if (getSystemAPILevel() < 17) { - AudioFileInfo info = getFileInfo(audioFilePath); - if (info.isValid()) { - return dynamic_cast(createUrlAudioPlayer(info)); - } - - return nullptr; - } - IAudioPlayer *player = nullptr; _pcmCacheMutex.lock(); @@ -121,7 +104,7 @@ IAudioPlayer *AudioPlayerProvider::getAudioPlayer(const std::string &audioFilePa // playing background music uses UrlAudioPlayer AudioFileInfo info = getFileInfo(audioFilePath); if (info.isValid()) { - if (isSmallFile(info)) { + if (info.smallFile) { // Put an empty lambda to preloadEffect since we only want the future object to get PcmData auto pcmData = std::make_shared(); auto isSucceed = std::make_shared(false); @@ -163,7 +146,7 @@ IAudioPlayer *AudioPlayerProvider::getAudioPlayer(const std::string &audioFilePa ALOGE("FileInfo (%{public}p), preloadEffect (%{public}s) failed", &info, audioFilePath.c_str()); } } else { - player = dynamic_cast(createUrlAudioPlayer(info)); + player = dynamic_cast(createBigAudioPlayer(info)); ALOGV_IF(player == nullptr, "%{public}s, %{public}d: player is nullptr, path: %{public}s", __FUNCTION__, __LINE__, audioFilePath.c_str()); } } else { @@ -176,13 +159,6 @@ IAudioPlayer *AudioPlayerProvider::getAudioPlayer(const std::string &audioFilePa } void AudioPlayerProvider::preloadEffect(const std::string &audioFilePath, const PreloadCallback &callback) { - // Pcm data decoding by OpenSLES API only supports in API level 17 and later. - if (getSystemAPILevel() < 17) { - PcmData data; - callback(true, data); - return; - } - _pcmCacheMutex.lock(); auto &&iter = _pcmCache.find(audioFilePath); if (iter != _pcmCache.end()) { @@ -212,7 +188,7 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload return; } - if (isSmallFile(info)) { + if (info.smallFile) { std::string audioFilePath = info.url; // 1. First time check, if it wasn't in the cache, goto 2 step @@ -261,10 +237,10 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload _preloadCallbackMap.insert(std::make_pair(audioFilePath, std::move(callbacks))); } - _threadPool->pushTask([this, audioFilePath](int /*tid*/) { + _threadPool->pushTask([this, audioFilePath, info](int /*tid*/) { ALOGV("AudioPlayerProvider::preloadEffect: (%{public}s)", audioFilePath.c_str()); PcmData d; - AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(_engineItf, audioFilePath, _bufferSizeInFrames, _deviceSampleRate, _fdGetterCallback); + AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(audioFilePath, _deviceSampleRate, info); bool ret = decoder != nullptr && decoder->start(); if (ret) { d = decoder->getResult(); @@ -307,9 +283,9 @@ AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo(const std::s int assetFd = -1; if(audioFilePath[0]!='/'){ - RawFileDescriptor descriptor; + RawFileDescriptor64 descriptor; FileUtilsOhos *utils = dynamic_cast(FileUtils::getInstance()); - FileUtils::Status result = utils->getRawFileDescriptor(audioFilePath, descriptor); + FileUtils::Status result = utils->getRawFileDescriptor(audioFilePath, &descriptor); if(result != FileUtils::Status::OK|| descriptor.fd <= 0){ ALOGE("Failed to open file descriptor for '%s'", audioFilePath.c_str()); return info; @@ -331,6 +307,7 @@ AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo(const std::s info.assetFd = std::make_shared(assetFd); info.start = start; info.length = fileSize; + info.smallFile = isSmallFile(info); ALOGI("AudioPlayerProvide::getFileInfo(%{public}s) file size:%{public}ld,fd is %d",audioFilePath.c_str(), fileSize,assetFd); return info; } @@ -338,10 +315,6 @@ AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo(const std::s bool AudioPlayerProvider::isSmallFile(const AudioFileInfo &info) { //NOLINT(readability-convert-member-functions-to-static) //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); - if(audioFileInfo.url[0] == '/') { - // avplayer does not support playing audio files in sandbox path currently. - return true; - } size_t judgeCount = sizeof(gAudioFileIndicator) / sizeof(gAudioFileIndicator[0]); size_t pos = audioFileInfo.url.rfind('.'); std::string extension; @@ -401,22 +374,28 @@ PcmAudioPlayer *AudioPlayerProvider::obtainPcmAudioPlayer(const std::string &url return pcmPlayer; } -UrlAudioPlayer *AudioPlayerProvider::createUrlAudioPlayer( - const AudioPlayerProvider::AudioFileInfo &info) { +BigAudioPlayer *AudioPlayerProvider::createBigAudioPlayer(const AudioFileInfo &info) { if (info.url.empty()) { - ALOGE("createUrlAudioPlayer failed, url is empty!"); + ALOGE("createBigAudioPlayer failed, url is empty!"); return nullptr; } - auto *urlPlayer = new (std::nothrow) UrlAudioPlayer(_callerThreadUtils); - bool ret = urlPlayer->prepare(info.url, info.assetFd, info.start, info.length); - if (!ret) { - if (urlPlayer != nullptr) { - delete urlPlayer; - urlPlayer = nullptr; - } - } - return urlPlayer; + auto pcmData = std::make_shared(); + std::unique_lock lck(_preloadWaitMutex); + auto *bigPlayer = new (std::nothrow) BigAudioPlayer(); + _threadPool->pushTask([this, info, bigPlayer, pcmData](int /*tid*/) { + AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(info.url, _deviceSampleRate, info); + ((AudioDecoderOH *) decoder)->demuxer(); + PcmData d = decoder->getResult(); + *pcmData = std::move(d); + bigPlayer->prepare(info.url, *pcmData); + _preloadWaitCond.notify_one(); + bool ret = decoder != nullptr && decoder->asyncStart(); + ALOGV("decoderBigAudio %{public}s", (ret ? "succeed" : "failed")); + AudioDecoderProvider::destroyAudioDecoder(&decoder); + }); + _preloadWaitCond.wait_for(lck, std::chrono::seconds(2)); + return bigPlayer; } void AudioPlayerProvider::pause() { diff --git a/cocos/audio/ohos/AudioPlayerProvider.h b/cocos/audio/ohos/AudioPlayerProvider.h index bbf914b9a85d..510b5fe88e9c 100644 --- a/cocos/audio/ohos/AudioPlayerProvider.h +++ b/cocos/audio/ohos/AudioPlayerProvider.h @@ -40,6 +40,7 @@ namespace cocos2d { namespace experimental { class PcmAudioPlayer; class PcmAudioService; class UrlAudioPlayer; +class BigAudioPlayer; class AudioMixerController; class ICallerThreadUtils; class AssetFd; @@ -73,6 +74,7 @@ class AudioPlayerProvider { std::shared_ptr assetFd; off_t start{}; off_t length; + bool smallFile = true; AudioFileInfo() : assetFd(nullptr) {} @@ -84,13 +86,13 @@ class AudioPlayerProvider { PcmAudioPlayer *obtainPcmAudioPlayer(const std::string &url, const PcmData &pcmData); - UrlAudioPlayer *createUrlAudioPlayer(const AudioFileInfo &info); + BigAudioPlayer *createBigAudioPlayer(const AudioFileInfo &info); void preloadEffect(const AudioFileInfo &info, const PreloadCallback &callback, bool isPreloadInPlay2d); - AudioFileInfo getFileInfo(const std::string &audioFilePath); + static AudioFileInfo getFileInfo(const std::string &audioFilePath); - bool isSmallFile(const AudioFileInfo &info); + static bool isSmallFile(const AudioFileInfo &info); SLEngineItf _engineItf; SLObjectItf _outputMixObject; diff --git a/cocos/audio/ohos/BigAudioPlayer.cpp b/cocos/audio/ohos/BigAudioPlayer.cpp new file mode 100644 index 000000000000..ca6859ce9e6c --- /dev/null +++ b/cocos/audio/ohos/BigAudioPlayer.cpp @@ -0,0 +1,149 @@ +#include "BigAudioPlayer.h" +#include "cutils/log.h" +#include "ICallerThreadUtils.h" + +namespace cocos2d { namespace experimental { + +BigAudioPlayer::BigAudioPlayer() +: _id(-1), _track(nullptr), _playEventCallback(nullptr), _service(nullptr) { + ALOGV("BigAudioPlayer constructor: %p", this); +} + +BigAudioPlayer::~BigAudioPlayer() { + ALOGV("In the destructor of BigAudioPlayer (%p)", this); + delete _track; + delete _service; +} + +bool BigAudioPlayer::prepare(const std::string &url, const PcmData &decResult) +{ + _url = url; + _duration = decResult.duration; + _track = new Track(decResult); + + _track->onStateChanged = [this](Track::State state) { + Track::State prevState = _track->getPrevState(); + ALOGE("PcmAudioPlayer %{public}p onStateChanged: preState = %{public}d, state = %{public}d", this, (int)prevState, (int)state); + if (state == Track::State::OVER && prevState != Track::State::STOPPED) { + if (_playEventCallback != nullptr) { + _playEventCallback(State::OVER); + } + } else if (state == Track::State::STOPPED) { + if (_playEventCallback != nullptr) { + _playEventCallback(State::STOPPED); + } + } else if (state == Track::State::DESTROYED) { + delete this; + } + }; + + setVolume(1.0f); + + _service = new BigAudioService(); + _service->init(decResult); + + return true; +} + +void BigAudioPlayer::rewind() { + ALOGW("BigAudioPlayer::rewind isn't supported!"); +} + +void BigAudioPlayer::setVolume(float volume) { + _track->setVolume(volume); +} + +float BigAudioPlayer::getVolume() const { + return _track->getVolume(); +} + +void BigAudioPlayer::setAudioFocus(bool isFocus) { + _track->setAudioFocus(isFocus); +} + +void BigAudioPlayer::setLoop(bool isLoop) { + _track->setLoop(isLoop); +} + +bool BigAudioPlayer::isLoop() const { + return _track->isLoop(); +} + +float BigAudioPlayer::getDuration() const { + return _duration; +} + +float BigAudioPlayer::getPosition() const { + return _track->getPosition(); +} + +bool BigAudioPlayer::setPosition(float pos) { + return _track->setPosition(pos); +} + +void BigAudioPlayer::setPlayEventCallback(const PlayEventCallback &playEventCallback) { + _playEventCallback = playEventCallback; +} + +void BigAudioPlayer::play() { + ALOGV("BigAudioPlayer (%{public}p) play, url: %{public}s", this, _url.c_str()); + _track->setState(Track::State::PLAYING); + _service->setTrack(_track); +} + +void BigAudioPlayer::pause() { + ALOGV("BigAudioPlayer (%{public}p) pause, url: %{public}s", this, _url.c_str()); + _service->pause(); +} + +void BigAudioPlayer::resume() { + ALOGV("BigAudioPlayer (%{public}p) resume, url: %{public}s", this, _url.c_str()); + _service->resume(); +} + +void BigAudioPlayer::stop() { + ALOGV("BigAudioPlayer (%{public}p) stop, url: %{public}s", this, _url.c_str()); + + setLoop(false); + _track->setState(Track::State::STOPPED); +} + +IAudioPlayer::State BigAudioPlayer::getState() const { + IAudioPlayer::State state = State::INVALID; + + if (_track != nullptr) { + switch (_track->getState()) { + case Track::State::IDLE: + state = State::INITIALIZED; + break; + + case Track::State::PLAYING: + state = State::PLAYING; + break; + + case Track::State::RESUMED: + state = State::PLAYING; + break; + + case Track::State::PAUSED: + state = State::PAUSED; + break; + + case Track::State::STOPPED: + state = State::STOPPED; + break; + + case Track::State::OVER: + state = State::OVER; + break; + + default: + state = State::INVALID; + break; + } + } + return state; +} + +}} // namespace cocos2d { namespace experimental + diff --git a/cocos/audio/ohos/BigAudioPlayer.h b/cocos/audio/ohos/BigAudioPlayer.h new file mode 100644 index 000000000000..ee8a79965be1 --- /dev/null +++ b/cocos/audio/ohos/BigAudioPlayer.h @@ -0,0 +1,80 @@ +#ifndef PROJ_OHOS_BIGAUDIOPLAYER_H +#define PROJ_OHOS_BIGAUDIOPLAYER_H + +#pragma once + +#include +#include +#include +#include +#include "AssetFd.h" +#include "IAudioPlayer.h" +#include "AssetFd.h" +#include "PcmData.h" +#include "Track.h" + +namespace cocos2d { namespace experimental { + +class BigAudioPlayer : public IAudioPlayer { + +public: + // Override Functions Begin + virtual int getId() const override { return _id; }; + + virtual void setId(int id) override { _id = id; }; + + virtual std::string getUrl() const override { return _url; }; + + virtual State getState() const override; + + virtual void play() override; + + virtual void pause() override; + + virtual void resume() override; + + virtual void stop() override; + + virtual void rewind() override; + + virtual void setVolume(float volume) override; + + virtual float getVolume() const override; + + virtual void setAudioFocus(bool isFocus) override; + + virtual void setLoop(bool isLoop) override; + + virtual bool isLoop() const override; + + virtual float getDuration() const override; + + virtual float getPosition() const override; + + virtual bool setPosition(float pos) override; + + virtual void setPlayEventCallback(const PlayEventCallback &playEventCallback) override; + + // Override Functions End + + bool prepare(const std::string &url, const PcmData &decResult); + + BigAudioPlayer(); + virtual ~BigAudioPlayer(); + +private: + int _id; + std::string _url; + + float _duration; + Track *_track; + + PlayEventCallback _playEventCallback; + BigAudioService *_service; + + friend class AudioPlayerProvider; +}; + +}} // namespace cocos2d { namespace experimental + +#endif //PROJ_OHOS_BIGAUDIOPLAYER_H \ No newline at end of file diff --git a/cocos/audio/ohos/BigAudioService.cpp b/cocos/audio/ohos/BigAudioService.cpp new file mode 100644 index 000000000000..0a3c03e16f67 --- /dev/null +++ b/cocos/audio/ohos/BigAudioService.cpp @@ -0,0 +1,153 @@ +#include "BigAudioService.h" + +namespace cocos2d { namespace experimental { + +BigAudioService::BigAudioService(): _audioRenderer(nullptr), _builder(nullptr) +{ +} + +BigAudioService::~BigAudioService() { + if (_audioRenderer != nullptr) { + OH_AudioRenderer_Release(_audioRenderer); + _audioRenderer = nullptr; + } + + if (_builder != nullptr) { + OH_AudioStreamBuilder_Destroy(_builder); + _builder = nullptr; + } +} + +int32_t BigAudioService::AudioRendererOnWriteData(OH_AudioRenderer* renderer, + void* userData, + void* buffer, + int32_t bufferLen) +{ + auto *thiz = reinterpret_cast(userData); + if (thiz->getNextTrackBuff(buffer, bufferLen)) { + return AUDIO_DATA_CALLBACK_RESULT_VALID; + } else { + return AUDIO_DATA_CALLBACK_RESULT_INVALID; + } +} + + +int32_t BigAudioService::AudioRendererOnInterrupt(OH_AudioRenderer* renderer, + void* userData, + OH_AudioInterrupt_ForceType type, + OH_AudioInterrupt_Hint hint) +{ + auto *thiz = reinterpret_cast(userData); + if (thiz->_audioRenderer != nullptr) { + if (hint == AUDIOSTREAM_INTERRUPT_HINT_RESUME) { + OH_AudioRenderer_Start(thiz->_audioRenderer); + } else if (hint == AUDIOSTREAM_INTERRUPT_HINT_PAUSE) { + OH_AudioRenderer_Pause(thiz->_audioRenderer); + } + } + return 0; +} + +bool BigAudioService::init(PcmData decResult) { + + _decResult = decResult; + OH_AudioStream_Result ret; + ret = OH_AudioStreamBuilder_Create(&_builder, AUDIOSTREAM_TYPE_RENDERER); + if (ret != AUDIOSTREAM_SUCCESS) { + return false; + } + + OH_AudioStreamBuilder_SetSamplingRate(_builder, decResult.sampleRate); + OH_AudioStreamBuilder_SetChannelCount(_builder, decResult.numChannels); + OH_AudioStreamBuilder_SetLatencyMode(_builder, AUDIOSTREAM_LATENCY_MODE_FAST); + OH_AudioStreamBuilder_SetRendererInfo(_builder, AUDIOSTREAM_USAGE_GAME); + + OH_AudioRenderer_Callbacks callbacks; + callbacks.OH_AudioRenderer_OnWriteData = AudioRendererOnWriteData; + callbacks.OH_AudioRenderer_OnInterruptEvent = AudioRendererOnInterrupt; + callbacks.OH_AudioRenderer_OnError = nullptr; + callbacks.OH_AudioRenderer_OnStreamEvent = nullptr; + ret = OH_AudioStreamBuilder_SetRendererCallback(_builder, callbacks, this); + if (ret != AUDIOSTREAM_SUCCESS) { + return false; + } + + ret = OH_AudioStreamBuilder_GenerateRenderer(_builder, &_audioRenderer); + if (ret != AUDIOSTREAM_SUCCESS) { + return false; + } + + int32_t buffer_size; + OH_AudioRenderer_GetFrameSizeInCallback(_audioRenderer, &buffer_size); + _bufferSizeInBytes = buffer_size * decResult.numChannels * 2; + + ret = OH_AudioRenderer_Start(_audioRenderer); + if (ret != AUDIOSTREAM_SUCCESS) { + return false; + } + + return true; +} + +void BigAudioService::setTrack(Track *track) { + _track = track; +} + +bool BigAudioService::getNextTrackBuff(void * buffer, int32_t bufferLen) { + if (_track == nullptr) { + return false; + } + bool validData = false; + bool need_destroy = false; + Track::State state = _track->getState(); + if (state == Track::State::PLAYING) { + std::lock_guard lk(_track->_volumeDirtyMutex); + if (_track->isVolumeDirty()) { + OH_AudioRenderer_SetVolume(_audioRenderer, _track->getVolume()); + _track->setVolumeDirty(false); + } + if (_decResult.pcmBuffer->size() >= bufferLen) { + int frameCount = _bufferSizeInBytes / _decResult.numChannels / 2; + memcpy(buffer, _decResult.pcmBuffer->data() + _track->_nextFrame * _track->_frameSize, bufferLen); + _track->_nextFrame += frameCount; + validData = true; + } + } else if (state == Track::State::RESUMED) { + _track->setState(Track::State::PLAYING); + } else if (state == Track::State::STOPPED) { + need_destroy = true; + } + + if (_track->isPlayOver()) { + if (_track->isLoop()) { + _track->reset(); + } else { + ALOGV("Play over ..."); + _track->setState(Track::State::OVER); + need_destroy = true; + } + } + + if (need_destroy) { + delete &_decResult.pcmBuffer; + _track->onStateChanged(Track::State::DESTROYED); + } + + return validData; +} + +void BigAudioService::pause() { + if (_audioRenderer != nullptr) { + OH_AudioRenderer_Pause(_audioRenderer); + } +} + +void BigAudioService::resume() { + if (_audioRenderer != nullptr) { + OH_AudioRenderer_Flush(_audioRenderer);// clear pop sound + OH_AudioRenderer_Start(_audioRenderer); + } +} + +}} // namespace cocos2d { namespace experimental + diff --git a/cocos/audio/ohos/BigAudioService.h b/cocos/audio/ohos/BigAudioService.h new file mode 100644 index 000000000000..b7e051cb1cde --- /dev/null +++ b/cocos/audio/ohos/BigAudioService.h @@ -0,0 +1,45 @@ +#ifndef PROJ_OHOS_BIGAUDIOSERVICE_H +#define PROJ_OHOS_BIGAUDIOSERVICE_H + +#pragma once + +#include "cutils/log.h" +#include +#include +#include "Track.h" + +namespace cocos2d { namespace experimental { + +class Track; + +class BigAudioService { +public: + + BigAudioService(); + + virtual ~BigAudioService(); + + bool init(PcmData decResult); + void setTrack(Track *track); + bool getNextTrackBuff(void* buffer, int32_t bufferLen); + static int32_t AudioRendererOnWriteData(OH_AudioRenderer* renderer, void* userData, void* buffer, int32_t bufferLen); + static int32_t AudioRendererOnInterrupt(OH_AudioRenderer* renderer, void* userData, OH_AudioInterrupt_ForceType type, OH_AudioInterrupt_Hint hint); + + void pause(); + void resume(); + + int _numChannels; + int _sampleRate; + int _bufferSizeInBytes; + + OH_AudioRenderer *_audioRenderer; + OH_AudioStreamBuilder *_builder; + +private: + Track *_track = nullptr; + PcmData _decResult; +}; + +}} // namespace cocos2d { namespace experimental + +#endif //PROJ_OHOS_BIGAUDIOSERVICE_H diff --git a/cocos/audio/ohos/OpenSLHelper.h b/cocos/audio/ohos/OpenSLHelper.h index aefce32f5ba7..6dadf1cc2d6d 100644 --- a/cocos/audio/ohos/OpenSLHelper.h +++ b/cocos/audio/ohos/OpenSLHelper.h @@ -26,12 +26,8 @@ THE SOFTWARE. #pragma once #include "cutils/log.h" - #include -#include - - #include #include diff --git a/cocos/audio/ohos/PcmAudioPlayer.cpp b/cocos/audio/ohos/PcmAudioPlayer.cpp index c7e0faa0ae7b..0a0773d8f327 100644 --- a/cocos/audio/ohos/PcmAudioPlayer.cpp +++ b/cocos/audio/ohos/PcmAudioPlayer.cpp @@ -64,7 +64,7 @@ bool PcmAudioPlayer::prepare(const std::string &url, const PcmData &decResult) { _track->onStateChanged = [this, callerThreadId](Track::State state) { // It maybe in sub thread Track::State prevState = _track->getPrevState(); - ALOGE("PcmAudioPlayer %{public}p onStateChanged: preState = %{public}d, state = %{public}d", this, prevState, state); + ALOGE("PcmAudioPlayer %{public}p onStateChanged: preState = %{public}d, state = %{public}d", this, (int)prevState, (int)state); auto func = [this, state, prevState]() { // It's in caller's thread if (state == Track::State::OVER && prevState != Track::State::STOPPED) { diff --git a/cocos/audio/ohos/PcmAudioService.cpp b/cocos/audio/ohos/PcmAudioService.cpp index ff33a876c7b0..9b765a0b4ebb 100644 --- a/cocos/audio/ohos/PcmAudioService.cpp +++ b/cocos/audio/ohos/PcmAudioService.cpp @@ -33,7 +33,6 @@ THE SOFTWARE. namespace cocos2d { namespace experimental { -static std::vector __silenceData;//NOLINT(bugprone-reserved-identifier, readability-identifier-naming) PcmAudioService::PcmAudioService() : _controller(nullptr) { @@ -59,14 +58,13 @@ int32_t PcmAudioService::AudioRendererOnWriteData(OH_AudioRenderer* renderer, { auto *thiz = reinterpret_cast(userData); if (bufferLen != thiz->_bufferSizeInBytes) { - __silenceData.resize(bufferLen, 0x00); thiz->_bufferSizeInBytes = bufferLen; thiz->_controller->updateBufferSize(thiz->_bufferSizeInBytes); } if (thiz->_controller->hasPlayingTacks()) { if (thiz->_controller->isPaused()) { - memcpy(buffer, __silenceData.data(), bufferLen); + return AUDIO_DATA_CALLBACK_RESULT_INVALID; } else { thiz->_controller->mixOneFrame(); @@ -75,10 +73,10 @@ int32_t PcmAudioService::AudioRendererOnWriteData(OH_AudioRenderer* renderer, memcpy(buffer, current->buf, current->size < bufferLen ? current->size : bufferLen); } } else { - memcpy(buffer, __silenceData.data(), bufferLen); + return AUDIO_DATA_CALLBACK_RESULT_INVALID; } - return 0; + return AUDIO_DATA_CALLBACK_RESULT_VALID; } int32_t PcmAudioService::AudioRendererOnInterrupt(OH_AudioRenderer* renderer, @@ -132,10 +130,6 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in _bufferSizeInBytes = buffer_size * numChannels * 2; *bufferSizeInBytes = buffer_size; - if (__silenceData.empty()) { - __silenceData.resize(_bufferSizeInBytes, 0x00); - } - ret = OH_AudioRenderer_Start(_audioRenderer); if (ret != AUDIOSTREAM_SUCCESS) { return false; @@ -146,6 +140,7 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in void PcmAudioService::pause() { if (_audioRenderer != nullptr) { + OH_AudioRenderer_Flush(_audioRenderer);// clear pop sound OH_AudioRenderer_Pause(_audioRenderer); } } diff --git a/cocos/audio/ohos/SimpleAudioEngine.cpp b/cocos/audio/ohos/SimpleAudioEngine.cpp index 30b0c81b12b5..b8364746deeb 100644 --- a/cocos/audio/ohos/SimpleAudioEngine.cpp +++ b/cocos/audio/ohos/SimpleAudioEngine.cpp @@ -41,7 +41,7 @@ static float _effectsVolume = 1.0; static std::string getFullPathWithoutAssetsPrefix(const char* pszFilename) { - std::string fullPath = cocos2d::FileUtils::sharedFileUtils()->fullPathForFilename(pszFilename); + std::string fullPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(pszFilename); size_t pos = fullPath.find("hap:/"); if (pos == 0) { diff --git a/cocos/audio/ohos/Track.h b/cocos/audio/ohos/Track.h index fab6df4af00c..ba6d8f62c15e 100644 --- a/cocos/audio/ohos/Track.h +++ b/cocos/audio/ohos/Track.h @@ -28,6 +28,7 @@ THE SOFTWARE. #include "PcmData.h" #include "IVolumeProvider.h" #include "PcmBufferProvider.h" +#include "audio/ohos/BigAudioService.h" #include #include @@ -96,6 +97,7 @@ class Track : public PcmBufferProvider, public IVolumeProvider { bool _isAudioFocus; friend class AudioMixerController; + friend class BigAudioService; }; }} // namespace cocos2d { namespace experimental diff --git a/cocos/audio/ohos/UrlAudioPlayer.cpp b/cocos/audio/ohos/UrlAudioPlayer.cpp deleted file mode 100644 index 8263428e46da..000000000000 --- a/cocos/audio/ohos/UrlAudioPlayer.cpp +++ /dev/null @@ -1,336 +0,0 @@ -/**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. -Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -http://www.cocos2d-x.org - -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. -****************************************************************************/ - -#define LOG_TAG "UrlAudioPlayer" - -#include "UrlAudioPlayer.h" -#include "ICallerThreadUtils.h" -#include -#include "Macros.h" -#include -#include // for std::find - -namespace { - -std::mutex __playerContainerMutex;//NOLINT(bugprone-reserved-identifier,readability-identifier-naming) -std::map __playerContainer;//NOLINT(bugprone-reserved-identifier,readability-identifier-naming) - -std::once_flag __onceFlag;//NOLINT(bugprone-reserved-identifier,readability-identifier-naming) - -} // namespace - -namespace cocos2d { namespace experimental { - -UrlAudioPlayer::UrlAudioPlayer(ICallerThreadUtils *callerThreadUtils) - : _callerThreadUtils(callerThreadUtils), _id(-1), _playObj(nullptr),_volume(0.0F), _duration(0.0F), _isLoop(false), _isAudioFocus(true), _state(State::INVALID), _playEventCallback(nullptr), _isDestroyed(std::make_shared(false)) -{ - _callerThreadId = callerThreadUtils->getCallerThreadId(); -} - -UrlAudioPlayer::~UrlAudioPlayer() -{ - __playerContainerMutex.lock(); - - auto it = __playerContainer.begin(); - while(it != __playerContainer.end()) - { - if(it->second == this) - { - it = __playerContainer.erase(it); - } - else - { - it++; - } - } - - __playerContainerMutex.unlock(); -} - -void UrlAudioPlayer::playEventCallback() { - std::shared_ptr isDestroyed = _isDestroyed; - - auto func = [this, isDestroyed]() { - // If it was destroyed, just return. - if (*isDestroyed) { - ALOGV("The UrlAudioPlayer (%p) was destroyed!", this); - return; - } - - //Note that It's in the caller's thread (Cocos Thread) - // If state is already stopped, ignore the play over event. - - if (_state == State::STOPPED) { - return; - } - - setState(State::OVER); - if (_playEventCallback != nullptr) { - _playEventCallback(State::OVER); - } - - ALOGV("UrlAudioPlayer (%p) played over, destroy self ...", this); - destroy(); - delete this; - }; - - if (_callerThreadId == std::this_thread::get_id()) { - func(); - } else { - _callerThreadUtils->performFunctionInCallerThread(func); - } -} - -void UrlAudioPlayer::setPlayEventCallback(const PlayEventCallback &playEventCallback) { - _playEventCallback = playEventCallback; -} - -void UrlAudioPlayer::stop() { - ALOGV("UrlAudioPlayer::stop (%p, %d)", this, getId()); - int32_t status = OH_AVPlayer_Stop(_playObj); - if(status != 0) { - ALOGE("UrlAudioPlayer::stop failed"); - return; - } - - if (_state == State::PLAYING || _state == State::PAUSED) { - setLoop(false); - setState(State::STOPPED); - - if (_playEventCallback != nullptr) { - _playEventCallback(State::STOPPED); - } - - destroy(); - delete this; - } else { - ALOGW("UrlAudioPlayer (%p, state:%d) isn't playing or paused, could not invoke stop!", this, static_cast(_state)); - } -} - -void UrlAudioPlayer::pause() { - if (_state == State::PLAYING) { - int32_t status = OH_AVPlayer_Pause(_playObj); - if(status != 0) { - ALOGE("UrlAudioPlayer::pause failed"); - return; - } - setState(State::PAUSED); - } else { - ALOGW("UrlAudioPlayer (%p, state:%d) isn't playing, could not invoke pause!", this, static_cast(_state)); - } -} - -void UrlAudioPlayer::resume() { - if (_state == State::PAUSED) { - int32_t status = OH_AVPlayer_Play(_playObj); - if(status != 0) { - ALOGE("UrlAudioPlayer::resume failed"); - return; - } - setState(State::PLAYING); - } else { - ALOGW("UrlAudioPlayer (%p, state:%d) isn't paused, could not invoke resume!", this, static_cast(_state)); - } -} - -void UrlAudioPlayer::play() { - if (_state == State::INITIALIZED || _state == State::PAUSED) { - int32_t status = OH_AVPlayer_Play(_playObj); - if(status != 0) { - ALOGE("UrlAudioPlayer::play failed"); - return; - } - setState(State::PLAYING); - } else { - ALOGW("UrlAudioPlayer (%p, state:%d) isn't paused or initialized, could not invoke play!", this, static_cast(_state)); - } -} - -void UrlAudioPlayer::setVolumeToAVPlayer(float volume) -{ - int32_t status = OH_AVPlayer_SetVolume(_playObj, volume, volume); - if(status != 0) { - ALOGE("UrlAudioPlayer::setVolume %d failed", volume); - } -} - -void UrlAudioPlayer::setVolume(float volume) { - _volume = volume; - if (_isAudioFocus) { - setVolumeToAVPlayer(_volume); - } -} - -float UrlAudioPlayer::getVolume() const { - return _volume; -} - -void UrlAudioPlayer::setAudioFocus(bool isFocus) { - _isAudioFocus = isFocus; - float volume = _isAudioFocus ? _volume : 0.0F; - setVolumeToAVPlayer(volume); -} - -float UrlAudioPlayer::getDuration() const { - if (_duration > 0) { - return _duration; - } - - int32_t duration = 0; - int32_t status = OH_AVPlayer_GetDuration(_playObj, &duration); - if(status != 0) { - ALOGE("UrlAudioPlayer::getDuration failed"); - return -1.0F; - } - const_cast(this)->_duration = duration / 1000.0F; - if (_duration <= 0) { - return -1.0F; - } - return _duration; -} - -float UrlAudioPlayer::getPosition() const { - int32_t currentTime = 0; - int status = OH_AVPlayer_GetCurrentTime(_playObj, ¤tTime); - if(status != 0) { - ALOGE("UrlAudioPlayer::getPosition failed"); - return -1.0F; - } - return currentTime / 1000.0F; -} - -bool UrlAudioPlayer::setPosition(float pos) -{ - int32_t millisecond = 1000.0F * pos; - int status = OH_AVPlayer_Seek(_playObj, millisecond, AV_SEEK_NEXT_SYNC); - if(status != 0) { - ALOGE("UrlAudioPlayer::setPosition %f failed", pos); - return false; - } - return true; -} - -void UrlAudioPlayer::onInfo(OH_AVPlayer *player, AVPlayerOnInfoType type, int32_t extra) -{ - if (type == AV_INFO_TYPE_STATE_CHANGE) { - if (extra == AV_COMPLETED) { - auto it = __playerContainer.find(player); - if (it != __playerContainer.end()) - { - UrlAudioPlayer *audioPlayer = it->second; - audioPlayer->playEventCallback(); - } - } - } else if (type == AV_INFO_TYPE_INTERRUPT_EVENT) { - auto it = __playerContainer.find(player); - if (it != __playerContainer.end()) { - UrlAudioPlayer *audioPlayer = it->second; - if (extra == 1) { - audioPlayer->resume(); - } else if (extra == 2) { - audioPlayer->pause(); - } else { - ALOGV("UrlAudioPlayer was interrupted, hint type is %d", extra); - } - } - } -} - -void UrlAudioPlayer::onError(OH_AVPlayer *player, int32_t errorCode, const char *errorMsg) { - ALOGE("UrlAudioPlayer play failed, errorCode is: %d, errorMsg is %s", errorCode, errorMsg); -} - -bool UrlAudioPlayer::prepare(const std::string &url, std::shared_ptr assetFd, int32_t start, int32_t length) -{ - _url = url; - _assetFd = assetFd; - _playObj = OH_AVPlayer_Create(); - __playerContainerMutex.lock(); - __playerContainer[_playObj] = this; - __playerContainerMutex.unlock(); - - AVPlayerCallback callback; - callback.onInfo = this->onInfo; - callback.onError = this->onError; - OH_AVPlayer_SetPlayerCallback(_playObj, callback); - OH_AVPlayer_SetFDSource(_playObj, _assetFd->getFd(), start, length); - OH_AVPlayer_SetAudioRendererInfo(_playObj, OH_AudioStream_Usage::AUDIOSTREAM_USAGE_GAME); - OH_AVErrCode code = OH_AVPlayer_Prepare(_playObj); - - if (code == AV_ERR_OK) { - setState(State::INITIALIZED); - setVolume(1.0f); - return true; - } - - ALOGE("Oops, prepare error: %d", (int)code); - return false; -} - -void UrlAudioPlayer::rewind() { - // Not supported currently. since cocos audio engine will new -> prepare -> play again. -} - -void UrlAudioPlayer::setLoop(bool isLoop) { - _isLoop = isLoop; - int status = OH_AVPlayer_SetLooping(_playObj, _isLoop); - if(status != 0) { - ALOGE( "UrlAudioPlayer::setLoop %d failed", _isLoop ? 1 : 0); - } -} - -bool UrlAudioPlayer::isLoop() const { - return _isLoop; -} - -void UrlAudioPlayer::stopAll() { - // To avoid break the for loop, we need to copy a new map - __playerContainerMutex.lock(); - auto temp = __playerContainer; - __playerContainerMutex.unlock(); - - auto it = temp.begin(); - while(it != temp.end()) - { - UrlAudioPlayer* thiz = it->second; - thiz->stop(); - it++; - } -} - -void UrlAudioPlayer::destroy() -{ - if (!*_isDestroyed) - { - *_isDestroyed = true; - OH_AVErrCode code = OH_AVPlayer_Release(_playObj); - if (code != AV_ERR_OK) { - ALOGE( "UrlAudioPlayer release failed, errcode is %d", code); - } - } -} - -}} // namespace cocos2d { namespace experimental diff --git a/cocos/audio/ohos/UrlAudioPlayer.h b/cocos/audio/ohos/UrlAudioPlayer.h deleted file mode 100644 index 62e4d4262494..000000000000 --- a/cocos/audio/ohos/UrlAudioPlayer.h +++ /dev/null @@ -1,125 +0,0 @@ -/**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. -Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -http://www.cocos2d-x.org - -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 -#include -#include -#include -#include "AssetFd.h" -#include "IAudioPlayer.h" -#include "cutils/log.h" -#include "multimedia/player_framework/avplayer.h" - -namespace cocos2d { namespace experimental { - -class ICallerThreadUtils; -class AssetFd; - -class UrlAudioPlayer : public IAudioPlayer { -public: - // Override Functions Begin - virtual int getId() const override { return _id; }; - - virtual void setId(int id) override { _id = id; }; - - virtual std::string getUrl() const override { return _url; }; - - virtual State getState() const override { return _state; }; - - virtual void play() override; - - virtual void pause() override; - - virtual void resume() override; - - virtual void stop() override; - - virtual void rewind() override; - - virtual void setVolume(float volume) override; - - virtual float getVolume() const override; - - virtual void setAudioFocus(bool isFocus) override; - - virtual void setLoop(bool isLoop) override; - - virtual bool isLoop() const override; - - virtual float getDuration() const override; - - virtual float getPosition() const override; - - virtual bool setPosition(float pos) override; - - virtual void setPlayEventCallback(const PlayEventCallback &playEventCallback) override; - - UrlAudioPlayer(ICallerThreadUtils *callerThreadUtils); - - virtual ~UrlAudioPlayer(); - - bool prepare(const std::string &url, std::shared_ptr assetFd, int32_t start, int32_t length); - - static void onInfo(OH_AVPlayer *player, AVPlayerOnInfoType type, int32_t extra); - - static void onError(OH_AVPlayer *player, int32_t errorCode, const char *errorMsg); - - static void stopAll(); - - void destroy(); - - inline void setState(State state) { _state = state; }; - - void playEventCallback(); - - void setVolumeToAVPlayer(float volume); - -private: - ICallerThreadUtils *_callerThreadUtils; - - int _id; - std::string _url; - - std::shared_ptr _assetFd; - - OH_AVPlayer *_playObj; - - float _volume; - float _duration; - bool _isLoop; - bool _isAudioFocus; - State _state; - - PlayEventCallback _playEventCallback; - - std::thread::id _callerThreadId; - std::shared_ptr _isDestroyed; - - friend class AudioPlayerProvider; -}; - -}} // namespace cocos2d { namespace experimental diff --git a/cocos/audio/ohos/mp3reader.cpp b/cocos/audio/ohos/mp3reader.cpp deleted file mode 100644 index 069570cdde0b..000000000000 --- a/cocos/audio/ohos/mp3reader.cpp +++ /dev/null @@ -1,497 +0,0 @@ -#define LOG_TAG "mp3reader" - -#include -#include -#include -#include // Resolves that memset, memcpy aren't found while APP_PLATFORM >= 22 on Android -#include -#include "cutils/log.h" - -#include "mp3reader.h" -#include "pvmp3decoder_api.h" - -static uint32_t U32_AT(const uint8_t *ptr) { - return ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3]; -} - -static bool parseHeader( - uint32_t header, size_t *frame_size, - uint32_t *out_sampling_rate = NULL, uint32_t *out_channels = NULL, - uint32_t *out_bitrate = NULL, uint32_t *out_num_samples = NULL) { - *frame_size = 0; - - if (out_sampling_rate) { - *out_sampling_rate = 0; - } - - if (out_channels) { - *out_channels = 0; - } - - if (out_bitrate) { - *out_bitrate = 0; - } - - if (out_num_samples) { - *out_num_samples = 1152; - } - - if ((header & 0xffe00000) != 0xffe00000) { - return false; - } - - unsigned version = (header >> 19) & 3; - - if (version == 0x01) { - return false; - } - - unsigned layer = (header >> 17) & 3; - - if (layer == 0x00) { - return false; - } - - unsigned bitrate_index = (header >> 12) & 0x0f; - - if (bitrate_index == 0 || bitrate_index == 0x0f) { - // Disallow "free" bitrate. - return false; - } - - unsigned sampling_rate_index = (header >> 10) & 3; - - if (sampling_rate_index == 3) { - return false; - } - - static const int kSamplingRateV1[] = {44100, 48000, 32000}; - int sampling_rate = kSamplingRateV1[sampling_rate_index]; - if (version == 2 /* V2 */) { - sampling_rate /= 2; - } else if (version == 0 /* V2.5 */) { - sampling_rate /= 4; - } - - unsigned padding = (header >> 9) & 1; - - if (layer == 3) { - // layer I - - static const int kBitrateV1[] = { - 32, 64, 96, 128, 160, 192, 224, 256, - 288, 320, 352, 384, 416, 448}; - - static const int kBitrateV2[] = { - 32, 48, 56, 64, 80, 96, 112, 128, - 144, 160, 176, 192, 224, 256}; - - int bitrate = - (version == 3 /* V1 */) - ? kBitrateV1[bitrate_index - 1] - : kBitrateV2[bitrate_index - 1]; - - if (out_bitrate) { - *out_bitrate = bitrate; - } - - *frame_size = (12000 * bitrate / sampling_rate + padding) * 4; - - if (out_num_samples) { - *out_num_samples = 384; - } - } else { - // layer II or III - - static const int kBitrateV1L2[] = { - 32, 48, 56, 64, 80, 96, 112, 128, - 160, 192, 224, 256, 320, 384}; - - static const int kBitrateV1L3[] = { - 32, 40, 48, 56, 64, 80, 96, 112, - 128, 160, 192, 224, 256, 320}; - - static const int kBitrateV2[] = { - 8, 16, 24, 32, 40, 48, 56, 64, - 80, 96, 112, 128, 144, 160}; - - int bitrate; - if (version == 3 /* V1 */) { - bitrate = (layer == 2 /* L2 */) - ? kBitrateV1L2[bitrate_index - 1] - : kBitrateV1L3[bitrate_index - 1]; - - if (out_num_samples) { - *out_num_samples = 1152; - } - } else { - // V2 (or 2.5) - - bitrate = kBitrateV2[bitrate_index - 1]; - if (out_num_samples) { - *out_num_samples = (layer == 1 /* L3 */) ? 576 : 1152; - } - } - - if (out_bitrate) { - *out_bitrate = bitrate; - } - - if (version == 3 /* V1 */) { - *frame_size = 144000 * bitrate / sampling_rate + padding; - } else { - // V2 or V2.5 - size_t tmp = (layer == 1 /* L3 */) ? 72000 : 144000; - *frame_size = tmp * bitrate / sampling_rate + padding; - } - } - - if (out_sampling_rate) { - *out_sampling_rate = sampling_rate; - } - - if (out_channels) { - int channel_mode = (header >> 6) & 3; - - *out_channels = (channel_mode == 3) ? 1 : 2; - } - - return true; -} - -// Mask to extract the version, layer, sampling rate parts of the MP3 header, -// which should be same for all MP3 frames. -static const uint32_t kMask = 0xfffe0c00; - -static ssize_t sourceReadAt(mp3_callbacks *callback, void *source, off64_t offset, void *data, size_t size) { - int retVal = callback->seek(source, offset, SEEK_SET); - if (retVal != EXIT_SUCCESS) { - return 0; - } else { - return callback->read(data, 1, size, source); - } -} - -// Resync to next valid MP3 frame in the file. -static bool resync( - mp3_callbacks *callback, void *source, uint32_t match_header, - off64_t *inout_pos, uint32_t *out_header) { - if (*inout_pos == 0) { - // Skip an optional ID3 header if syncing at the very beginning - // of the datasource. - - for (;;) { - uint8_t id3header[10]; - int retVal = sourceReadAt(callback, source, *inout_pos, id3header, - sizeof(id3header)); - if (retVal < (ssize_t)sizeof(id3header)) { - // If we can't even read these 10 bytes, we might as well bail - // out, even if there _were_ 10 bytes of valid mp3 audio data... - return false; - } - - if (memcmp("ID3", id3header, 3)) { - break; - } - - // Skip the ID3v2 header. - - size_t len = - ((id3header[6] & 0x7f) << 21) | ((id3header[7] & 0x7f) << 14) | ((id3header[8] & 0x7f) << 7) | (id3header[9] & 0x7f); - - len += 10; - - *inout_pos += len; - - ALOGV("skipped ID3 tag, new starting offset is %lld (0x%016llx)", - (long long)*inout_pos, (long long)*inout_pos); - } - } - - off64_t pos = *inout_pos; - bool valid = false; - - const int32_t kMaxReadBytes = 1024; - const int32_t kMaxBytesChecked = 128 * 1024; - uint8_t buf[kMaxReadBytes]; - ssize_t bytesToRead = kMaxReadBytes; - ssize_t totalBytesRead = 0; - ssize_t remainingBytes = 0; - bool reachEOS = false; - uint8_t *tmp = buf; - - do { - if (pos >= (off64_t)(*inout_pos + kMaxBytesChecked)) { - // Don't scan forever. - ALOGV("giving up at offset %lld", (long long)pos); - break; - } - - if (remainingBytes < 4) { - if (reachEOS) { - break; - } else { - memcpy(buf, tmp, remainingBytes); - bytesToRead = kMaxReadBytes - remainingBytes; - - /* - * The next read position should start from the end of - * the last buffer, and thus should include the remaining - * bytes in the buffer. - */ - totalBytesRead = sourceReadAt(callback, source, pos + remainingBytes, - buf + remainingBytes, bytesToRead); - - if (totalBytesRead <= 0) { - break; - } - reachEOS = (totalBytesRead != bytesToRead); - remainingBytes += totalBytesRead; - tmp = buf; - continue; - } - } - - uint32_t header = U32_AT(tmp); - - if (match_header != 0 && (header & kMask) != (match_header & kMask)) { - ++pos; - ++tmp; - --remainingBytes; - continue; - } - - size_t frame_size; - uint32_t sample_rate, num_channels, bitrate; - if (!parseHeader( - header, &frame_size, - &sample_rate, &num_channels, &bitrate)) { - ++pos; - ++tmp; - --remainingBytes; - continue; - } - - // ALOGV("found possible 1st frame at %lld (header = 0x%08x)", (long long)pos, header); - // We found what looks like a valid frame, - // now find its successors. - - off64_t test_pos = pos + frame_size; - - valid = true; - const int FRAME_MATCH_REQUIRED = 3; - for (int j = 0; j < FRAME_MATCH_REQUIRED; ++j) { - uint8_t tmp[4]; - ssize_t retval = sourceReadAt(callback, source, test_pos, tmp, sizeof(tmp)); - if (retval < (ssize_t)sizeof(tmp)) { - valid = false; - break; - } - - uint32_t test_header = U32_AT(tmp); - - ALOGV("subsequent header is %08x", test_header); - - if ((test_header & kMask) != (header & kMask)) { - valid = false; - break; - } - - size_t test_frame_size; - if (!parseHeader(test_header, &test_frame_size)) { - valid = false; - break; - } - - ALOGV("found subsequent frame #%d at %lld", j + 2, (long long)test_pos); - test_pos += test_frame_size; - } - - if (valid) { - *inout_pos = pos; - - if (out_header != NULL) { - *out_header = header; - } - } else { - ALOGV("no dice, no valid sequence of frames found."); - } - - ++pos; - ++tmp; - --remainingBytes; - } while (!valid); - - return valid; -} - -Mp3Reader::Mp3Reader() : mSource(NULL), mCallback(NULL) { -} - -// Initialize the MP3 reader. -bool Mp3Reader::init(mp3_callbacks *callback, void *source) { - mSource = source; - mCallback = callback; - // Open the file. - // mFp = fopen(file, "rb"); - // if (mFp == NULL) return false; - - // Sync to the first valid frame. - off64_t pos = 0; - uint32_t header; - bool success = resync(callback, source, 0 /*match_header*/, &pos, &header); - if (!success) { - ALOGE("%s, resync failed", __FUNCTION__); - return false; - } - - mCurrentPos = pos; - mFixedHeader = header; - - size_t frame_size; - return parseHeader(header, &frame_size, &mSampleRate, - &mNumChannels, &mBitrate); -} - -// Get the next valid MP3 frame. -bool Mp3Reader::getFrame(void *buffer, uint32_t *size) { - size_t frame_size; - uint32_t bitrate; - uint32_t num_samples; - uint32_t sample_rate; - for (;;) { - ssize_t n = sourceReadAt(mCallback, mSource, mCurrentPos, buffer, 4); - if (n < 4) { - return false; - } - - uint32_t header = U32_AT((const uint8_t *)buffer); - - if ((header & kMask) == (mFixedHeader & kMask) && parseHeader( - header, &frame_size, &sample_rate, NULL /*out_channels*/, - &bitrate, &num_samples)) { - break; - } - - // Lost sync. - off64_t pos = mCurrentPos; - if (!resync(mCallback, mSource, mFixedHeader, &pos, NULL /*out_header*/)) { - // Unable to resync. Signalling end of stream. - return false; - } - - mCurrentPos = pos; - - // Try again with the new position. - } - ssize_t n = sourceReadAt(mCallback, mSource, mCurrentPos, buffer, frame_size); - if (n < (ssize_t)frame_size) { - return false; - } - - *size = frame_size; - mCurrentPos += frame_size; - return true; -} - -// Close the MP3 reader. -void Mp3Reader::close() { - assert(mCallback != NULL); - mCallback->close(mSource); -} - -Mp3Reader::~Mp3Reader() { -} - -enum { - kInputBufferSize = 10 * 1024, - kOutputBufferSize = 4608 * 2, -}; - -int decodeMP3(mp3_callbacks *cb, void *source, std::vector &pcmBuffer, int *numChannels, int *sampleRate, int *numFrames) { - // Initialize the config. - tPVMP3DecoderExternal config; - config.equalizerType = flat; - config.crcEnabled = false; - - // Allocate the decoder memory. - uint32_t memRequirements = pvmp3_decoderMemRequirements(); - void *decoderBuf = malloc(memRequirements); - assert(decoderBuf != NULL); - - // Initialize the decoder. - pvmp3_InitDecoder(&config, decoderBuf); - - // Open the input file. - Mp3Reader mp3Reader; - bool success = mp3Reader.init(cb, source); - if (!success) { - ALOGE("mp3Reader.init: Encountered error reading\n"); - free(decoderBuf); - return EXIT_FAILURE; - } - - // Open the output file. - // SF_INFO sfInfo; - // memset(&sfInfo, 0, sizeof(SF_INFO)); - // sfInfo.channels = mp3Reader.getNumChannels(); - // sfInfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16; - // sfInfo.samplerate = mp3Reader.getSampleRate(); - // SNDFILE *handle = sf_open(argv[2], SFM_WRITE, &sfInfo); - // if (handle == NULL) { - // ALOGE("Encountered error writing %s\n", argv[2]); - // mp3Reader.close(); - // free(decoderBuf); - // return EXIT_FAILURE; - // } - - // Allocate input buffer. - uint8_t *inputBuf = static_cast(malloc(kInputBufferSize)); - assert(inputBuf != NULL); - - // Allocate output buffer. - int16_t *outputBuf = static_cast(malloc(kOutputBufferSize)); - assert(outputBuf != NULL); - - // Decode loop. - int retVal = EXIT_SUCCESS; - while (1) { - // Read input from the file. - uint32_t bytesRead; - bool success = mp3Reader.getFrame(inputBuf, &bytesRead); - if (!success) break; - - *numChannels = mp3Reader.getNumChannels(); - *sampleRate = mp3Reader.getSampleRate(); - - // Set the input config. - config.inputBufferCurrentLength = bytesRead; - config.inputBufferMaxLength = 0; - config.inputBufferUsedLength = 0; - config.pInputBuffer = inputBuf; - config.pOutputBuffer = outputBuf; - config.outputFrameSize = kOutputBufferSize / sizeof(int16_t); - - ERROR_CODE decoderErr; - decoderErr = pvmp3_framedecoder(&config, decoderBuf); - if (decoderErr != NO_DECODING_ERROR) { - ALOGE("Decoder encountered error=%d", decoderErr); - retVal = EXIT_FAILURE; - break; - } - - pcmBuffer.insert(pcmBuffer.end(), (char *)outputBuf, ((char *)outputBuf) + config.outputFrameSize * 2); - *numFrames += config.outputFrameSize / mp3Reader.getNumChannels(); - } - - // Close input reader and output writer. - mp3Reader.close(); - // sf_close(handle); - - // Free allocated memory. - free(inputBuf); - free(outputBuf); - free(decoderBuf); - - return retVal; -} \ No newline at end of file diff --git a/cocos/audio/ohos/mp3reader.h b/cocos/audio/ohos/mp3reader.h deleted file mode 100644 index 9efd317e26eb..000000000000 --- a/cocos/audio/ohos/mp3reader.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef MP3READER_H_ -#define MP3READER_H_ - -typedef struct { - size_t (*read)(void *ptr, size_t size, size_t nmemb, void *datasource); - int (*seek)(void *datasource, int64_t offset, int whence); - int (*close)(void *datasource); - long (*tell)(void *datasource); -} mp3_callbacks; - -class Mp3Reader { -public: - Mp3Reader(); - bool init(mp3_callbacks *callback, void *source); - bool getFrame(void *buffer, uint32_t *size); - uint32_t getSampleRate() { return mSampleRate; } - uint32_t getNumChannels() { return mNumChannels; } - void close(); - ~Mp3Reader(); - -private: - void *mSource; - mp3_callbacks *mCallback; - uint32_t mFixedHeader; - off64_t mCurrentPos; - uint32_t mSampleRate; - uint32_t mNumChannels; - uint32_t mBitrate; -}; - -int decodeMP3(mp3_callbacks *cb, void *source, std::vector &pcmBuffer, int *numChannels, int *sampleRate, int *numFrames); - -#endif /* MP3READER_H_ */ diff --git a/cocos/base/CCUserDefault-ohos.cpp b/cocos/base/CCUserDefault-ohos.cpp new file mode 100644 index 000000000000..f921bfde228a --- /dev/null +++ b/cocos/base/CCUserDefault-ohos.cpp @@ -0,0 +1,537 @@ +/**************************************************************************** +Copyright (c) 2010-2012 cocos2d-x.org +Copyright (c) 2013-2016 Chukong Technologies Inc. +Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +http://www.cocos2d-x.org + +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 "base/CCUserDefault.h" +#include "platform/CCPlatformConfig.h" +#include "base/ccUtils.h" +#include "platform/CCCommon.h" +#include "base/base64.h" + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_OHOS) +#include "platform/ohos/napi/helper/NapiHelper.h" + +// root name of xml +#define USERDEFAULT_ROOT_NAME "userDefaultRoot" + +#define KEEP_COMPATABILITY + +#define XML_FILE_NAME "UserDefault.xml" + +#ifdef KEEP_COMPATABILITY +#include "platform/CCFileUtils.h" +#include "tinyxml2.h" +#endif + +using namespace std; +NS_CC_BEGIN + +/** + * implements of UserDefault + */ + +UserDefault* UserDefault::_userDefault = nullptr; +string UserDefault::_filePath = string(""); +bool UserDefault::_isFilePathInitialized = false; + +#ifdef KEEP_COMPATABILITY +static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLDocument **doc) +{ + tinyxml2::XMLElement* curNode = nullptr; + tinyxml2::XMLElement* rootNode = nullptr; + + if (! UserDefault::isXMLFileExist()) + { + return nullptr; + } + + // check the key value + if (! pKey) + { + return nullptr; + } + + do + { + tinyxml2::XMLDocument* xmlDoc = new (std::nothrow) tinyxml2::XMLDocument(); + *doc = xmlDoc; + + std::string xmlBuffer = FileUtils::getInstance()->getStringFromFile(UserDefault::getInstance()->getXMLFilePath()); + + if (xmlBuffer.empty()) + { + CCLOG("can not read xml file"); + break; + } + xmlDoc->Parse(xmlBuffer.c_str()); + + // get root node + rootNode = xmlDoc->RootElement(); + if (nullptr == rootNode) + { + CCLOG("read root node error"); + break; + } + // find the node + curNode = rootNode->FirstChildElement(); + if (!curNode) + { + // There is not xml node, delete xml file. + remove(UserDefault::getInstance()->getXMLFilePath().c_str()); + + return nullptr; + } + + while (nullptr != curNode) + { + const char* nodeName = curNode->Value(); + if (!strcmp(nodeName, pKey)) + { + // delete the node + break; + } + + curNode = curNode->NextSiblingElement(); + } + } while (0); + + return curNode; +} + +static void deleteNode(tinyxml2::XMLDocument* doc, tinyxml2::XMLElement* node) +{ + if (node) + { + doc->DeleteNode(node); + doc->SaveFile(UserDefault::getInstance()->getXMLFilePath().c_str()); + delete doc; + } +} + +static void deleteNodeByKey(const char *pKey) +{ + tinyxml2::XMLDocument* doc = nullptr; + tinyxml2::XMLElement* node = getXMLNodeForKey(pKey, &doc); + deleteNode(doc, node); +} +#endif + +UserDefault::~UserDefault() +{ +} + +UserDefault::UserDefault() +{ +} + +// FIXME:: deprecated +void UserDefault::purgeSharedUserDefault() +{ + UserDefault::destroyInstance(); +} + +void UserDefault::destroyInstance() +{ + CC_SAFE_DELETE(_userDefault); +} + +bool UserDefault::getBoolForKey(const char* pKey) +{ + return getBoolForKey(pKey, false); +} + +bool UserDefault::getBoolForKey(const char* pKey, bool defaultValue) +{ +#ifdef KEEP_COMPATABILITY + tinyxml2::XMLDocument* doc = nullptr; + tinyxml2::XMLElement* node = getXMLNodeForKey(pKey, &doc); + if (node) + { + if (node->FirstChild()) + { + const char* value = (const char*)node->FirstChild()->Value(); + bool ret = (! strcmp(value, "true")); + + // set value in NSUserDefaults + setBoolForKey(pKey, ret); + flush(); + + // delete xmle node + deleteNode(doc, node); + + return ret; + } + else + { + // delete xmle node + deleteNode(doc, node); + } + } +#endif + + return JSFunction::getFunction("Preferences.get").invoke(pKey, defaultValue); +} + +int UserDefault::getIntegerForKey(const char* pKey) +{ + return getIntegerForKey(pKey, 0); +} + +int UserDefault::getIntegerForKey(const char* pKey, int defaultValue) +{ +#ifdef KEEP_COMPATABILITY + tinyxml2::XMLDocument* doc = nullptr; + tinyxml2::XMLElement* node = getXMLNodeForKey(pKey, &doc); + if (node) + { + if (node->FirstChild()) + { + int ret = atoi((const char*)node->FirstChild()->Value()); + + // set value in NSUserDefaults + setIntegerForKey(pKey, ret); + flush(); + + // delete xmle node + deleteNode(doc, node); + + return ret; + } + else + { + // delete xmle node + deleteNode(doc, node); + } + } +#endif + + return JSFunction::getFunction("Preferences.get").invoke(pKey, defaultValue); +} + +float UserDefault::getFloatForKey(const char* pKey) +{ + return getFloatForKey(pKey, 0.0f); +} + +float UserDefault::getFloatForKey(const char* pKey, float defaultValue) +{ +#ifdef KEEP_COMPATABILITY + tinyxml2::XMLDocument* doc = nullptr; + tinyxml2::XMLElement* node = getXMLNodeForKey(pKey, &doc); + if (node) + { + if (node->FirstChild()) + { + float ret = utils::atof((const char*)node->FirstChild()->Value()); + + // set value in NSUserDefaults + setFloatForKey(pKey, ret); + flush(); + + // delete xmle node + deleteNode(doc, node); + + return ret; + } + else + { + // delete xmle node + deleteNode(doc, node); + } + } +#endif + + return JSFunction::getFunction("Preferences.get").invoke(pKey, defaultValue); +} + +double UserDefault::getDoubleForKey(const char* pKey) +{ + return getDoubleForKey(pKey, 0.0); +} + +double UserDefault::getDoubleForKey(const char* pKey, double defaultValue) +{ +#ifdef KEEP_COMPATABILITY + tinyxml2::XMLDocument* doc = nullptr; + tinyxml2::XMLElement* node = getXMLNodeForKey(pKey, &doc); + if (node) + { + if (node->FirstChild()) + { + double ret = utils::atof((const char*)node->FirstChild()->Value()); + + // set value in NSUserDefaults + setDoubleForKey(pKey, ret); + flush(); + + // delete xmle node + deleteNode(doc, node); + + return ret; + } + else + { + // delete xmle node + deleteNode(doc, node); + } + } +#endif + + return JSFunction::getFunction("Preferences.get").invoke(pKey, defaultValue); +} + +std::string UserDefault::getStringForKey(const char* pKey) +{ + return getStringForKey(pKey, ""); +} + +string UserDefault::getStringForKey(const char* pKey, const std::string & defaultValue) +{ +#ifdef KEEP_COMPATABILITY + tinyxml2::XMLDocument* doc = nullptr; + tinyxml2::XMLElement* node = getXMLNodeForKey(pKey, &doc); + if (node) + { + if (node->FirstChild()) + { + string ret = (const char*)node->FirstChild()->Value(); + + // set value in NSUserDefaults + setStringForKey(pKey, ret); + flush(); + + // delete xmle node + deleteNode(doc, node); + + return ret; + } + else + { + // delete xmle node + deleteNode(doc, node); + } + } +#endif + + return JSFunction::getFunction("Preferences.get").invoke(pKey, defaultValue); +} + +Data UserDefault::getDataForKey(const char* pKey) +{ + return getDataForKey(pKey, Data::Null); +} + +Data UserDefault::getDataForKey(const char* pKey, const Data& defaultValue) +{ +#ifdef KEEP_COMPATABILITY + tinyxml2::XMLDocument* doc = nullptr; + tinyxml2::XMLElement* node = getXMLNodeForKey(pKey, &doc); + if (node) + { + if (node->FirstChild()) + { + const char * encodedData = node->FirstChild()->Value(); + + unsigned char * decodedData; + int decodedDataLen = base64Decode((unsigned char*)encodedData, (unsigned int)strlen(encodedData), &decodedData); + + if (decodedData) { + Data ret; + ret.fastSet(decodedData, decodedDataLen); + + // set value in NSUserDefaults + setDataForKey(pKey, ret); + + flush(); + + // delete xmle node + deleteNode(doc, node); + + return ret; + } + } + else + { + // delete xmle node + deleteNode(doc, node); + } + } +#endif + + char * encodedDefaultData = NULL; + unsigned int encodedDefaultDataLen = defaultValue.isNull() ? 0 : base64Encode(defaultValue.getBytes(), defaultValue.getSize(), &encodedDefaultData); + + std::string encodedStr; + if (encodedDefaultData) { + encodedStr = JSFunction::getFunction("Preferences.get").invoke(pKey, (const char*)encodedDefaultData); + } else { + encodedStr = JSFunction::getFunction("Preferences.get").invoke(pKey, ""); + } + + if (encodedDefaultData) + free(encodedDefaultData); + + CCLOG("ENCODED STRING: --%s--%d", encodedStr.c_str(), (int)encodedStr.length()); + + unsigned char * decodedData = NULL; + int decodedDataLen = base64Decode((unsigned char*)encodedStr.c_str(), (unsigned int)encodedStr.length(), &decodedData); + + CCLOG("DECODED DATA: %s %d", decodedData, decodedDataLen); + + if (decodedData && decodedDataLen) { + Data ret; + ret.fastSet(decodedData, decodedDataLen); + return ret; + } + + return defaultValue; +} + + +void UserDefault::setBoolForKey(const char* pKey, bool value) +{ +#ifdef KEEP_COMPATABILITY + deleteNodeByKey(pKey); +#endif + + JSFunction::getFunction("Preferences.put").invoke(pKey, value); +} + +void UserDefault::setIntegerForKey(const char* pKey, int value) +{ +#ifdef KEEP_COMPATABILITY + deleteNodeByKey(pKey); +#endif + + JSFunction::getFunction("Preferences.put").invoke(pKey, value); +} + +void UserDefault::setFloatForKey(const char* pKey, float value) +{ +#ifdef KEEP_COMPATABILITY + deleteNodeByKey(pKey); +#endif + + JSFunction::getFunction("Preferences.put").invoke(pKey, value); +} + +void UserDefault::setDoubleForKey(const char* pKey, double value) +{ +#ifdef KEEP_COMPATABILITY + deleteNodeByKey(pKey); +#endif + + JSFunction::getFunction("Preferences.put").invoke(pKey, value); +} + +void UserDefault::setStringForKey(const char* pKey, const std::string& value) +{ +#ifdef KEEP_COMPATABILITY + deleteNodeByKey(pKey); +#endif + + JSFunction::getFunction("Preferences.put").invoke(pKey, value); +} + +void UserDefault::setDataForKey(const char* pKey, const Data& value) +{ +#ifdef KEEP_COMPATABILITY + deleteNodeByKey(pKey); +#endif + + CCLOG("SET DATA FOR KEY: --%s--%d", value.getBytes(), (int)(value.getSize())); + char * encodedData = nullptr; + unsigned int encodedDataLen = base64Encode(value.getBytes(), value.getSize(), &encodedData); + + CCLOG("SET DATA ENCODED: --%s", encodedData); + + JSFunction::getFunction("Preferences.put").invoke(pKey, (const char*)encodedData); + + if (encodedData) + free(encodedData); +} + +// FIXME:: deprecated +UserDefault* UserDefault::sharedUserDefault() +{ + return UserDefault::getInstance(); +} + +UserDefault* UserDefault::getInstance() +{ + if (! _userDefault) + { +#ifdef KEEP_COMPATABILITY + initXMLFilePath(); +#endif + _userDefault = new (std::nothrow) UserDefault(); + } + + return _userDefault; +} + +bool UserDefault::isXMLFileExist() +{ + return FileUtils::getInstance()->isFileExist(_filePath); +} + +void UserDefault::initXMLFilePath() +{ + if (! _isFilePathInitialized) + { + _filePath += FileUtils::getInstance()->getWritablePath() + XML_FILE_NAME; + _isFilePathInitialized = true; + } +} + +// create new xml file +bool UserDefault::createXMLFile() +{ + return false; +} + +const string& UserDefault::getXMLFilePath() +{ + return _filePath; +} + +void UserDefault::flush() +{ +} + +void UserDefault::deleteValueForKey(const char* key) +{ + // check the params + if (!key) + { + CCLOG("the key is invalid"); + } + + JSFunction::getFunction("Preferences.delete").invoke(key); + + flush(); +} +NS_CC_END + +#endif // (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) diff --git a/cocos/base/CCUserDefault.cpp b/cocos/base/CCUserDefault.cpp index d729f2f77175..8e0e5e349e20 100644 --- a/cocos/base/CCUserDefault.cpp +++ b/cocos/base/CCUserDefault.cpp @@ -29,7 +29,7 @@ THE SOFTWARE. #include "base/base64.h" #include "base/ccUtils.h" -#if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS && CC_TARGET_PLATFORM != CC_PLATFORM_MAC && CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) +#if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS && CC_TARGET_PLATFORM != CC_PLATFORM_MAC && CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID && CC_TARGET_PLATFORM != CC_PLATFORM_OHOS) // root name of xml #define USERDEFAULT_ROOT_NAME "userDefaultRoot" diff --git a/cocos/base/CMakeLists.txt b/cocos/base/CMakeLists.txt index 3d8c98b2162a..814d7dbb5899 100644 --- a/cocos/base/CMakeLists.txt +++ b/cocos/base/CMakeLists.txt @@ -12,6 +12,7 @@ elseif(ANDROID) elseif(OHOS) set(COCOS_BASE_SPECIFIC_SRC base/CCController-ohos.cpp + base/CCUserDefault-ohos.cpp ) elseif(LINUX) set(COCOS_BASE_SPECIFIC_SRC @@ -19,6 +20,13 @@ elseif(LINUX) ) endif() +if(!OHOS) + set(COCOS_BASE_SPECIFIC_SRC + ${COCOS_BASE_SPECIFIC_SRC} + base/CCUserDefault.cpp + ) +endif() + set(COCOS_BASE_SRC base/CCAsyncTaskPool.cpp base/CCAutoreleasePool.cpp @@ -54,7 +62,6 @@ set(COCOS_BASE_SRC base/CCScheduler.cpp base/CCScriptSupport.cpp base/CCTouch.cpp - base/CCUserDefault.cpp base/CCValue.cpp base/ObjectFactory.cpp base/CCStencilStateManager.cpp diff --git a/cocos/platform/CCApplicationProtocol.h b/cocos/platform/CCApplicationProtocol.h index 4fea15141bdb..a49826336349 100644 --- a/cocos/platform/CCApplicationProtocol.h +++ b/cocos/platform/CCApplicationProtocol.h @@ -59,7 +59,7 @@ class CC_DLL ApplicationProtocol OS_TIZEN, /**< Tizen */ OS_WINRT, /**< Windows Runtime Applications */ OS_WP8, /**< Windows Phone 8 Applications */ - OS_OPENHARMONY /**< OPENHARMONY */ + OS_HARMONY_NEXT /**< HarmonyOS Next OS */ }; /** diff --git a/cocos/platform/CCDevice.h b/cocos/platform/CCDevice.h index 1d40005f9a42..d010ab410a33 100644 --- a/cocos/platform/CCDevice.h +++ b/cocos/platform/CCDevice.h @@ -26,6 +26,7 @@ THE SOFTWARE. #ifndef __CCDEVICE_H__ #define __CCDEVICE_H__ +#include "base/ccTypes.h" #include "platform/CCPlatformMacros.h" #include "base/ccMacros.h" #include "base/CCData.h" @@ -75,6 +76,10 @@ class CC_DLL Device * Sets the interval of accelerometer. */ static void setAccelerometerInterval(float interval); + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_OHOS) + static void sendAndClearAcc(); +#endif // (CC_TARGET_PLATFORM == CC_PLATFORM_OHOS) /** * Controls whether the screen should remain on. diff --git a/cocos/platform/CMakeLists.txt b/cocos/platform/CMakeLists.txt index 54f997147f1a..9c8087e400c0 100644 --- a/cocos/platform/CMakeLists.txt +++ b/cocos/platform/CMakeLists.txt @@ -115,7 +115,6 @@ elseif(OHOS) platform/ohos/napi/modules/InputNapi.cpp platform/ohos/napi/modules/MouseNapi.cpp platform/ohos/napi/modules/WebViewNapi.cpp - platform/ohos/napi/modules/SensorNapi.cpp platform/ohos/napi/modules/VideoPlayerNapi.cpp platform/ohos/napi/helper/NapiValueConverter.cpp platform/ohos/napi/helper/Js_Cocos2dxHelper.cpp diff --git a/cocos/platform/ohos/CCApplication-ohos.cpp b/cocos/platform/ohos/CCApplication-ohos.cpp index 53d0917eb801..33f998aeef0f 100644 --- a/cocos/platform/ohos/CCApplication-ohos.cpp +++ b/cocos/platform/ohos/CCApplication-ohos.cpp @@ -127,7 +127,7 @@ LanguageType Application::getCurrentLanguage() { } ApplicationProtocol::Platform Application::getTargetPlatform() { - return ApplicationProtocol::Platform::OS_OPENHARMONY; + return ApplicationProtocol::Platform::OS_HARMONY_NEXT; } diff --git a/cocos/platform/ohos/CCDevice-ohos.cpp b/cocos/platform/ohos/CCDevice-ohos.cpp index f2c49d4f6e52..2efc9c78ddd2 100644 --- a/cocos/platform/ohos/CCDevice-ohos.cpp +++ b/cocos/platform/ohos/CCDevice-ohos.cpp @@ -1,30 +1,146 @@ #include "platform/CCPlatformConfig.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_OHOS -#include "napi/helper/Js_Cocos2dxHelper.h" #include "platform/CCDevice.h" #include "base/ccTypes.h" #include "CCTextBitmap.h" #include "napi/helper/NapiHelper.h" +#include "sensors/oh_sensor.h" +#include +#include +#include "cocos2d.h" NS_CC_BEGIN +#define TG3_GRAVITY_EARTH (9.80665f) +float SENSOR_SAMPLE_PERIOD = 10000000.0f; +Sensor_Subscriber *accelerometer_g_user = nullptr; +Sensor_SubscriptionAttribute *accelerometer_sensor_attr = nullptr; +Sensor_SubscriptionId *accelerometer_sensor_id = nullptr; +cocos2d::Acceleration *acceleration = nullptr; +class DeviceSensor { +public: + static void enableSensor() { + enableAccelerometer(); + } + static void disableSensor() { + disableAccelerometer(); + } +private: + static void enableAccelerometer() { + if (accelerometer_g_user != nullptr) { + LOGI("Sensor Accelerometer is Listen"); + return; + } + accelerometer_g_user = OH_Sensor_CreateSubscriber(); + OH_SensorSubscriber_SetCallback(accelerometer_g_user, dispatchAccelerometer); + accelerometer_sensor_attr = OH_Sensor_CreateSubscriptionAttribute(); + OH_SensorSubscriptionAttribute_SetSamplingInterval(accelerometer_sensor_attr, SENSOR_SAMPLE_PERIOD); + accelerometer_sensor_id = OH_Sensor_CreateSubscriptionId(); + OH_SensorSubscriptionId_SetType(accelerometer_sensor_id, SENSOR_TYPE_ACCELEROMETER); + OH_Sensor_Subscribe(accelerometer_sensor_id, accelerometer_sensor_attr, accelerometer_g_user); + LOGI("Sensor Accelerometer is enable Listen"); + } + static void disableAccelerometer() { + if (accelerometer_g_user == nullptr) { + LOGI("Sensor Accelerometer is not Listen"); + return; + } + if (accelerometer_sensor_id != nullptr) { + OH_Sensor_Unsubscribe(accelerometer_sensor_id, accelerometer_g_user); + OH_Sensor_DestroySubscriptionId(accelerometer_sensor_id); + } + if (accelerometer_sensor_attr != nullptr) { + OH_Sensor_DestroySubscriptionAttribute(accelerometer_sensor_attr); + } + OH_Sensor_DestroySubscriber(accelerometer_g_user); + accelerometer_g_user = nullptr; + accelerometer_sensor_id = nullptr; + accelerometer_sensor_attr = nullptr; + LOGI("Sensor Accelerometer is disable Listen"); + } + static void dispatchAccelerometer(Sensor_Event *event) { + if (event == nullptr) { + LOGI("dispatchAccelerometer event is null"); + return; + } + float *data = nullptr; + uint32_t length = 0; + int32_t ret = OH_SensorEvent_GetData(event, &data, &length); + if (ret != SENSOR_SUCCESS) { + return; + } + int64_t timeStamp = -1; + OH_SensorEvent_GetTimestamp(event, &timeStamp); + NativeDisplayManager_Rotation displayRotation; + NativeDisplayManager_ErrorCode errCode = OH_NativeDisplayManager_GetDefaultDisplayRotation(&displayRotation); + if (errCode != NativeDisplayManager_ErrorCode::DISPLAY_MANAGER_OK) { + LOGI("dispatchAccelerometer displayRotation error code = %{public}d", errCode); + return; + } + double x, y, z; + if (displayRotation == DISPLAY_MANAGER_ROTATION_0) { + x = data[0]; + y = data[1]; + z = data[2]; + } else if (displayRotation == DISPLAY_MANAGER_ROTATION_90) { + x = data[1]; + y = -data[0]; + z = data[2]; + } else if (displayRotation == DISPLAY_MANAGER_ROTATION_180) { + x = -data[0]; + y = -data[1]; + z = data[2]; + } else if (displayRotation == DISPLAY_MANAGER_ROTATION_270) { + x = -data[1]; + y = data[0]; + z = data[2]; + } + if (acceleration == nullptr) { + acceleration = new (std::nothrow) cocos2d::Acceleration(); + } + acceleration->x = -(x / TG3_GRAVITY_EARTH); + acceleration->y = -(y / TG3_GRAVITY_EARTH); + acceleration->z = -(z / TG3_GRAVITY_EARTH); + acceleration->timestamp = (double)timeStamp; + } +}; int Device::getDPI() { - return JSFunction::getFunction("DeviceUtils.getDpi").invoke(); + static int dpi = -1; + if (dpi == -1) + { + dpi = JSFunction::getFunction("DeviceUtils.getDpi").invoke(); + } + return dpi; } void Device::setAccelerometerEnabled(bool isEnabled) { if (isEnabled) { - Js_Cocos2dxHelper::enableAccelerometer(); + DeviceSensor::enableSensor(); } - else - { - Js_Cocos2dxHelper::disableAccelerometer(); + else { + DeviceSensor::disableSensor(); + } +} + +void Device::sendAndClearAcc() { + if (acceleration == nullptr) { + return; } + cocos2d::EventAcceleration cocosEvent(*acceleration); + cocos2d::Director::getInstance()->getEventDispatcher()->dispatchEvent(&cocosEvent); + acceleration = nullptr; } void Device::setAccelerometerInterval(float interval) { - Js_Cocos2dxHelper::setAccelerometerInterval(interval); + if (interval == SENSOR_SAMPLE_PERIOD) { + return; + } + SENSOR_SAMPLE_PERIOD = interval; + if (accelerometer_sensor_attr != nullptr) { + OH_SensorSubscriptionAttribute_SetSamplingInterval(accelerometer_sensor_attr, SENSOR_SAMPLE_PERIOD); + } +// Js_Cocos2dxHelper::setAccelerometerInterval(interval); } class BitmapDC diff --git a/cocos/platform/ohos/CCFileUtils-ohos.cpp b/cocos/platform/ohos/CCFileUtils-ohos.cpp index 2cac7b62c40b..3a4b679c7e76 100644 --- a/cocos/platform/ohos/CCFileUtils-ohos.cpp +++ b/cocos/platform/ohos/CCFileUtils-ohos.cpp @@ -58,7 +58,7 @@ bool FileUtilsOhos::isFileExistInternal(const std::string& strFilePath) const { bool bFound = false; if (strFilePath[0] != '/') { - RawFile *fp = RawFileUtils::GetInstance().Open(strFilePath.c_str()); + RawFile64 *fp = RawFileUtils::GetInstance().Open(strFilePath.c_str()); if(fp) { OHOS_LOGI("FileUtilsOhos::isFileExistInternal() - open %{public}s success", strFilePath.c_str()); bFound = true; @@ -113,7 +113,7 @@ long FileUtilsOhos::getFileSize(const std::string& filepath) { return FileUtils::getFileSize(filepath); } - RawFile *fp = RawFileUtils::GetInstance().Open(filepath.c_str());//fopen(strFilePath.c_str(), "r"); + RawFile64 *fp = RawFileUtils::GetInstance().Open(filepath.c_str());//fopen(strFilePath.c_str(), "r"); OHOS_LOGI("FileUtilsOhos::getFileSize ===================> doGetFileData %{public}s", filepath.c_str()); long size = RawFileUtils::GetInstance().GetSize(fp); RawFileUtils::GetInstance().Close(fp); @@ -143,7 +143,7 @@ FileUtils::Status FileUtilsOhos::getContents(const std::string& filename, Resiza return FileUtils::getContents(fullPath, buffer); } - RawFile *fp = RawFileUtils::GetInstance().Open(fullPath.c_str()); + RawFile64 *fp = RawFileUtils::GetInstance().Open(fullPath.c_str()); if (!fp) { OHOS_LOGD("FileUtilsOhos::fp is nullptr"); return FileUtils::Status::NotInitialized; @@ -171,13 +171,13 @@ FileUtils::Status FileUtilsOhos::getContents(const std::string& filename, Resiza return FileUtils::Status::OK; } -FileUtils::Status FileUtilsOhos::getRawFileDescriptor(const std::string &filename, RawFileDescriptor &descriptor) { +FileUtils::Status FileUtilsOhos::getRawFileDescriptor(const std::string &filename, RawFileDescriptor64 *descriptor) { if (filename.empty()) { return FileUtils::Status::NotExists; } string fullPath = fullPathForFilename(filename); - RawFile *fp = RawFileUtils::GetInstance().Open(fullPath.c_str());//fopen(strFilePath.c_str(), "r"); + RawFile64 *fp = RawFileUtils::GetInstance().Open(fullPath.c_str());//fopen(strFilePath.c_str(), "r"); if (!fp) { OHOS_LOGD("FileUtilsOhos::fp is nullptr"); return FileUtils::Status::NotInitialized; diff --git a/cocos/platform/ohos/CCFileUtils-ohos.h b/cocos/platform/ohos/CCFileUtils-ohos.h index 862e345112a1..961eb032978d 100644 --- a/cocos/platform/ohos/CCFileUtils-ohos.h +++ b/cocos/platform/ohos/CCFileUtils-ohos.h @@ -38,7 +38,7 @@ class CC_DLL FileUtilsOhos : public FileUtils static void setassetmanager(NativeResourceManager* a); static NativeResourceManager* getAssetManager() { return nativeResourceManager_; } static ZipFile* getObbFile() { return obbfile; } - FileUtils::Status getRawFileDescriptor(const std::string &filename, RawFileDescriptor &descriptor); + FileUtils::Status getRawFileDescriptor(const std::string &filename, RawFileDescriptor64 *descriptor); /* override functions */ bool init() override; diff --git a/cocos/platform/ohos/CCTextBitmap.cpp b/cocos/platform/ohos/CCTextBitmap.cpp index 4312ac73ea13..76340c33ca08 100644 --- a/cocos/platform/ohos/CCTextBitmap.cpp +++ b/cocos/platform/ohos/CCTextBitmap.cpp @@ -1,4 +1,6 @@ #include +#include +#include #include "CCTextBitmap.h" #include "platform/CCPlatformMacros.h" #include "platform/CCCommon.h" @@ -6,6 +8,8 @@ NS_CC_BEGIN +std::unordered_set CCTextBitmap::_setFontCollection; +OH_Drawing_FontCollection * CCTextBitmap::_fontCollection = OH_Drawing_CreateSharedFontCollection(); void CCTextBitmap::createCCTextBitmap(CCTextBitmap *cCTextBitmap, const char *text, const char *pFontName, const float a, const float r, const float g, const float b, const Device::TextAlign eAlignMask, int width_, int height_, double fontSize) { @@ -78,11 +82,7 @@ void CCTextBitmap::createCCTextBitmap(CCTextBitmap* cCTextBitmap, const char *te int align = processTextAlign((int)eAlignMask); // Set text alignment OH_Drawing_SetTypographyTextAlign(cCTextBitmap->_typographyStyle, align); - // Used to load fonts - cCTextBitmap->_fontCollection = OH_Drawing_CreateFontCollection(); - // Creates a pointer to the OH_Drawing_TypographyCreate object - cCTextBitmap->_typographyCreate = OH_Drawing_CreateTypographyHandler(cCTextBitmap->_typographyStyle, cCTextBitmap->_fontCollection); - // Used to manage font colors, decorations, etc. + cCTextBitmap->_textStyle = OH_Drawing_CreateTextStyle(); // Set Text Color @@ -97,13 +97,22 @@ void CCTextBitmap::createCCTextBitmap(CCTextBitmap* cCTextBitmap, const char *te OH_Drawing_SetTextStyleBaseLine(cCTextBitmap->_textStyle, TEXT_BASELINE_ALPHABETIC); // Set font height OH_Drawing_SetTextStyleFontHeight(cCTextBitmap->_textStyle, 1); + const char* fontFamily = pFontName; + char* Path = new char[1000]; + std::strcpy(Path, "/system/fonts/"); + const char* fontPath = strcat(Path,fontFamily); + auto iter = cCTextBitmap->_setFontCollection.find(fontPath); + if (iter == cCTextBitmap->_setFontCollection.end()) + { + OH_Drawing_RegisterFont(cCTextBitmap->_fontCollection, pFontName, fontPath); + cCTextBitmap->_setFontCollection.insert(fontPath); + } const char *fontFamilies[] = {pFontName}; // Set the font type OH_Drawing_SetTextStyleFontFamilies(cCTextBitmap->_textStyle, 1, fontFamilies); - // Set the font style. The font style is not italicized. FONT_EVEN_ITALIC Italic - OH_Drawing_SetTextStyleFontStyle(cCTextBitmap->_textStyle, FONT_STYLE_NORMAL); - // Setting the Language Area - OH_Drawing_SetTextStyleLocale(cCTextBitmap->_textStyle, "en"); + // Creates a pointer to the OH_Drawing_TypographyCreate object + cCTextBitmap->_typographyCreate = OH_Drawing_CreateTypographyHandler(cCTextBitmap->_typographyStyle, cCTextBitmap->_fontCollection); + // Set the typesetting style OH_Drawing_TypographyHandlerPushTextStyle(cCTextBitmap->_typographyCreate, cCTextBitmap->_textStyle); @@ -160,6 +169,7 @@ void CCTextBitmap::createCCTextBitmap(CCTextBitmap* cCTextBitmap, const char *te cCTextBitmap->pixelAddr = OH_Drawing_BitmapGetPixels(cCTextBitmap->_bitmap); cCTextBitmap->width = textWidth; cCTextBitmap->height = textHeight; + delete [] Path; } void *CCTextBitmap::getPixelAddr() { @@ -177,12 +187,10 @@ CCTextBitmap::~CCTextBitmap() { _textStyle = nullptr; OH_Drawing_DestroyTypographyHandler(_typographyCreate); _typographyCreate = nullptr; - OH_Drawing_DestroyFontCollection(_fontCollection); - _fontCollection = nullptr; OH_Drawing_DestroyTypographyStyle(_typographyStyle); _typographyStyle = nullptr; pixelAddr = nullptr; } -NS_CC_END \ No newline at end of file +NS_CC_END diff --git a/cocos/platform/ohos/CCTextBitmap.h b/cocos/platform/ohos/CCTextBitmap.h index 39cea74e5c70..6cdfbe04ebe9 100644 --- a/cocos/platform/ohos/CCTextBitmap.h +++ b/cocos/platform/ohos/CCTextBitmap.h @@ -10,6 +10,7 @@ #include #include +#include #define DEFAULT_FONTSIZE 20 NS_CC_BEGIN @@ -64,9 +65,10 @@ class CCTextBitmap { 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}; OH_Drawing_Typography *_typography{nullptr}; + static std::unordered_set _setFontCollection; + static OH_Drawing_FontCollection *_fontCollection; }; NS_CC_END #endif diff --git a/cocos/platform/ohos/napi/helper/Js_Cocos2dxHelper.cpp b/cocos/platform/ohos/napi/helper/Js_Cocos2dxHelper.cpp index a833d8b07969..9d42be1267f4 100644 --- a/cocos/platform/ohos/napi/helper/Js_Cocos2dxHelper.cpp +++ b/cocos/platform/ohos/napi/helper/Js_Cocos2dxHelper.cpp @@ -24,31 +24,5 @@ void Js_Cocos2dxHelper::terminateProcess() { JSFunction::getFunction("ApplicationManager.exit").invoke(); } -// The default accelerometer interval is 10000000 ns, that is, 10 ms. -float Js_Cocos2dxHelper::_accelerometerInterval = 10000000.0f; -bool Js_Cocos2dxHelper::_accelerometerFlag = false; -void Js_Cocos2dxHelper::enableAccelerometer() { - // Start accelerometer subscription when allowed use default interval - JSFunction::getFunction("Accelerometer.enable").invoke(_accelerometerInterval); - _accelerometerFlag = true; -} - -void Js_Cocos2dxHelper::disableAccelerometer() { - JSFunction::getFunction("Accelerometer.disable").invoke(); - _accelerometerFlag = false; -} -void Js_Cocos2dxHelper::setAccelerometerInterval(float interval) { - OHOS_LOGD("accelerometer setAccelerometerInterval, change to %{public}f", interval); - // Same as the original one. No handling is required. - if(_accelerometerInterval == interval) { - return; - } - _accelerometerInterval = interval; - - // if accelerometer running, restart with new interval - if(_accelerometerFlag) { - JSFunction::getFunction("Accelerometer.enable").invoke(_accelerometerInterval); - } -} diff --git a/cocos/platform/ohos/napi/helper/Js_Cocos2dxHelper.h b/cocos/platform/ohos/napi/helper/Js_Cocos2dxHelper.h index 1d0001badff6..9b8c8e4c99bf 100644 --- a/cocos/platform/ohos/napi/helper/Js_Cocos2dxHelper.h +++ b/cocos/platform/ohos/napi/helper/Js_Cocos2dxHelper.h @@ -28,14 +28,9 @@ class Js_Cocos2dxHelper { } static void terminateProcess(); - static void enableAccelerometer(); - static void disableAccelerometer(); - static void setAccelerometerInterval(float interval); private: static std::string _asyncInfoMap[]; static napi_env _env; - static float _accelerometerInterval; - static bool _accelerometerFlag; }; #endif /* __Js_Cocos2dxHelper_H__ */ diff --git a/cocos/platform/ohos/napi/modules/RawFileUtils.h b/cocos/platform/ohos/napi/modules/RawFileUtils.h index 86fec15b7fe1..90f0bd648cc1 100644 --- a/cocos/platform/ohos/napi/modules/RawFileUtils.h +++ b/cocos/platform/ohos/napi/modules/RawFileUtils.h @@ -32,40 +32,40 @@ class RawFileUtils { return instance; } - RawFile *Open(const char *fileName) { - return OH_ResourceManager_OpenRawFile(nativeResourceManager_, fileName); + RawFile64 *Open(const char *fileName) { + return OH_ResourceManager_OpenRawFile64(nativeResourceManager_, fileName); } RawDir *OpenDir(const char *dirName) { return OH_ResourceManager_OpenRawDir(nativeResourceManager_, dirName); } - void Close(RawFile *file) { - return OH_ResourceManager_CloseRawFile(file); + void Close(RawFile64 *file) { + return OH_ResourceManager_CloseRawFile64(file); } void CloseDir(RawDir *rawDir) { return OH_ResourceManager_CloseRawDir(rawDir); } - int Seek(const RawFile *file, long offset, int whence) { - return OH_ResourceManager_SeekRawFile(file, offset, whence); + int Seek(const RawFile64 *file, long offset, int whence) { + return OH_ResourceManager_SeekRawFile64(file, offset, whence); } - long GetSize(RawFile* file) { - return OH_ResourceManager_GetRawFileSize(file); + long GetSize(RawFile64* file) { + return OH_ResourceManager_GetRawFileSize64(file); } - long Read(RawFile *file, void* buf, size_t length) { - return OH_ResourceManager_ReadRawFile(file, buf, length); + long Read(RawFile64 *file, void* buf, size_t length) { + return OH_ResourceManager_ReadRawFile64(file, buf, length); } int GetDirSize(RawDir* rawDir) { return OH_ResourceManager_GetRawFileCount(rawDir); } - bool GetRawFileDescriptor(RawFile *file, RawFileDescriptor &descriptor) { - return OH_ResourceManager_GetRawFileDescriptor(file, descriptor); + bool GetRawFileDescriptor(RawFile64 *file, RawFileDescriptor64 *descriptor) { + return OH_ResourceManager_GetRawFileDescriptor64(file, descriptor); } bool ReleaseRawFileDescriptor(RawFileDescriptor &descriptor) { diff --git a/cocos/platform/ohos/napi/modules/SensorNapi.cpp b/cocos/platform/ohos/napi/modules/SensorNapi.cpp deleted file mode 100644 index b8f3eeb56449..000000000000 --- a/cocos/platform/ohos/napi/modules/SensorNapi.cpp +++ /dev/null @@ -1,63 +0,0 @@ -#include -#include -#include "cocos2d.h" -#include "base/CCEventAcceleration.h" -#include "platform/ohos/CCLogOhos.h" -#include "SensorNapi.h" -#include "../common/native_common.h" - -napi_value SensorNapi::onAccelerometerCallBack(napi_env env, napi_callback_info info) { - napi_status status; - size_t argc = 4; - napi_value args[4]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); - if (argc != 4) { - 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; - } - - status = napi_typeof(env, args[3], &valuetype); - if (status != napi_ok) { - return nullptr; - } - if (valuetype != napi_number) { - napi_throw_type_error(env, NULL, "Wrong arguments"); - return nullptr; - } - - double x; - NAPI_CALL(env, napi_get_value_double(env, args[0], &x)); - double y; - NAPI_CALL(env, napi_get_value_double(env, args[1], &y)); - double z; - NAPI_CALL(env, napi_get_value_double(env, args[2], &z)); - long timestamp; - NAPI_CALL(env, napi_get_value_int64(env, args[3], ×tamp)); - - dispatchAccelerometer(x, y, z, timestamp); - return nullptr; -} - -#define TG3_GRAVITY_EARTH (9.80665f) - -void SensorNapi::dispatchAccelerometer(double x, double y, double z, long timeStamp) { - OHOS_LOGD("accelerometer callback, interval is %{public}d", timeStamp); - cocos2d::Acceleration a; - a.x = -(x / TG3_GRAVITY_EARTH); - a.y = -(y / TG3_GRAVITY_EARTH); - a.z = -(z / TG3_GRAVITY_EARTH); - a.timestamp = (double)timeStamp; - - cocos2d::EventAcceleration event(a); - cocos2d::Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); -} \ No newline at end of file diff --git a/cocos/platform/ohos/napi/modules/SensorNapi.h b/cocos/platform/ohos/napi/modules/SensorNapi.h deleted file mode 100644 index 2325d5767c54..000000000000 --- a/cocos/platform/ohos/napi/modules/SensorNapi.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef _SENSOR_NAPI_H -#define _SENSOR_NAPI_H - -#include - -class SensorNapi { -public: - static napi_value onAccelerometerCallBack(napi_env env, napi_callback_info info); - -private: - static void dispatchAccelerometer(double x, double y, double z, long timeStamp); -}; - -#endif //_SENSOR_NAPI_H \ No newline at end of file diff --git a/cocos/platform/ohos/napi/plugin_manager.cpp b/cocos/platform/ohos/napi/plugin_manager.cpp index c85f68e521ee..768598c945a7 100644 --- a/cocos/platform/ohos/napi/plugin_manager.cpp +++ b/cocos/platform/ohos/napi/plugin_manager.cpp @@ -8,7 +8,6 @@ #include "modules/InputNapi.h" #include "modules/MouseNapi.h" #include "modules/WebViewNapi.h" -#include "modules/SensorNapi.h" #include "modules/VideoPlayerNapi.h" #include "plugin_manager.h" #include "../CCLogOhos.h" @@ -158,14 +157,6 @@ napi_value NapiManager::GetContext(napi_env env, napi_callback_info info) { OHOS_LOGE("VideoPlayerNapi::Export finish"); } break; - case SENSOR_API: { - OHOS_LOGD("NapiManager::GetContext SENSOR_API"); - napi_property_descriptor desc[] = { - DECLARE_NAPI_FUNCTION("onAccelerometerCallBack", SensorNapi::onAccelerometerCallBack), - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); - } - break; default: OHOS_LOGE("unknown type"); } diff --git a/cocos/platform/ohos/napi/render/plugin_render.cpp b/cocos/platform/ohos/napi/render/plugin_render.cpp index 4ec6576ab6c1..1db076d0fe54 100644 --- a/cocos/platform/ohos/napi/render/plugin_render.cpp +++ b/cocos/platform/ohos/napi/render/plugin_render.cpp @@ -133,7 +133,7 @@ void DispatchKeyEventCB(OH_NativeXComponent* component, void* window) PluginRender::keyEventQueue_.push(keyEvent); PluginRender::GetInstance()->sendMsgToWorker(MessageType::WM_XCOMPONENT_KEY_EVENT, component, window); } else { - OHOS_LOGE("OpenHarmonyPlatform::getKeyEventError"); + OHOS_LOGE("HarmonyOS Next Platform::getKeyEventError"); } } @@ -145,13 +145,13 @@ void DispatchMouseEventCB(OH_NativeXComponent* component, void* window) PluginRender::mouseEventQueue_.push(mouseEvent); PluginRender::GetInstance()->sendMsgToWorker(MessageType::WM_XCOMPONENT_MOUSE_EVENT, component, window); } else { - OHOS_LOGE("OpenHarmonyPlatform::getMouseEventError"); + OHOS_LOGE("HarmonyOS Next Platform::getMouseEventError"); } } void DispatchHoverEventCB(OH_NativeXComponent* component, bool isHover) { - OHOS_LOGD("OpenHarmonyPlatform::DispatchHoverEventCB"); + OHOS_LOGD("HarmonyOS Next Platform::DispatchHoverEventCB"); } void DispatchTouchEventCB(OH_NativeXComponent* component, void* window) @@ -257,6 +257,7 @@ void PluginRender::timerCb(uv_timer_t* handle) { // OHOS_LOGD("PluginRender::timerCb, animationInterval_ is %{public}lu", animationInterval_); if (PluginRender::GetInstance()->eglCore_ != nullptr) { + Device::sendAndClearAcc(); cocos2d::CCDirector::sharedDirector()->mainLoop(); PluginRender::GetInstance()->eglCore_->Update(); } diff --git a/cocos/scripting/js-bindings/manual/ScriptingCore.cpp b/cocos/scripting/js-bindings/manual/ScriptingCore.cpp index 961b80ed0c1c..58d0d8d5fda5 100644 --- a/cocos/scripting/js-bindings/manual/ScriptingCore.cpp +++ b/cocos/scripting/js-bindings/manual/ScriptingCore.cpp @@ -338,7 +338,7 @@ bool JSBCore_os(JSContext *cx, uint32_t argc, jsval *vp) #elif (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) os = JS_InternString(cx, "WINRT"); #elif (CC_TARGET_PLATFORM == CC_PLATFORM_OHOS) - os = JS_InternString(cx, "OHOS"); + os = JS_InternString(cx, "HarmonyOS Next"); #else os = JS_InternString(cx, "Unknown"); #endif diff --git a/cocos/scripting/js-bindings/script/jsb_boot.js b/cocos/scripting/js-bindings/script/jsb_boot.js index 37c5701c03af..fc05085e250c 100644 --- a/cocos/scripting/js-bindings/script/jsb_boot.js +++ b/cocos/scripting/js-bindings/script/jsb_boot.js @@ -1172,7 +1172,7 @@ var _initSys = function () { * @constant * @type {string} */ - sys.OS_OHOS = "OHOS"; + sys.OS_OHOS = "HarmonyOS Next"; /** * @memberof cc.sys * @name OS_UNKNOWN diff --git a/cocos/scripting/lua-bindings/script/framework/device.lua b/cocos/scripting/lua-bindings/script/framework/device.lua index 346fd6c5bcf7..021827d254f4 100644 --- a/cocos/scripting/lua-bindings/script/framework/device.lua +++ b/cocos/scripting/lua-bindings/script/framework/device.lua @@ -59,7 +59,7 @@ elseif target == cc.PLATFORM_OS_WINRT then elseif target == cc.PLATFORM_OS_WP8 then device.platform = "wp8" elseif target == cc.PLATFORM_OS_OHOS then - device.platform = "openharmony" + device.platform = "HarmonyOS Next" end local language_ = app:getCurrentLanguage() diff --git a/tests/cpp-tests/CMakeLists.txt b/tests/cpp-tests/CMakeLists.txt index 629d15c43c52..f0ab94553d04 100644 --- a/tests/cpp-tests/CMakeLists.txt +++ b/tests/cpp-tests/CMakeLists.txt @@ -342,25 +342,53 @@ if(ANDROID) ADD_CUSTOM_COMMAND(TARGET ${APP_NAME} POST_BUILD COMMAND ${CMAKE_STRIP} lib${APP_NAME}.so) ENDIF() elseif (OHOS) + set(COCOS2DX_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../..) + set(CLASSES_PATH ${CMAKE_CURRENT_SOURCE_DIR}/Classes) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -frtti -fexceptions -fsigned-char") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O2") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O2") add_library(${APP_NAME} STATIC ${TESTS_SRC} ${EXTENDED_TESTS_SRC}) find_library( # Sets the name of the path variable. GLES-lib # Specifies the name of the NDK library that # you want CMake to locate. GLESv3 ) - find_library( # Sets the name of the path variable. - hilog-lib - # Specifies the name of the NDK library that - # you want CMake to locate. - hilog_ndk.z ) find_library( # Sets the name of the path variable. libnapi-lib # Specifies the name of the NDK library that # you want CMake to locate. ace_napi.z ) + + 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. + libace-lib + # Specifies the name of the NDK library that + # you want CMake to locate. + ace_ndk.z ) + + find_library( # Sets the name of the path variable. + rawfile-lib + # Specifies the name of the NDK library that + # you want CMake to locate. + rawfile.z ) + + message(" *************** target link cpptest and gles : ${GLES-lib} ******************") - target_link_libraries(${APP_NAME} cocos2d ${GLES-lib} ${hilog-lib} ${libnapi-lib}) + target_include_directories(${APP_NAME} PUBLIC ${CLASSES_PATH} + PUBLIC ${CLASSES_PATH}/../.. + ) + + #TBD need fixed + target_include_directories(${APP_NAME} PUBLIC ${COCOS2DX_ROOT_PATH}/external/chipmunk/include + ) + + target_link_libraries(${APP_NAME} cocos2d ${GLES-lib} ${libnapi-lib}) target_include_directories(${APP_NAME} PRIVATE Classes ) diff --git a/tests/cpp-tests/proj.ohos b/tests/cpp-tests/proj.ohos new file mode 160000 index 000000000000..98a643f46069 --- /dev/null +++ b/tests/cpp-tests/proj.ohos @@ -0,0 +1 @@ +Subproject commit 98a643f46069806f94e210cd2e0386d9d112811d diff --git a/tests/cpp-tests/proj.ohos/.gitignore b/tests/cpp-tests/proj.ohos/.gitignore deleted file mode 100644 index ad5f40166130..000000000000 --- a/tests/cpp-tests/proj.ohos/.gitignore +++ /dev/null @@ -1,15 +0,0 @@ -.hvigor -.idea -node_modules -entry/build -entry/.idea -entry/.cxx -local.properties -oh-package-lock.json5 -entry/src/main/resources/rawfile -oh_modules -libSysCapabilities/build -/.clangd -/.clang-tidy -.clang-format -hvigor/hvigor-wrapper.js \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/AppScope/app.json5 b/tests/cpp-tests/proj.ohos/AppScope/app.json5 deleted file mode 100644 index 98792f35fec2..000000000000 --- a/tests/cpp-tests/proj.ohos/AppScope/app.json5 +++ /dev/null @@ -1,11 +0,0 @@ -{ - "app": { - "bundleName": "ohos.cocos3_16.cpp.tests", - "vendor": "example", - "versionCode": 1000000, - "versionName": "1.0.0", - "icon": "$media:app_icon", - "label": "$string:app_name", - "distributedNotificationEnabled": true - } -} diff --git a/tests/cpp-tests/proj.ohos/AppScope/resources/base/element/string.json b/tests/cpp-tests/proj.ohos/AppScope/resources/base/element/string.json deleted file mode 100644 index 130280e637fd..000000000000 --- a/tests/cpp-tests/proj.ohos/AppScope/resources/base/element/string.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "string": [ - { - "name": "app_name", - "value": "3.16_cpp_tests" - } - ] -} \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/AppScope/resources/base/media/app_icon.png b/tests/cpp-tests/proj.ohos/AppScope/resources/base/media/app_icon.png deleted file mode 100644 index ce307a8827bd75456441ceb57d530e4c8d45d36c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6790 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 { - OHOS_LOGD("Cocos2dxRenderer_nativeInit() - branch 1"); - GLView *view = GLViewImpl::sharedOpenGLView(); - view->setFrameSize(w, h); - CCDirector::sharedDirector()->setOpenGLView(view); - - AppDelegate *pAppDelegate = new AppDelegate(); - CCApplication::sharedApplication()->run(); - } else { - OHOS_LOGD("Cocos2dxRenderer_nativeInit() - branch 2"); - ccGLInvalidateStateCache(); - CCShaderCache::sharedShaderCache()->reloadDefaultShaders(); - ccDrawInit(); - CCTextureCache::reloadAllTextures(); - CCNotificationCenter::sharedNotificationCenter()->postNotification(EVENT_COME_TO_FOREGROUND, NULL); - CCDirector::sharedDirector()->setGLDefaultValues(); - } -} - -} \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/entry/src/main/cpp/napi_init.cpp b/tests/cpp-tests/proj.ohos/entry/src/main/cpp/napi_init.cpp deleted file mode 100644 index 5524d88b40bb..000000000000 --- a/tests/cpp-tests/proj.ohos/entry/src/main/cpp/napi_init.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "CCLogOhos.h" -#include "napi/plugin_manager.h" - -/* - * function for module exports - */ -static napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor desc[] ={ - DECLARE_NAPI_FUNCTION("getContext", NapiManager::GetContext), - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); - - bool ret = NapiManager::GetInstance()->Export(env, exports); - if (!ret) { - OHOS_LOGE("Init failed"); - } - return exports; -} - -/* - * Napi Module define - */ -static napi_module nativerenderModule = { - .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = Init, - .nm_modname = "nativerender", - .nm_priv = ((void*)0), - .reserved = { 0 }, -}; -/* - * Module register function - */ -extern "C" __attribute__((constructor)) void RegisterModule(void) { - napi_module_register(&nativerenderModule); -} \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/entry/src/main/cpp/types/libentry/index.d.ts b/tests/cpp-tests/proj.ohos/entry/src/main/cpp/types/libentry/index.d.ts deleted file mode 100644 index 6a9293652bfe..000000000000 --- a/tests/cpp-tests/proj.ohos/entry/src/main/cpp/types/libentry/index.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -import resmgr from '@ohos.resourceManager'; - -export interface CPPFunctions { - onCreate: () => void; - onShow: () => void; - onHide: () => void; - onBackPress: () => void; - onDestroy: () => void; - onPageShow: () => void; - onPageHide: () => void; - nativeResourceManagerInit: (resourceManager: resmgr.ResourceManager) => void; - writablePathInit: (writePath: string) => void; - workerInit: () => void; - nativeEngineStart: () => void; - registerFunction: () => void; - initAsyncInfo: () => void; - mouseWheelCB: (eventType: string, scrollY : number) => void; - editBoxOnFocusCB: (viewTag: number) => void; - editBoxOnChangeCB: (viewTag: number, text: string) => void; - editBoxOnEnterCB: (viewTag: number, text: string) => void; - textFieldTTFOnChangeCB: (text: string) => void; - shouldStartLoading: (viewTag: number, url: string) => void; - finishLoading: (viewTag: number, url: string) => void; - failLoading: (viewTag: number, url: string) => void; - jsCallback: () => void; - onVideoCallBack: (viewTag: number, event: number) => void; - onAccelerometerCallBack: (x: number, y: number, z: number, interval: number) => void; -} - -export const getContext: (a: number) => CPPFunctions; diff --git a/tests/cpp-tests/proj.ohos/entry/src/main/cpp/types/libentry/oh-package.json5 b/tests/cpp-tests/proj.ohos/entry/src/main/cpp/types/libentry/oh-package.json5 deleted file mode 100644 index fa7874d5940d..000000000000 --- a/tests/cpp-tests/proj.ohos/entry/src/main/cpp/types/libentry/oh-package.json5 +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "libnativerender.so", - "types": "./index.d.ts", - "version": "", - "description": "Please describe the basic information." -} \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/entry/src/main/ets/MainAbility/MainAbility.ts b/tests/cpp-tests/proj.ohos/entry/src/main/ets/MainAbility/MainAbility.ts deleted file mode 100644 index a89ce067f484..000000000000 --- a/tests/cpp-tests/proj.ohos/entry/src/main/ets/MainAbility/MainAbility.ts +++ /dev/null @@ -1,80 +0,0 @@ -import window from '@ohos.window'; -import UIAbility from '@ohos.app.ability.UIAbility'; -import web_webview from '@ohos.web.webview'; -import nativeRender from "libnativerender.so"; -import { ContextType } from "@ohos/libSysCapabilities" -import { GlobalContext,GlobalContextConstants} from "@ohos/libSysCapabilities" - -const nativeAppLifecycle: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.APP_LIFECYCLE); -const rawFileUtils: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.RAW_FILE_UTILS); - -export default class MainAbility extends UIAbility { - onCreate(want, launchParam) { - nativeAppLifecycle.onCreate(); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT, this.context); - // Initializes the webView kernel of the system. This parameter is optional if it is not used. - web_webview.WebviewController.initializeWebEngine(); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_WANT, this.context); - console.info('[LIFECYCLE-App] onCreate') - } - - onDestroy() { - nativeAppLifecycle.onDestroy(); - console.info('[LIFECYCLE-App] onDestroy') - } - - onWindowStageCreate(windowStage) { - // Main window is created, set main page for this ability - windowStage.loadContent('pages/Index', (err, data) => { - if (err.code) { - return; - } - rawFileUtils.nativeResourceManagerInit(this.context.resourceManager); - rawFileUtils.writablePathInit(this.context.filesDir); - }); - - windowStage.getMainWindow().then((windowIns: window.Window) => { - // Set whether to display the status bar and navigation bar. If they are not displayed, [] is displayed. - let systemBarPromise = windowIns.setWindowSystemBarEnable([]); - // Whether the window layout is displayed in full screen mode - let fullScreenPromise = windowIns.setWindowLayoutFullScreen(true); - // Sets whether the screen is always on. - let keepScreenOnPromise = windowIns.setWindowKeepScreenOn(true); - Promise.all([systemBarPromise, fullScreenPromise, keepScreenOnPromise]).then(() => { - console.info('Succeeded in setting the window'); - }).catch((err) => { - console.error('Failed to set the window, cause ' + JSON.stringify(err)); - }); - }) - - windowStage.on("windowStageEvent", (data) => { - let stageEventType: window.WindowStageEventType = data; - switch (stageEventType) { - case window.WindowStageEventType.RESUMED: - nativeAppLifecycle.onShow(); - break; - case window.WindowStageEventType.PAUSED: - nativeAppLifecycle.onHide(); - break; - default: - break; - } - }); - } - - onWindowStageDestroy() { - // Main window is destroyed, release UI related resources - } - - onForeground() { - // Ability has brought to foreground - console.info('[LIFECYCLE-App] onShow') - nativeAppLifecycle.onShow(); - } - - onBackground() { - // Ability has back to background - console.info('[LIFECYCLE-App] onDestroy') - nativeAppLifecycle.onHide(); - } -}; diff --git a/tests/cpp-tests/proj.ohos/entry/src/main/ets/components/CocosEditBox.ets b/tests/cpp-tests/proj.ohos/entry/src/main/ets/components/CocosEditBox.ets deleted file mode 100644 index 2587169f240f..000000000000 --- a/tests/cpp-tests/proj.ohos/entry/src/main/ets/components/CocosEditBox.ets +++ /dev/null @@ -1,82 +0,0 @@ -import { TextInputInfo } from '@ohos/libSysCapabilities/src/main/ets/components/editbox/EditBoxMsg' -import worker from '@ohos.worker'; -import { WorkerManager } from '../workers/WorkerManager'; - -@Component -export struct CocosEditBox { - @ObjectLink textInputInfo: TextInputInfo; - cocosWorker: worker.ThreadWorker = WorkerManager.getInstance().getWorker(); - - build(){ - if(this.textInputInfo.multiline){ - TextArea({text: this.textInputInfo.text, placeholder: this.textInputInfo.placeHolder}) - .id('TextArea'+this.textInputInfo.viewTag) - .position({x: px2vp(this.textInputInfo.x), y: px2vp(this.textInputInfo.y)}) - .size({width: px2vp(this.textInputInfo.w), height: px2vp(this.textInputInfo.h)}) - .padding({top: px2vp(this.textInputInfo.paddingH), right: px2vp(this.textInputInfo.paddingW), - bottom: px2vp(this.textInputInfo.paddingH), left: px2vp(this.textInputInfo.paddingW)}) - .borderRadius(0) - .maxLength(this.textInputInfo.maxLength) - .type(TextAreaType.NORMAL) - .fontFamily($rawfile(this.textInputInfo.fontPath)) - .fontSize(px2fp(this.textInputInfo.fontSize)) - .fontColor(`rgba(${this.textInputInfo.fontColor.r}, ${this.textInputInfo.fontColor.g}, ${this.textInputInfo.fontColor.b}, ${this.textInputInfo.fontColor.a})`) - .placeholderFont({size: px2fp(this.textInputInfo.placeholderFontSize), family: $rawfile(this.textInputInfo.placeHolderFontPath)}) - .placeholderColor(`rgba(${this.textInputInfo.placeholderFontColor.r}, ${this.textInputInfo.placeholderFontColor.g}, ${this.textInputInfo.placeholderFontColor.b}, ${this.textInputInfo.placeholderFontColor.a})`) - .backgroundColor(Color.Transparent) - .visibility(this.textInputInfo.visible ? Visibility.Visible : Visibility.None) - .onVisibleAreaChange([0.0, 1.0], () => { - focusControl.requestFocus('TextArea' + this.textInputInfo.viewTag); - }) - .onFocus(() => { - this.cocosWorker.postMessage({type: "editBoxOnFocus", viewTag: this.textInputInfo.viewTag}); - }) - .onChange((value: string)=>{ - this.textInputInfo.text = value; - this.cocosWorker.postMessage({type: "editBoxOnChange", viewTag: this.textInputInfo.viewTag, value: value}); - }) - .onBlur(()=> { - this.textInputInfo.visible = false - this.cocosWorker.postMessage({type: "editBoxOnEnter", viewTag: this.textInputInfo.viewTag, text: this.textInputInfo.text}); - }) - .onSubmit(()=>{ - this.cocosWorker.postMessage({type: "editBoxOnEnter", viewTag: this.textInputInfo.viewTag, text: this.textInputInfo.text}); - }) - }else{ - TextInput({text: this.textInputInfo.text, placeholder: this.textInputInfo.placeHolder}) - .id('TextInput'+this.textInputInfo.viewTag) - .position({x: px2vp(this.textInputInfo.x), y: px2vp(this.textInputInfo.y)}) - .size({width: px2vp(this.textInputInfo.w), height: px2vp(this.textInputInfo.h)}) - .padding({top: px2vp(this.textInputInfo.paddingH), right: px2vp(this.textInputInfo.paddingW), - bottom: px2vp(this.textInputInfo.paddingH), left: px2vp(this.textInputInfo.paddingW)}) - .borderRadius(0) - .maxLength(this.textInputInfo.maxLength) - .type(this.textInputInfo.inputMode) - .fontFamily($rawfile(this.textInputInfo.fontPath)) - .fontSize(px2fp(this.textInputInfo.fontSize)) - .fontColor(`rgba(${this.textInputInfo.fontColor.r}, ${this.textInputInfo.fontColor.g}, ${this.textInputInfo.fontColor.b}, ${this.textInputInfo.fontColor.a})`) - .placeholderFont({size: px2fp(this.textInputInfo.placeholderFontSize), family: $rawfile(this.textInputInfo.placeHolderFontPath)}) - .placeholderColor(`rgba(${this.textInputInfo.placeholderFontColor.r}, ${this.textInputInfo.placeholderFontColor.g}, ${this.textInputInfo.placeholderFontColor.b}, ${this.textInputInfo.placeholderFontColor.a})`) - .backgroundColor(Color.Transparent) - .visibility(this.textInputInfo.visible ? Visibility.Visible : Visibility.None) - .showPasswordIcon(false) - .onVisibleAreaChange([0.0, 1.0], () => { - focusControl.requestFocus('TextInput' + this.textInputInfo.viewTag); - }) - .onFocus(() => { - this.cocosWorker.postMessage({type: "editBoxOnFocus", viewTag: this.textInputInfo.viewTag}); - }) - .onChange((value: string)=>{ - this.textInputInfo.text = value; - this.cocosWorker.postMessage({type: "editBoxOnChange", viewTag: this.textInputInfo.viewTag, value: value}); - }) - .onBlur(()=> { - this.textInputInfo.visible = false - this.cocosWorker.postMessage({type: "editBoxOnEnter", viewTag: this.textInputInfo.viewTag, text: this.textInputInfo.text}); - }) - .onSubmit(()=>{ - this.cocosWorker.postMessage({type: "editBoxOnEnter", viewTag: this.textInputInfo.viewTag, text: this.textInputInfo.text}); - }) - } - } -} diff --git a/tests/cpp-tests/proj.ohos/entry/src/main/ets/components/CocosVideoPlayer.ets b/tests/cpp-tests/proj.ohos/entry/src/main/ets/components/CocosVideoPlayer.ets deleted file mode 100644 index 6f67afe3b443..000000000000 --- a/tests/cpp-tests/proj.ohos/entry/src/main/ets/components/CocosVideoPlayer.ets +++ /dev/null @@ -1,39 +0,0 @@ -import { WorkerManager } from '../workers/WorkerManager' -import { VideoPlayerInfo, VideoEvent } from '@ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayerMsg'; -import worker from '@ohos.worker'; - -@Component -export struct CocosVideoPlayer { - @ObjectLink videoPlayerInfo: VideoPlayerInfo; - cocosWorker: worker.ThreadWorker = WorkerManager.getInstance().getWorker(); - - build() { - Column() { - Video({ - src: this.videoPlayerInfo.isUrl ? this.videoPlayerInfo.url : this.videoPlayerInfo.rawfile, - controller: this.videoPlayerInfo.controller - }) - .width(this.videoPlayerInfo.w) - .height(this.videoPlayerInfo.h) - .visibility(this.videoPlayerInfo.visible ? Visibility.Visible : Visibility.None) - .controls(false) - .loop(this.videoPlayerInfo.isLoop) - .objectFit(this.videoPlayerInfo.objectFit) - .onPrepared(()=>{ - if(this.videoPlayerInfo.isPlay) { - this.videoPlayerInfo.controller.start() - } - this.videoPlayerInfo.controller.requestFullscreen(this.videoPlayerInfo.isFullScreen) - }) - .onStart(()=>{ - this.cocosWorker.postMessage({type: "onVideoCallBack", viewTag: this.videoPlayerInfo.viewTag, event: VideoEvent.PLAYING}); - }) - .onPause(()=>{ - this.cocosWorker.postMessage({type: "onVideoCallBack", viewTag: this.videoPlayerInfo.viewTag, event: VideoEvent.PAUSED}); - }) - .onFinish(()=>{ - this.cocosWorker.postMessage({type: "onVideoCallBack", viewTag: this.videoPlayerInfo.viewTag, event: VideoEvent.COMPLETED}); - }) - } - } -} diff --git a/tests/cpp-tests/proj.ohos/entry/src/main/ets/components/CocosWebview.ets b/tests/cpp-tests/proj.ohos/entry/src/main/ets/components/CocosWebview.ets deleted file mode 100644 index f26ba14cc6e7..000000000000 --- a/tests/cpp-tests/proj.ohos/entry/src/main/ets/components/CocosWebview.ets +++ /dev/null @@ -1,43 +0,0 @@ -import { WebViewInfo } from "@ohos/libSysCapabilities/src/main/ets/components/webview/WebViewMsg" -import worker from '@ohos.worker'; -import { WorkerManager } from '../workers/WorkerManager'; - -@Component -export struct CocosWebView { - viewInfo: WebViewInfo = new WebViewInfo(0, 0, 0, 0, 0); - cocosWorker: worker.ThreadWorker = WorkerManager.getInstance().getWorker(); - - build() { - Web({ src: this.viewInfo.isUrl ? this.viewInfo.url : $rawfile(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 }) - .domStorageAccess(true) - .databaseAccess(true) - .imageAccess(true) - .onlineImageAccess(true) - .zoomAccess(this.viewInfo.zoomAccess) - .javaScriptAccess(true) - .visibility(this.viewInfo.visible ? Visibility.Visible : Visibility.None) - .opacity(this.viewInfo.opacity) - .backgroundColor(this.viewInfo.backgroundColor) - .onPageBegin((event) => { - this.cocosWorker.postMessage({ type: "onPageBegin", viewTag: this.viewInfo.viewTag, url: event == null ? '' : event.url }); - }) - .onPageEnd((event) => { - this.cocosWorker.postMessage({ type: "onPageEnd", viewTag: this.viewInfo.viewTag, url: event == null ? '' : event.url }) - if(this.viewInfo.jsInterfaceScheme != "" && event != null && event.url.startsWith(this.viewInfo.jsInterfaceScheme)) { - this.cocosWorker.postMessage({ type: "onJsCallBack", viewTag: this.viewInfo.viewTag, url: event == null ? '' : event.url }) - } - // if u want use the javascript on ur page, u can use registerJavaScriptProxy() to register js function here - // and confirm that just register once by a local variable - }) - .onErrorReceive((event) => { - this.cocosWorker.postMessage({ type: "onErrorReceive", viewTag: this.viewInfo.viewTag, url: this.viewInfo.url }) - }) - .onHttpErrorReceive((event) => { - this.cocosWorker.postMessage({ type: "onErrorReceive", viewTag: this.viewInfo.viewTag, url: this.viewInfo.url }) - }) - } -} \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/entry/src/main/ets/components/TextInputDialog.ets b/tests/cpp-tests/proj.ohos/entry/src/main/ets/components/TextInputDialog.ets deleted file mode 100644 index 4a689341cc0a..000000000000 --- a/tests/cpp-tests/proj.ohos/entry/src/main/ets/components/TextInputDialog.ets +++ /dev/null @@ -1,33 +0,0 @@ -import { TextInputDialogEntity } from '@ohos/libSysCapabilities' -import worker from '@ohos.worker'; -import { WorkerManager } from '../workers/WorkerManager'; - -@CustomDialog -export struct TextInputDialog { - @State showMessage: TextInputDialogEntity = new TextInputDialogEntity(''); - cocosWorker: worker.ThreadWorker = WorkerManager.getInstance().getWorker(); - controller?: CustomDialogController - - build() { - Column() { - Row() { - TextInput({ text: this.showMessage.message }) - .backgroundColor('#ffffff') - .layoutWeight(1) - .defaultFocus(true) - .caretColor(Color.Transparent) - .onChange((value) => { - this.cocosWorker.postMessage({type: "textFieldTTFOnChange", data: value}) - }) - Blank(8).width(16) - Button($r('app.string.text_field_ttf_complete')).onClick(() => { - this.controller!.close(); - }) - }.padding({ left: 8, right: 8, top: 8, bottom: 8 }) - .backgroundColor(Color.Gray) - } - .width('100%') - - .justifyContent(FlexAlign.End) - } -} \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/entry/src/main/ets/pages/Index.ets b/tests/cpp-tests/proj.ohos/entry/src/main/ets/pages/Index.ets deleted file mode 100644 index dbb983025e14..000000000000 --- a/tests/cpp-tests/proj.ohos/entry/src/main/ets/pages/Index.ets +++ /dev/null @@ -1,158 +0,0 @@ -import deviceInfo from '@ohos.deviceInfo'; - -import nativeRender from 'libnativerender.so' -import { ContextType } from '@ohos/libSysCapabilities' -import { TextInputInfo } from '@ohos/libSysCapabilities/src/main/ets/components/editbox/EditBoxMsg' -import { TextInputDialogEntity } from '@ohos/libSysCapabilities' -import { WebViewInfo } from '@ohos/libSysCapabilities/src/main/ets/components/webview/WebViewMsg' -import { VideoPlayerInfo } from '@ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayerMsg' -import { WorkerMsgUtils } from '@ohos/libSysCapabilities/src/main/ets/utils/WorkerMsgUtils' -import { WorkerManager } from '../workers/WorkerManager' -import { CocosEditBox } from '../components/CocosEditBox' -import { CocosWebView } from '../components/CocosWebview' -import { CocosVideoPlayer } from '../components/CocosVideoPlayer' -import { TextInputDialog } from '../components/TextInputDialog' -import { GlobalContext,GlobalContextConstants} from "@ohos/libSysCapabilities" -import promptAction from '@ohos.promptAction'; -import process from '@ohos.process'; -const nativePageLifecycle:nativeRender.CPPFunctions = nativeRender.getContext(ContextType.JSPAGE_LIFECYCLE); - -let cocosWorker = WorkerManager.getInstance().getWorker(); - -@Entry -@Component -struct Index { - xcomponentController: XComponentController = new XComponentController(); - - processMgr = new process.ProcessManager(); - - - // EditBox - @State editBoxArray: TextInputInfo[] = []; - private editBoxIndexMap: Map = new Map; - - // WebView - @State webViewArray: WebViewInfo[] = []; - private webViewIndexMap: Map = new Map; - - // videoPlayer - @State videoPlayerInfoArray: VideoPlayerInfo[] = []; - private videoPlayerIndexMap: Map = new Map; - - // textInputDialog - showMessage: TextInputDialogEntity = new TextInputDialogEntity(''); - dialogController: CustomDialogController = new CustomDialogController({ - builder: TextInputDialog({ - showMessage: this.showMessage - }), - autoCancel: true, - alignment: DialogAlignment.Bottom, - customStyle: true, - }) - // PanGesture - private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down }); - - onPageShow() { - console.log('[LIFECYCLE-Page] onPageShow'); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_ARRAY, this.editBoxArray); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP, this.editBoxIndexMap); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_COCOS_WORKER, cocosWorker); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY, this.webViewArray); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP, this.webViewIndexMap); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_ARRAY, this.videoPlayerInfoArray); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP, this.videoPlayerIndexMap); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_DIALOG_CONTROLLER, this.dialogController); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_SHOW_MESSAGE, this.showMessage); - nativePageLifecycle.onPageShow(); - } - - onPageHide() { - console.log('[LIFECYCLE-Page] onPageHide'); - nativePageLifecycle.onPageHide(); - } - - onBackPress() { - console.log('[LIFECYCLE-Page] onBackPress'); - try { - promptAction.showDialog({ - title: "提示", - message: "确认退出游戏吗", - buttons: [ - { - text: '取消', - color: '#000000' - }, - { - text: '确认', - color: '#000000' - } - ], - }).then(data => { - console.info('showDialog success, click button: ' + data.index); - if(data.index == 0) { - console.info('showDialog click button cancel'); - return; - } else { - console.info('showDialog click button ok'); - this.processMgr.exit(0); - } - }) - } catch (error) { - console.error(`showDialog args error code is ${error.code}, message is ${error.message}`); - }; - // If disable system exit needed, remove comment "return true" - return true; - } - - onMouseWheel(eventType: string, scrollY: number) { - cocosWorker.postMessage({ type: "onMouseWheel", eventType: eventType, scrollY: scrollY }); - } - - build() { - Stack() { - XComponent({ - id: 'xcomponentId', - type: 'surface', - libraryname: 'nativerender', - controller: this.xcomponentController - }) - .focusable(true) - .focusOnTouch(true) - .gesture( - PanGesture(this.panOption) - .onActionStart(() => { - this.onMouseWheel("actionStart", 0); - }) - .onActionUpdate((event: GestureEvent) => { - if (deviceInfo.deviceType === '2in1') { - this.onMouseWheel("actionUpdate", event.offsetY); - } - }) - .onActionEnd(() => { - this.onMouseWheel("actionEnd", 0); - }) - ) - .onLoad((context) => { - console.log('[cocos] XComponent.onLoad Callback'); - cocosWorker.postMessage({ type: "abilityContextInit", data: GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT)}); - cocosWorker.postMessage({ type: "onXCLoad", data: "XComponent" }); - cocosWorker.onmessage = WorkerMsgUtils.recvWorkerThreadMessage; - }) - .onDestroy(() => { - }) - ForEach(this.editBoxArray, (item:TextInputInfo) => { - CocosEditBox({ textInputInfo: item}); - }, (item:TextInputInfo) => item.viewTag.toString()) - - ForEach(this.webViewArray, (item:WebViewInfo) => { - CocosWebView({ viewInfo: item }) - }, (item:WebViewInfo) => item.uniqueId.toString()) - - ForEach(this.videoPlayerInfoArray, (item:VideoPlayerInfo) => { - CocosVideoPlayer({ videoPlayerInfo: item }) - }, (item:VideoPlayerInfo) => item.viewTag.toString()) - } - .width('100%') - .height('100%') - } -} diff --git a/tests/cpp-tests/proj.ohos/entry/src/main/ets/workers/CocosWorker.ts b/tests/cpp-tests/proj.ohos/entry/src/main/ets/workers/CocosWorker.ts deleted file mode 100644 index 94ddb8d38920..000000000000 --- a/tests/cpp-tests/proj.ohos/entry/src/main/ets/workers/CocosWorker.ts +++ /dev/null @@ -1,79 +0,0 @@ -import worker, { ThreadWorkerGlobalScope } from '@ohos.worker'; -import nativeRender from "libnativerender.so"; -import { ContextType } from "@ohos/libSysCapabilities" -import { VideoPlayer } from "@ohos/libSysCapabilities" -import { CocosEditBox } from "@ohos/libSysCapabilities" -import { Dialog } from "@ohos/libSysCapabilities" -import { WebView } from "@ohos/libSysCapabilities" -import { JumpManager } from "@ohos/libSysCapabilities" -import { NapiHelper } from "@ohos/libSysCapabilities" -import { ApplicationManager } from "@ohos/libSysCapabilities" -import { GlobalContext,GlobalContextConstants} from "@ohos/libSysCapabilities" - -const appLifecycle: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.APP_LIFECYCLE); -const workerContext: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.WORKER_INIT); -const inputNapi: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.INPUT_NAPI); -const mouseNapi: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.MOUSE_NAPI); -const webViewNapi: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.WEBVIEW_NAPI); -const videoPlayNapi: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.VIDEOPLAYER_NAPI); -const napiContext: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.NATIVE_API); -workerContext.workerInit() - -napiContext.nativeEngineStart(); -NapiHelper.registerFunctions(napiContext.registerFunction) - -const workerPort: ThreadWorkerGlobalScope = worker.workerPort; - -workerPort.onmessage = function(e) : void { - let data = e.data; - switch(data.type) { - case "onXCLoad": - console.log("[cocos] onXCLoad Callback"); - Dialog.init(workerPort); - CocosEditBox.init(workerPort); - JumpManager.init(workerPort); - WebView.init(workerPort); - VideoPlayer.init(workerPort); - ApplicationManager.init(workerPort); - napiContext.initAsyncInfo(); - break; - case "abilityContextInit": - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT, data.data); - break; - case "editBoxOnFocus": - inputNapi.editBoxOnFocusCB(data.viewTag); - break; - case "editBoxOnChange": - inputNapi.editBoxOnChangeCB(data.viewTag, data.value); - break; - case "editBoxOnEnter": - inputNapi.editBoxOnEnterCB(data.viewTag, data.text); - break; - case "textFieldTTFOnChange": - inputNapi.textFieldTTFOnChangeCB(data.data); - break; - case "onMouseWheel": - mouseNapi.mouseWheelCB(data.eventType, data.scrollY); - break; - case "onPageBegin": - webViewNapi.shouldStartLoading(data.viewTag, data.url); - break; - case "onPageEnd": - webViewNapi.finishLoading(data.viewTag, data.url); - break; - case "onJsCallBack": - webViewNapi.jsCallback(); - break; - case "onErrorReceive": - webViewNapi.failLoading(data.viewTag, data.url); - break; - case "onVideoCallBack": - videoPlayNapi.onVideoCallBack(data.viewTag, data.event); - break; - case "exit": - appLifecycle.onBackPress(); - break; - default: - console.error("cocos worker: message type unknown") - } -} diff --git a/tests/cpp-tests/proj.ohos/entry/src/main/ets/workers/WorkerManager.ts b/tests/cpp-tests/proj.ohos/entry/src/main/ets/workers/WorkerManager.ts deleted file mode 100644 index e2ec70b1873e..000000000000 --- a/tests/cpp-tests/proj.ohos/entry/src/main/ets/workers/WorkerManager.ts +++ /dev/null @@ -1,34 +0,0 @@ -import worker from '@ohos.worker'; -import { Constants } from '@ohos/libSysCapabilities'; - -export class WorkerManager { - private cocosWorker: worker.ThreadWorker; - - private constructor() { - this.cocosWorker = new worker.ThreadWorker("entry/ets/workers/CocosWorker.ts", { - type: "classic", - name: "CocosWorker" - }); - this.cocosWorker.onerror = (e) => { - let msg = e.message; - let filename = e.filename; - let lineno = e.lineno; - let colno = e.colno; - console.error(`on Error ${msg} ${filename} ${lineno} ${colno}`); - } - } - - public static getInstance(): WorkerManager { - let workerManger: WorkerManager | undefined = AppStorage.get(Constants.APP_KEY_WORKER_MANAGER); - if (workerManger == undefined) { - workerManger = new WorkerManager; - AppStorage.setOrCreate(Constants.APP_KEY_WORKER_MANAGER, workerManger); - return workerManger; - } - return workerManger; - } - - public getWorker(): worker.ThreadWorker { - return this.cocosWorker; - } -} \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/entry/src/main/module.json5 b/tests/cpp-tests/proj.ohos/entry/src/main/module.json5 deleted file mode 100644 index f5b65c3319a3..000000000000 --- a/tests/cpp-tests/proj.ohos/entry/src/main/module.json5 +++ /dev/null @@ -1,71 +0,0 @@ -{ - "module": { - "name": "entry", - "type": "entry", - "description": "$string:entry_desc", - "mainElement": "MainAbility", - "deviceTypes": [ - "phone", - "tablet", - "2in1" - ], - "deliveryWithInstall": true, - "installationFree": false, - "pages": "$profile:main_pages", - "abilities": [ - { - "name": "MainAbility", - "srcEntry": "./ets/MainAbility/MainAbility.ts", - "description": "$string:MainAbility_desc", - "icon": "$media:icon", - "label": "$string:MainAbility_label", - "startWindowIcon": "$media:icon", - "startWindowBackground": "$color:white", - "exported": true, - // "orientation": "landscape", - "skills": [ - { - "entities": [ - "entity.system.home" - ], - "actions": [ - "action.system.home" - ] - } - ], - // https://docs.openharmony.cn/pages/v4.0/zh-cn/application-dev/quick-start/module-configuration-file.md/ - "orientation": "auto_rotation", - "supportWindowMode": ["fullscreen"], - "maxWindowWidth": 1080, - "minWindowWidth": 1080, - "maxWindowHeight": 720, - "minWindowHeight": 720 - } - ], - "requestPermissions": [ - { - "name": "ohos.permission.INTERNET" - }, { - "name" : "ohos.permission.SET_NETWORK_INFO" - }, { - "name" : "ohos.permission.GET_NETWORK_INFO" - }, { - "name": "ohos.permission.GET_WIFI_INFO" - }, { - "name": "ohos.permission.ACCELEROMETER" - },{ - "name": "ohos.permission.VIBRATE" - } - ], - "metadata": [ - { - "name": "ArkTSPartialUpdate", - "value": "true" - }, - { - "name": "partialUpdateStrictCheck", - "value": "warn" - } - ] - } -} \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/entry/src/main/resources/base/element/color.json b/tests/cpp-tests/proj.ohos/entry/src/main/resources/base/element/color.json deleted file mode 100644 index 1bbc9aa9617e..000000000000 --- a/tests/cpp-tests/proj.ohos/entry/src/main/resources/base/element/color.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "color": [ - { - "name": "white", - "value": "#FFFFFF" - } - ] -} \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/entry/src/main/resources/base/element/string.json b/tests/cpp-tests/proj.ohos/entry/src/main/resources/base/element/string.json deleted file mode 100644 index 7a087a7ced5f..000000000000 --- a/tests/cpp-tests/proj.ohos/entry/src/main/resources/base/element/string.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "string": [ - { - "name": "entry_desc", - "value": "3.16_cpp_tests" - }, - { - "name": "MainAbility_label", - "value": "3.16_cpp_tests" - }, - { - "name": "MainAbility_desc", - "value": "description" - }, - { - "name": "text_field_ttf_complete", - "value": "完成" - } - ] -} \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/entry/src/main/resources/base/media/icon.png b/tests/cpp-tests/proj.ohos/entry/src/main/resources/base/media/icon.png deleted file mode 100644 index ce307a8827bd75456441ceb57d530e4c8d45d36c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6790 zcmX|G1ymHk)?T_}Vd;>R?p|tHQo6fg38|$UVM!6BLrPFWk?s;$LOP{GmJpBl$qoSA!PUg~PA65-S00{{S`XKG6NkG0RgjEntPrmV+?0|00mu7;+5 zrdpa{2QLqPJ4Y{j7=Mrl{BaxrkdY69+c~(w{Fv-v&aR%aEI&JYSeRTLWm!zbv;?)_ ziZB;fwGbbeL5Q}YLx`J$lp~A09KK8t_z}PZ=4ZzgdeKtgoc+o5EvN9A1K1_<>M?MBqb#!ASf&# zEX?<)!RH(7>1P+j=jqG(58}TVN-$psA6K}atCuI!KTJD&FMmH-78ZejBm)0qc{ESp z|LuG1{QnBUJRg_E=h1#XMWt2%fcoN@l7eAS!Es?Q+;XsRNPhiiE=@AqlLkJzF`O18 zbsbSmKN=aaq8k3NFYZfDWpKmM!coBU0(XnL8R{4=i|wi{!uWYM2je{U{B*K2PVdu&=E zTq*-XsEsJ$u5H4g6DIm2Y!DN`>^v|AqlwuCD;w45K0@eqauiqWf7l&o)+YLHm~|L~ z7$0v5mkobriU!H<@mVJHLlmQqzQ3d6Rh_-|%Yy2li*tHO>_vcnuZ7OR_xkAIuIU&x z-|8Y0wj|6|a6_I(v91y%k_kNw6pnkNdxjqG8!%Vz_d%c_!X+6-;1`GC9_FpjoHev5fEV7RhJ>r=mh-jp$fqbqRJ=obwdgLDVP5+s zy1=_DWG0Y-Jb3t^WXmkr(d9~08k-|#Ly zaNOmT(^9tIb&eb4%CzIT zAm3CUtWSr1t4?h1kk#NBi{U|pJslvME{q|_eS^3En>SOqSxyuN1x;Is@8~m?*>}** znrRFArP!K_52RpX*&JHMR<^lVdm8ypJ}0R(SD(51j;6@ni$6bQ+2XL+R^|NnSp5}(kzvMZ^(@4fD_{QVu$(&K6H|C37TG1Am9Re{<<3gd zh@`>;BqkXMW&p0T6rt|iB$)~CvFe(XC)F9WgAZn*0@t$oZo;!*}r@_`h?KKH&6A@3= zISXoQB+~`op>NP-buiA*^0n{@i{_?MRG)&k)c)k_F+-2Lud!S9pc+i`s74NpBCaGF zXN+pHkubw*msGBTY27BKHv)RRh3;nMg4&$fD_6X9Vt~;_4D+5XPH~#Kn-yjcy!$}1 zigv#FNY>TqMhtIBb@UoF!cE~Q8~;!Pek>SQQwHnHuWKoVBosAiOr}q>!>aE*Krc)V zBUMEcJ5NU0g8}-h6i1zpMY9>m4ne?=U2~`w7K7Q0gB_=p@$5K7p6}thw z-~3dMj?YNX2X$lZ+7ngQ$=s}3mizNN@kE%OtB)?c&i~2L55z8^=yz;xMHLmlY>&Q# zJj?!)M#q_SyfkQh)k?j8IfLtB)ZCp|*vf4_B zos?73yd^h-Ac+;?E4*bpf=o*^3x3-`TVjbY4n6!EN10K6o@fxdyps05Vo3PU)otB} z`3kR+2w7_C#8Z!q`J)p{Vh!+m9-UP!$STp+Hb}}#@#_u^SsUQg<}59< zTvH3%XS4G+6FF^(m6bVF&nSUIXcl;nw{=H$%fgeJ>CgDYiLdpDXr{;-AnG z8dvcrHYVMI&`R6;GWekI@Ir3!uo)oz4^{6q0m^}@f2tM9&=YHNi6-?rh0-{+k@cQm zdp`g#YdQn%MDVg2GR>wZ`n2<0l4)9nx1Wfr&!Dvz=bPwU!h2S?ez6MVc5APE4-xLB zi&W9Q8k2@0w!C53g?iAIQ}~p*3O(@zja6KQ=M3zfW*_6o5SwR-)6VBh~m7{^-=MC-owYH5-u40a}a0liho3QZZ5L{bS_xM1)4}19)zTU$$MY zq3eZML1WC{K%YFd`Be0M-rkO^l?h{kM{$2oK1*A@HVJ57*yhDkUF!2WZ&oA4Y-sK( zCY69%#`mBCi6>6uw(x4gbFaP0+FD*JKJ-q!F1E?vLJ+d35!I5d7@^eU?(CS|C^tmI5?lv@s{{*|1F zFg|OzNpZ0hxljdjaW%45O0MOttRrd(Z?h{HYbB-KFUx&9GfFL3b8NwZ$zNu)WbBD` zYkj$^UB5%3Pj1MDr>S2Ejr9pUcgA!;ZG!@{uAy12)vG=*^9-|dNQBc8&`oxBlU~#y zs!anJX&T?57Jdr^sb>e+V`MVfY>Y0ESg7MG<7W0g&bR-ZYzzZ%2H&Etcp zcd6QeXO1D!5A#zM0lx*GH}`M)2~ZFLE;sP^RSB5wVMNfiZXPd(cmO>j=OSA3`o5r& zna(|^jGXbdN7PK)U8b7^zYtYkkeb%<%F~=OqB~kXMQkq}ii|skh@WSRt>5za;cjP0 zZ~nD%6)wzedqE}BMLt~qKwlvTr33))#uP~xyw#*Eaa|DbMQ_%mG0U8numf8)0DX`r zRoG2bM;#g|p-8gWnwRV5SCW0tLjLO&9Z?K>FImeIxlGUgo0Zk`9Qzhj1eco~7XZy+hXc@YF&ZQ=? zn*^1O56yK^x{y}q`j7}blGCx%dydV!c7)g~tJzmHhV=W~jbWRRR{1<^oDK+1clprm zz$eCy7y9+?{E|YgkW~}}iB#I4XoJ*xr8R?i_Hv$=Cof5bo-Nj~f`-DLebH}&0% zfQj9@WGd4;N~Y?mzQsHJTJq6!Qzl^-vwol(+fMt#Pl=Wh#lI5Vmu@QM0=_r+1wHt` z+8WZ~c2}KQQ+q)~2Ki77QvV&`xb|xVcTms99&cD$Zz4+-^R4kvUBxG8gDk7Y`K*)JZ^2rL(+ZWV~%W(@6 z)0bPArG#BROa_PHs~&WplQ_UIrpd)1N1QGPfv!J(Z9jNT#i%H?CE6|pPZb9hJ1JW4 z^q;ft#!HRNV0YgPojzIYT`8LuET2rUe-J|c!9l4`^*;4WtY@Ew@pL>wkjmMgGfN7 ze}}GtmU0@<_#08~I-Suk=^*9GLW=H4xhsml;vAV{%hy5Eegl@!6qKqbG024%n2HHw zCc@ivW_$@5ZoHP70(7D+(`PvgjW1Pd`wsiuv-aCukMrafwDm)B!xXVy*j2opohhoU zcJz%ADmj>i3`-3-$7nQKBQQuGY;2Qt&+(L~C>vSGFj5{Mlv?T_^dql;{zkpe4R1}R z%XfZyQ}wr*sr>jrKgm*PWLjuVc%6&&`Kbf1SuFpHPN&>W)$GmqC;pIoBC`=4-hPY8 zT*>%I2fP}vGW;R=^!1be?ta2UQd2>alOFFbVl;(SQJ4Jk#)4Z0^wpWEVvY4=vyDk@ zqlModi@iVPMC+{?rm=4(n+<;|lmUO@UKYA>EPTS~AndtK^Wy^%#3<;(dQdk3WaUkRtzSMC9}7x2||CNpF#(3T4C)@ z$~RWs`BNABKX|{cmBt>Q=&gkXl&x!!NK_%5hW0LS)Z4PB>%sV?F-{Wyj#s7W%$F{D zXdK^Fp3wvy+48+GP6F_|^PCRx=ddcTO3sG;B23A49~Qaw31SZ0Rc~`r4qqt%#OGW{ zCA_(LG5^N>yzUn&kAgVmxb=EA8s&tBXC}S1CZ(KoW)(%^JjLTPo^fs`Va;`=YlVPgmB$!yB}<(4ym6OeZ3xAJJ#;)2+B%p3P1Wt+d$eo`vz`T zXfUP2))kBDPoscH;Jc7I3NU<({|@wM$&GaDt`n7WLgIY3IA7A6-_R?z8N3mz|}*i z(zl5ot--Oq@f2-nv{X(ujT2T(k1vY_qh93pK@>H-qc%2Xta)IP0Q%zt%bqYgI`o!wv!0QerB`nCN^1n|@$sVOQ!V0teVG!I z_fD%JvfDeT1cK#-{o6Gv7}& zY0#NWin~kVaf$aufV&;63Hbs|`QVZWpDX6IMk1Hj2G}fiH9e-^6u2zf^FIr^BwD<6zjw63+{yUe8PUFvk8v{sJ=R{d#`O!sz`Q13~< zPT$JS(w=yQfU2`zPCNfSw=&zup@DXc(98afjhv@1w_f!m2Z>rMJ19AB&dB%P#Ls3b z=lK7OILM+SQ&VEd=1GN6o&>YVVtIzoZ%=Z_SdqJN2}E43{bE`>w+A;=y->@^k{oCC z$F*WTY&?34;kfyFV?b*Xb1Pq`Z=%OgwEg)Rz)tx=`f%5#w_INP=x&z5!jI;#;N$ma zhO)+MDm;SxOEVL15; zGq(v2pL3&P1Sl)8P*;G-fd{l1QJsv@e@d8)1PK4w2m*M%V3j-V~L^$i|&C@b?D?9tfwE{B^}Z$k8e5FmQ>v7Xz)sG32g9t}YBt zyR$+*_00RmPx+0mW+vVG4mxd(n$(eQf3-w>JPl2UJpafrPaL5@2j}%{VE-) zBI%6Qpj*dsdH<;g!S!avA~bv^0E+ zfyJbSjPb+j;J52U)<|cIcntQBI2T#>2;tOxu{%D?kML476AErF(qN9hPva5Nkc@BF zC-tLF@3ZFb%Kpj)M<{)x*l|*Ia@ECeXo2E4h2f!aV=cHAhi_E_mfUth(sM4^hJq7B zQsGWqdZUm9S%F`$nQ*_#NcuD`&)Ek%_s{&^78{9Hm ztri&rYLOxgFdG>O@+XHy z9#;|&vBCPXH5Mon^I`jSuR$&~ZWtyB67ujzFSj!51>#C}C17~TffQ{c-!QFQkTQ%! zIR^b1`zHx|*1GU?tbBx23weFLz5H?y_Q%N&t$}k?w+``2A=aotj0;2v$~AL z{scF-cL{wsdrmPvf#a9OHyYLcwQD4Kcm)`LLwMh4WT~p29f7M!iafJSU`IV}QY5Wa z(n44-9oA}?J{a+ah*@31WTs#&J#o1`H98#6IQf;Wv0N_!);f&9g7o-k(lW5rWnDUR zQBFIRG+X=6NnsI@mxnwm;tf5;_Uxg?jZ8m-m0}&6+DA!qam(p$mN5R})yA_7m$q@| zFEd|dpS595rxQr-n#GjI5i-AhnUE>Cr;jpCqSrD~EwK_DqI^7%3#p5)%T_od!t3SOmH9MyXeeGO2(UQL;ax|x?Ncixmeo1=$ z{-);Au{*tfzOG?KQ~K|ak8-HQ?`Pekhe2WM(8s{xv-p>Zmu_6{G!-oE$7$mY`MOJorI=+mMx?H;`pr!;fVYz?5~yXBACruWB`Ph zZM}90_<^OBxIhyZ9BW$`>6JvO;%VFpqVr8|7t3~AmxYak6?`Pp#c;**_SYmi`&z23 z`p6_~ePvH)C6x-G9$hgL=eVALq`-AiamN>!3~Lxw&{H(b{B(7xSRm6<3<{%{yXiH# zos5Rv1L+8fUKJLo%P>4I&$}y { - if (item.viewTag == eventData.viewTag) { - removeIndex = index; - } - }); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_ARRAY).splice(removeIndex, 1); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP).delete(eventData.viewTag); - break; - } - case "setCurrentText": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.text = eventData.text; - break; - } - case "setEditBoxViewRect": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.x = eventData.viewRect.x; - textInputInfo.y = eventData.viewRect.y; - textInputInfo.w = eventData.viewRect.w; - textInputInfo.h = eventData.viewRect.h; - break; - } - case "setEditBoxVisible": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.visible = eventData.visible; - break; - } - case "setEditBoxFontSize": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.fontSize = eventData.fontSize; - break; - } - case "setEditBoxFontColor": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.fontColor = new FontColor(eventData.color.r, eventData.color.g, eventData.color.b, eventData.color.a / 255); - break; - } - case "setEditBoxPlaceHolderFontSize": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.placeholderFontSize = eventData.placeHolderSize; - break; - } - case "setEditBoxPlaceHolderFontColor": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.placeholderFontColor = new FontColor(eventData.placeHolderColor.r, eventData.placeHolderColor.g, eventData.placeHolderColor.b, eventData.placeHolderColor.a / 255); - break; - } - case "setEditBoxPlaceHolder": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.placeHolder = eventData.placeHolderText; - break; - } - case "setEditBoxMaxLength": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.maxLength = eventData.maxLength; - break; - } - case "setNativeInputMode": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.multiline = (eventData.inputMode == 0) ? true : false; - if (textInputInfo.inputMode != InputType.Password) { - switch (eventData.inputMode) { - case 0: - case 4: - case 6: - textInputInfo.inputMode = InputType.Normal; - break; - case 2: - case 5: - textInputInfo.inputMode = InputType.Number; - break; - case 3: - textInputInfo.inputMode = InputType.PhoneNumber; - break; - case 1: - textInputInfo.inputMode = InputType.Email; - break; - default: - break; - } - } - break; - } - case "setNativeInputFlag": { - // Any type can be changed to a password. The password can be changed to any type, - // but the password is mapped to the general type. Other changes are not allowed. - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - if (eventData.inputFlag == 0) { - textInputInfo.inputMode = InputType.Password; - } else if (textInputInfo.inputMode == InputType.Password) { - textInputInfo.inputMode = InputType.Normal; - } - break; - } - case "setEditBoxFontPath": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.fontPath = eventData.fontPath; - break; - } - case "setEditBoxPlaceHolderFontPath": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.placeHolderFontPath = eventData.placeHolderFontPath; - break; - } - case "hideAllEditBox": { - let editBoxArray: TextInputInfo[] = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_ARRAY); - editBoxArray.forEach(item => { - if (item.visible) { - item.visible = false; - let cocosWorker: worker.ThreadWorker = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_COCOS_WORKER); - cocosWorker.postMessage({ type: "editBoxOnEnter", viewTag: item.viewTag, text: item.text }) - } - }) - break; - } - } -} diff --git a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayer.ts b/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayer.ts deleted file mode 100644 index 50b7a7e69d00..000000000000 --- a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayer.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { VideoPlayMsgEntity, ViewRect } from '../../entity/WorkerMsgEntity'; - -export class VideoPlayer { - static MODULE_NAME: string = 'VideoPlay'; - - private static workerPort; - - static init(workerPort) : void { - VideoPlayer.workerPort = workerPort; - } - - static setURL(viewTag: number, url: string, isUrl: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'setURL', viewTag); - videoPlayMsgEntity.url = url; - videoPlayMsgEntity.isUrl = isUrl; - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static setLooping(viewTag: number, isLoop: boolean) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'setLooping', viewTag); - videoPlayMsgEntity.isLoop = isLoop; - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static createVideoPlayer(viewTag: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'createVideoPlayer', viewTag); - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static removeVideoPlayer(viewTag: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'removeVideoPlayer', viewTag); - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static setVideoPlayerRect(viewTag: number, x: number, y: number, w: number, h: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'setVideoPlayerRect', viewTag); - let viewRect: ViewRect = new ViewRect(x, y, w, h); - videoPlayMsgEntity.viewRect = viewRect; - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static play(viewTag: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'play', viewTag); - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - static pause(viewTag: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'pause', viewTag); - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static stop(viewTag: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'stop', viewTag); - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static setVisible(viewTag: number, visible: boolean) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'setVisible', viewTag); - videoPlayMsgEntity.visible = visible - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static requestFullscreen(viewTag: number, isFullScreen: boolean) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'requestFullscreen', viewTag); - videoPlayMsgEntity.isFullScreen = isFullScreen; - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static seekTo(viewTag: number, seekTo: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'seekTo', viewTag); - videoPlayMsgEntity.seekTo = seekTo; - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static setKeepAspectRatioEnabled(viewTag: number, enable: boolean) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'setKeepAspectRatioEnabled', viewTag); - videoPlayMsgEntity.keepAspectRatioEnabled = enable; - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } -} diff --git a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayerMsg.ets b/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayerMsg.ets deleted file mode 100644 index f11bdac82c9a..000000000000 --- a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayerMsg.ets +++ /dev/null @@ -1,145 +0,0 @@ -import Logger from '../../utils/Logger' -import { BusinessError } from '@ohos.base'; -import { GlobalContext,GlobalContextConstants } from "../../common/GlobalContext" -import { VideoPlayMsgEntity } from '../../entity/WorkerMsgEntity'; - -let log: Logger = new Logger(0x0001, "VideoPlayerMsg"); - -@Observed -export class VideoPlayerInfo { - // position - public x: number = 0; - public y: number = 0; - // size - public w: number = 0; - public h: number = 0; - // url - public url: string = '' - - public rawfile?: Resource; - public isUrl: boolean = false - // tag - public viewTag: number = 0 - - public isPlay: boolean = false - public isFullScreen: boolean = false - - // Whether to display - public visible: boolean = true - - public isLoop: boolean = false - - public objectFit: ImageFit = ImageFit.Auto - - public controller: VideoController = new VideoController() - - constructor(x: number, y: number, w: number, h: number, viewTag: number) { - this.x = x; - this.y = y; - this.w = w; - this.h = h; - this.viewTag = viewTag; - } -} - -export enum VideoEvent { - PLAYING = 0, - PAUSED, - STOPPED, - COMPLETED, -} - -export function handleVideoPlayMsg(eventData: VideoPlayMsgEntity) { - - switch (eventData.function) { - case "createVideoPlayer": { - let newVideoPlayerInfo = new VideoPlayerInfo(0, 0, 0, 0, eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_ARRAY).push(newVideoPlayerInfo); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).set(eventData.viewTag, newVideoPlayerInfo); - break; - } - case "removeVideoPlayer": { - let removeIndex = -1; - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_ARRAY).forEach((item:VideoPlayerInfo,index:number) => { - if (item.viewTag == eventData.viewTag) { - removeIndex = index; - } - }); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag).controller.requestFullscreen(false); //4.x已修复 - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_ARRAY).splice(removeIndex, 1); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).delete(eventData.viewTag); - break; - } - case "play": { - let videoPlayInfo :VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.controller.start(); - videoPlayInfo.isPlay = true; - break; - } - case "pause": { - let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.controller.pause(); - videoPlayInfo.isPlay = false; - break; - } - case "stop": { - let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.controller.stop(); - videoPlayInfo.isPlay = false; - break; - } - case "setURL": { - let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - if(eventData.isUrl == 0) { - videoPlayInfo.isUrl = false; - videoPlayInfo.rawfile = $rawfile(eventData.url); - } else { - videoPlayInfo.isUrl = true; - videoPlayInfo.url = eventData.url; - } - break; - } - case "setLooping": { - let videoPlayInfo: VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.isLoop = eventData.isLoop; - break; - } - case "setVideoPlayerRect": { - let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - try { - videoPlayInfo.x = px2vp(eventData.viewRect.x); - videoPlayInfo.y = px2vp(eventData.viewRect.y); - videoPlayInfo.w = px2vp(eventData.viewRect.w); - videoPlayInfo.h = px2vp(eventData.viewRect.h); - } catch (error) { - let e: BusinessError = error as BusinessError; - log.error('videoPlayerInfo ErrorCode: %{public}d, Message: %{public}s', e.code, e.message); - } - break; - } - case "setVisible": { - let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - if (videoPlayInfo.visible == eventData.visible) { - return; - } - videoPlayInfo.visible = eventData.visible; - break; - } - case "requestFullscreen": { - let videoPlayInfo: VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.controller.requestFullscreen(eventData.isFullScreen); - videoPlayInfo.isFullScreen = eventData.isFullScreen; - break; - } - case "seekTo": { - let videoPlayInfo: VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.controller.setCurrentTime(eventData.seekTo, SeekMode.Accurate); - break; - } - case "setKeepAspectRatioEnabled": { - let videoPlayInfo: VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.objectFit = eventData.keepAspectRatioEnabled? ImageFit.Cover : ImageFit.Auto; - break; - } - } -} \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebView.ts b/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebView.ts deleted file mode 100644 index 872ec4ce70fe..000000000000 --- a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebView.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { ViewRect, WebViewMsgEntity } from '../../entity/WorkerMsgEntity'; - -export class WebView { - static MODULE_NAME: string = 'WebView'; - - private static workerPort; - - static init(workerPort) : void { - WebView.workerPort = workerPort; - } - - static createWebView(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'createWebView', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static removeWebView(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'removeWebView', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static setJavascriptInterfaceScheme(viewTag: number, jsInterfaceScheme: string) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'setJavascriptInterfaceScheme', viewTag); - webViewMsgEntity.jsInterfaceScheme = jsInterfaceScheme; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static loadData(viewTag: number, data: string, mimeType: string, encoding: string, baseURL: string) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'loadData', viewTag); - webViewMsgEntity.data = data; - webViewMsgEntity.mimeType = mimeType; - webViewMsgEntity.encoding = encoding; - webViewMsgEntity.baseURL = baseURL; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static loadURL(viewTag: number, url: string) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'loadURL', viewTag); - webViewMsgEntity.url = url; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static loadFile(viewTag: number, filePath: string) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'loadFile', viewTag); - webViewMsgEntity.filePath = filePath; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static stopLoading(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'stopLoading', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static reload(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'reload', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static canGoBack(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'canGoBack', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static canGoForward(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'canGoForward', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static goBack(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'goBack', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static goForward(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'goForward', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static setWebViewRect(viewTag: number, x: number, y: number, w: number, h: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'setWebViewRect', viewTag); - let viewRect: ViewRect = new ViewRect(x, y, w, h); - webViewMsgEntity.viewRect = viewRect; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static setVisible(viewTag: number, visible: boolean) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'setVisible', viewTag); - webViewMsgEntity.visible = visible; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static setOpacityWebView(viewTag: number, opacity: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'setOpacityWebView', viewTag); - webViewMsgEntity.opacity = opacity; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static setBackgroundTransparent(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'setBackgroundTransparent', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static evaluateJS(viewTag: number, js: string) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'evaluateJS', viewTag); - webViewMsgEntity.js = js; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static setScalesPageToFit(viewTag: number, scalesPageToFit: boolean) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'setScalesPageToFit', viewTag); - webViewMsgEntity.scalesPageToFit = scalesPageToFit; - WebView.workerPort.postMessage(webViewMsgEntity); - } -} \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebViewMsg.ets b/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebViewMsg.ets deleted file mode 100644 index 24e1f86d9779..000000000000 --- a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebViewMsg.ets +++ /dev/null @@ -1,245 +0,0 @@ -import web_webview from '@ohos.web.webview' -import Logger from '../../utils/Logger'; -import { GlobalContext, GlobalContextConstants } from '../../common/GlobalContext'; -import { WebViewMsgEntity } from '../../entity/WorkerMsgEntity'; -import { BusinessError } from '@ohos.base'; - -let log: Logger = new Logger(0x0001, "WebViewMsg"); - -export class WebViewInfo { - public uniqueId : number = 0; - // position - public x: number = 0; - public y: number = 0; - // size - public w: number = 0; - public h: number = 0; - // url - public url: string = ''; - public isUrl: boolean = true; - - public viewTag: number = 0 - public zoomAccess: boolean = true - public visible: boolean = true - public opacity: number = 1 - public backgroundColor: number = 0xffffff; - public jsInterfaceScheme: string = ""; - public controller: web_webview.WebviewController = new web_webview.WebviewController() - - constructor(x: number, y: number, w: number, h: number, viewTag: number) { - this.x = x; - this.y = y; - this.w = w; - this.h = h; - this.viewTag = viewTag - this.uniqueId = viewTag; - } -} - -function copyWebViewInfo(viewInfo: WebViewInfo) : WebViewInfo { - let newViewInfo: WebViewInfo = new WebViewInfo(viewInfo.x, viewInfo.y, viewInfo.w, viewInfo.h, viewInfo.viewTag); - newViewInfo.url = viewInfo.url; - newViewInfo.isUrl = viewInfo.isUrl; - newViewInfo.zoomAccess = viewInfo.zoomAccess; - newViewInfo.visible = viewInfo.visible; - newViewInfo.controller = viewInfo.controller; - newViewInfo.opacity = viewInfo.opacity; - newViewInfo.backgroundColor = viewInfo.backgroundColor; - newViewInfo.jsInterfaceScheme = viewInfo.jsInterfaceScheme; - newViewInfo.uniqueId = 100000 - viewInfo.uniqueId; // support 50000 webView exist at the same time - return newViewInfo; -} - -function waitUtilControllerAttached() : Promise { - return new Promise((resolve, reject) => { - resolve(1); - }) -} - -export function handleWebViewMsg(eventData: WebViewMsgEntity) { - let index: number; - switch (eventData.function) { - case "createWebView": { - let view = new WebViewInfo(0, 0, 0, 0, eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY).push(view); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP) - .set(eventData.viewTag, GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY) - .length - 1); - break; - } - case "removeWebView": { - if (GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY).length > 0) { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY).splice(index, 1); - // Do not assume the invoking time of removeWebView. After an element is deleted, the following elements need to be advanced by one bit. - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP) - .forEach((value: number, key: number, map: Map) => { - if (value > index) { - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).set(key, value - 1); - } - }) - - // Delete the subscript mapping of the removed webView. - let tempInfoMap: Map = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP); - tempInfoMap.delete(eventData.viewTag); - } - break; - } - case "setJavascriptInterfaceScheme": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - webViewInfo.jsInterfaceScheme = eventData.jsInterfaceScheme; - break; - } - case "loadData": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - waitUtilControllerAttached().then(() => { - webViewInfo.controller.loadData(eventData.data, eventData.mimeType, eventData.encoding, eventData.baseURL) - }); - break; - } - case "loadURL": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index].url = eventData.url; - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index].isUrl = true; - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - waitUtilControllerAttached().then(() => { - webViewInfo.controller.loadUrl(eventData.url); - }) - break; - } - case "loadFile": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index].url = eventData.filePath; - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index].isUrl = false; - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - waitUtilControllerAttached().then(() => { - webViewInfo.controller.loadUrl($rawfile(eventData.filePath)); - }) - break; - } - case "stopLoading": - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index].controller.stop(); - break; - case "reload": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - waitUtilControllerAttached().then(() => { - webViewInfo.controller.refresh(); - }) - break; - } - case "canGoBack": - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let result: number = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .controller - .accessBackward(); - // todo The value needs to be sent back to the worker thread. - break; - case "canGoForward": - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - result = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .controller - .accessForward(); - // todo The value needs to be sent back to the worker thread. - break; - case "goBack": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - waitUtilControllerAttached().then(() => { - webViewInfo.controller.backward(); - }) - break; - } - case "goForward": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - waitUtilControllerAttached().then(() => { - webViewInfo.controller.forward(); - }) - break; - } - case "setWebViewRect": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let tmpWebInfo :WebViewInfo= GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - tmpWebInfo.x = px2vp(eventData.viewRect.x); - tmpWebInfo.y = px2vp(eventData.viewRect.y); - tmpWebInfo.w = px2vp(eventData.viewRect.w); - tmpWebInfo.h = px2vp(eventData.viewRect.h); - let newViewInfo:WebViewInfo = copyWebViewInfo(tmpWebInfo); - let tempInfoArray :WebViewInfo[]= GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY); - tempInfoArray[index] = newViewInfo; - break; - } - case "setVisible": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - if (GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .visible == eventData.visible) { - return; - } - let tmpWebInfo:WebViewInfo= GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - tmpWebInfo.visible = eventData.visible; - let newViewInfo:WebViewInfo = copyWebViewInfo(tmpWebInfo); - let tempInfoArray :WebViewInfo[]= GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY); - tempInfoArray[index] = newViewInfo; - break; - } - case "setOpacityWebView": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - if (GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .opacity == eventData.opacity) { - return; - } - let tmpWebInfo :WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - tmpWebInfo.opacity = eventData.opacity; - let newViewInfo :WebViewInfo= copyWebViewInfo(tmpWebInfo); - let tempInfoArray :WebViewInfo[]= GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY); - tempInfoArray[index] = newViewInfo; - break; - } - case "setBackgroundTransparent": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - if (GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .backgroundColor == Color.Transparent) { - return; - } - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .backgroundColor = Color.Transparent; - let newViewInfo :WebViewInfo= copyWebViewInfo(GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]); - let tempInfoArray :WebViewInfo[]= GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY); - tempInfoArray[index] = newViewInfo; - break; - } - case "evaluateJS": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .controller - .runJavaScript(eventData.js, (error:BusinessError, result:string) => { - if (error) { - log.warn("webView run JavaScript error:%{public}s", JSON.stringify(error)); - return; - } - if (result) { - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_WEB_RESULT,result) - log.debug("webView run JavaScript result is %{public}s:", result); - } - }) - break; - } - case "setScalesPageToFit": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - if (GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .zoomAccess == eventData.scalesPageToFit) { - return; - } - let tmpWebInfo:WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - tmpWebInfo.zoomAccess == eventData.scalesPageToFit - let newViewInfo:WebViewInfo = copyWebViewInfo(tmpWebInfo); - let tempInfoArray:WebViewInfo[] = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY); - tempInfoArray[index] = newViewInfo; - } - break; - } -} diff --git a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/entity/Result.ts b/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/entity/Result.ts deleted file mode 100644 index dd9e38897da3..000000000000 --- a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/entity/Result.ts +++ /dev/null @@ -1,16 +0,0 @@ -export class Result { - public static success(data){ - return { - "errCode": 0, - "errMsg": "", - "data": data, - }; - } - - public static error(errCode, errMsg) { - return { - "errCode": errCode, - "errMsg": errMsg, - }; - } -}; \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/entity/TextInputDialogEntity.ts b/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/entity/TextInputDialogEntity.ts deleted file mode 100644 index 39d272a0b68c..000000000000 --- a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/entity/TextInputDialogEntity.ts +++ /dev/null @@ -1,7 +0,0 @@ -export class TextInputDialogEntity { - message : string; - - constructor(msg: string) { - this.message = msg; - } -} \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/entity/WorkerMsgEntity.ts b/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/entity/WorkerMsgEntity.ts deleted file mode 100644 index 70216b1e14e5..000000000000 --- a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/entity/WorkerMsgEntity.ts +++ /dev/null @@ -1,141 +0,0 @@ -export class ViewRect { - x: number - y: number - w: number - h: number - - constructor(x: number, y: number, w: number, h: number) { - this.x = x; - this.y = y; - this.w = w; - this.h = h; - } -} - -export class Color4B { - r: number - g: number - b: number - a: number - - constructor(r: number, g: number, b: number, a: number) { - this.r = r; - this.g = g; - this.b = b; - this.a = a; - } -} - -export class BaseWorkerMsgEntity { - module: string; - - function: string; - - constructor(module: string, func: string) { - this.module = module; - this.function = func; - } -} - -export class DialogMsgEntity extends BaseWorkerMsgEntity { - title: string; - - message: string; - - constructor(module: string, func: string) { - super(module, func); - } -} - -export class EditBoxMsgEntity extends BaseWorkerMsgEntity { - viewTag: number - - viewRect: ViewRect - - paddingW: number - paddingH: number - - visible: boolean - - text: string - fontSize: number - color: Color4B - fontPath: string - - placeHolderText: string - placeHolderSize: number - placeHolderColor: Color4B - placeHolderFontPath: string - - maxLength: number - - inputMode: number - - inputFlag: number - - constructor(module: string, func: string, viewTag?: number) { - super(module, func); - this.viewTag = viewTag; - } -} - -export class VideoPlayMsgEntity extends BaseWorkerMsgEntity { - viewTag: number - - url: string - isUrl: number - - isLoop: boolean - - viewRect: ViewRect - - visible: boolean - - isFullScreen: boolean - - seekTo: number - - keepAspectRatioEnabled: boolean - - constructor(module: string, func: string, viewTag: number) { - super(module, func); - this.viewTag = viewTag; - } -} - -export class WebViewMsgEntity extends BaseWorkerMsgEntity { - viewTag: number - - data: string - mimeType: string - encoding: string - baseURL: string - - url: string - - filePath: string - - viewRect: ViewRect - - visible: boolean - - opacity: number - - js: string - - scalesPageToFit: boolean - jsInterfaceScheme: string - - constructor(module: string, func: string, viewTag: number) { - super(module, func); - this.viewTag = viewTag; - } -} - -export class JumpMsgEntity extends BaseWorkerMsgEntity { - url: string; - - constructor(module: string, func: string) { - super(module, func); - } -} diff --git a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/napi/NapiHelper.ts b/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/napi/NapiHelper.ts deleted file mode 100644 index d4df1a5f9806..000000000000 --- a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/napi/NapiHelper.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { Dialog } from '../components/dialog/DialogWorker' -import StringUtils from '../utils/StringUtils' -import { JumpManager } from '../system/appJump/JumpManager' -import { DeviceUtils } from '../system/device/DeviceUtils' -import { ApplicationManager } from '../system/application/ApplicationManager' -import { CocosEditBox } from '../components/editbox/CocosEditBox' -import { WebView } from '../components/webview/WebView' -import { VideoPlayer } from '../components/videoplayer/VideoPlayer' -import Accelerometer from '../system/sensor/AccelerometerUtils' -import Preferences from '../preferences/Preferences' - -export class NapiHelper { - - static registerFunctions(registerFunc : Function) { - NapiHelper.registerOthers(registerFunc); - NapiHelper.registerDeviceUtils(registerFunc); - NapiHelper.registerEditBox(registerFunc); - NapiHelper.registerWebView(registerFunc); - NapiHelper.registerVideoPlay(registerFunc); - NapiHelper.registerSensor(registerFunc); - NapiHelper.registerPreferences(registerFunc); - } - - private static registerOthers(registerFunc : Function) { - registerFunc('DiaLog.showDialog', Dialog.showDialog); - registerFunc('DiaLog.showTextInputDialog', Dialog.showTextInputDialog); - registerFunc('DiaLog.hideTextInputDialog', Dialog.hideTextInputDialog); - registerFunc('StringUtils.getWidth', StringUtils.getWidth); - registerFunc('ApplicationManager.exit', ApplicationManager.exit); - registerFunc('ApplicationManager.getVersionName', ApplicationManager.getVersionName); - registerFunc('JumpManager.openUrl', JumpManager.openUrl); - } - - private static registerDeviceUtils(registerFunc : Function) { - registerFunc('DeviceUtils.getDpi', DeviceUtils.getDpi); - registerFunc('DeviceUtils.getSystemLanguage', DeviceUtils.getSystemLanguage); - registerFunc('DeviceUtils.startVibration', DeviceUtils.startVibration); - registerFunc('DeviceUtils.setKeepScreenOn', DeviceUtils.setKeepScreenOn); - registerFunc('DeviceUtils.isRoundScreen', DeviceUtils.isRoundScreen); - registerFunc('DeviceUtils.hasSoftKeys', DeviceUtils.hasSoftKeys); - registerFunc('DeviceUtils.isCutoutEnable', DeviceUtils.isCutoutEnable); - registerFunc('DeviceUtils.initScreenInfo', DeviceUtils.initScreenInfo); - registerFunc('DeviceUtils.getOrientation', DeviceUtils.getOrientation); - registerFunc('DeviceUtils.getCutoutHeight', DeviceUtils.getCutoutHeight); - registerFunc('DeviceUtils.getCutoutWidth', DeviceUtils.getCutoutWidth); - } - - private static registerEditBox(registerFunc : Function) { - registerFunc('CocosEditBox.createCocosEditBox', CocosEditBox.createCocosEditBox); - registerFunc('CocosEditBox.removeCocosEditBox', CocosEditBox.removeCocosEditBox); - registerFunc('CocosEditBox.setCurrentText', CocosEditBox.setCurrentText); - registerFunc('CocosEditBox.setEditBoxViewRect', CocosEditBox.setEditBoxViewRect); - registerFunc('CocosEditBox.setEditBoxVisible', CocosEditBox.setEditBoxVisible); - registerFunc('CocosEditBox.setEditBoxPlaceHolder', CocosEditBox.setEditBoxPlaceHolder); - registerFunc('CocosEditBox.setEditBoxFontSize', CocosEditBox.setEditBoxFontSize); - registerFunc('CocosEditBox.setEditBoxFontColor', CocosEditBox.setEditBoxFontColor); - registerFunc('CocosEditBox.setEditBoxFontPath', CocosEditBox.setEditBoxFontPath); - registerFunc('CocosEditBox.setEditBoxPlaceHolderFontSize', CocosEditBox.setEditBoxPlaceHolderFontSize); - registerFunc('CocosEditBox.setEditBoxPlaceHolderFontColor', CocosEditBox.setEditBoxPlaceHolderFontColor); - registerFunc('CocosEditBox.setEditBoxPlaceHolderFontPath', CocosEditBox.setEditBoxPlaceHolderFontPath); - registerFunc('CocosEditBox.setEditBoxMaxLength', CocosEditBox.setEditBoxMaxLength); - registerFunc('CocosEditBox.setNativeInputMode', CocosEditBox.setNativeInputMode); - registerFunc('CocosEditBox.setNativeInputFlag', CocosEditBox.setNativeInputFlag); - registerFunc('CocosEditBox.hideAllEditBox', CocosEditBox.hideAllEditBox); - } - - private static registerWebView(registerFunc : Function) { - registerFunc('WebView.createWebView', WebView.createWebView); - registerFunc('WebView.removeWebView', WebView.removeWebView); - registerFunc('WebView.setJavascriptInterfaceScheme', WebView.setJavascriptInterfaceScheme); - registerFunc('WebView.loadData', WebView.loadData); - registerFunc('WebView.loadURL', WebView.loadURL); - registerFunc('WebView.loadFile', WebView.loadFile); - registerFunc('WebView.stopLoading', WebView.stopLoading); - registerFunc('WebView.reload', WebView.reload); - registerFunc('WebView.canGoBack', WebView.canGoBack); - registerFunc('WebView.canGoForward', WebView.canGoForward); - registerFunc('WebView.goBack', WebView.goBack); - registerFunc('WebView.goForward', WebView.goForward); - registerFunc('WebView.setWebViewRect', WebView.setWebViewRect); - registerFunc('WebView.setVisible', WebView.setVisible); - registerFunc('WebView.setOpacityWebView', WebView.setOpacityWebView); - registerFunc('WebView.setBackgroundTransparent', WebView.setBackgroundTransparent); - registerFunc('WebView.evaluateJS', WebView.evaluateJS); - registerFunc('WebView.setScalesPageToFit', WebView.setScalesPageToFit); - } - - private static registerVideoPlay(registerFunc : Function) { - registerFunc('VideoPlayer.createVideoPlayer', VideoPlayer.createVideoPlayer); - registerFunc('VideoPlayer.removeVideoPlayer', VideoPlayer.removeVideoPlayer); - registerFunc('VideoPlayer.setURL', VideoPlayer.setURL); - registerFunc('VideoPlayer.setLooping', VideoPlayer.setLooping); - registerFunc('VideoPlayer.setVideoPlayerRect', VideoPlayer.setVideoPlayerRect); - registerFunc('VideoPlayer.play', VideoPlayer.play); - registerFunc('VideoPlayer.pause', VideoPlayer.pause); - registerFunc('VideoPlayer.stop', VideoPlayer.stop); - registerFunc('VideoPlayer.setVisible', VideoPlayer.setVisible); - registerFunc('VideoPlayer.requestFullscreen', VideoPlayer.requestFullscreen); - registerFunc('VideoPlayer.seekTo', VideoPlayer.seekTo); - registerFunc('VideoPlayer.setKeepAspectRatioEnabled', VideoPlayer.setKeepAspectRatioEnabled); - } - - private static registerSensor(registerFunc : Function) { - registerFunc('Accelerometer.enable', Accelerometer.enable); - registerFunc('Accelerometer.disable', Accelerometer.disable); - } - - private static registerPreferences(registerFunc : Function) { - registerFunc('Preferences.get', Preferences.get); - registerFunc('Preferences.getAll', Preferences.getAll); - registerFunc('Preferences.put', Preferences.put); - registerFunc('Preferences.has', Preferences.has); - registerFunc('Preferences.delete', Preferences.delete); - registerFunc('Preferences.flush', Preferences.flush); - registerFunc('Preferences.clear', Preferences.clear); - } - -} diff --git a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/preferences/Preferences.ts b/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/preferences/Preferences.ts deleted file mode 100644 index e95e89b29d10..000000000000 --- a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/preferences/Preferences.ts +++ /dev/null @@ -1,218 +0,0 @@ -import Logger from '../utils/Logger'; -import data_preferences from '@ohos.data.preferences'; -import { BusinessError } from '@ohos.base'; -import common from '@ohos.app.ability.common'; -import { GlobalContext, GlobalContextConstants } from '../common/GlobalContext'; - -let log: Logger = new Logger(0x0001, "Preferences"); -let preferences: data_preferences.Preferences | null = null; -const PREFS_NAME: string = "Cocos2dxPreferences"; - -export default class Preferences { - - // 通过 preferencesName 获取Preferences实例 - static getPreferences(): data_preferences.Preferences { - let context: common.UIAbilityContext = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT); - try { - preferences = data_preferences.getPreferencesSync(context, {name: PREFS_NAME}); - log.info("Succeeded in getting preferences."); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to get preferences. code =" + code + ", message =" + message); - } - return preferences; - } - - /* - 通过 preferencesName 从缓存中移出指定的Preferences实例,若Preferences实例有对应的持久化文件,则同时删除其持久化文件。使用Promise异步回调。 - 调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 - */ - static deletePreferences(): void { - let context: common.UIAbilityContext = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT); - try { - data_preferences.deletePreferences(context, PREFS_NAME).then(() => { - log.info("Succeeded in deleting preferences."); - }); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to delete preferences. code =" + code + ", message =" + message); - } - } - - /* - 通过 preferencesName 从缓存中移出指定的Preferences实例,使用Promise异步回调。 - 应用首次调用getPreferences接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次getPreferences时不会再次从持久化文件中读取, - 直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。 - 调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 - */ - static removePreferencesFromCache(): void { - let context: common.UIAbilityContext = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT); - try { - data_preferences.removePreferencesFromCacheSync(context, PREFS_NAME); - log.info("Succeeded in removing preferences."); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to remove preferences. code =" + code + ", message =" + message); - } - } - - // 从缓存的Preferences实例中获取键对应的值,如果值为null或者非默认值类型,返回默认数据defValue - static get(key: string, defValue: data_preferences.ValueType): data_preferences.ValueType { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - let data = preferences.getSync(key, defValue); - log.info("Succeeded in getting value of 'startup'. Data: " + data); - return data; - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to get value of 'startup'. code =" + code + ", message =" + message); - return defValue; - } - } - - // 将数据写入缓存的Preferences实例中,可通过flush将Preferences实例持久化 - static put(key: string, value: data_preferences.ValueType): void { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - preferences.putSync(key, value); - log.info("Succeeded in put the key."); - Preferences.flush(); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to put. code =" + code + ", message =" + message); - } - } - - // 从缓存的Preferences实例中获取所有键值数据。 - static getAll(): string | undefined { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - let object = preferences.getAllSync(); - let allKeys = getObjKeys(object); - log.info('getAll keys = ' + allKeys); - log.info("getAll object = " + JSON.stringify(object)); - return JSON.stringify(object); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to getAll. code =" + code + ", message =" + message); - return undefined; - } - } - - // 检查缓存的Preferences实例中是否包含名为给定Key的存储键值对 - static has(key: string): boolean { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - let val = preferences.hasSync(key); - if (val) { - log.info("The key 'startup' is contained."); - return true; - } else { - log.info("The key 'startup' dose not contain."); - return false; - } - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to has. code =" + code + ", message =" + message); - return false; - } - } - - // 从缓存的Preferences实例中删除名为给定Key的存储键值对,可通过flush将Preferences实例持久化 - static delete(key: string): void { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - preferences.deleteSync(key); - log.info("Succeeded in deleting the key."); - Preferences.flush(); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to delete. code =" + code + ", message =" + message); - } - } - - // 将缓存的Preferences实例中的数据异步存储到用户首选项的持久化文件中,使用Promise异步回调。 - static flush(): void { - if (preferences === null) { - Preferences.getPreferences(); - } - preferences.flush().then(()=>{ - log.info("Succeeded in flushing."); - }); - } - - // 清除缓存的Preferences实例中的所有数据,可通过flush将Preferences实例持久化,使用Promise异步回调。 - static clear(): void { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - preferences.clearSync(); - log.info("Succeeded in clearing."); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to clear. code =" + code + ", message =" + message); - } - } - - - // 订阅数据变更,订阅的Key的值发生变更后,在执行flush方法后,触发callback回调。 - static onChange(cb: Function): void { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - preferences.on('change', (key: string) => { - log.info("The key " + key + " changed."); - cb(key); - }); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to flush. code =" + code + ", message =" + message); - } - } - - // 取消订阅数据变更。 - static offChange(cb: Function): void { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - preferences.off('change', (key: string) => { - log.info("The key " + key + " changed."); - cb(key); - }); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to flush. code =" + code + ", message =" + message); - } - } -} - -// 由于ArkTS中无Object.keys,且无法使用for..in... -// 若报ArkTS问题,请将此方法单独抽离至一个ts文件中并暴露,在需要用到的ets文件中引入使用 -function getObjKeys(obj: Object): string[] { - let keys = Object.keys(obj); - return keys; -} \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManager.ts b/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManager.ts deleted file mode 100644 index dfa95dfaa5ab..000000000000 --- a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManager.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { ThreadWorkerGlobalScope } from '@ohos.worker'; -import { JumpMsgEntity } from '../../entity/WorkerMsgEntity'; - -export class JumpManager { - - static MODULE_NAME: string = 'JumpManager'; - - private static workerPort: ThreadWorkerGlobalScope; - - static init(workerPort: ThreadWorkerGlobalScope) : void { - JumpManager.workerPort = workerPort; - } - - static openUrl(url: string) : void { - let jumpMsgEntity: JumpMsgEntity = new JumpMsgEntity(JumpManager.MODULE_NAME, 'openUrl'); - jumpMsgEntity.url = url; - JumpManager.workerPort.postMessage(jumpMsgEntity); - } -} diff --git a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManagerMsg.ts b/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManagerMsg.ts deleted file mode 100644 index ea373af90811..000000000000 --- a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManagerMsg.ts +++ /dev/null @@ -1,31 +0,0 @@ -import type common from '@ohos.app.ability.common'; -import { GlobalContext, GlobalContextConstants } from '../../common/GlobalContext'; -import {Result} from "../../entity/Result" -import type { JumpMsgEntity } from '../../entity/WorkerMsgEntity'; -import Logger from '../../utils/Logger' - -let log: Logger = new Logger(0x0001, "JumpManagerMsg"); - -export function handleJumpManagerMsg(eventData: JumpMsgEntity) : void { - switch (eventData.function) { - case "openUrl": - openUrl(eventData.url); - break; - default: - log.error('%{public}s has not implement yet', eventData.function); - } -} - -function openUrl(url: string): void { - let context: common.UIAbilityContext = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT); - let wantInfo = { - 'action': 'ohos.want.action.viewData', - 'entities': ['entity.system.browsable'], - 'uri': url - } - context.startAbility(wantInfo).then(() => { - log.info('%{public}s', JSON.stringify(Result.success({}))); - }).catch((err) => { - log.error('openUrl : err : %{public}s', JSON.stringify(Result.error(-1, JSON.stringify(err))) ?? ''); - }); -} \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/system/application/ApplicationManager.ts b/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/system/application/ApplicationManager.ts deleted file mode 100644 index 9a552f56e49f..000000000000 --- a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/system/application/ApplicationManager.ts +++ /dev/null @@ -1,54 +0,0 @@ -import bundleManager from '@ohos.bundle.bundleManager'; -import type { ThreadWorkerGlobalScope } from '@ohos.worker'; -import { BaseWorkerMsgEntity } from '../../entity/WorkerMsgEntity'; -import { common } from '@kit.AbilityKit'; -import { BusinessError } from '@kit.BasicServicesKit'; -import { GlobalContext, GlobalContextConstants } from '../../common/GlobalContext'; - -export class ApplicationManager { - static MODULE_NAME: string = 'ApplicationManager'; - - private static workerPort: ThreadWorkerGlobalScope; - - static init(workerPort: ThreadWorkerGlobalScope): void { - ApplicationManager.workerPort = workerPort; - } - - static exit(): void { - let workerMsg: BaseWorkerMsgEntity = new BaseWorkerMsgEntity(ApplicationManager.MODULE_NAME, 'exit'); - ApplicationManager.workerPort.postMessage(workerMsg); - } - - static getVersionName(): string { - let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; - return bundleManager.getBundleInfoForSelfSync(bundleFlags).versionName; - } -} - -export function handleApplicationMsg(eventData: BaseWorkerMsgEntity): void { - switch (eventData.function) { - case "exit": - terminateSelf(); - break; - default: - console.error('%{public}s has not implement yet', eventData.function); - } -} - -function terminateSelf(): void { - try { - let context: common.UIAbilityContext = - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT); - context.terminateSelf((err: BusinessError) => { - if (err.code) { - console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`); - return; - } - console.info('terminateSelf succeed'); - }); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - console.error(`terminateSelf failed, code is ${code}, message is ${message}`); - } -} diff --git a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/system/device/DeviceUtils.ts b/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/system/device/DeviceUtils.ts deleted file mode 100644 index b778f1584810..000000000000 --- a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/system/device/DeviceUtils.ts +++ /dev/null @@ -1,164 +0,0 @@ -import display from '@ohos.display' -import i18n from '@ohos.i18n'; -import vibrator from '@ohos.vibrator'; -import Logger from '../../utils/Logger'; -import window from '@ohos.window'; -import { GlobalContext, GlobalContextConstants } from '../../common/GlobalContext'; -import { Rect } from '@ohos.application.AccessibilityExtensionAbility'; - -let log = new Logger(0x0001, "DeviceUtils"); - -export class DeviceUtils { - static MODULE_NAME: string = 'DeviceUtils'; - static _roundScreen: boolean = false; - static _hasSoftKeys: boolean = false; - static _isCutoutEnable: boolean = false; - static _cutoutLeft: number; - static _cutoutWidth: number; - static _cutoutTop: number; - static _cutoutHeight: number; - - static getDpi(): number { - return display.getDefaultDisplaySync().densityDPI; - } - - static getSystemLanguage(): string { - return i18n.System.getSystemLanguage(); - } - - static startVibration(time: number) { - try { - vibrator.startVibration({ - type: 'time', - duration: time * 1000, // Seconds to milliseconds - }, { - id: 0, - usage: 'unknown' - }, (error) => { - if (error) { - log.error('vibrate fail, error.code: %{public}d, error.message: %{public}s', error.code, error.message); - return; - } - }); - } catch (err) { - log.error('error.code: %{public}d, error.message: %{public}s', err.code, err.message); - } - } - - static setKeepScreenOn(value: boolean) { - let windowClass = null; - try { - window.getLastWindow(GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT), (err, data) => { //获取窗口实例 - if (err.code) { - log.error('Failed to obtain last window when setKeepScreenOn. Cause:%{public}s', JSON.stringify(err)); - return; - } - windowClass = data; - // Sets whether the screen is always on. - let keepScreenOnPromise = windowClass.setWindowKeepScreenOn(value); - Promise.all([keepScreenOnPromise]).then(() => { - log.info('Succeeded in setKeepScreenOn, value:%{public}s', value); - }).catch((err) => { - log.error('Failed to setKeepScreenOn, cause:%{public}s', JSON.stringify(err)); - }); - }); - } catch (exception) { - log.error('Failed to get or set the window when setKeepScreenOn, cause:%{public}s', JSON.stringify(exception)); - } - } - - static isRoundScreen() : boolean { - return DeviceUtils._roundScreen; - } - - static hasSoftKeys() : boolean { - return DeviceUtils._hasSoftKeys; - } - - static isCutoutEnable() : boolean { - return DeviceUtils._isCutoutEnable; - } - - static initScreenInfo() : void { - let windowClass = null; - try { - window.getLastWindow(GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT), (err, data) => { - if (err.code) { - log.error('Failed to obtain last window when initScreenInfo. Cause:%{public}s', JSON.stringify(err)); - return; - } - - windowClass = data; - let windowProperties: window.WindowProperties = windowClass.getWindowProperties(); - DeviceUtils._roundScreen = windowProperties.isRoundCorner; - let rect: Rect = windowProperties.windowRect; - if(rect.top + rect.height < display.getDefaultDisplaySync().height) { - DeviceUtils._hasSoftKeys = true; - } else { - DeviceUtils._hasSoftKeys = false; - } - }); - } catch (exception) { - log.error('Failed to get or set the window when initScreenInfo, cause:%{public}s', JSON.stringify(exception)); - } - - display.getDefaultDisplaySync().getCutoutInfo().then((data) => { - if(data.boundingRects.length == 0) { - DeviceUtils._isCutoutEnable = false; - return; - } - - DeviceUtils._isCutoutEnable = true; - DeviceUtils._cutoutLeft = data.boundingRects[0].left; - DeviceUtils._cutoutTop = data.boundingRects[0].top; - DeviceUtils._cutoutWidth = data.boundingRects[0].width; - DeviceUtils._cutoutHeight = data.boundingRects[0].height; - }).catch((err) => { - log.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); - }); - } - - static getOrientation() : number { - let orientation: display.Orientation = display.getDefaultDisplaySync().orientation; - - // If the system enumeration value changes, the processing logic in the C++ code needs to be changed. Therefore, the mapping is performed again. - if(orientation == display.Orientation.PORTRAIT) { - return 0; - } - - if(orientation == display.Orientation.LANDSCAPE) { - return 1; - } - - if(orientation == display.Orientation.PORTRAIT_INVERTED) { - return 2; - } - - if(orientation == display.Orientation.LANDSCAPE_INVERTED) { - return 3; - } - - return 4; - } - - static getCutoutHeight() : number { - if(DeviceUtils._cutoutHeight) { - let height = DeviceUtils._cutoutTop + DeviceUtils._cutoutHeight; - return height; - } - return 0; - } - - static getCutoutWidth() : number { - if(!DeviceUtils._cutoutWidth) { - return 0; - } - - let disPlayWidth = display.getDefaultDisplaySync().width; - if(DeviceUtils._cutoutLeft + DeviceUtils._cutoutWidth > disPlayWidth - DeviceUtils._cutoutLeft) { - return disPlayWidth - DeviceUtils._cutoutLeft; - } - - return DeviceUtils._cutoutLeft + DeviceUtils._cutoutWidth; - } -} \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/system/sensor/AccelerometerUtils.ts b/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/system/sensor/AccelerometerUtils.ts deleted file mode 100644 index 56309439f011..000000000000 --- a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/system/sensor/AccelerometerUtils.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { getContext } from "libnativerender.so"; -import { ContextType } from "../../common/Constants" -import sensor from '@ohos.sensor'; -import display from '@ohos.display'; -import {Result} from "../../entity/Result" -import Logger from '../../utils/Logger' - -let log: Logger = new Logger(0x0001, "AccelerometerUtils"); - -const accUtils = getContext(ContextType.SENSOR_API); - -export default class Accelerometer { - - private static instance = new Accelerometer(); - - static getInstance() : Accelerometer { - return Accelerometer.instance; - } - - static enable(intervalTime: number) : void { - try { - /* HarmonyOS allow multiple subscriptions, but the game only need one - so if the interval changed, cancel subscription and redo with the new interval */ - sensor.off(sensor.SensorId.ACCELEROMETER); - sensor.on(sensor.SensorId.ACCELEROMETER, function (data) { - let rotation = display.getDefaultDisplaySync().rotation; - if (rotation === 0) { - // Display device screen rotation 0° - accUtils.onAccelerometerCallBack(data.x, data.y, data.z, intervalTime); - } else if (rotation === 1) { - // Display device screen rotation 90° - accUtils.onAccelerometerCallBack(data.y, -data.x, data.z, intervalTime); - } else if (rotation === 2) { - // Display device screen rotation 180° - accUtils.onAccelerometerCallBack(-data.x, -data.y, data.z, intervalTime); - } else if (rotation === 3) { - // Display device screen rotation 270° - accUtils.onAccelerometerCallBack(-data.y, data.x, data.z, intervalTime); - } else { - log.error('Accelerometer init fail, err: %{public}s', JSON.stringify(Result.error(-1, 'unsupported rotation: ' + rotation))); - } - }, { interval: intervalTime }); - } catch (err) { - log.error('Accelerometer init fail, err: %{public}s', JSON.stringify(Result.error(-1, JSON.stringify(err))) ?? ''); - } - } - - static disable() : void { - try { - sensor.off(sensor.SensorId.ACCELEROMETER); - } catch (err) { - log.error('Accelerometer off fail, err: %{public}s', JSON.stringify(Result.error(-1, JSON.stringify(err))) ?? ''); - } - } -} \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/utils/Logger.ts b/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/utils/Logger.ts deleted file mode 100644 index 6277b0e1ab52..000000000000 --- a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/utils/Logger.ts +++ /dev/null @@ -1,27 +0,0 @@ -import hilog from '@ohos.hilog' - -export default class Logger { - private domain: number - private prefix: string - - constructor(domain : number, prefix: string) { - this.domain = domain - this.prefix = prefix - } - - debug(format: string, ...args: any[]) { - hilog.debug(this.domain, this.prefix, format, args) - } - - info(format: string, ...args: any[]) { - hilog.info(this.domain, this.prefix, format, args) - } - - warn(format: string, ...args: any[]) { - hilog.warn(this.domain, this.prefix, format, args) - } - - error(format: string, ...args: any[]) { - hilog.error(this.domain, this.prefix, format, args) - } -} \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/utils/StringUtils.ts b/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/utils/StringUtils.ts deleted file mode 100644 index 4e3d20ec55e1..000000000000 --- a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/utils/StringUtils.ts +++ /dev/null @@ -1,8 +0,0 @@ -import measure from '@ohos.measure'; - -export default class StringUtils { - - public static getWidth(text: string, fontSize: number, fontWeight: number): number { - return measure.measureText({ textContent: text, fontSize: fontSize + 'px', fontWeight: fontWeight }); - } -} \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/utils/WorkerMsgUtils.ets b/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/utils/WorkerMsgUtils.ets deleted file mode 100644 index b9cac7106b18..000000000000 --- a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/ets/utils/WorkerMsgUtils.ets +++ /dev/null @@ -1,42 +0,0 @@ -import worker, { MessageEvents } from '@ohos.worker'; -import Logger from './Logger'; -import { handleEditBoxMsg } from '../components/editbox/EditBoxMsg' -import { handleWebViewMsg } from '../components/webview/WebViewMsg' -import { handleVideoPlayMsg } from '../components/videoplayer/VideoPlayerMsg' -import { handleDialogMsg } from '../components/dialog/DialogMsg' -import { handleJumpManagerMsg } from '../system/appJump/JumpManagerMsg' -import { handleApplicationMsg } from '../system/application/ApplicationManager' -import { BaseWorkerMsgEntity, DialogMsgEntity, EditBoxMsgEntity, JumpMsgEntity, VideoPlayMsgEntity, WebViewMsgEntity } from '../entity/WorkerMsgEntity'; - -export class WorkerMsgUtils { - static workPort = worker.workerPort; - static log : Logger = new Logger(0x0001, 'WorkerMsgUtils') - - static async recvWorkerThreadMessage(event: MessageEvents) { - let eventData: BaseWorkerMsgEntity = event.data; - WorkerMsgUtils.log.debug('mainThread receiveMsg, module:%{public}s, function:%{public}s', eventData.module, eventData.function); - - switch (eventData.module) { - case 'EditBox': - handleEditBoxMsg(eventData as EditBoxMsgEntity); - break; - case "Dialog": - handleDialogMsg(eventData as DialogMsgEntity); - break; - case 'WebView': - handleWebViewMsg(eventData as WebViewMsgEntity); - break; - case 'VideoPlay': - handleVideoPlayMsg(eventData as VideoPlayMsgEntity); - break; - case 'JumpManager': - handleJumpManagerMsg(eventData as JumpMsgEntity); - break; - case 'ApplicationManager': - handleApplicationMsg(eventData as BaseWorkerMsgEntity); - break; - default: - WorkerMsgUtils.log.error('%{public}s has not implement yet', eventData.module); - } - } -} diff --git a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/module.json5 b/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/module.json5 deleted file mode 100644 index ff4b2e3e82bf..000000000000 --- a/tests/cpp-tests/proj.ohos/libSysCapabilities/src/main/module.json5 +++ /dev/null @@ -1,11 +0,0 @@ -{ - "module": { - "name": "libSysCapabilities", - "type": "har", - "deviceTypes": [ - "phone", - "tablet", - "2in1" - ] - } -} \ No newline at end of file diff --git a/tests/cpp-tests/proj.ohos/oh-package.json5 b/tests/cpp-tests/proj.ohos/oh-package.json5 deleted file mode 100644 index 89c79559f675..000000000000 --- a/tests/cpp-tests/proj.ohos/oh-package.json5 +++ /dev/null @@ -1,11 +0,0 @@ -{ - "modelVersion": "5.0.0", - "license": "", - "devDependencies": {}, - "author": "", - "name": "proj.ohos", - "description": "Please describe the basic information.", - "main": "", - "version": "1.0.0", - "dependencies": {} -} \ No newline at end of file diff --git a/tests/js-tests/project/proj.ohos b/tests/js-tests/project/proj.ohos new file mode 160000 index 000000000000..8d5e6a65a4b7 --- /dev/null +++ b/tests/js-tests/project/proj.ohos @@ -0,0 +1 @@ +Subproject commit 8d5e6a65a4b7b5015fbb83ea16e86bdf771956fb diff --git a/tests/js-tests/project/proj.ohos/.gitignore b/tests/js-tests/project/proj.ohos/.gitignore deleted file mode 100644 index f02e936298b3..000000000000 --- a/tests/js-tests/project/proj.ohos/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -/node_modules -/local.properties -/.idea -**/build -/.hvigor -.cxx -/.clangd -/.clang-format -/.clang-tidy -oh_modules -entry/src/main/resources/rawfile -libSysCapabilities/build -oh-package-lock.json5 diff --git a/tests/js-tests/project/proj.ohos/AppScope/app.json5 b/tests/js-tests/project/proj.ohos/AppScope/app.json5 deleted file mode 100644 index a4cc05523576..000000000000 --- a/tests/js-tests/project/proj.ohos/AppScope/app.json5 +++ /dev/null @@ -1,11 +0,0 @@ -{ - "app": { - "bundleName": "ohos.cocos3.16.2.js.tests", - "vendor": "example", - "versionCode": 1000000, - "versionName": "1.0.0", - "icon": "$media:app_icon", - "label": "$string:app_name", - "distributedNotificationEnabled": true - } -} diff --git a/tests/js-tests/project/proj.ohos/AppScope/resources/base/element/string.json b/tests/js-tests/project/proj.ohos/AppScope/resources/base/element/string.json deleted file mode 100644 index e9ffc0391d25..000000000000 --- a/tests/js-tests/project/proj.ohos/AppScope/resources/base/element/string.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "string": [ - { - "name": "app_name", - "value": "3.16.2_js_tests" - } - ] -} diff --git a/tests/js-tests/project/proj.ohos/AppScope/resources/base/media/app_icon.png b/tests/js-tests/project/proj.ohos/AppScope/resources/base/media/app_icon.png deleted file mode 100644 index ce307a8827bd75456441ceb57d530e4c8d45d36c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6790 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 - { - OHOS_LOGD("Cocos2dxRenderer_nativeInit() - branch 1"); - GLView *view = GLViewImpl::sharedOpenGLView(); - view->setFrameSize(w, h); - CCDirector::sharedDirector()->setOpenGLView(view); - - AppDelegate *pAppDelegate = new AppDelegate(); - CCApplication::sharedApplication()->run(); - } - else - { - OHOS_LOGD("Cocos2dxRenderer_nativeInit() - branch 2"); - ccGLInvalidateStateCache(); - CCShaderCache::sharedShaderCache()->reloadDefaultShaders(); - ccDrawInit(); - CCTextureCache::reloadAllTextures(); - CCNotificationCenter::sharedNotificationCenter()->postNotification(EVENT_COME_TO_FOREGROUND, NULL); - CCDirector::sharedDirector()->setGLDefaultValues(); - } -} - -} \ No newline at end of file diff --git a/tests/js-tests/project/proj.ohos/entry/src/main/cpp/napi_init.cpp b/tests/js-tests/project/proj.ohos/entry/src/main/cpp/napi_init.cpp deleted file mode 100644 index 29e456357c61..000000000000 --- a/tests/js-tests/project/proj.ohos/entry/src/main/cpp/napi_init.cpp +++ /dev/null @@ -1,39 +0,0 @@ -#include "platform/ohos/CCLogOhos.h" -#include "plugin_manager.h" - -/* - * function for module exports - */ -static napi_value Init(napi_env env, napi_value exports) -{ - napi_property_descriptor desc[] ={ - DECLARE_NAPI_FUNCTION("getContext", NapiManager::GetContext), - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); - - bool ret = NapiManager::GetInstance()->Export(env, exports); - if (!ret) { - OHOS_LOGE("Init failed"); - } - return exports; -} - -/* - * Napi Module define - */ -static napi_module nativerenderModule = { - .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = Init, - .nm_modname = "nativerender", - .nm_priv = ((void*)0), - .reserved = { 0 }, -}; -/* - * Module register function - */ -extern "C" __attribute__((constructor)) void RegisterModule(void) -{ - napi_module_register(&nativerenderModule); -} \ No newline at end of file diff --git a/tests/js-tests/project/proj.ohos/entry/src/main/cpp/types/libentry/index.d.ts b/tests/js-tests/project/proj.ohos/entry/src/main/cpp/types/libentry/index.d.ts deleted file mode 100644 index 6a9293652bfe..000000000000 --- a/tests/js-tests/project/proj.ohos/entry/src/main/cpp/types/libentry/index.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -import resmgr from '@ohos.resourceManager'; - -export interface CPPFunctions { - onCreate: () => void; - onShow: () => void; - onHide: () => void; - onBackPress: () => void; - onDestroy: () => void; - onPageShow: () => void; - onPageHide: () => void; - nativeResourceManagerInit: (resourceManager: resmgr.ResourceManager) => void; - writablePathInit: (writePath: string) => void; - workerInit: () => void; - nativeEngineStart: () => void; - registerFunction: () => void; - initAsyncInfo: () => void; - mouseWheelCB: (eventType: string, scrollY : number) => void; - editBoxOnFocusCB: (viewTag: number) => void; - editBoxOnChangeCB: (viewTag: number, text: string) => void; - editBoxOnEnterCB: (viewTag: number, text: string) => void; - textFieldTTFOnChangeCB: (text: string) => void; - shouldStartLoading: (viewTag: number, url: string) => void; - finishLoading: (viewTag: number, url: string) => void; - failLoading: (viewTag: number, url: string) => void; - jsCallback: () => void; - onVideoCallBack: (viewTag: number, event: number) => void; - onAccelerometerCallBack: (x: number, y: number, z: number, interval: number) => void; -} - -export const getContext: (a: number) => CPPFunctions; diff --git a/tests/js-tests/project/proj.ohos/entry/src/main/cpp/types/libentry/oh-package.json5 b/tests/js-tests/project/proj.ohos/entry/src/main/cpp/types/libentry/oh-package.json5 deleted file mode 100644 index fa7874d5940d..000000000000 --- a/tests/js-tests/project/proj.ohos/entry/src/main/cpp/types/libentry/oh-package.json5 +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "libnativerender.so", - "types": "./index.d.ts", - "version": "", - "description": "Please describe the basic information." -} \ No newline at end of file diff --git a/tests/js-tests/project/proj.ohos/entry/src/main/ets/MainAbility/MainAbility.ts b/tests/js-tests/project/proj.ohos/entry/src/main/ets/MainAbility/MainAbility.ts deleted file mode 100644 index a89ce067f484..000000000000 --- a/tests/js-tests/project/proj.ohos/entry/src/main/ets/MainAbility/MainAbility.ts +++ /dev/null @@ -1,80 +0,0 @@ -import window from '@ohos.window'; -import UIAbility from '@ohos.app.ability.UIAbility'; -import web_webview from '@ohos.web.webview'; -import nativeRender from "libnativerender.so"; -import { ContextType } from "@ohos/libSysCapabilities" -import { GlobalContext,GlobalContextConstants} from "@ohos/libSysCapabilities" - -const nativeAppLifecycle: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.APP_LIFECYCLE); -const rawFileUtils: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.RAW_FILE_UTILS); - -export default class MainAbility extends UIAbility { - onCreate(want, launchParam) { - nativeAppLifecycle.onCreate(); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT, this.context); - // Initializes the webView kernel of the system. This parameter is optional if it is not used. - web_webview.WebviewController.initializeWebEngine(); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_WANT, this.context); - console.info('[LIFECYCLE-App] onCreate') - } - - onDestroy() { - nativeAppLifecycle.onDestroy(); - console.info('[LIFECYCLE-App] onDestroy') - } - - onWindowStageCreate(windowStage) { - // Main window is created, set main page for this ability - windowStage.loadContent('pages/Index', (err, data) => { - if (err.code) { - return; - } - rawFileUtils.nativeResourceManagerInit(this.context.resourceManager); - rawFileUtils.writablePathInit(this.context.filesDir); - }); - - windowStage.getMainWindow().then((windowIns: window.Window) => { - // Set whether to display the status bar and navigation bar. If they are not displayed, [] is displayed. - let systemBarPromise = windowIns.setWindowSystemBarEnable([]); - // Whether the window layout is displayed in full screen mode - let fullScreenPromise = windowIns.setWindowLayoutFullScreen(true); - // Sets whether the screen is always on. - let keepScreenOnPromise = windowIns.setWindowKeepScreenOn(true); - Promise.all([systemBarPromise, fullScreenPromise, keepScreenOnPromise]).then(() => { - console.info('Succeeded in setting the window'); - }).catch((err) => { - console.error('Failed to set the window, cause ' + JSON.stringify(err)); - }); - }) - - windowStage.on("windowStageEvent", (data) => { - let stageEventType: window.WindowStageEventType = data; - switch (stageEventType) { - case window.WindowStageEventType.RESUMED: - nativeAppLifecycle.onShow(); - break; - case window.WindowStageEventType.PAUSED: - nativeAppLifecycle.onHide(); - break; - default: - break; - } - }); - } - - onWindowStageDestroy() { - // Main window is destroyed, release UI related resources - } - - onForeground() { - // Ability has brought to foreground - console.info('[LIFECYCLE-App] onShow') - nativeAppLifecycle.onShow(); - } - - onBackground() { - // Ability has back to background - console.info('[LIFECYCLE-App] onDestroy') - nativeAppLifecycle.onHide(); - } -}; diff --git a/tests/js-tests/project/proj.ohos/entry/src/main/ets/components/CocosEditBox.ets b/tests/js-tests/project/proj.ohos/entry/src/main/ets/components/CocosEditBox.ets deleted file mode 100644 index 2587169f240f..000000000000 --- a/tests/js-tests/project/proj.ohos/entry/src/main/ets/components/CocosEditBox.ets +++ /dev/null @@ -1,82 +0,0 @@ -import { TextInputInfo } from '@ohos/libSysCapabilities/src/main/ets/components/editbox/EditBoxMsg' -import worker from '@ohos.worker'; -import { WorkerManager } from '../workers/WorkerManager'; - -@Component -export struct CocosEditBox { - @ObjectLink textInputInfo: TextInputInfo; - cocosWorker: worker.ThreadWorker = WorkerManager.getInstance().getWorker(); - - build(){ - if(this.textInputInfo.multiline){ - TextArea({text: this.textInputInfo.text, placeholder: this.textInputInfo.placeHolder}) - .id('TextArea'+this.textInputInfo.viewTag) - .position({x: px2vp(this.textInputInfo.x), y: px2vp(this.textInputInfo.y)}) - .size({width: px2vp(this.textInputInfo.w), height: px2vp(this.textInputInfo.h)}) - .padding({top: px2vp(this.textInputInfo.paddingH), right: px2vp(this.textInputInfo.paddingW), - bottom: px2vp(this.textInputInfo.paddingH), left: px2vp(this.textInputInfo.paddingW)}) - .borderRadius(0) - .maxLength(this.textInputInfo.maxLength) - .type(TextAreaType.NORMAL) - .fontFamily($rawfile(this.textInputInfo.fontPath)) - .fontSize(px2fp(this.textInputInfo.fontSize)) - .fontColor(`rgba(${this.textInputInfo.fontColor.r}, ${this.textInputInfo.fontColor.g}, ${this.textInputInfo.fontColor.b}, ${this.textInputInfo.fontColor.a})`) - .placeholderFont({size: px2fp(this.textInputInfo.placeholderFontSize), family: $rawfile(this.textInputInfo.placeHolderFontPath)}) - .placeholderColor(`rgba(${this.textInputInfo.placeholderFontColor.r}, ${this.textInputInfo.placeholderFontColor.g}, ${this.textInputInfo.placeholderFontColor.b}, ${this.textInputInfo.placeholderFontColor.a})`) - .backgroundColor(Color.Transparent) - .visibility(this.textInputInfo.visible ? Visibility.Visible : Visibility.None) - .onVisibleAreaChange([0.0, 1.0], () => { - focusControl.requestFocus('TextArea' + this.textInputInfo.viewTag); - }) - .onFocus(() => { - this.cocosWorker.postMessage({type: "editBoxOnFocus", viewTag: this.textInputInfo.viewTag}); - }) - .onChange((value: string)=>{ - this.textInputInfo.text = value; - this.cocosWorker.postMessage({type: "editBoxOnChange", viewTag: this.textInputInfo.viewTag, value: value}); - }) - .onBlur(()=> { - this.textInputInfo.visible = false - this.cocosWorker.postMessage({type: "editBoxOnEnter", viewTag: this.textInputInfo.viewTag, text: this.textInputInfo.text}); - }) - .onSubmit(()=>{ - this.cocosWorker.postMessage({type: "editBoxOnEnter", viewTag: this.textInputInfo.viewTag, text: this.textInputInfo.text}); - }) - }else{ - TextInput({text: this.textInputInfo.text, placeholder: this.textInputInfo.placeHolder}) - .id('TextInput'+this.textInputInfo.viewTag) - .position({x: px2vp(this.textInputInfo.x), y: px2vp(this.textInputInfo.y)}) - .size({width: px2vp(this.textInputInfo.w), height: px2vp(this.textInputInfo.h)}) - .padding({top: px2vp(this.textInputInfo.paddingH), right: px2vp(this.textInputInfo.paddingW), - bottom: px2vp(this.textInputInfo.paddingH), left: px2vp(this.textInputInfo.paddingW)}) - .borderRadius(0) - .maxLength(this.textInputInfo.maxLength) - .type(this.textInputInfo.inputMode) - .fontFamily($rawfile(this.textInputInfo.fontPath)) - .fontSize(px2fp(this.textInputInfo.fontSize)) - .fontColor(`rgba(${this.textInputInfo.fontColor.r}, ${this.textInputInfo.fontColor.g}, ${this.textInputInfo.fontColor.b}, ${this.textInputInfo.fontColor.a})`) - .placeholderFont({size: px2fp(this.textInputInfo.placeholderFontSize), family: $rawfile(this.textInputInfo.placeHolderFontPath)}) - .placeholderColor(`rgba(${this.textInputInfo.placeholderFontColor.r}, ${this.textInputInfo.placeholderFontColor.g}, ${this.textInputInfo.placeholderFontColor.b}, ${this.textInputInfo.placeholderFontColor.a})`) - .backgroundColor(Color.Transparent) - .visibility(this.textInputInfo.visible ? Visibility.Visible : Visibility.None) - .showPasswordIcon(false) - .onVisibleAreaChange([0.0, 1.0], () => { - focusControl.requestFocus('TextInput' + this.textInputInfo.viewTag); - }) - .onFocus(() => { - this.cocosWorker.postMessage({type: "editBoxOnFocus", viewTag: this.textInputInfo.viewTag}); - }) - .onChange((value: string)=>{ - this.textInputInfo.text = value; - this.cocosWorker.postMessage({type: "editBoxOnChange", viewTag: this.textInputInfo.viewTag, value: value}); - }) - .onBlur(()=> { - this.textInputInfo.visible = false - this.cocosWorker.postMessage({type: "editBoxOnEnter", viewTag: this.textInputInfo.viewTag, text: this.textInputInfo.text}); - }) - .onSubmit(()=>{ - this.cocosWorker.postMessage({type: "editBoxOnEnter", viewTag: this.textInputInfo.viewTag, text: this.textInputInfo.text}); - }) - } - } -} diff --git a/tests/js-tests/project/proj.ohos/entry/src/main/ets/components/CocosVideoPlayer.ets b/tests/js-tests/project/proj.ohos/entry/src/main/ets/components/CocosVideoPlayer.ets deleted file mode 100644 index 6f67afe3b443..000000000000 --- a/tests/js-tests/project/proj.ohos/entry/src/main/ets/components/CocosVideoPlayer.ets +++ /dev/null @@ -1,39 +0,0 @@ -import { WorkerManager } from '../workers/WorkerManager' -import { VideoPlayerInfo, VideoEvent } from '@ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayerMsg'; -import worker from '@ohos.worker'; - -@Component -export struct CocosVideoPlayer { - @ObjectLink videoPlayerInfo: VideoPlayerInfo; - cocosWorker: worker.ThreadWorker = WorkerManager.getInstance().getWorker(); - - build() { - Column() { - Video({ - src: this.videoPlayerInfo.isUrl ? this.videoPlayerInfo.url : this.videoPlayerInfo.rawfile, - controller: this.videoPlayerInfo.controller - }) - .width(this.videoPlayerInfo.w) - .height(this.videoPlayerInfo.h) - .visibility(this.videoPlayerInfo.visible ? Visibility.Visible : Visibility.None) - .controls(false) - .loop(this.videoPlayerInfo.isLoop) - .objectFit(this.videoPlayerInfo.objectFit) - .onPrepared(()=>{ - if(this.videoPlayerInfo.isPlay) { - this.videoPlayerInfo.controller.start() - } - this.videoPlayerInfo.controller.requestFullscreen(this.videoPlayerInfo.isFullScreen) - }) - .onStart(()=>{ - this.cocosWorker.postMessage({type: "onVideoCallBack", viewTag: this.videoPlayerInfo.viewTag, event: VideoEvent.PLAYING}); - }) - .onPause(()=>{ - this.cocosWorker.postMessage({type: "onVideoCallBack", viewTag: this.videoPlayerInfo.viewTag, event: VideoEvent.PAUSED}); - }) - .onFinish(()=>{ - this.cocosWorker.postMessage({type: "onVideoCallBack", viewTag: this.videoPlayerInfo.viewTag, event: VideoEvent.COMPLETED}); - }) - } - } -} diff --git a/tests/js-tests/project/proj.ohos/entry/src/main/ets/components/CocosWebview.ets b/tests/js-tests/project/proj.ohos/entry/src/main/ets/components/CocosWebview.ets deleted file mode 100644 index f26ba14cc6e7..000000000000 --- a/tests/js-tests/project/proj.ohos/entry/src/main/ets/components/CocosWebview.ets +++ /dev/null @@ -1,43 +0,0 @@ -import { WebViewInfo } from "@ohos/libSysCapabilities/src/main/ets/components/webview/WebViewMsg" -import worker from '@ohos.worker'; -import { WorkerManager } from '../workers/WorkerManager'; - -@Component -export struct CocosWebView { - viewInfo: WebViewInfo = new WebViewInfo(0, 0, 0, 0, 0); - cocosWorker: worker.ThreadWorker = WorkerManager.getInstance().getWorker(); - - build() { - Web({ src: this.viewInfo.isUrl ? this.viewInfo.url : $rawfile(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 }) - .domStorageAccess(true) - .databaseAccess(true) - .imageAccess(true) - .onlineImageAccess(true) - .zoomAccess(this.viewInfo.zoomAccess) - .javaScriptAccess(true) - .visibility(this.viewInfo.visible ? Visibility.Visible : Visibility.None) - .opacity(this.viewInfo.opacity) - .backgroundColor(this.viewInfo.backgroundColor) - .onPageBegin((event) => { - this.cocosWorker.postMessage({ type: "onPageBegin", viewTag: this.viewInfo.viewTag, url: event == null ? '' : event.url }); - }) - .onPageEnd((event) => { - this.cocosWorker.postMessage({ type: "onPageEnd", viewTag: this.viewInfo.viewTag, url: event == null ? '' : event.url }) - if(this.viewInfo.jsInterfaceScheme != "" && event != null && event.url.startsWith(this.viewInfo.jsInterfaceScheme)) { - this.cocosWorker.postMessage({ type: "onJsCallBack", viewTag: this.viewInfo.viewTag, url: event == null ? '' : event.url }) - } - // if u want use the javascript on ur page, u can use registerJavaScriptProxy() to register js function here - // and confirm that just register once by a local variable - }) - .onErrorReceive((event) => { - this.cocosWorker.postMessage({ type: "onErrorReceive", viewTag: this.viewInfo.viewTag, url: this.viewInfo.url }) - }) - .onHttpErrorReceive((event) => { - this.cocosWorker.postMessage({ type: "onErrorReceive", viewTag: this.viewInfo.viewTag, url: this.viewInfo.url }) - }) - } -} \ No newline at end of file diff --git a/tests/js-tests/project/proj.ohos/entry/src/main/ets/components/TextInputDialog.ets b/tests/js-tests/project/proj.ohos/entry/src/main/ets/components/TextInputDialog.ets deleted file mode 100644 index 6830af22cfad..000000000000 --- a/tests/js-tests/project/proj.ohos/entry/src/main/ets/components/TextInputDialog.ets +++ /dev/null @@ -1,33 +0,0 @@ -import { TextInputDialogEntity } from '@ohos/libSysCapabilities' -import worker from '@ohos.worker'; -import { WorkerManager } from '../workers/WorkerManager'; - -@CustomDialog -export struct TextInputDialog { - @State showMessage: TextInputDialogEntity = new TextInputDialogEntity(''); - cocosWorker: worker.ThreadWorker = WorkerManager.getInstance().getWorker(); - controller?: CustomDialogController - - build() { - Column() { - Row() { - TextInput({ text: this.showMessage.message }) - .backgroundColor('#ffffff') - .layoutWeight(1) - .defaultFocus(true) - .caretColor(Color.Transparent) - .onChange((value) => { - this.cocosWorker.postMessage({type: "textFieldTTFOnChange", data: value}) - }) - Blank(8).width(16) - Button($r('app.string.text_field_ttf_complete')).onClick(() => { - this.controller!.close(); - }) - }.padding({ left: 8, right: 8, top: 8, bottom: 8 }) - .backgroundColor(Color.Gray) - } - .width('100%') - - .justifyContent(FlexAlign.End) - } -} diff --git a/tests/js-tests/project/proj.ohos/entry/src/main/ets/pages/Index.ets b/tests/js-tests/project/proj.ohos/entry/src/main/ets/pages/Index.ets deleted file mode 100644 index c1c8a93084be..000000000000 --- a/tests/js-tests/project/proj.ohos/entry/src/main/ets/pages/Index.ets +++ /dev/null @@ -1,158 +0,0 @@ -import deviceInfo from '@ohos.deviceInfo'; - -import nativeRender from 'libnativerender.so' -import { ContextType } from '@ohos/libSysCapabilities' -import { TextInputInfo } from '@ohos/libSysCapabilities/src/main/ets/components/editbox/EditBoxMsg' -import { TextInputDialogEntity } from '@ohos/libSysCapabilities' -import { WebViewInfo } from '@ohos/libSysCapabilities/src/main/ets/components/webview/WebViewMsg' -import { VideoPlayerInfo } from '@ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayerMsg' -import { WorkerMsgUtils } from '@ohos/libSysCapabilities/src/main/ets/utils/WorkerMsgUtils' -import { WorkerManager } from '../workers/WorkerManager' -import { CocosEditBox } from '../components/CocosEditBox' -import { CocosWebView } from '../components/CocosWebview' -import { CocosVideoPlayer } from '../components/CocosVideoPlayer' -import { TextInputDialog } from '../components/TextInputDialog' -import { GlobalContext,GlobalContextConstants} from "@ohos/libSysCapabilities" -import promptAction from '@ohos.promptAction'; -import process from '@ohos.process'; -const nativePageLifecycle:nativeRender.CPPFunctions = nativeRender.getContext(ContextType.JSPAGE_LIFECYCLE); - -@Entry -@Component -struct Index { - - cocosWorker = WorkerManager.getInstance().getWorker(); - xcomponentController: XComponentController = new XComponentController(); - - processMgr = new process.ProcessManager(); - - - // EditBox - @State editBoxArray: TextInputInfo[] = []; - private editBoxIndexMap: Map = new Map; - - // WebView - @State webViewArray: WebViewInfo[] = []; - private webViewIndexMap: Map = new Map; - - // videoPlayer - @State videoPlayerInfoArray: VideoPlayerInfo[] = []; - private videoPlayerIndexMap: Map = new Map; - - // textInputDialog - showMessage: TextInputDialogEntity = new TextInputDialogEntity(''); - dialogController: CustomDialogController = new CustomDialogController({ - builder: TextInputDialog({ - showMessage: this.showMessage - }), - autoCancel: true, - alignment: DialogAlignment.Bottom, - customStyle: true, - }) - // PanGesture - private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down }); - - onPageShow() { - console.log('[LIFECYCLE-Page] onPageShow'); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_ARRAY, this.editBoxArray); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP, this.editBoxIndexMap); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_COCOS_WORKER, this.cocosWorker); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY, this.webViewArray); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP, this.webViewIndexMap); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_ARRAY, this.videoPlayerInfoArray); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP, this.videoPlayerIndexMap); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_DIALOG_CONTROLLER, this.dialogController); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_SHOW_MESSAGE, this.showMessage); - nativePageLifecycle.onPageShow(); - } - - onPageHide() { - console.log('[LIFECYCLE-Page] onPageHide'); - nativePageLifecycle.onPageHide(); - } - - onBackPress() { - console.log('[LIFECYCLE-Page] onBackPress'); - try { - promptAction.showDialog({ - title: "提示", - message: "确认退出游戏吗", - buttons: [ - { - text: '取消', - color: '#000000' - }, - { - text: '确认', - color: '#000000' - } - ], - }).then(data => { - console.info('showDialog success, click button: ' + data.index); - if(data.index == 0) { - console.info('showDialog click button cancel'); - return; - } else { - console.info('showDialog click button ok'); - this.processMgr.exit(0); - } - }) - } catch (error) { - console.error(`showDialog args error code is ${error.code}, message is ${error.message}`); - }; - // If disable system exit needed, remove comment "return true" - return true; - } - - onMouseWheel(eventType: string, scrollY: number) { - this.cocosWorker.postMessage({ type: "onMouseWheel", eventType: eventType, scrollY: scrollY }); - } - - build() { - Stack() { - XComponent({ - id: 'xcomponentId', - type: 'surface', - libraryname: 'nativerender', - controller: this.xcomponentController - }) - .focusable(true) - .focusOnTouch(true) - .gesture( - PanGesture(this.panOption) - .onActionStart(() => { - this.onMouseWheel("actionStart", 0); - }) - .onActionUpdate((event: GestureEvent) => { - if (deviceInfo.deviceType === '2in1') { - this.onMouseWheel("actionUpdate", event.offsetY); - } - }) - .onActionEnd(() => { - this.onMouseWheel("actionEnd", 0); - }) - ) - .onLoad((context) => { - console.log('[cocos] XComponent.onLoad Callback'); - this.cocosWorker.postMessage({ type: "abilityContextInit", data: GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT)}); - this.cocosWorker.postMessage({ type: "onXCLoad", data: "XComponent" }); - this.cocosWorker.onmessage = WorkerMsgUtils.recvWorkerThreadMessage; - }) - .onDestroy(() => { - }) - ForEach(this.editBoxArray, (item:TextInputInfo) => { - CocosEditBox({ textInputInfo: item}); - }, (item:TextInputInfo) => item.viewTag.toString()) - - ForEach(this.webViewArray, (item:WebViewInfo) => { - CocosWebView({ viewInfo: item }) - }, (item:WebViewInfo) => item.uniqueId.toString()) - - ForEach(this.videoPlayerInfoArray, (item:VideoPlayerInfo) => { - CocosVideoPlayer({ videoPlayerInfo: item }) - }, (item:VideoPlayerInfo) => item.viewTag.toString()) - } - .width('100%') - .height('100%') - } -} diff --git a/tests/js-tests/project/proj.ohos/entry/src/main/ets/workers/CocosWorker.ts b/tests/js-tests/project/proj.ohos/entry/src/main/ets/workers/CocosWorker.ts deleted file mode 100644 index 94ddb8d38920..000000000000 --- a/tests/js-tests/project/proj.ohos/entry/src/main/ets/workers/CocosWorker.ts +++ /dev/null @@ -1,79 +0,0 @@ -import worker, { ThreadWorkerGlobalScope } from '@ohos.worker'; -import nativeRender from "libnativerender.so"; -import { ContextType } from "@ohos/libSysCapabilities" -import { VideoPlayer } from "@ohos/libSysCapabilities" -import { CocosEditBox } from "@ohos/libSysCapabilities" -import { Dialog } from "@ohos/libSysCapabilities" -import { WebView } from "@ohos/libSysCapabilities" -import { JumpManager } from "@ohos/libSysCapabilities" -import { NapiHelper } from "@ohos/libSysCapabilities" -import { ApplicationManager } from "@ohos/libSysCapabilities" -import { GlobalContext,GlobalContextConstants} from "@ohos/libSysCapabilities" - -const appLifecycle: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.APP_LIFECYCLE); -const workerContext: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.WORKER_INIT); -const inputNapi: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.INPUT_NAPI); -const mouseNapi: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.MOUSE_NAPI); -const webViewNapi: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.WEBVIEW_NAPI); -const videoPlayNapi: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.VIDEOPLAYER_NAPI); -const napiContext: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.NATIVE_API); -workerContext.workerInit() - -napiContext.nativeEngineStart(); -NapiHelper.registerFunctions(napiContext.registerFunction) - -const workerPort: ThreadWorkerGlobalScope = worker.workerPort; - -workerPort.onmessage = function(e) : void { - let data = e.data; - switch(data.type) { - case "onXCLoad": - console.log("[cocos] onXCLoad Callback"); - Dialog.init(workerPort); - CocosEditBox.init(workerPort); - JumpManager.init(workerPort); - WebView.init(workerPort); - VideoPlayer.init(workerPort); - ApplicationManager.init(workerPort); - napiContext.initAsyncInfo(); - break; - case "abilityContextInit": - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT, data.data); - break; - case "editBoxOnFocus": - inputNapi.editBoxOnFocusCB(data.viewTag); - break; - case "editBoxOnChange": - inputNapi.editBoxOnChangeCB(data.viewTag, data.value); - break; - case "editBoxOnEnter": - inputNapi.editBoxOnEnterCB(data.viewTag, data.text); - break; - case "textFieldTTFOnChange": - inputNapi.textFieldTTFOnChangeCB(data.data); - break; - case "onMouseWheel": - mouseNapi.mouseWheelCB(data.eventType, data.scrollY); - break; - case "onPageBegin": - webViewNapi.shouldStartLoading(data.viewTag, data.url); - break; - case "onPageEnd": - webViewNapi.finishLoading(data.viewTag, data.url); - break; - case "onJsCallBack": - webViewNapi.jsCallback(); - break; - case "onErrorReceive": - webViewNapi.failLoading(data.viewTag, data.url); - break; - case "onVideoCallBack": - videoPlayNapi.onVideoCallBack(data.viewTag, data.event); - break; - case "exit": - appLifecycle.onBackPress(); - break; - default: - console.error("cocos worker: message type unknown") - } -} diff --git a/tests/js-tests/project/proj.ohos/entry/src/main/ets/workers/WorkerManager.ts b/tests/js-tests/project/proj.ohos/entry/src/main/ets/workers/WorkerManager.ts deleted file mode 100644 index e2ec70b1873e..000000000000 --- a/tests/js-tests/project/proj.ohos/entry/src/main/ets/workers/WorkerManager.ts +++ /dev/null @@ -1,34 +0,0 @@ -import worker from '@ohos.worker'; -import { Constants } from '@ohos/libSysCapabilities'; - -export class WorkerManager { - private cocosWorker: worker.ThreadWorker; - - private constructor() { - this.cocosWorker = new worker.ThreadWorker("entry/ets/workers/CocosWorker.ts", { - type: "classic", - name: "CocosWorker" - }); - this.cocosWorker.onerror = (e) => { - let msg = e.message; - let filename = e.filename; - let lineno = e.lineno; - let colno = e.colno; - console.error(`on Error ${msg} ${filename} ${lineno} ${colno}`); - } - } - - public static getInstance(): WorkerManager { - let workerManger: WorkerManager | undefined = AppStorage.get(Constants.APP_KEY_WORKER_MANAGER); - if (workerManger == undefined) { - workerManger = new WorkerManager; - AppStorage.setOrCreate(Constants.APP_KEY_WORKER_MANAGER, workerManger); - return workerManger; - } - return workerManger; - } - - public getWorker(): worker.ThreadWorker { - return this.cocosWorker; - } -} \ No newline at end of file diff --git a/tests/js-tests/project/proj.ohos/entry/src/main/module.json5 b/tests/js-tests/project/proj.ohos/entry/src/main/module.json5 deleted file mode 100644 index 5ebaad45e418..000000000000 --- a/tests/js-tests/project/proj.ohos/entry/src/main/module.json5 +++ /dev/null @@ -1,82 +0,0 @@ -{ - "module": { - "name": "entry", - "type": "entry", - "description": "$string:entry_desc", - "mainElement": "MainAbility", - "deviceTypes": [ - "phone", - "tablet" - ], - "deliveryWithInstall": true, - "installationFree": false, - "pages": "$profile:main_pages", - "abilities": [ - { - "name": "MainAbility", - "srcEntry": "./ets/MainAbility/MainAbility.ts", - "description": "$string:MainAbility_desc", - "icon": "$media:icon", - "label": "$string:MainAbility_label", - "startWindowIcon": "$media:icon", - "startWindowBackground": "$color:white", - "exported": true, - "orientation": "landscape", - "skills": [ - { - "entities": [ - "entity.system.home" - ], - "actions": [ - "action.system.home" - ] - } - ], - // https://docs.openharmony.cn/pages/v4.0/zh-cn/application-dev/quick-start/module-configuration-file.md/ - //ģʽΪֻ֧ȫ - "supportWindowMode": ["fullscreen"], -// Ϸڹ̶ڻ -// "supportWindowMode": ["floating"], -// ȫ󣬿ͬʱfullscreenfloatingڻֻʾȫȫʾ - // "supportWindowMode": ["fullscreen","floating"], - //߱ -// "maxWindowRatio": 3.5, - //С߱ -// "minWindowRatio": 0.5, - //Ϊ1080 - "maxWindowWidth": 1080, - //СΪ1080 - "minWindowWidth": 1080, - //߶Ϊ720 - "maxWindowHeight": 720, - //С߶Ϊ720 - "minWindowHeight": 720 - } - ], - "requestPermissions": [ - { - "name": "ohos.permission.INTERNET" - }, { - "name" : "ohos.permission.SET_NETWORK_INFO" - }, { - "name" : "ohos.permission.GET_NETWORK_INFO" - }, { - "name": "ohos.permission.GET_WIFI_INFO" - }, { - "name": "ohos.permission.ACCELEROMETER" - },{ - "name": "ohos.permission.VIBRATE" - } - ], - "metadata": [ - { - "name": "ArkTSPartialUpdate", - "value": "true" - }, - { - "name": "partialUpdateStrictCheck", - "value": "warn" - } - ] - } -} \ No newline at end of file diff --git a/tests/js-tests/project/proj.ohos/entry/src/main/resources/base/element/color.json b/tests/js-tests/project/proj.ohos/entry/src/main/resources/base/element/color.json deleted file mode 100644 index 1bbc9aa9617e..000000000000 --- a/tests/js-tests/project/proj.ohos/entry/src/main/resources/base/element/color.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "color": [ - { - "name": "white", - "value": "#FFFFFF" - } - ] -} \ No newline at end of file diff --git a/tests/js-tests/project/proj.ohos/entry/src/main/resources/base/element/string.json b/tests/js-tests/project/proj.ohos/entry/src/main/resources/base/element/string.json deleted file mode 100644 index b5ac01150169..000000000000 --- a/tests/js-tests/project/proj.ohos/entry/src/main/resources/base/element/string.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "string": [ - { - "name": "entry_desc", - "value": "3.16.2_js_tests" - }, - { - "name": "MainAbility_label", - "value": "3.16.2_js_tests" - }, - { - "name": "MainAbility_desc", - "value": "description" - }, - { - "name": "text_field_ttf_complete", - "value": "完成" - } - ] -} \ No newline at end of file diff --git a/tests/js-tests/project/proj.ohos/entry/src/main/resources/base/media/icon.png b/tests/js-tests/project/proj.ohos/entry/src/main/resources/base/media/icon.png deleted file mode 100644 index ce307a8827bd75456441ceb57d530e4c8d45d36c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6790 zcmX|G1ymHk)?T_}Vd;>R?p|tHQo6fg38|$UVM!6BLrPFWk?s;$LOP{GmJpBl$qoSA!PUg~PA65-S00{{S`XKG6NkG0RgjEntPrmV+?0|00mu7;+5 zrdpa{2QLqPJ4Y{j7=Mrl{BaxrkdY69+c~(w{Fv-v&aR%aEI&JYSeRTLWm!zbv;?)_ ziZB;fwGbbeL5Q}YLx`J$lp~A09KK8t_z}PZ=4ZzgdeKtgoc+o5EvN9A1K1_<>M?MBqb#!ASf&# zEX?<)!RH(7>1P+j=jqG(58}TVN-$psA6K}atCuI!KTJD&FMmH-78ZejBm)0qc{ESp z|LuG1{QnBUJRg_E=h1#XMWt2%fcoN@l7eAS!Es?Q+;XsRNPhiiE=@AqlLkJzF`O18 zbsbSmKN=aaq8k3NFYZfDWpKmM!coBU0(XnL8R{4=i|wi{!uWYM2je{U{B*K2PVdu&=E zTq*-XsEsJ$u5H4g6DIm2Y!DN`>^v|AqlwuCD;w45K0@eqauiqWf7l&o)+YLHm~|L~ z7$0v5mkobriU!H<@mVJHLlmQqzQ3d6Rh_-|%Yy2li*tHO>_vcnuZ7OR_xkAIuIU&x z-|8Y0wj|6|a6_I(v91y%k_kNw6pnkNdxjqG8!%Vz_d%c_!X+6-;1`GC9_FpjoHev5fEV7RhJ>r=mh-jp$fqbqRJ=obwdgLDVP5+s zy1=_DWG0Y-Jb3t^WXmkr(d9~08k-|#Ly zaNOmT(^9tIb&eb4%CzIT zAm3CUtWSr1t4?h1kk#NBi{U|pJslvME{q|_eS^3En>SOqSxyuN1x;Is@8~m?*>}** znrRFArP!K_52RpX*&JHMR<^lVdm8ypJ}0R(SD(51j;6@ni$6bQ+2XL+R^|NnSp5}(kzvMZ^(@4fD_{QVu$(&K6H|C37TG1Am9Re{<<3gd zh@`>;BqkXMW&p0T6rt|iB$)~CvFe(XC)F9WgAZn*0@t$oZo;!*}r@_`h?KKH&6A@3= zISXoQB+~`op>NP-buiA*^0n{@i{_?MRG)&k)c)k_F+-2Lud!S9pc+i`s74NpBCaGF zXN+pHkubw*msGBTY27BKHv)RRh3;nMg4&$fD_6X9Vt~;_4D+5XPH~#Kn-yjcy!$}1 zigv#FNY>TqMhtIBb@UoF!cE~Q8~;!Pek>SQQwHnHuWKoVBosAiOr}q>!>aE*Krc)V zBUMEcJ5NU0g8}-h6i1zpMY9>m4ne?=U2~`w7K7Q0gB_=p@$5K7p6}thw z-~3dMj?YNX2X$lZ+7ngQ$=s}3mizNN@kE%OtB)?c&i~2L55z8^=yz;xMHLmlY>&Q# zJj?!)M#q_SyfkQh)k?j8IfLtB)ZCp|*vf4_B zos?73yd^h-Ac+;?E4*bpf=o*^3x3-`TVjbY4n6!EN10K6o@fxdyps05Vo3PU)otB} z`3kR+2w7_C#8Z!q`J)p{Vh!+m9-UP!$STp+Hb}}#@#_u^SsUQg<}59< zTvH3%XS4G+6FF^(m6bVF&nSUIXcl;nw{=H$%fgeJ>CgDYiLdpDXr{;-AnG z8dvcrHYVMI&`R6;GWekI@Ir3!uo)oz4^{6q0m^}@f2tM9&=YHNi6-?rh0-{+k@cQm zdp`g#YdQn%MDVg2GR>wZ`n2<0l4)9nx1Wfr&!Dvz=bPwU!h2S?ez6MVc5APE4-xLB zi&W9Q8k2@0w!C53g?iAIQ}~p*3O(@zja6KQ=M3zfW*_6o5SwR-)6VBh~m7{^-=MC-owYH5-u40a}a0liho3QZZ5L{bS_xM1)4}19)zTU$$MY zq3eZML1WC{K%YFd`Be0M-rkO^l?h{kM{$2oK1*A@HVJ57*yhDkUF!2WZ&oA4Y-sK( zCY69%#`mBCi6>6uw(x4gbFaP0+FD*JKJ-q!F1E?vLJ+d35!I5d7@^eU?(CS|C^tmI5?lv@s{{*|1F zFg|OzNpZ0hxljdjaW%45O0MOttRrd(Z?h{HYbB-KFUx&9GfFL3b8NwZ$zNu)WbBD` zYkj$^UB5%3Pj1MDr>S2Ejr9pUcgA!;ZG!@{uAy12)vG=*^9-|dNQBc8&`oxBlU~#y zs!anJX&T?57Jdr^sb>e+V`MVfY>Y0ESg7MG<7W0g&bR-ZYzzZ%2H&Etcp zcd6QeXO1D!5A#zM0lx*GH}`M)2~ZFLE;sP^RSB5wVMNfiZXPd(cmO>j=OSA3`o5r& zna(|^jGXbdN7PK)U8b7^zYtYkkeb%<%F~=OqB~kXMQkq}ii|skh@WSRt>5za;cjP0 zZ~nD%6)wzedqE}BMLt~qKwlvTr33))#uP~xyw#*Eaa|DbMQ_%mG0U8numf8)0DX`r zRoG2bM;#g|p-8gWnwRV5SCW0tLjLO&9Z?K>FImeIxlGUgo0Zk`9Qzhj1eco~7XZy+hXc@YF&ZQ=? zn*^1O56yK^x{y}q`j7}blGCx%dydV!c7)g~tJzmHhV=W~jbWRRR{1<^oDK+1clprm zz$eCy7y9+?{E|YgkW~}}iB#I4XoJ*xr8R?i_Hv$=Cof5bo-Nj~f`-DLebH}&0% zfQj9@WGd4;N~Y?mzQsHJTJq6!Qzl^-vwol(+fMt#Pl=Wh#lI5Vmu@QM0=_r+1wHt` z+8WZ~c2}KQQ+q)~2Ki77QvV&`xb|xVcTms99&cD$Zz4+-^R4kvUBxG8gDk7Y`K*)JZ^2rL(+ZWV~%W(@6 z)0bPArG#BROa_PHs~&WplQ_UIrpd)1N1QGPfv!J(Z9jNT#i%H?CE6|pPZb9hJ1JW4 z^q;ft#!HRNV0YgPojzIYT`8LuET2rUe-J|c!9l4`^*;4WtY@Ew@pL>wkjmMgGfN7 ze}}GtmU0@<_#08~I-Suk=^*9GLW=H4xhsml;vAV{%hy5Eegl@!6qKqbG024%n2HHw zCc@ivW_$@5ZoHP70(7D+(`PvgjW1Pd`wsiuv-aCukMrafwDm)B!xXVy*j2opohhoU zcJz%ADmj>i3`-3-$7nQKBQQuGY;2Qt&+(L~C>vSGFj5{Mlv?T_^dql;{zkpe4R1}R z%XfZyQ}wr*sr>jrKgm*PWLjuVc%6&&`Kbf1SuFpHPN&>W)$GmqC;pIoBC`=4-hPY8 zT*>%I2fP}vGW;R=^!1be?ta2UQd2>alOFFbVl;(SQJ4Jk#)4Z0^wpWEVvY4=vyDk@ zqlModi@iVPMC+{?rm=4(n+<;|lmUO@UKYA>EPTS~AndtK^Wy^%#3<;(dQdk3WaUkRtzSMC9}7x2||CNpF#(3T4C)@ z$~RWs`BNABKX|{cmBt>Q=&gkXl&x!!NK_%5hW0LS)Z4PB>%sV?F-{Wyj#s7W%$F{D zXdK^Fp3wvy+48+GP6F_|^PCRx=ddcTO3sG;B23A49~Qaw31SZ0Rc~`r4qqt%#OGW{ zCA_(LG5^N>yzUn&kAgVmxb=EA8s&tBXC}S1CZ(KoW)(%^JjLTPo^fs`Va;`=YlVPgmB$!yB}<(4ym6OeZ3xAJJ#;)2+B%p3P1Wt+d$eo`vz`T zXfUP2))kBDPoscH;Jc7I3NU<({|@wM$&GaDt`n7WLgIY3IA7A6-_R?z8N3mz|}*i z(zl5ot--Oq@f2-nv{X(ujT2T(k1vY_qh93pK@>H-qc%2Xta)IP0Q%zt%bqYgI`o!wv!0QerB`nCN^1n|@$sVOQ!V0teVG!I z_fD%JvfDeT1cK#-{o6Gv7}& zY0#NWin~kVaf$aufV&;63Hbs|`QVZWpDX6IMk1Hj2G}fiH9e-^6u2zf^FIr^BwD<6zjw63+{yUe8PUFvk8v{sJ=R{d#`O!sz`Q13~< zPT$JS(w=yQfU2`zPCNfSw=&zup@DXc(98afjhv@1w_f!m2Z>rMJ19AB&dB%P#Ls3b z=lK7OILM+SQ&VEd=1GN6o&>YVVtIzoZ%=Z_SdqJN2}E43{bE`>w+A;=y->@^k{oCC z$F*WTY&?34;kfyFV?b*Xb1Pq`Z=%OgwEg)Rz)tx=`f%5#w_INP=x&z5!jI;#;N$ma zhO)+MDm;SxOEVL15; zGq(v2pL3&P1Sl)8P*;G-fd{l1QJsv@e@d8)1PK4w2m*M%V3j-V~L^$i|&C@b?D?9tfwE{B^}Z$k8e5FmQ>v7Xz)sG32g9t}YBt zyR$+*_00RmPx+0mW+vVG4mxd(n$(eQf3-w>JPl2UJpafrPaL5@2j}%{VE-) zBI%6Qpj*dsdH<;g!S!avA~bv^0E+ zfyJbSjPb+j;J52U)<|cIcntQBI2T#>2;tOxu{%D?kML476AErF(qN9hPva5Nkc@BF zC-tLF@3ZFb%Kpj)M<{)x*l|*Ia@ECeXo2E4h2f!aV=cHAhi_E_mfUth(sM4^hJq7B zQsGWqdZUm9S%F`$nQ*_#NcuD`&)Ek%_s{&^78{9Hm ztri&rYLOxgFdG>O@+XHy z9#;|&vBCPXH5Mon^I`jSuR$&~ZWtyB67ujzFSj!51>#C}C17~TffQ{c-!QFQkTQ%! zIR^b1`zHx|*1GU?tbBx23weFLz5H?y_Q%N&t$}k?w+``2A=aotj0;2v$~AL z{scF-cL{wsdrmPvf#a9OHyYLcwQD4Kcm)`LLwMh4WT~p29f7M!iafJSU`IV}QY5Wa z(n44-9oA}?J{a+ah*@31WTs#&J#o1`H98#6IQf;Wv0N_!);f&9g7o-k(lW5rWnDUR zQBFIRG+X=6NnsI@mxnwm;tf5;_Uxg?jZ8m-m0}&6+DA!qam(p$mN5R})yA_7m$q@| zFEd|dpS595rxQr-n#GjI5i-AhnUE>Cr;jpCqSrD~EwK_DqI^7%3#p5)%T_od!t3SOmH9MyXeeGO2(UQL;ax|x?Ncixmeo1=$ z{-);Au{*tfzOG?KQ~K|ak8-HQ?`Pekhe2WM(8s{xv-p>Zmu_6{G!-oE$7$mY`MOJorI=+mMx?H;`pr!;fVYz?5~yXBACruWB`Ph zZM}90_<^OBxIhyZ9BW$`>6JvO;%VFpqVr8|7t3~AmxYak6?`Pp#c;**_SYmi`&z23 z`p6_~ePvH)C6x-G9$hgL=eVALq`-AiamN>!3~Lxw&{H(b{B(7xSRm6<3<{%{yXiH# zos5Rv1L+8fUKJLo%P>4I&$}y { - if (item.viewTag == eventData.viewTag) { - removeIndex = index; - } - }); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_ARRAY).splice(removeIndex, 1); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP).delete(eventData.viewTag); - break; - } - case "setCurrentText": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.text = eventData.text; - break; - } - case "setEditBoxViewRect": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.x = eventData.viewRect.x; - textInputInfo.y = eventData.viewRect.y; - textInputInfo.w = eventData.viewRect.w; - textInputInfo.h = eventData.viewRect.h; - break; - } - case "setEditBoxVisible": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.visible = eventData.visible; - break; - } - case "setEditBoxFontSize": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.fontSize = eventData.fontSize; - break; - } - case "setEditBoxFontColor": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.fontColor = new FontColor(eventData.color.r, eventData.color.g, eventData.color.b, eventData.color.a / 255); - break; - } - case "setEditBoxPlaceHolderFontSize": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.placeholderFontSize = eventData.placeHolderSize; - break; - } - case "setEditBoxPlaceHolderFontColor": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.placeholderFontColor = new FontColor(eventData.placeHolderColor.r, eventData.placeHolderColor.g, eventData.placeHolderColor.b, eventData.placeHolderColor.a / 255); - break; - } - case "setEditBoxPlaceHolder": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.placeHolder = eventData.placeHolderText; - break; - } - case "setEditBoxMaxLength": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.maxLength = eventData.maxLength; - break; - } - case "setNativeInputMode": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.multiline = (eventData.inputMode == 0) ? true : false; - if (textInputInfo.inputMode != InputType.Password) { - switch (eventData.inputMode) { - case 0: - case 4: - case 6: - textInputInfo.inputMode = InputType.Normal; - break; - case 2: - case 5: - textInputInfo.inputMode = InputType.Number; - break; - case 3: - textInputInfo.inputMode = InputType.PhoneNumber; - break; - case 1: - textInputInfo.inputMode = InputType.Email; - break; - default: - break; - } - } - break; - } - case "setNativeInputFlag": { - // Any type can be changed to a password. The password can be changed to any type, - // but the password is mapped to the general type. Other changes are not allowed. - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - if (eventData.inputFlag == 0) { - textInputInfo.inputMode = InputType.Password; - } else if (textInputInfo.inputMode == InputType.Password) { - textInputInfo.inputMode = InputType.Normal; - } - break; - } - case "setEditBoxFontPath": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.fontPath = eventData.fontPath; - break; - } - case "setEditBoxPlaceHolderFontPath": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.placeHolderFontPath = eventData.placeHolderFontPath; - break; - } - case "hideAllEditBox": { - let editBoxArray: TextInputInfo[] = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_ARRAY); - editBoxArray.forEach(item => { - if (item.visible) { - item.visible = false; - let cocosWorker: worker.ThreadWorker = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_COCOS_WORKER); - cocosWorker.postMessage({ type: "editBoxOnEnter", viewTag: item.viewTag, text: item.text }) - } - }) - break; - } - } -} diff --git a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayer.ts b/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayer.ts deleted file mode 100644 index 50b7a7e69d00..000000000000 --- a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayer.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { VideoPlayMsgEntity, ViewRect } from '../../entity/WorkerMsgEntity'; - -export class VideoPlayer { - static MODULE_NAME: string = 'VideoPlay'; - - private static workerPort; - - static init(workerPort) : void { - VideoPlayer.workerPort = workerPort; - } - - static setURL(viewTag: number, url: string, isUrl: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'setURL', viewTag); - videoPlayMsgEntity.url = url; - videoPlayMsgEntity.isUrl = isUrl; - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static setLooping(viewTag: number, isLoop: boolean) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'setLooping', viewTag); - videoPlayMsgEntity.isLoop = isLoop; - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static createVideoPlayer(viewTag: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'createVideoPlayer', viewTag); - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static removeVideoPlayer(viewTag: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'removeVideoPlayer', viewTag); - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static setVideoPlayerRect(viewTag: number, x: number, y: number, w: number, h: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'setVideoPlayerRect', viewTag); - let viewRect: ViewRect = new ViewRect(x, y, w, h); - videoPlayMsgEntity.viewRect = viewRect; - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static play(viewTag: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'play', viewTag); - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - static pause(viewTag: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'pause', viewTag); - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static stop(viewTag: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'stop', viewTag); - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static setVisible(viewTag: number, visible: boolean) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'setVisible', viewTag); - videoPlayMsgEntity.visible = visible - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static requestFullscreen(viewTag: number, isFullScreen: boolean) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'requestFullscreen', viewTag); - videoPlayMsgEntity.isFullScreen = isFullScreen; - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static seekTo(viewTag: number, seekTo: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'seekTo', viewTag); - videoPlayMsgEntity.seekTo = seekTo; - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static setKeepAspectRatioEnabled(viewTag: number, enable: boolean) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'setKeepAspectRatioEnabled', viewTag); - videoPlayMsgEntity.keepAspectRatioEnabled = enable; - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } -} diff --git a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayerMsg.ets b/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayerMsg.ets deleted file mode 100644 index f11bdac82c9a..000000000000 --- a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayerMsg.ets +++ /dev/null @@ -1,145 +0,0 @@ -import Logger from '../../utils/Logger' -import { BusinessError } from '@ohos.base'; -import { GlobalContext,GlobalContextConstants } from "../../common/GlobalContext" -import { VideoPlayMsgEntity } from '../../entity/WorkerMsgEntity'; - -let log: Logger = new Logger(0x0001, "VideoPlayerMsg"); - -@Observed -export class VideoPlayerInfo { - // position - public x: number = 0; - public y: number = 0; - // size - public w: number = 0; - public h: number = 0; - // url - public url: string = '' - - public rawfile?: Resource; - public isUrl: boolean = false - // tag - public viewTag: number = 0 - - public isPlay: boolean = false - public isFullScreen: boolean = false - - // Whether to display - public visible: boolean = true - - public isLoop: boolean = false - - public objectFit: ImageFit = ImageFit.Auto - - public controller: VideoController = new VideoController() - - constructor(x: number, y: number, w: number, h: number, viewTag: number) { - this.x = x; - this.y = y; - this.w = w; - this.h = h; - this.viewTag = viewTag; - } -} - -export enum VideoEvent { - PLAYING = 0, - PAUSED, - STOPPED, - COMPLETED, -} - -export function handleVideoPlayMsg(eventData: VideoPlayMsgEntity) { - - switch (eventData.function) { - case "createVideoPlayer": { - let newVideoPlayerInfo = new VideoPlayerInfo(0, 0, 0, 0, eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_ARRAY).push(newVideoPlayerInfo); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).set(eventData.viewTag, newVideoPlayerInfo); - break; - } - case "removeVideoPlayer": { - let removeIndex = -1; - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_ARRAY).forEach((item:VideoPlayerInfo,index:number) => { - if (item.viewTag == eventData.viewTag) { - removeIndex = index; - } - }); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag).controller.requestFullscreen(false); //4.x已修复 - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_ARRAY).splice(removeIndex, 1); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).delete(eventData.viewTag); - break; - } - case "play": { - let videoPlayInfo :VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.controller.start(); - videoPlayInfo.isPlay = true; - break; - } - case "pause": { - let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.controller.pause(); - videoPlayInfo.isPlay = false; - break; - } - case "stop": { - let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.controller.stop(); - videoPlayInfo.isPlay = false; - break; - } - case "setURL": { - let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - if(eventData.isUrl == 0) { - videoPlayInfo.isUrl = false; - videoPlayInfo.rawfile = $rawfile(eventData.url); - } else { - videoPlayInfo.isUrl = true; - videoPlayInfo.url = eventData.url; - } - break; - } - case "setLooping": { - let videoPlayInfo: VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.isLoop = eventData.isLoop; - break; - } - case "setVideoPlayerRect": { - let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - try { - videoPlayInfo.x = px2vp(eventData.viewRect.x); - videoPlayInfo.y = px2vp(eventData.viewRect.y); - videoPlayInfo.w = px2vp(eventData.viewRect.w); - videoPlayInfo.h = px2vp(eventData.viewRect.h); - } catch (error) { - let e: BusinessError = error as BusinessError; - log.error('videoPlayerInfo ErrorCode: %{public}d, Message: %{public}s', e.code, e.message); - } - break; - } - case "setVisible": { - let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - if (videoPlayInfo.visible == eventData.visible) { - return; - } - videoPlayInfo.visible = eventData.visible; - break; - } - case "requestFullscreen": { - let videoPlayInfo: VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.controller.requestFullscreen(eventData.isFullScreen); - videoPlayInfo.isFullScreen = eventData.isFullScreen; - break; - } - case "seekTo": { - let videoPlayInfo: VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.controller.setCurrentTime(eventData.seekTo, SeekMode.Accurate); - break; - } - case "setKeepAspectRatioEnabled": { - let videoPlayInfo: VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.objectFit = eventData.keepAspectRatioEnabled? ImageFit.Cover : ImageFit.Auto; - break; - } - } -} \ No newline at end of file diff --git a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebView.ts b/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebView.ts deleted file mode 100644 index 872ec4ce70fe..000000000000 --- a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebView.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { ViewRect, WebViewMsgEntity } from '../../entity/WorkerMsgEntity'; - -export class WebView { - static MODULE_NAME: string = 'WebView'; - - private static workerPort; - - static init(workerPort) : void { - WebView.workerPort = workerPort; - } - - static createWebView(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'createWebView', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static removeWebView(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'removeWebView', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static setJavascriptInterfaceScheme(viewTag: number, jsInterfaceScheme: string) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'setJavascriptInterfaceScheme', viewTag); - webViewMsgEntity.jsInterfaceScheme = jsInterfaceScheme; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static loadData(viewTag: number, data: string, mimeType: string, encoding: string, baseURL: string) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'loadData', viewTag); - webViewMsgEntity.data = data; - webViewMsgEntity.mimeType = mimeType; - webViewMsgEntity.encoding = encoding; - webViewMsgEntity.baseURL = baseURL; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static loadURL(viewTag: number, url: string) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'loadURL', viewTag); - webViewMsgEntity.url = url; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static loadFile(viewTag: number, filePath: string) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'loadFile', viewTag); - webViewMsgEntity.filePath = filePath; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static stopLoading(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'stopLoading', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static reload(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'reload', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static canGoBack(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'canGoBack', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static canGoForward(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'canGoForward', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static goBack(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'goBack', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static goForward(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'goForward', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static setWebViewRect(viewTag: number, x: number, y: number, w: number, h: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'setWebViewRect', viewTag); - let viewRect: ViewRect = new ViewRect(x, y, w, h); - webViewMsgEntity.viewRect = viewRect; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static setVisible(viewTag: number, visible: boolean) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'setVisible', viewTag); - webViewMsgEntity.visible = visible; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static setOpacityWebView(viewTag: number, opacity: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'setOpacityWebView', viewTag); - webViewMsgEntity.opacity = opacity; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static setBackgroundTransparent(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'setBackgroundTransparent', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static evaluateJS(viewTag: number, js: string) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'evaluateJS', viewTag); - webViewMsgEntity.js = js; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static setScalesPageToFit(viewTag: number, scalesPageToFit: boolean) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'setScalesPageToFit', viewTag); - webViewMsgEntity.scalesPageToFit = scalesPageToFit; - WebView.workerPort.postMessage(webViewMsgEntity); - } -} \ No newline at end of file diff --git a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebViewMsg.ets b/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebViewMsg.ets deleted file mode 100644 index 24e1f86d9779..000000000000 --- a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebViewMsg.ets +++ /dev/null @@ -1,245 +0,0 @@ -import web_webview from '@ohos.web.webview' -import Logger from '../../utils/Logger'; -import { GlobalContext, GlobalContextConstants } from '../../common/GlobalContext'; -import { WebViewMsgEntity } from '../../entity/WorkerMsgEntity'; -import { BusinessError } from '@ohos.base'; - -let log: Logger = new Logger(0x0001, "WebViewMsg"); - -export class WebViewInfo { - public uniqueId : number = 0; - // position - public x: number = 0; - public y: number = 0; - // size - public w: number = 0; - public h: number = 0; - // url - public url: string = ''; - public isUrl: boolean = true; - - public viewTag: number = 0 - public zoomAccess: boolean = true - public visible: boolean = true - public opacity: number = 1 - public backgroundColor: number = 0xffffff; - public jsInterfaceScheme: string = ""; - public controller: web_webview.WebviewController = new web_webview.WebviewController() - - constructor(x: number, y: number, w: number, h: number, viewTag: number) { - this.x = x; - this.y = y; - this.w = w; - this.h = h; - this.viewTag = viewTag - this.uniqueId = viewTag; - } -} - -function copyWebViewInfo(viewInfo: WebViewInfo) : WebViewInfo { - let newViewInfo: WebViewInfo = new WebViewInfo(viewInfo.x, viewInfo.y, viewInfo.w, viewInfo.h, viewInfo.viewTag); - newViewInfo.url = viewInfo.url; - newViewInfo.isUrl = viewInfo.isUrl; - newViewInfo.zoomAccess = viewInfo.zoomAccess; - newViewInfo.visible = viewInfo.visible; - newViewInfo.controller = viewInfo.controller; - newViewInfo.opacity = viewInfo.opacity; - newViewInfo.backgroundColor = viewInfo.backgroundColor; - newViewInfo.jsInterfaceScheme = viewInfo.jsInterfaceScheme; - newViewInfo.uniqueId = 100000 - viewInfo.uniqueId; // support 50000 webView exist at the same time - return newViewInfo; -} - -function waitUtilControllerAttached() : Promise { - return new Promise((resolve, reject) => { - resolve(1); - }) -} - -export function handleWebViewMsg(eventData: WebViewMsgEntity) { - let index: number; - switch (eventData.function) { - case "createWebView": { - let view = new WebViewInfo(0, 0, 0, 0, eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY).push(view); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP) - .set(eventData.viewTag, GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY) - .length - 1); - break; - } - case "removeWebView": { - if (GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY).length > 0) { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY).splice(index, 1); - // Do not assume the invoking time of removeWebView. After an element is deleted, the following elements need to be advanced by one bit. - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP) - .forEach((value: number, key: number, map: Map) => { - if (value > index) { - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).set(key, value - 1); - } - }) - - // Delete the subscript mapping of the removed webView. - let tempInfoMap: Map = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP); - tempInfoMap.delete(eventData.viewTag); - } - break; - } - case "setJavascriptInterfaceScheme": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - webViewInfo.jsInterfaceScheme = eventData.jsInterfaceScheme; - break; - } - case "loadData": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - waitUtilControllerAttached().then(() => { - webViewInfo.controller.loadData(eventData.data, eventData.mimeType, eventData.encoding, eventData.baseURL) - }); - break; - } - case "loadURL": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index].url = eventData.url; - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index].isUrl = true; - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - waitUtilControllerAttached().then(() => { - webViewInfo.controller.loadUrl(eventData.url); - }) - break; - } - case "loadFile": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index].url = eventData.filePath; - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index].isUrl = false; - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - waitUtilControllerAttached().then(() => { - webViewInfo.controller.loadUrl($rawfile(eventData.filePath)); - }) - break; - } - case "stopLoading": - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index].controller.stop(); - break; - case "reload": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - waitUtilControllerAttached().then(() => { - webViewInfo.controller.refresh(); - }) - break; - } - case "canGoBack": - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let result: number = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .controller - .accessBackward(); - // todo The value needs to be sent back to the worker thread. - break; - case "canGoForward": - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - result = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .controller - .accessForward(); - // todo The value needs to be sent back to the worker thread. - break; - case "goBack": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - waitUtilControllerAttached().then(() => { - webViewInfo.controller.backward(); - }) - break; - } - case "goForward": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - waitUtilControllerAttached().then(() => { - webViewInfo.controller.forward(); - }) - break; - } - case "setWebViewRect": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let tmpWebInfo :WebViewInfo= GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - tmpWebInfo.x = px2vp(eventData.viewRect.x); - tmpWebInfo.y = px2vp(eventData.viewRect.y); - tmpWebInfo.w = px2vp(eventData.viewRect.w); - tmpWebInfo.h = px2vp(eventData.viewRect.h); - let newViewInfo:WebViewInfo = copyWebViewInfo(tmpWebInfo); - let tempInfoArray :WebViewInfo[]= GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY); - tempInfoArray[index] = newViewInfo; - break; - } - case "setVisible": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - if (GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .visible == eventData.visible) { - return; - } - let tmpWebInfo:WebViewInfo= GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - tmpWebInfo.visible = eventData.visible; - let newViewInfo:WebViewInfo = copyWebViewInfo(tmpWebInfo); - let tempInfoArray :WebViewInfo[]= GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY); - tempInfoArray[index] = newViewInfo; - break; - } - case "setOpacityWebView": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - if (GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .opacity == eventData.opacity) { - return; - } - let tmpWebInfo :WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - tmpWebInfo.opacity = eventData.opacity; - let newViewInfo :WebViewInfo= copyWebViewInfo(tmpWebInfo); - let tempInfoArray :WebViewInfo[]= GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY); - tempInfoArray[index] = newViewInfo; - break; - } - case "setBackgroundTransparent": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - if (GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .backgroundColor == Color.Transparent) { - return; - } - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .backgroundColor = Color.Transparent; - let newViewInfo :WebViewInfo= copyWebViewInfo(GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]); - let tempInfoArray :WebViewInfo[]= GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY); - tempInfoArray[index] = newViewInfo; - break; - } - case "evaluateJS": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .controller - .runJavaScript(eventData.js, (error:BusinessError, result:string) => { - if (error) { - log.warn("webView run JavaScript error:%{public}s", JSON.stringify(error)); - return; - } - if (result) { - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_WEB_RESULT,result) - log.debug("webView run JavaScript result is %{public}s:", result); - } - }) - break; - } - case "setScalesPageToFit": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - if (GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .zoomAccess == eventData.scalesPageToFit) { - return; - } - let tmpWebInfo:WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - tmpWebInfo.zoomAccess == eventData.scalesPageToFit - let newViewInfo:WebViewInfo = copyWebViewInfo(tmpWebInfo); - let tempInfoArray:WebViewInfo[] = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY); - tempInfoArray[index] = newViewInfo; - } - break; - } -} diff --git a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/Result.ts b/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/Result.ts deleted file mode 100644 index dd9e38897da3..000000000000 --- a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/Result.ts +++ /dev/null @@ -1,16 +0,0 @@ -export class Result { - public static success(data){ - return { - "errCode": 0, - "errMsg": "", - "data": data, - }; - } - - public static error(errCode, errMsg) { - return { - "errCode": errCode, - "errMsg": errMsg, - }; - } -}; \ No newline at end of file diff --git a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/TextInputDialogEntity.ts b/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/TextInputDialogEntity.ts deleted file mode 100644 index 39d272a0b68c..000000000000 --- a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/TextInputDialogEntity.ts +++ /dev/null @@ -1,7 +0,0 @@ -export class TextInputDialogEntity { - message : string; - - constructor(msg: string) { - this.message = msg; - } -} \ No newline at end of file diff --git a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/WorkerMsgEntity.ts b/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/WorkerMsgEntity.ts deleted file mode 100644 index 70216b1e14e5..000000000000 --- a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/WorkerMsgEntity.ts +++ /dev/null @@ -1,141 +0,0 @@ -export class ViewRect { - x: number - y: number - w: number - h: number - - constructor(x: number, y: number, w: number, h: number) { - this.x = x; - this.y = y; - this.w = w; - this.h = h; - } -} - -export class Color4B { - r: number - g: number - b: number - a: number - - constructor(r: number, g: number, b: number, a: number) { - this.r = r; - this.g = g; - this.b = b; - this.a = a; - } -} - -export class BaseWorkerMsgEntity { - module: string; - - function: string; - - constructor(module: string, func: string) { - this.module = module; - this.function = func; - } -} - -export class DialogMsgEntity extends BaseWorkerMsgEntity { - title: string; - - message: string; - - constructor(module: string, func: string) { - super(module, func); - } -} - -export class EditBoxMsgEntity extends BaseWorkerMsgEntity { - viewTag: number - - viewRect: ViewRect - - paddingW: number - paddingH: number - - visible: boolean - - text: string - fontSize: number - color: Color4B - fontPath: string - - placeHolderText: string - placeHolderSize: number - placeHolderColor: Color4B - placeHolderFontPath: string - - maxLength: number - - inputMode: number - - inputFlag: number - - constructor(module: string, func: string, viewTag?: number) { - super(module, func); - this.viewTag = viewTag; - } -} - -export class VideoPlayMsgEntity extends BaseWorkerMsgEntity { - viewTag: number - - url: string - isUrl: number - - isLoop: boolean - - viewRect: ViewRect - - visible: boolean - - isFullScreen: boolean - - seekTo: number - - keepAspectRatioEnabled: boolean - - constructor(module: string, func: string, viewTag: number) { - super(module, func); - this.viewTag = viewTag; - } -} - -export class WebViewMsgEntity extends BaseWorkerMsgEntity { - viewTag: number - - data: string - mimeType: string - encoding: string - baseURL: string - - url: string - - filePath: string - - viewRect: ViewRect - - visible: boolean - - opacity: number - - js: string - - scalesPageToFit: boolean - jsInterfaceScheme: string - - constructor(module: string, func: string, viewTag: number) { - super(module, func); - this.viewTag = viewTag; - } -} - -export class JumpMsgEntity extends BaseWorkerMsgEntity { - url: string; - - constructor(module: string, func: string) { - super(module, func); - } -} diff --git a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/napi/NapiHelper.ts b/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/napi/NapiHelper.ts deleted file mode 100644 index d4df1a5f9806..000000000000 --- a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/napi/NapiHelper.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { Dialog } from '../components/dialog/DialogWorker' -import StringUtils from '../utils/StringUtils' -import { JumpManager } from '../system/appJump/JumpManager' -import { DeviceUtils } from '../system/device/DeviceUtils' -import { ApplicationManager } from '../system/application/ApplicationManager' -import { CocosEditBox } from '../components/editbox/CocosEditBox' -import { WebView } from '../components/webview/WebView' -import { VideoPlayer } from '../components/videoplayer/VideoPlayer' -import Accelerometer from '../system/sensor/AccelerometerUtils' -import Preferences from '../preferences/Preferences' - -export class NapiHelper { - - static registerFunctions(registerFunc : Function) { - NapiHelper.registerOthers(registerFunc); - NapiHelper.registerDeviceUtils(registerFunc); - NapiHelper.registerEditBox(registerFunc); - NapiHelper.registerWebView(registerFunc); - NapiHelper.registerVideoPlay(registerFunc); - NapiHelper.registerSensor(registerFunc); - NapiHelper.registerPreferences(registerFunc); - } - - private static registerOthers(registerFunc : Function) { - registerFunc('DiaLog.showDialog', Dialog.showDialog); - registerFunc('DiaLog.showTextInputDialog', Dialog.showTextInputDialog); - registerFunc('DiaLog.hideTextInputDialog', Dialog.hideTextInputDialog); - registerFunc('StringUtils.getWidth', StringUtils.getWidth); - registerFunc('ApplicationManager.exit', ApplicationManager.exit); - registerFunc('ApplicationManager.getVersionName', ApplicationManager.getVersionName); - registerFunc('JumpManager.openUrl', JumpManager.openUrl); - } - - private static registerDeviceUtils(registerFunc : Function) { - registerFunc('DeviceUtils.getDpi', DeviceUtils.getDpi); - registerFunc('DeviceUtils.getSystemLanguage', DeviceUtils.getSystemLanguage); - registerFunc('DeviceUtils.startVibration', DeviceUtils.startVibration); - registerFunc('DeviceUtils.setKeepScreenOn', DeviceUtils.setKeepScreenOn); - registerFunc('DeviceUtils.isRoundScreen', DeviceUtils.isRoundScreen); - registerFunc('DeviceUtils.hasSoftKeys', DeviceUtils.hasSoftKeys); - registerFunc('DeviceUtils.isCutoutEnable', DeviceUtils.isCutoutEnable); - registerFunc('DeviceUtils.initScreenInfo', DeviceUtils.initScreenInfo); - registerFunc('DeviceUtils.getOrientation', DeviceUtils.getOrientation); - registerFunc('DeviceUtils.getCutoutHeight', DeviceUtils.getCutoutHeight); - registerFunc('DeviceUtils.getCutoutWidth', DeviceUtils.getCutoutWidth); - } - - private static registerEditBox(registerFunc : Function) { - registerFunc('CocosEditBox.createCocosEditBox', CocosEditBox.createCocosEditBox); - registerFunc('CocosEditBox.removeCocosEditBox', CocosEditBox.removeCocosEditBox); - registerFunc('CocosEditBox.setCurrentText', CocosEditBox.setCurrentText); - registerFunc('CocosEditBox.setEditBoxViewRect', CocosEditBox.setEditBoxViewRect); - registerFunc('CocosEditBox.setEditBoxVisible', CocosEditBox.setEditBoxVisible); - registerFunc('CocosEditBox.setEditBoxPlaceHolder', CocosEditBox.setEditBoxPlaceHolder); - registerFunc('CocosEditBox.setEditBoxFontSize', CocosEditBox.setEditBoxFontSize); - registerFunc('CocosEditBox.setEditBoxFontColor', CocosEditBox.setEditBoxFontColor); - registerFunc('CocosEditBox.setEditBoxFontPath', CocosEditBox.setEditBoxFontPath); - registerFunc('CocosEditBox.setEditBoxPlaceHolderFontSize', CocosEditBox.setEditBoxPlaceHolderFontSize); - registerFunc('CocosEditBox.setEditBoxPlaceHolderFontColor', CocosEditBox.setEditBoxPlaceHolderFontColor); - registerFunc('CocosEditBox.setEditBoxPlaceHolderFontPath', CocosEditBox.setEditBoxPlaceHolderFontPath); - registerFunc('CocosEditBox.setEditBoxMaxLength', CocosEditBox.setEditBoxMaxLength); - registerFunc('CocosEditBox.setNativeInputMode', CocosEditBox.setNativeInputMode); - registerFunc('CocosEditBox.setNativeInputFlag', CocosEditBox.setNativeInputFlag); - registerFunc('CocosEditBox.hideAllEditBox', CocosEditBox.hideAllEditBox); - } - - private static registerWebView(registerFunc : Function) { - registerFunc('WebView.createWebView', WebView.createWebView); - registerFunc('WebView.removeWebView', WebView.removeWebView); - registerFunc('WebView.setJavascriptInterfaceScheme', WebView.setJavascriptInterfaceScheme); - registerFunc('WebView.loadData', WebView.loadData); - registerFunc('WebView.loadURL', WebView.loadURL); - registerFunc('WebView.loadFile', WebView.loadFile); - registerFunc('WebView.stopLoading', WebView.stopLoading); - registerFunc('WebView.reload', WebView.reload); - registerFunc('WebView.canGoBack', WebView.canGoBack); - registerFunc('WebView.canGoForward', WebView.canGoForward); - registerFunc('WebView.goBack', WebView.goBack); - registerFunc('WebView.goForward', WebView.goForward); - registerFunc('WebView.setWebViewRect', WebView.setWebViewRect); - registerFunc('WebView.setVisible', WebView.setVisible); - registerFunc('WebView.setOpacityWebView', WebView.setOpacityWebView); - registerFunc('WebView.setBackgroundTransparent', WebView.setBackgroundTransparent); - registerFunc('WebView.evaluateJS', WebView.evaluateJS); - registerFunc('WebView.setScalesPageToFit', WebView.setScalesPageToFit); - } - - private static registerVideoPlay(registerFunc : Function) { - registerFunc('VideoPlayer.createVideoPlayer', VideoPlayer.createVideoPlayer); - registerFunc('VideoPlayer.removeVideoPlayer', VideoPlayer.removeVideoPlayer); - registerFunc('VideoPlayer.setURL', VideoPlayer.setURL); - registerFunc('VideoPlayer.setLooping', VideoPlayer.setLooping); - registerFunc('VideoPlayer.setVideoPlayerRect', VideoPlayer.setVideoPlayerRect); - registerFunc('VideoPlayer.play', VideoPlayer.play); - registerFunc('VideoPlayer.pause', VideoPlayer.pause); - registerFunc('VideoPlayer.stop', VideoPlayer.stop); - registerFunc('VideoPlayer.setVisible', VideoPlayer.setVisible); - registerFunc('VideoPlayer.requestFullscreen', VideoPlayer.requestFullscreen); - registerFunc('VideoPlayer.seekTo', VideoPlayer.seekTo); - registerFunc('VideoPlayer.setKeepAspectRatioEnabled', VideoPlayer.setKeepAspectRatioEnabled); - } - - private static registerSensor(registerFunc : Function) { - registerFunc('Accelerometer.enable', Accelerometer.enable); - registerFunc('Accelerometer.disable', Accelerometer.disable); - } - - private static registerPreferences(registerFunc : Function) { - registerFunc('Preferences.get', Preferences.get); - registerFunc('Preferences.getAll', Preferences.getAll); - registerFunc('Preferences.put', Preferences.put); - registerFunc('Preferences.has', Preferences.has); - registerFunc('Preferences.delete', Preferences.delete); - registerFunc('Preferences.flush', Preferences.flush); - registerFunc('Preferences.clear', Preferences.clear); - } - -} diff --git a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/preferences/Preferences.ts b/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/preferences/Preferences.ts deleted file mode 100644 index e95e89b29d10..000000000000 --- a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/preferences/Preferences.ts +++ /dev/null @@ -1,218 +0,0 @@ -import Logger from '../utils/Logger'; -import data_preferences from '@ohos.data.preferences'; -import { BusinessError } from '@ohos.base'; -import common from '@ohos.app.ability.common'; -import { GlobalContext, GlobalContextConstants } from '../common/GlobalContext'; - -let log: Logger = new Logger(0x0001, "Preferences"); -let preferences: data_preferences.Preferences | null = null; -const PREFS_NAME: string = "Cocos2dxPreferences"; - -export default class Preferences { - - // 通过 preferencesName 获取Preferences实例 - static getPreferences(): data_preferences.Preferences { - let context: common.UIAbilityContext = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT); - try { - preferences = data_preferences.getPreferencesSync(context, {name: PREFS_NAME}); - log.info("Succeeded in getting preferences."); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to get preferences. code =" + code + ", message =" + message); - } - return preferences; - } - - /* - 通过 preferencesName 从缓存中移出指定的Preferences实例,若Preferences实例有对应的持久化文件,则同时删除其持久化文件。使用Promise异步回调。 - 调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 - */ - static deletePreferences(): void { - let context: common.UIAbilityContext = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT); - try { - data_preferences.deletePreferences(context, PREFS_NAME).then(() => { - log.info("Succeeded in deleting preferences."); - }); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to delete preferences. code =" + code + ", message =" + message); - } - } - - /* - 通过 preferencesName 从缓存中移出指定的Preferences实例,使用Promise异步回调。 - 应用首次调用getPreferences接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次getPreferences时不会再次从持久化文件中读取, - 直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。 - 调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 - */ - static removePreferencesFromCache(): void { - let context: common.UIAbilityContext = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT); - try { - data_preferences.removePreferencesFromCacheSync(context, PREFS_NAME); - log.info("Succeeded in removing preferences."); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to remove preferences. code =" + code + ", message =" + message); - } - } - - // 从缓存的Preferences实例中获取键对应的值,如果值为null或者非默认值类型,返回默认数据defValue - static get(key: string, defValue: data_preferences.ValueType): data_preferences.ValueType { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - let data = preferences.getSync(key, defValue); - log.info("Succeeded in getting value of 'startup'. Data: " + data); - return data; - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to get value of 'startup'. code =" + code + ", message =" + message); - return defValue; - } - } - - // 将数据写入缓存的Preferences实例中,可通过flush将Preferences实例持久化 - static put(key: string, value: data_preferences.ValueType): void { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - preferences.putSync(key, value); - log.info("Succeeded in put the key."); - Preferences.flush(); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to put. code =" + code + ", message =" + message); - } - } - - // 从缓存的Preferences实例中获取所有键值数据。 - static getAll(): string | undefined { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - let object = preferences.getAllSync(); - let allKeys = getObjKeys(object); - log.info('getAll keys = ' + allKeys); - log.info("getAll object = " + JSON.stringify(object)); - return JSON.stringify(object); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to getAll. code =" + code + ", message =" + message); - return undefined; - } - } - - // 检查缓存的Preferences实例中是否包含名为给定Key的存储键值对 - static has(key: string): boolean { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - let val = preferences.hasSync(key); - if (val) { - log.info("The key 'startup' is contained."); - return true; - } else { - log.info("The key 'startup' dose not contain."); - return false; - } - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to has. code =" + code + ", message =" + message); - return false; - } - } - - // 从缓存的Preferences实例中删除名为给定Key的存储键值对,可通过flush将Preferences实例持久化 - static delete(key: string): void { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - preferences.deleteSync(key); - log.info("Succeeded in deleting the key."); - Preferences.flush(); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to delete. code =" + code + ", message =" + message); - } - } - - // 将缓存的Preferences实例中的数据异步存储到用户首选项的持久化文件中,使用Promise异步回调。 - static flush(): void { - if (preferences === null) { - Preferences.getPreferences(); - } - preferences.flush().then(()=>{ - log.info("Succeeded in flushing."); - }); - } - - // 清除缓存的Preferences实例中的所有数据,可通过flush将Preferences实例持久化,使用Promise异步回调。 - static clear(): void { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - preferences.clearSync(); - log.info("Succeeded in clearing."); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to clear. code =" + code + ", message =" + message); - } - } - - - // 订阅数据变更,订阅的Key的值发生变更后,在执行flush方法后,触发callback回调。 - static onChange(cb: Function): void { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - preferences.on('change', (key: string) => { - log.info("The key " + key + " changed."); - cb(key); - }); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to flush. code =" + code + ", message =" + message); - } - } - - // 取消订阅数据变更。 - static offChange(cb: Function): void { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - preferences.off('change', (key: string) => { - log.info("The key " + key + " changed."); - cb(key); - }); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to flush. code =" + code + ", message =" + message); - } - } -} - -// 由于ArkTS中无Object.keys,且无法使用for..in... -// 若报ArkTS问题,请将此方法单独抽离至一个ts文件中并暴露,在需要用到的ets文件中引入使用 -function getObjKeys(obj: Object): string[] { - let keys = Object.keys(obj); - return keys; -} \ No newline at end of file diff --git a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManager.ts b/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManager.ts deleted file mode 100644 index dfa95dfaa5ab..000000000000 --- a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManager.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { ThreadWorkerGlobalScope } from '@ohos.worker'; -import { JumpMsgEntity } from '../../entity/WorkerMsgEntity'; - -export class JumpManager { - - static MODULE_NAME: string = 'JumpManager'; - - private static workerPort: ThreadWorkerGlobalScope; - - static init(workerPort: ThreadWorkerGlobalScope) : void { - JumpManager.workerPort = workerPort; - } - - static openUrl(url: string) : void { - let jumpMsgEntity: JumpMsgEntity = new JumpMsgEntity(JumpManager.MODULE_NAME, 'openUrl'); - jumpMsgEntity.url = url; - JumpManager.workerPort.postMessage(jumpMsgEntity); - } -} diff --git a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManagerMsg.ts b/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManagerMsg.ts deleted file mode 100644 index ea373af90811..000000000000 --- a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManagerMsg.ts +++ /dev/null @@ -1,31 +0,0 @@ -import type common from '@ohos.app.ability.common'; -import { GlobalContext, GlobalContextConstants } from '../../common/GlobalContext'; -import {Result} from "../../entity/Result" -import type { JumpMsgEntity } from '../../entity/WorkerMsgEntity'; -import Logger from '../../utils/Logger' - -let log: Logger = new Logger(0x0001, "JumpManagerMsg"); - -export function handleJumpManagerMsg(eventData: JumpMsgEntity) : void { - switch (eventData.function) { - case "openUrl": - openUrl(eventData.url); - break; - default: - log.error('%{public}s has not implement yet', eventData.function); - } -} - -function openUrl(url: string): void { - let context: common.UIAbilityContext = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT); - let wantInfo = { - 'action': 'ohos.want.action.viewData', - 'entities': ['entity.system.browsable'], - 'uri': url - } - context.startAbility(wantInfo).then(() => { - log.info('%{public}s', JSON.stringify(Result.success({}))); - }).catch((err) => { - log.error('openUrl : err : %{public}s', JSON.stringify(Result.error(-1, JSON.stringify(err))) ?? ''); - }); -} \ No newline at end of file diff --git a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/application/ApplicationManager.ts b/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/application/ApplicationManager.ts deleted file mode 100644 index 9a552f56e49f..000000000000 --- a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/application/ApplicationManager.ts +++ /dev/null @@ -1,54 +0,0 @@ -import bundleManager from '@ohos.bundle.bundleManager'; -import type { ThreadWorkerGlobalScope } from '@ohos.worker'; -import { BaseWorkerMsgEntity } from '../../entity/WorkerMsgEntity'; -import { common } from '@kit.AbilityKit'; -import { BusinessError } from '@kit.BasicServicesKit'; -import { GlobalContext, GlobalContextConstants } from '../../common/GlobalContext'; - -export class ApplicationManager { - static MODULE_NAME: string = 'ApplicationManager'; - - private static workerPort: ThreadWorkerGlobalScope; - - static init(workerPort: ThreadWorkerGlobalScope): void { - ApplicationManager.workerPort = workerPort; - } - - static exit(): void { - let workerMsg: BaseWorkerMsgEntity = new BaseWorkerMsgEntity(ApplicationManager.MODULE_NAME, 'exit'); - ApplicationManager.workerPort.postMessage(workerMsg); - } - - static getVersionName(): string { - let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; - return bundleManager.getBundleInfoForSelfSync(bundleFlags).versionName; - } -} - -export function handleApplicationMsg(eventData: BaseWorkerMsgEntity): void { - switch (eventData.function) { - case "exit": - terminateSelf(); - break; - default: - console.error('%{public}s has not implement yet', eventData.function); - } -} - -function terminateSelf(): void { - try { - let context: common.UIAbilityContext = - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT); - context.terminateSelf((err: BusinessError) => { - if (err.code) { - console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`); - return; - } - console.info('terminateSelf succeed'); - }); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - console.error(`terminateSelf failed, code is ${code}, message is ${message}`); - } -} diff --git a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/device/DeviceUtils.ts b/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/device/DeviceUtils.ts deleted file mode 100644 index b778f1584810..000000000000 --- a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/device/DeviceUtils.ts +++ /dev/null @@ -1,164 +0,0 @@ -import display from '@ohos.display' -import i18n from '@ohos.i18n'; -import vibrator from '@ohos.vibrator'; -import Logger from '../../utils/Logger'; -import window from '@ohos.window'; -import { GlobalContext, GlobalContextConstants } from '../../common/GlobalContext'; -import { Rect } from '@ohos.application.AccessibilityExtensionAbility'; - -let log = new Logger(0x0001, "DeviceUtils"); - -export class DeviceUtils { - static MODULE_NAME: string = 'DeviceUtils'; - static _roundScreen: boolean = false; - static _hasSoftKeys: boolean = false; - static _isCutoutEnable: boolean = false; - static _cutoutLeft: number; - static _cutoutWidth: number; - static _cutoutTop: number; - static _cutoutHeight: number; - - static getDpi(): number { - return display.getDefaultDisplaySync().densityDPI; - } - - static getSystemLanguage(): string { - return i18n.System.getSystemLanguage(); - } - - static startVibration(time: number) { - try { - vibrator.startVibration({ - type: 'time', - duration: time * 1000, // Seconds to milliseconds - }, { - id: 0, - usage: 'unknown' - }, (error) => { - if (error) { - log.error('vibrate fail, error.code: %{public}d, error.message: %{public}s', error.code, error.message); - return; - } - }); - } catch (err) { - log.error('error.code: %{public}d, error.message: %{public}s', err.code, err.message); - } - } - - static setKeepScreenOn(value: boolean) { - let windowClass = null; - try { - window.getLastWindow(GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT), (err, data) => { //获取窗口实例 - if (err.code) { - log.error('Failed to obtain last window when setKeepScreenOn. Cause:%{public}s', JSON.stringify(err)); - return; - } - windowClass = data; - // Sets whether the screen is always on. - let keepScreenOnPromise = windowClass.setWindowKeepScreenOn(value); - Promise.all([keepScreenOnPromise]).then(() => { - log.info('Succeeded in setKeepScreenOn, value:%{public}s', value); - }).catch((err) => { - log.error('Failed to setKeepScreenOn, cause:%{public}s', JSON.stringify(err)); - }); - }); - } catch (exception) { - log.error('Failed to get or set the window when setKeepScreenOn, cause:%{public}s', JSON.stringify(exception)); - } - } - - static isRoundScreen() : boolean { - return DeviceUtils._roundScreen; - } - - static hasSoftKeys() : boolean { - return DeviceUtils._hasSoftKeys; - } - - static isCutoutEnable() : boolean { - return DeviceUtils._isCutoutEnable; - } - - static initScreenInfo() : void { - let windowClass = null; - try { - window.getLastWindow(GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT), (err, data) => { - if (err.code) { - log.error('Failed to obtain last window when initScreenInfo. Cause:%{public}s', JSON.stringify(err)); - return; - } - - windowClass = data; - let windowProperties: window.WindowProperties = windowClass.getWindowProperties(); - DeviceUtils._roundScreen = windowProperties.isRoundCorner; - let rect: Rect = windowProperties.windowRect; - if(rect.top + rect.height < display.getDefaultDisplaySync().height) { - DeviceUtils._hasSoftKeys = true; - } else { - DeviceUtils._hasSoftKeys = false; - } - }); - } catch (exception) { - log.error('Failed to get or set the window when initScreenInfo, cause:%{public}s', JSON.stringify(exception)); - } - - display.getDefaultDisplaySync().getCutoutInfo().then((data) => { - if(data.boundingRects.length == 0) { - DeviceUtils._isCutoutEnable = false; - return; - } - - DeviceUtils._isCutoutEnable = true; - DeviceUtils._cutoutLeft = data.boundingRects[0].left; - DeviceUtils._cutoutTop = data.boundingRects[0].top; - DeviceUtils._cutoutWidth = data.boundingRects[0].width; - DeviceUtils._cutoutHeight = data.boundingRects[0].height; - }).catch((err) => { - log.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); - }); - } - - static getOrientation() : number { - let orientation: display.Orientation = display.getDefaultDisplaySync().orientation; - - // If the system enumeration value changes, the processing logic in the C++ code needs to be changed. Therefore, the mapping is performed again. - if(orientation == display.Orientation.PORTRAIT) { - return 0; - } - - if(orientation == display.Orientation.LANDSCAPE) { - return 1; - } - - if(orientation == display.Orientation.PORTRAIT_INVERTED) { - return 2; - } - - if(orientation == display.Orientation.LANDSCAPE_INVERTED) { - return 3; - } - - return 4; - } - - static getCutoutHeight() : number { - if(DeviceUtils._cutoutHeight) { - let height = DeviceUtils._cutoutTop + DeviceUtils._cutoutHeight; - return height; - } - return 0; - } - - static getCutoutWidth() : number { - if(!DeviceUtils._cutoutWidth) { - return 0; - } - - let disPlayWidth = display.getDefaultDisplaySync().width; - if(DeviceUtils._cutoutLeft + DeviceUtils._cutoutWidth > disPlayWidth - DeviceUtils._cutoutLeft) { - return disPlayWidth - DeviceUtils._cutoutLeft; - } - - return DeviceUtils._cutoutLeft + DeviceUtils._cutoutWidth; - } -} \ No newline at end of file diff --git a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/sensor/AccelerometerUtils.ts b/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/sensor/AccelerometerUtils.ts deleted file mode 100644 index 56309439f011..000000000000 --- a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/sensor/AccelerometerUtils.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { getContext } from "libnativerender.so"; -import { ContextType } from "../../common/Constants" -import sensor from '@ohos.sensor'; -import display from '@ohos.display'; -import {Result} from "../../entity/Result" -import Logger from '../../utils/Logger' - -let log: Logger = new Logger(0x0001, "AccelerometerUtils"); - -const accUtils = getContext(ContextType.SENSOR_API); - -export default class Accelerometer { - - private static instance = new Accelerometer(); - - static getInstance() : Accelerometer { - return Accelerometer.instance; - } - - static enable(intervalTime: number) : void { - try { - /* HarmonyOS allow multiple subscriptions, but the game only need one - so if the interval changed, cancel subscription and redo with the new interval */ - sensor.off(sensor.SensorId.ACCELEROMETER); - sensor.on(sensor.SensorId.ACCELEROMETER, function (data) { - let rotation = display.getDefaultDisplaySync().rotation; - if (rotation === 0) { - // Display device screen rotation 0° - accUtils.onAccelerometerCallBack(data.x, data.y, data.z, intervalTime); - } else if (rotation === 1) { - // Display device screen rotation 90° - accUtils.onAccelerometerCallBack(data.y, -data.x, data.z, intervalTime); - } else if (rotation === 2) { - // Display device screen rotation 180° - accUtils.onAccelerometerCallBack(-data.x, -data.y, data.z, intervalTime); - } else if (rotation === 3) { - // Display device screen rotation 270° - accUtils.onAccelerometerCallBack(-data.y, data.x, data.z, intervalTime); - } else { - log.error('Accelerometer init fail, err: %{public}s', JSON.stringify(Result.error(-1, 'unsupported rotation: ' + rotation))); - } - }, { interval: intervalTime }); - } catch (err) { - log.error('Accelerometer init fail, err: %{public}s', JSON.stringify(Result.error(-1, JSON.stringify(err))) ?? ''); - } - } - - static disable() : void { - try { - sensor.off(sensor.SensorId.ACCELEROMETER); - } catch (err) { - log.error('Accelerometer off fail, err: %{public}s', JSON.stringify(Result.error(-1, JSON.stringify(err))) ?? ''); - } - } -} \ No newline at end of file diff --git a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/Logger.ts b/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/Logger.ts deleted file mode 100644 index 6277b0e1ab52..000000000000 --- a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/Logger.ts +++ /dev/null @@ -1,27 +0,0 @@ -import hilog from '@ohos.hilog' - -export default class Logger { - private domain: number - private prefix: string - - constructor(domain : number, prefix: string) { - this.domain = domain - this.prefix = prefix - } - - debug(format: string, ...args: any[]) { - hilog.debug(this.domain, this.prefix, format, args) - } - - info(format: string, ...args: any[]) { - hilog.info(this.domain, this.prefix, format, args) - } - - warn(format: string, ...args: any[]) { - hilog.warn(this.domain, this.prefix, format, args) - } - - error(format: string, ...args: any[]) { - hilog.error(this.domain, this.prefix, format, args) - } -} \ No newline at end of file diff --git a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/StringUtils.ts b/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/StringUtils.ts deleted file mode 100644 index 4e3d20ec55e1..000000000000 --- a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/StringUtils.ts +++ /dev/null @@ -1,8 +0,0 @@ -import measure from '@ohos.measure'; - -export default class StringUtils { - - public static getWidth(text: string, fontSize: number, fontWeight: number): number { - return measure.measureText({ textContent: text, fontSize: fontSize + 'px', fontWeight: fontWeight }); - } -} \ No newline at end of file diff --git a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/WorkerMsgUtils.ets b/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/WorkerMsgUtils.ets deleted file mode 100644 index b9cac7106b18..000000000000 --- a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/WorkerMsgUtils.ets +++ /dev/null @@ -1,42 +0,0 @@ -import worker, { MessageEvents } from '@ohos.worker'; -import Logger from './Logger'; -import { handleEditBoxMsg } from '../components/editbox/EditBoxMsg' -import { handleWebViewMsg } from '../components/webview/WebViewMsg' -import { handleVideoPlayMsg } from '../components/videoplayer/VideoPlayerMsg' -import { handleDialogMsg } from '../components/dialog/DialogMsg' -import { handleJumpManagerMsg } from '../system/appJump/JumpManagerMsg' -import { handleApplicationMsg } from '../system/application/ApplicationManager' -import { BaseWorkerMsgEntity, DialogMsgEntity, EditBoxMsgEntity, JumpMsgEntity, VideoPlayMsgEntity, WebViewMsgEntity } from '../entity/WorkerMsgEntity'; - -export class WorkerMsgUtils { - static workPort = worker.workerPort; - static log : Logger = new Logger(0x0001, 'WorkerMsgUtils') - - static async recvWorkerThreadMessage(event: MessageEvents) { - let eventData: BaseWorkerMsgEntity = event.data; - WorkerMsgUtils.log.debug('mainThread receiveMsg, module:%{public}s, function:%{public}s', eventData.module, eventData.function); - - switch (eventData.module) { - case 'EditBox': - handleEditBoxMsg(eventData as EditBoxMsgEntity); - break; - case "Dialog": - handleDialogMsg(eventData as DialogMsgEntity); - break; - case 'WebView': - handleWebViewMsg(eventData as WebViewMsgEntity); - break; - case 'VideoPlay': - handleVideoPlayMsg(eventData as VideoPlayMsgEntity); - break; - case 'JumpManager': - handleJumpManagerMsg(eventData as JumpMsgEntity); - break; - case 'ApplicationManager': - handleApplicationMsg(eventData as BaseWorkerMsgEntity); - break; - default: - WorkerMsgUtils.log.error('%{public}s has not implement yet', eventData.module); - } - } -} diff --git a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/module.json5 b/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/module.json5 deleted file mode 100644 index daa1891126f5..000000000000 --- a/tests/js-tests/project/proj.ohos/libSysCapabilities/src/main/module.json5 +++ /dev/null @@ -1,10 +0,0 @@ -{ - "module": { - "name": "libSysCapabilities", - "type": "har", - "deviceTypes": [ - "phone", - "tablet" - ] - } -} diff --git a/tests/js-tests/project/proj.ohos/oh-package.json5 b/tests/js-tests/project/proj.ohos/oh-package.json5 deleted file mode 100644 index 1ebf93ed2afb..000000000000 --- a/tests/js-tests/project/proj.ohos/oh-package.json5 +++ /dev/null @@ -1,10 +0,0 @@ -{ - "modelVersion": "5.0.0", - "license": "ISC", - "devDependencies": {}, - "name": "proj.ohos", - "description": "example description", - "repository": {}, - "version": "1.0.0", - "dependencies": {} -} \ No newline at end of file diff --git a/tests/lua-tests/project/CMakeLists.txt b/tests/lua-tests/project/CMakeLists.txt index 14ef017e834f..85ab348ff4d7 100644 --- a/tests/lua-tests/project/CMakeLists.txt +++ b/tests/lua-tests/project/CMakeLists.txt @@ -30,13 +30,12 @@ elseif(OHOS) file(GLOB resFiles "${CMAKE_CURRENT_LIST_DIR}/../res/*") file(COPY ${resFiles} DESTINATION ${CMAKE_CURRENT_LIST_DIR}/proj.ohos/entry/src/main/resources/rawfile) file(GLOB srcFiles "${CMAKE_CURRENT_LIST_DIR}/../src/*") - file(COPY ${srcFiles} DESTINATION ${CMAKE_CURRENT_LIST_DIR}/proj.ohos/entry/src/main/resources/rawfile) + file(COPY ${srcFiles} DESTINATION ${CMAKE_CURRENT_LIST_DIR}/proj.ohos/entry/src/main/resources/rawfile/src) file(GLOB testResource ${COCOS2DX_ROOT_PATH}/tests/cpp-tests/Resources/*) file(COPY ${testResource} DESTINATION ${CMAKE_CURRENT_LIST_DIR}/proj.ohos/entry/src/main/resources/rawfile) - if(NOT EXISTS ${CMAKE_CURRENT_LIST_DIR}/proj.ohos/entry/src/main/resources/rawfile/cocos) file(GLOB cocosFiles "${COCOS2DX_ROOT_PATH}/cocos/scripting/lua-bindings/script/*") - file(COPY ${cocosFiles} DESTINATION ${CMAKE_CURRENT_LIST_DIR}/proj.ohos/entry/src/main/resources/rawfile/cocos) - endif() + file(COPY ${cocosFiles} DESTINATION ${CMAKE_CURRENT_LIST_DIR}/proj.ohos/entry/src/main/resources/rawfile/src/cocos) + endif() include_directories( @@ -49,6 +48,65 @@ include_directories( if (OHOS) add_library(${APP_NAME} STATIC ${SAMPLE_SRC}) + set(CMAKE_CXX_FLAGS "-frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -fsigned-char ${CMAKE_CXX_FLAGS}") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O2") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O2") + 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. + GLES-lib + # Specifies the name of the NDK library that + # you want CMake to locate. + GLESv3 ) + + find_library( # Sets the name of the path variable. + hilog-lib + # Specifies the name of the NDK library that + # you want CMake to locate. + hilog_ndk.z ) + + find_library( # Sets the name of the path variable. + libace-lib + # Specifies the name of the NDK library that + # you want CMake to locate. + ace_ndk.z ) + + find_library( # Sets the name of the path variable. + libnapi-lib + # Specifies the name of the NDK library that + # you want CMake to locate. + ace_napi.z ) + + find_library( # Sets the name of the path variable. + libuv-lib + # Specifies the name of the NDK library that + # you want CMake to locate. + uv ) + find_library( # Sets the name of the path variable. + rawfile-lib + # Specifies the name of the NDK library that + # you want CMake to locate. + rawfile.z ) + + + include_directories(${COCOS2DX_ROOT_PATH}/external/opengles/api) + include_directories(${COCOS2DX_ROOT_PATH}/external/bullet/include) + include_directories(${COCOS2DX_ROOT_PATH}/external/bullet/include/bullet) + target_include_directories(${APP_NAME} PUBLIC ${COCOS2DX_ROOT_PATH}/external/chipmunk/include) + target_include_directories(${APP_NAME} PUBLIC ${CLASSES_PATH} + PUBLIC ${CLASSES_PATH}/../.. + ) + target_include_directories(${APP_NAME} PUBLIC ${COCOS2DX_ROOT_PATH}/cocos/platform/ohos/napi/common + PUBLIC ${COCOS2DX_ROOT_PATH}/cocos/platform/ohos/napi/modules + PUBLIC ${COCOS2DX_ROOT_PATH}/cocos/platform/ohos/napi + PUBLIC ${COCOS2DX_ROOT_PATH}/cocos/platform/ohos + PUBLIC ${COCOS2DX_ROOT_PATH}/cocos + PUBLIC ${COCOS2DX_ROOT_PATH}/cocos/base + ) else() # add the executable add_executable(${APP_NAME} ${SAMPLE_SRC}) diff --git a/tests/lua-tests/project/proj.ohos b/tests/lua-tests/project/proj.ohos new file mode 160000 index 000000000000..75d72fc6133b --- /dev/null +++ b/tests/lua-tests/project/proj.ohos @@ -0,0 +1 @@ +Subproject commit 75d72fc6133ba367c0e10617042c2bf910ca93fe diff --git a/tests/lua-tests/project/proj.ohos/.gitignore b/tests/lua-tests/project/proj.ohos/.gitignore deleted file mode 100644 index ec2bca6cb530..000000000000 --- a/tests/lua-tests/project/proj.ohos/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -.hvigor -.idea -node_modules -entry/build -entry/.idea -entry/.cxx -local.properties -package-lock.json -entry/src/main/resources/rawfile -oh_modules -/.clangd -/.clang-tidy -.clang-format -hvigor/hvigor-wrapper.js \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/AppScope/app.json5 b/tests/lua-tests/project/proj.ohos/AppScope/app.json5 deleted file mode 100644 index 74c42525fffc..000000000000 --- a/tests/lua-tests/project/proj.ohos/AppScope/app.json5 +++ /dev/null @@ -1,11 +0,0 @@ -{ - "app": { - "bundleName": "ohos.cocos3_16.lua.tests", - "vendor": "example", - "versionCode": 1000000, - "versionName": "1.0.0", - "icon": "$media:app_icon", - "label": "$string:app_name", - "distributedNotificationEnabled": true - } -} diff --git a/tests/lua-tests/project/proj.ohos/AppScope/resources/base/element/string.json b/tests/lua-tests/project/proj.ohos/AppScope/resources/base/element/string.json deleted file mode 100644 index 2eab588856e7..000000000000 --- a/tests/lua-tests/project/proj.ohos/AppScope/resources/base/element/string.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "string": [ - { - "name": "app_name", - "value": "3.16_lua_tests" - } - ] -} diff --git a/tests/lua-tests/project/proj.ohos/AppScope/resources/base/media/app_icon.png b/tests/lua-tests/project/proj.ohos/AppScope/resources/base/media/app_icon.png deleted file mode 100644 index ce307a8827bd75456441ceb57d530e4c8d45d36c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6790 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 { - OHOS_LOGD("Cocos2dxRenderer_nativeInit() - branch 1"); - GLView *view = GLViewImpl::sharedOpenGLView(); - view->setFrameSize(w, h); - CCDirector::sharedDirector()->setOpenGLView(view); - - AppDelegate *pAppDelegate = new AppDelegate(); - CCApplication::sharedApplication()->run(); - } else { - OHOS_LOGD("Cocos2dxRenderer_nativeInit() - branch 2"); - ccGLInvalidateStateCache(); - CCShaderCache::sharedShaderCache()->reloadDefaultShaders(); - ccDrawInit(); - CCTextureCache::reloadAllTextures(); - CCNotificationCenter::sharedNotificationCenter()->postNotification(EVENT_COME_TO_FOREGROUND, NULL); - CCDirector::sharedDirector()->setGLDefaultValues(); - } -} - -} diff --git a/tests/lua-tests/project/proj.ohos/entry/src/main/cpp/napi_init.cpp b/tests/lua-tests/project/proj.ohos/entry/src/main/cpp/napi_init.cpp deleted file mode 100644 index 5524d88b40bb..000000000000 --- a/tests/lua-tests/project/proj.ohos/entry/src/main/cpp/napi_init.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "CCLogOhos.h" -#include "napi/plugin_manager.h" - -/* - * function for module exports - */ -static napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor desc[] ={ - DECLARE_NAPI_FUNCTION("getContext", NapiManager::GetContext), - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); - - bool ret = NapiManager::GetInstance()->Export(env, exports); - if (!ret) { - OHOS_LOGE("Init failed"); - } - return exports; -} - -/* - * Napi Module define - */ -static napi_module nativerenderModule = { - .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = Init, - .nm_modname = "nativerender", - .nm_priv = ((void*)0), - .reserved = { 0 }, -}; -/* - * Module register function - */ -extern "C" __attribute__((constructor)) void RegisterModule(void) { - napi_module_register(&nativerenderModule); -} \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/entry/src/main/cpp/types/libentry/index.d.ts b/tests/lua-tests/project/proj.ohos/entry/src/main/cpp/types/libentry/index.d.ts deleted file mode 100644 index 039f1682c3da..000000000000 --- a/tests/lua-tests/project/proj.ohos/entry/src/main/cpp/types/libentry/index.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -import resmgr from '@ohos.resourceManager'; - -export interface CPPFunctions { - onCreate: () => void; - onShow: () => void; - onHide: () => void; - onBackPress: () => void; - onDestroy: () => void; - onPageShow: () => void; - onPageHide: () => void; - nativeResourceManagerInit: (resourceManager: resmgr.ResourceManager) => void; - writablePathInit: (writePath: string) => void; - workerInit: () => void; - nativeEngineStart: () => void; - registerFunction: () => void; - initAsyncInfo: () => void; - mouseWheelCB: (eventType: string, scrollY : number) => void; - editBoxOnFocusCB: (viewTag: number) => void; - editBoxOnChangeCB: (viewTag: number, text: string) => void; - editBoxOnEnterCB: (viewTag: number, text: string) => void; - textFieldTTFOnChangeCB: (text: string) => void; - shouldStartLoading: (viewTag: number, url: string) => void; - finishLoading: (viewTag: number, url: string) => void; - failLoading: (viewTag: number, url: string) => void; - jsCallback: () => void; - onVideoCallBack: (viewTag: number, event: number) => void; - onAccelerometerCallBack: (x: number, y: number, z: number, interval: number) => void; -} - -export const getContext: (a: number) => CPPFunctions; \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/entry/src/main/cpp/types/libentry/oh-package.json5 b/tests/lua-tests/project/proj.ohos/entry/src/main/cpp/types/libentry/oh-package.json5 deleted file mode 100644 index fa7874d5940d..000000000000 --- a/tests/lua-tests/project/proj.ohos/entry/src/main/cpp/types/libentry/oh-package.json5 +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "libnativerender.so", - "types": "./index.d.ts", - "version": "", - "description": "Please describe the basic information." -} \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/entry/src/main/ets/MainAbility/MainAbility.ts b/tests/lua-tests/project/proj.ohos/entry/src/main/ets/MainAbility/MainAbility.ts deleted file mode 100644 index a4378409d4f4..000000000000 --- a/tests/lua-tests/project/proj.ohos/entry/src/main/ets/MainAbility/MainAbility.ts +++ /dev/null @@ -1,80 +0,0 @@ -import window from '@ohos.window'; -import UIAbility from '@ohos.app.ability.UIAbility'; -import web_webview from '@ohos.web.webview'; -import nativeRender from "libnativerender.so"; -import { ContextType } from "@ohos/libSysCapabilities" -import { GlobalContext,GlobalContextConstants} from "@ohos/libSysCapabilities" - -const nativeAppLifecycle: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.APP_LIFECYCLE); -const rawFileUtils: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.RAW_FILE_UTILS); - -export default class MainAbility extends UIAbility { - onCreate(want, launchParam) { - nativeAppLifecycle.onCreate(); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT, this.context); - // Initializes the webView kernel of the system. This parameter is optional if it is not used. - web_webview.WebviewController.initializeWebEngine(); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_WANT, this.context); - console.info('[LIFECYCLE-App] onCreate') - } - - onDestroy() { - nativeAppLifecycle.onDestroy(); - console.info('[LIFECYCLE-App] onDestroy') - } - - onWindowStageCreate(windowStage) { - // Main window is created, set main page for this ability - windowStage.loadContent('pages/Index', (err, data) => { - if (err.code) { - return; - } - rawFileUtils.nativeResourceManagerInit(this.context.resourceManager); - rawFileUtils.writablePathInit(this.context.filesDir); - }); - - windowStage.getMainWindow().then((windowIns: window.Window) => { - // Set whether to display the status bar and navigation bar. If they are not displayed, [] is displayed. - let systemBarPromise = windowIns.setWindowSystemBarEnable([]); - // Whether the window layout is displayed in full screen mode - let fullScreenPromise = windowIns.setWindowLayoutFullScreen(true); - // Sets whether the screen is always on. - let keepScreenOnPromise = windowIns.setWindowKeepScreenOn(true); - Promise.all([systemBarPromise, fullScreenPromise, keepScreenOnPromise]).then(() => { - console.info('Succeeded in setting the window'); - }).catch((err) => { - console.error('Failed to set the window, cause ' + JSON.stringify(err)); - }); - }) - - windowStage.on("windowStageEvent", (data) => { - let stageEventType: window.WindowStageEventType = data; - switch (stageEventType) { - case window.WindowStageEventType.RESUMED: - nativeAppLifecycle.onShow(); - break; - case window.WindowStageEventType.PAUSED: - nativeAppLifecycle.onHide(); - break; - default: - break; - } - }); - } - - onWindowStageDestroy() { - // Main window is destroyed, release UI related resources - } - - onForeground() { - // Ability has brought to foreground - console.info('[LIFECYCLE-App] onShow') - nativeAppLifecycle.onShow(); - } - - onBackground() { - // Ability has back to background - console.info('[LIFECYCLE-App] onDestroy') - nativeAppLifecycle.onHide(); - } -}; diff --git a/tests/lua-tests/project/proj.ohos/entry/src/main/ets/components/CocosEditBox.ets b/tests/lua-tests/project/proj.ohos/entry/src/main/ets/components/CocosEditBox.ets deleted file mode 100644 index 2587169f240f..000000000000 --- a/tests/lua-tests/project/proj.ohos/entry/src/main/ets/components/CocosEditBox.ets +++ /dev/null @@ -1,82 +0,0 @@ -import { TextInputInfo } from '@ohos/libSysCapabilities/src/main/ets/components/editbox/EditBoxMsg' -import worker from '@ohos.worker'; -import { WorkerManager } from '../workers/WorkerManager'; - -@Component -export struct CocosEditBox { - @ObjectLink textInputInfo: TextInputInfo; - cocosWorker: worker.ThreadWorker = WorkerManager.getInstance().getWorker(); - - build(){ - if(this.textInputInfo.multiline){ - TextArea({text: this.textInputInfo.text, placeholder: this.textInputInfo.placeHolder}) - .id('TextArea'+this.textInputInfo.viewTag) - .position({x: px2vp(this.textInputInfo.x), y: px2vp(this.textInputInfo.y)}) - .size({width: px2vp(this.textInputInfo.w), height: px2vp(this.textInputInfo.h)}) - .padding({top: px2vp(this.textInputInfo.paddingH), right: px2vp(this.textInputInfo.paddingW), - bottom: px2vp(this.textInputInfo.paddingH), left: px2vp(this.textInputInfo.paddingW)}) - .borderRadius(0) - .maxLength(this.textInputInfo.maxLength) - .type(TextAreaType.NORMAL) - .fontFamily($rawfile(this.textInputInfo.fontPath)) - .fontSize(px2fp(this.textInputInfo.fontSize)) - .fontColor(`rgba(${this.textInputInfo.fontColor.r}, ${this.textInputInfo.fontColor.g}, ${this.textInputInfo.fontColor.b}, ${this.textInputInfo.fontColor.a})`) - .placeholderFont({size: px2fp(this.textInputInfo.placeholderFontSize), family: $rawfile(this.textInputInfo.placeHolderFontPath)}) - .placeholderColor(`rgba(${this.textInputInfo.placeholderFontColor.r}, ${this.textInputInfo.placeholderFontColor.g}, ${this.textInputInfo.placeholderFontColor.b}, ${this.textInputInfo.placeholderFontColor.a})`) - .backgroundColor(Color.Transparent) - .visibility(this.textInputInfo.visible ? Visibility.Visible : Visibility.None) - .onVisibleAreaChange([0.0, 1.0], () => { - focusControl.requestFocus('TextArea' + this.textInputInfo.viewTag); - }) - .onFocus(() => { - this.cocosWorker.postMessage({type: "editBoxOnFocus", viewTag: this.textInputInfo.viewTag}); - }) - .onChange((value: string)=>{ - this.textInputInfo.text = value; - this.cocosWorker.postMessage({type: "editBoxOnChange", viewTag: this.textInputInfo.viewTag, value: value}); - }) - .onBlur(()=> { - this.textInputInfo.visible = false - this.cocosWorker.postMessage({type: "editBoxOnEnter", viewTag: this.textInputInfo.viewTag, text: this.textInputInfo.text}); - }) - .onSubmit(()=>{ - this.cocosWorker.postMessage({type: "editBoxOnEnter", viewTag: this.textInputInfo.viewTag, text: this.textInputInfo.text}); - }) - }else{ - TextInput({text: this.textInputInfo.text, placeholder: this.textInputInfo.placeHolder}) - .id('TextInput'+this.textInputInfo.viewTag) - .position({x: px2vp(this.textInputInfo.x), y: px2vp(this.textInputInfo.y)}) - .size({width: px2vp(this.textInputInfo.w), height: px2vp(this.textInputInfo.h)}) - .padding({top: px2vp(this.textInputInfo.paddingH), right: px2vp(this.textInputInfo.paddingW), - bottom: px2vp(this.textInputInfo.paddingH), left: px2vp(this.textInputInfo.paddingW)}) - .borderRadius(0) - .maxLength(this.textInputInfo.maxLength) - .type(this.textInputInfo.inputMode) - .fontFamily($rawfile(this.textInputInfo.fontPath)) - .fontSize(px2fp(this.textInputInfo.fontSize)) - .fontColor(`rgba(${this.textInputInfo.fontColor.r}, ${this.textInputInfo.fontColor.g}, ${this.textInputInfo.fontColor.b}, ${this.textInputInfo.fontColor.a})`) - .placeholderFont({size: px2fp(this.textInputInfo.placeholderFontSize), family: $rawfile(this.textInputInfo.placeHolderFontPath)}) - .placeholderColor(`rgba(${this.textInputInfo.placeholderFontColor.r}, ${this.textInputInfo.placeholderFontColor.g}, ${this.textInputInfo.placeholderFontColor.b}, ${this.textInputInfo.placeholderFontColor.a})`) - .backgroundColor(Color.Transparent) - .visibility(this.textInputInfo.visible ? Visibility.Visible : Visibility.None) - .showPasswordIcon(false) - .onVisibleAreaChange([0.0, 1.0], () => { - focusControl.requestFocus('TextInput' + this.textInputInfo.viewTag); - }) - .onFocus(() => { - this.cocosWorker.postMessage({type: "editBoxOnFocus", viewTag: this.textInputInfo.viewTag}); - }) - .onChange((value: string)=>{ - this.textInputInfo.text = value; - this.cocosWorker.postMessage({type: "editBoxOnChange", viewTag: this.textInputInfo.viewTag, value: value}); - }) - .onBlur(()=> { - this.textInputInfo.visible = false - this.cocosWorker.postMessage({type: "editBoxOnEnter", viewTag: this.textInputInfo.viewTag, text: this.textInputInfo.text}); - }) - .onSubmit(()=>{ - this.cocosWorker.postMessage({type: "editBoxOnEnter", viewTag: this.textInputInfo.viewTag, text: this.textInputInfo.text}); - }) - } - } -} diff --git a/tests/lua-tests/project/proj.ohos/entry/src/main/ets/components/CocosVideoPlayer.ets b/tests/lua-tests/project/proj.ohos/entry/src/main/ets/components/CocosVideoPlayer.ets deleted file mode 100644 index 6f67afe3b443..000000000000 --- a/tests/lua-tests/project/proj.ohos/entry/src/main/ets/components/CocosVideoPlayer.ets +++ /dev/null @@ -1,39 +0,0 @@ -import { WorkerManager } from '../workers/WorkerManager' -import { VideoPlayerInfo, VideoEvent } from '@ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayerMsg'; -import worker from '@ohos.worker'; - -@Component -export struct CocosVideoPlayer { - @ObjectLink videoPlayerInfo: VideoPlayerInfo; - cocosWorker: worker.ThreadWorker = WorkerManager.getInstance().getWorker(); - - build() { - Column() { - Video({ - src: this.videoPlayerInfo.isUrl ? this.videoPlayerInfo.url : this.videoPlayerInfo.rawfile, - controller: this.videoPlayerInfo.controller - }) - .width(this.videoPlayerInfo.w) - .height(this.videoPlayerInfo.h) - .visibility(this.videoPlayerInfo.visible ? Visibility.Visible : Visibility.None) - .controls(false) - .loop(this.videoPlayerInfo.isLoop) - .objectFit(this.videoPlayerInfo.objectFit) - .onPrepared(()=>{ - if(this.videoPlayerInfo.isPlay) { - this.videoPlayerInfo.controller.start() - } - this.videoPlayerInfo.controller.requestFullscreen(this.videoPlayerInfo.isFullScreen) - }) - .onStart(()=>{ - this.cocosWorker.postMessage({type: "onVideoCallBack", viewTag: this.videoPlayerInfo.viewTag, event: VideoEvent.PLAYING}); - }) - .onPause(()=>{ - this.cocosWorker.postMessage({type: "onVideoCallBack", viewTag: this.videoPlayerInfo.viewTag, event: VideoEvent.PAUSED}); - }) - .onFinish(()=>{ - this.cocosWorker.postMessage({type: "onVideoCallBack", viewTag: this.videoPlayerInfo.viewTag, event: VideoEvent.COMPLETED}); - }) - } - } -} diff --git a/tests/lua-tests/project/proj.ohos/entry/src/main/ets/components/CocosWebview.ets b/tests/lua-tests/project/proj.ohos/entry/src/main/ets/components/CocosWebview.ets deleted file mode 100644 index f26ba14cc6e7..000000000000 --- a/tests/lua-tests/project/proj.ohos/entry/src/main/ets/components/CocosWebview.ets +++ /dev/null @@ -1,43 +0,0 @@ -import { WebViewInfo } from "@ohos/libSysCapabilities/src/main/ets/components/webview/WebViewMsg" -import worker from '@ohos.worker'; -import { WorkerManager } from '../workers/WorkerManager'; - -@Component -export struct CocosWebView { - viewInfo: WebViewInfo = new WebViewInfo(0, 0, 0, 0, 0); - cocosWorker: worker.ThreadWorker = WorkerManager.getInstance().getWorker(); - - build() { - Web({ src: this.viewInfo.isUrl ? this.viewInfo.url : $rawfile(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 }) - .domStorageAccess(true) - .databaseAccess(true) - .imageAccess(true) - .onlineImageAccess(true) - .zoomAccess(this.viewInfo.zoomAccess) - .javaScriptAccess(true) - .visibility(this.viewInfo.visible ? Visibility.Visible : Visibility.None) - .opacity(this.viewInfo.opacity) - .backgroundColor(this.viewInfo.backgroundColor) - .onPageBegin((event) => { - this.cocosWorker.postMessage({ type: "onPageBegin", viewTag: this.viewInfo.viewTag, url: event == null ? '' : event.url }); - }) - .onPageEnd((event) => { - this.cocosWorker.postMessage({ type: "onPageEnd", viewTag: this.viewInfo.viewTag, url: event == null ? '' : event.url }) - if(this.viewInfo.jsInterfaceScheme != "" && event != null && event.url.startsWith(this.viewInfo.jsInterfaceScheme)) { - this.cocosWorker.postMessage({ type: "onJsCallBack", viewTag: this.viewInfo.viewTag, url: event == null ? '' : event.url }) - } - // if u want use the javascript on ur page, u can use registerJavaScriptProxy() to register js function here - // and confirm that just register once by a local variable - }) - .onErrorReceive((event) => { - this.cocosWorker.postMessage({ type: "onErrorReceive", viewTag: this.viewInfo.viewTag, url: this.viewInfo.url }) - }) - .onHttpErrorReceive((event) => { - this.cocosWorker.postMessage({ type: "onErrorReceive", viewTag: this.viewInfo.viewTag, url: this.viewInfo.url }) - }) - } -} \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/entry/src/main/ets/components/TextInputDialog.ets b/tests/lua-tests/project/proj.ohos/entry/src/main/ets/components/TextInputDialog.ets deleted file mode 100644 index 4a689341cc0a..000000000000 --- a/tests/lua-tests/project/proj.ohos/entry/src/main/ets/components/TextInputDialog.ets +++ /dev/null @@ -1,33 +0,0 @@ -import { TextInputDialogEntity } from '@ohos/libSysCapabilities' -import worker from '@ohos.worker'; -import { WorkerManager } from '../workers/WorkerManager'; - -@CustomDialog -export struct TextInputDialog { - @State showMessage: TextInputDialogEntity = new TextInputDialogEntity(''); - cocosWorker: worker.ThreadWorker = WorkerManager.getInstance().getWorker(); - controller?: CustomDialogController - - build() { - Column() { - Row() { - TextInput({ text: this.showMessage.message }) - .backgroundColor('#ffffff') - .layoutWeight(1) - .defaultFocus(true) - .caretColor(Color.Transparent) - .onChange((value) => { - this.cocosWorker.postMessage({type: "textFieldTTFOnChange", data: value}) - }) - Blank(8).width(16) - Button($r('app.string.text_field_ttf_complete')).onClick(() => { - this.controller!.close(); - }) - }.padding({ left: 8, right: 8, top: 8, bottom: 8 }) - .backgroundColor(Color.Gray) - } - .width('100%') - - .justifyContent(FlexAlign.End) - } -} \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/entry/src/main/ets/pages/Index.ets b/tests/lua-tests/project/proj.ohos/entry/src/main/ets/pages/Index.ets deleted file mode 100644 index 0a46024aa591..000000000000 --- a/tests/lua-tests/project/proj.ohos/entry/src/main/ets/pages/Index.ets +++ /dev/null @@ -1,157 +0,0 @@ -import deviceInfo from '@ohos.deviceInfo'; - -import nativeRender from 'libnativerender.so' -import { ContextType } from '@ohos/libSysCapabilities' -import { TextInputInfo } from '@ohos/libSysCapabilities/src/main/ets/components/editbox/EditBoxMsg' -import { TextInputDialogEntity } from '@ohos/libSysCapabilities' -import { WebViewInfo } from '@ohos/libSysCapabilities/src/main/ets/components/webview/WebViewMsg' -import { VideoPlayerInfo } from '@ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayerMsg' -import { WorkerMsgUtils } from '@ohos/libSysCapabilities/src/main/ets/utils/WorkerMsgUtils' -import { WorkerManager } from '../workers/WorkerManager' -import { CocosEditBox } from '../components/CocosEditBox' -import { CocosWebView } from '../components/CocosWebview' -import { CocosVideoPlayer } from '../components/CocosVideoPlayer' -import { TextInputDialog } from '../components/TextInputDialog' -import { GlobalContext,GlobalContextConstants} from "@ohos/libSysCapabilities" -import promptAction from '@ohos.promptAction'; -import process from '@ohos.process'; -const nativePageLifecycle:nativeRender.CPPFunctions = nativeRender.getContext(ContextType.JSPAGE_LIFECYCLE); - -@Entry -@Component -struct Index { - - cocosWorker = WorkerManager.getInstance().getWorker(); - xcomponentController: XComponentController = new XComponentController(); - - processMgr = new process.ProcessManager(); - - - // EditBox - @State editBoxArray: TextInputInfo[] = []; - private editBoxIndexMap: Map = new Map; - - // WebView - @State webViewArray: WebViewInfo[] = []; - private webViewIndexMap: Map = new Map; - - // videoPlayer - @State videoPlayerInfoArray: VideoPlayerInfo[] = []; - private videoPlayerIndexMap: Map = new Map; - - // textInputDialog - showMessage: TextInputDialogEntity = new TextInputDialogEntity(''); - dialogController: CustomDialogController = new CustomDialogController({ - builder: TextInputDialog({ - showMessage: this.showMessage - }), - autoCancel: true, - alignment: DialogAlignment.Bottom, - customStyle: true, - }) - // PanGesture - private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down }); - - onPageShow() { - console.log('[LIFECYCLE-Page] onPageShow'); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_ARRAY, this.editBoxArray); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP, this.editBoxIndexMap); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_COCOS_WORKER, this.cocosWorker); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY, this.webViewArray); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP, this.webViewIndexMap); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_ARRAY, this.videoPlayerInfoArray); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP, this.videoPlayerIndexMap); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_DIALOG_CONTROLLER, this.dialogController); - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_SHOW_MESSAGE, this.showMessage); - nativePageLifecycle.onPageShow(); - } - - onPageHide() { - console.log('[LIFECYCLE-Page] onPageHide'); - nativePageLifecycle.onPageHide(); - } - - onBackPress() { - console.log('[LIFECYCLE-Page] onBackPress'); - try { - promptAction.showDialog({ - title: "提示", - message: "确认退出游戏吗", - buttons: [ - { - text: '取消', - color: '#000000' - }, - { - text: '确认', - color: '#000000' - } - ], - }).then(data => { - console.info('showDialog success, click button: ' + data.index); - if(data.index == 0) { - console.info('showDialog click button cancel'); - return; - } else { - console.info('showDialog click button ok'); - this.processMgr.exit(0); - } - }) - } catch (error) { - console.error(`showDialog args error code is ${error.code}, message is ${error.message}`); - }; - // If disable system exit needed, remove comment "return true" - return true; - } - onMouseWheel(eventType: string, scrollY: number) { - this.cocosWorker.postMessage({ type: "onMouseWheel", eventType: eventType, scrollY: scrollY }); - } - - build() { - Stack() { - XComponent({ - id: 'xcomponentId', - type: 'surface', - libraryname: 'nativerender', - controller: this.xcomponentController - }) - .focusable(true) - .focusOnTouch(true) - .gesture( - PanGesture(this.panOption) - .onActionStart(() => { - this.onMouseWheel("actionStart", 0); - }) - .onActionUpdate((event: GestureEvent) => { - if (deviceInfo.deviceType === '2in1') { - this.onMouseWheel("actionUpdate", event.offsetY); - } - }) - .onActionEnd(() => { - this.onMouseWheel("actionEnd", 0); - }) - ) - .onLoad((context) => { - console.log('[cocos] XComponent.onLoad Callback'); - this.cocosWorker.postMessage({ type: "abilityContextInit", data: GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT)}); - this.cocosWorker.postMessage({ type: "onXCLoad", data: "XComponent" }); - this.cocosWorker.onmessage = WorkerMsgUtils.recvWorkerThreadMessage; - }) - .onDestroy(() => { - }) - ForEach(this.editBoxArray, (item:TextInputInfo) => { - CocosEditBox({ textInputInfo: item}); - }, (item:TextInputInfo) => item.viewTag.toString()) - - ForEach(this.webViewArray, (item:WebViewInfo) => { - CocosWebView({ viewInfo: item }) - }, (item:WebViewInfo) => item.uniqueId.toString()) - - ForEach(this.videoPlayerInfoArray, (item:VideoPlayerInfo) => { - CocosVideoPlayer({ videoPlayerInfo: item }) - }, (item:VideoPlayerInfo) => item.viewTag.toString()) - } - .width('100%') - .height('100%') - } -} diff --git a/tests/lua-tests/project/proj.ohos/entry/src/main/ets/workers/CocosWorker.ts b/tests/lua-tests/project/proj.ohos/entry/src/main/ets/workers/CocosWorker.ts deleted file mode 100644 index 94ddb8d38920..000000000000 --- a/tests/lua-tests/project/proj.ohos/entry/src/main/ets/workers/CocosWorker.ts +++ /dev/null @@ -1,79 +0,0 @@ -import worker, { ThreadWorkerGlobalScope } from '@ohos.worker'; -import nativeRender from "libnativerender.so"; -import { ContextType } from "@ohos/libSysCapabilities" -import { VideoPlayer } from "@ohos/libSysCapabilities" -import { CocosEditBox } from "@ohos/libSysCapabilities" -import { Dialog } from "@ohos/libSysCapabilities" -import { WebView } from "@ohos/libSysCapabilities" -import { JumpManager } from "@ohos/libSysCapabilities" -import { NapiHelper } from "@ohos/libSysCapabilities" -import { ApplicationManager } from "@ohos/libSysCapabilities" -import { GlobalContext,GlobalContextConstants} from "@ohos/libSysCapabilities" - -const appLifecycle: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.APP_LIFECYCLE); -const workerContext: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.WORKER_INIT); -const inputNapi: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.INPUT_NAPI); -const mouseNapi: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.MOUSE_NAPI); -const webViewNapi: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.WEBVIEW_NAPI); -const videoPlayNapi: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.VIDEOPLAYER_NAPI); -const napiContext: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.NATIVE_API); -workerContext.workerInit() - -napiContext.nativeEngineStart(); -NapiHelper.registerFunctions(napiContext.registerFunction) - -const workerPort: ThreadWorkerGlobalScope = worker.workerPort; - -workerPort.onmessage = function(e) : void { - let data = e.data; - switch(data.type) { - case "onXCLoad": - console.log("[cocos] onXCLoad Callback"); - Dialog.init(workerPort); - CocosEditBox.init(workerPort); - JumpManager.init(workerPort); - WebView.init(workerPort); - VideoPlayer.init(workerPort); - ApplicationManager.init(workerPort); - napiContext.initAsyncInfo(); - break; - case "abilityContextInit": - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT, data.data); - break; - case "editBoxOnFocus": - inputNapi.editBoxOnFocusCB(data.viewTag); - break; - case "editBoxOnChange": - inputNapi.editBoxOnChangeCB(data.viewTag, data.value); - break; - case "editBoxOnEnter": - inputNapi.editBoxOnEnterCB(data.viewTag, data.text); - break; - case "textFieldTTFOnChange": - inputNapi.textFieldTTFOnChangeCB(data.data); - break; - case "onMouseWheel": - mouseNapi.mouseWheelCB(data.eventType, data.scrollY); - break; - case "onPageBegin": - webViewNapi.shouldStartLoading(data.viewTag, data.url); - break; - case "onPageEnd": - webViewNapi.finishLoading(data.viewTag, data.url); - break; - case "onJsCallBack": - webViewNapi.jsCallback(); - break; - case "onErrorReceive": - webViewNapi.failLoading(data.viewTag, data.url); - break; - case "onVideoCallBack": - videoPlayNapi.onVideoCallBack(data.viewTag, data.event); - break; - case "exit": - appLifecycle.onBackPress(); - break; - default: - console.error("cocos worker: message type unknown") - } -} diff --git a/tests/lua-tests/project/proj.ohos/entry/src/main/ets/workers/WorkerManager.ts b/tests/lua-tests/project/proj.ohos/entry/src/main/ets/workers/WorkerManager.ts deleted file mode 100644 index e2ec70b1873e..000000000000 --- a/tests/lua-tests/project/proj.ohos/entry/src/main/ets/workers/WorkerManager.ts +++ /dev/null @@ -1,34 +0,0 @@ -import worker from '@ohos.worker'; -import { Constants } from '@ohos/libSysCapabilities'; - -export class WorkerManager { - private cocosWorker: worker.ThreadWorker; - - private constructor() { - this.cocosWorker = new worker.ThreadWorker("entry/ets/workers/CocosWorker.ts", { - type: "classic", - name: "CocosWorker" - }); - this.cocosWorker.onerror = (e) => { - let msg = e.message; - let filename = e.filename; - let lineno = e.lineno; - let colno = e.colno; - console.error(`on Error ${msg} ${filename} ${lineno} ${colno}`); - } - } - - public static getInstance(): WorkerManager { - let workerManger: WorkerManager | undefined = AppStorage.get(Constants.APP_KEY_WORKER_MANAGER); - if (workerManger == undefined) { - workerManger = new WorkerManager; - AppStorage.setOrCreate(Constants.APP_KEY_WORKER_MANAGER, workerManger); - return workerManger; - } - return workerManger; - } - - public getWorker(): worker.ThreadWorker { - return this.cocosWorker; - } -} \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/entry/src/main/module.json5 b/tests/lua-tests/project/proj.ohos/entry/src/main/module.json5 deleted file mode 100644 index 40769a17fb9e..000000000000 --- a/tests/lua-tests/project/proj.ohos/entry/src/main/module.json5 +++ /dev/null @@ -1,68 +0,0 @@ -{ - "module": { - "name": "entry", - "type": "entry", - "description": "$string:entry_desc", - "mainElement": "MainAbility", - "deviceTypes": [ - "phone", - "tablet", - "2in1" - ], - "deliveryWithInstall": true, - "installationFree": false, - "pages": "$profile:main_pages", - "abilities": [ - { - "name": "MainAbility", - "srcEntry": "./ets/MainAbility/MainAbility.ts", - "description": "$string:MainAbility_desc", - "icon": "$media:icon", - "label": "$string:MainAbility_label", - "startWindowIcon": "$media:icon", - "startWindowBackground": "$color:white", - "exported": true, - "skills": [ - { - "entities": [ - "entity.system.home" - ], - "actions": [ - "action.system.home" - ] - } - ], - "supportWindowMode": ["fullscreen"], - "maxWindowWidth": 1080, - "minWindowWidth": 1080, - "maxWindowHeight": 720, - "minWindowHeight": 720 - } - ], - "requestPermissions": [ - { - "name": "ohos.permission.INTERNET" - }, { - "name" : "ohos.permission.SET_NETWORK_INFO" - }, { - "name" : "ohos.permission.GET_NETWORK_INFO" - }, { - "name": "ohos.permission.GET_WIFI_INFO" - }, { - "name": "ohos.permission.ACCELEROMETER" - },{ - "name": "ohos.permission.VIBRATE" - } - ], - "metadata": [ - { - "name": "ArkTSPartialUpdate", - "value": "true" - }, - { - "name": "partialUpdateStrictCheck", - "value": "warn" - } - ] - } -} \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/entry/src/main/resources/base/element/color.json b/tests/lua-tests/project/proj.ohos/entry/src/main/resources/base/element/color.json deleted file mode 100644 index 1bbc9aa9617e..000000000000 --- a/tests/lua-tests/project/proj.ohos/entry/src/main/resources/base/element/color.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "color": [ - { - "name": "white", - "value": "#FFFFFF" - } - ] -} \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/entry/src/main/resources/base/element/string.json b/tests/lua-tests/project/proj.ohos/entry/src/main/resources/base/element/string.json deleted file mode 100644 index 99f3332dab95..000000000000 --- a/tests/lua-tests/project/proj.ohos/entry/src/main/resources/base/element/string.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "string": [ - { - "name": "entry_desc", - "value": "3.16_lua_tests" - }, - { - "name": "MainAbility_label", - "value": "3.16_lua_tests" - }, - { - "name": "MainAbility_desc", - "value": "description" - }, - { - "name": "text_field_ttf_complete", - "value": "完成" - } - ] -} \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/entry/src/main/resources/base/media/icon.png b/tests/lua-tests/project/proj.ohos/entry/src/main/resources/base/media/icon.png deleted file mode 100644 index ce307a8827bd75456441ceb57d530e4c8d45d36c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6790 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 { - if (item.viewTag == eventData.viewTag) { - removeIndex = index; - } - }); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_ARRAY).splice(removeIndex, 1); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP).delete(eventData.viewTag); - break; - } - case "setCurrentText": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.text = eventData.text; - break; - } - case "setEditBoxViewRect": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.x = eventData.viewRect.x; - textInputInfo.y = eventData.viewRect.y; - textInputInfo.w = eventData.viewRect.w; - textInputInfo.h = eventData.viewRect.h; - break; - } - case "setEditBoxVisible": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.visible = eventData.visible; - break; - } - case "setEditBoxFontSize": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.fontSize = eventData.fontSize; - break; - } - case "setEditBoxFontColor": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.fontColor = new FontColor(eventData.color.r, eventData.color.g, eventData.color.b, eventData.color.a / 255); - break; - } - case "setEditBoxPlaceHolderFontSize": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.placeholderFontSize = eventData.placeHolderSize; - break; - } - case "setEditBoxPlaceHolderFontColor": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.placeholderFontColor = new FontColor(eventData.placeHolderColor.r, eventData.placeHolderColor.g, eventData.placeHolderColor.b, eventData.placeHolderColor.a / 255); - break; - } - case "setEditBoxPlaceHolder": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.placeHolder = eventData.placeHolderText; - break; - } - case "setEditBoxMaxLength": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.maxLength = eventData.maxLength; - break; - } - case "setNativeInputMode": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.multiline = (eventData.inputMode == 0) ? true : false; - if (textInputInfo.inputMode != InputType.Password) { - switch (eventData.inputMode) { - case 0: - case 4: - case 6: - textInputInfo.inputMode = InputType.Normal; - break; - case 2: - case 5: - textInputInfo.inputMode = InputType.Number; - break; - case 3: - textInputInfo.inputMode = InputType.PhoneNumber; - break; - case 1: - textInputInfo.inputMode = InputType.Email; - break; - default: - break; - } - } - break; - } - case "setNativeInputFlag": { - // Any type can be changed to a password. The password can be changed to any type, - // but the password is mapped to the general type. Other changes are not allowed. - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - if (eventData.inputFlag == 0) { - textInputInfo.inputMode = InputType.Password; - } else if (textInputInfo.inputMode == InputType.Password) { - textInputInfo.inputMode = InputType.Normal; - } - break; - } - case "setEditBoxFontPath": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.fontPath = eventData.fontPath; - break; - } - case "setEditBoxPlaceHolderFontPath": { - let textInputInfo: TextInputInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP) - .get(eventData.viewTag); - textInputInfo.placeHolderFontPath = eventData.placeHolderFontPath; - break; - } - case "hideAllEditBox": { - let editBoxArray: TextInputInfo[] = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_ARRAY); - editBoxArray.forEach(item => { - if (item.visible) { - item.visible = false; - let cocosWorker: worker.ThreadWorker = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_COCOS_WORKER); - cocosWorker.postMessage({ type: "editBoxOnEnter", viewTag: item.viewTag, text: item.text }) - } - }) - break; - } - } -} diff --git a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayer.ts b/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayer.ts deleted file mode 100644 index 50b7a7e69d00..000000000000 --- a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayer.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { VideoPlayMsgEntity, ViewRect } from '../../entity/WorkerMsgEntity'; - -export class VideoPlayer { - static MODULE_NAME: string = 'VideoPlay'; - - private static workerPort; - - static init(workerPort) : void { - VideoPlayer.workerPort = workerPort; - } - - static setURL(viewTag: number, url: string, isUrl: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'setURL', viewTag); - videoPlayMsgEntity.url = url; - videoPlayMsgEntity.isUrl = isUrl; - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static setLooping(viewTag: number, isLoop: boolean) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'setLooping', viewTag); - videoPlayMsgEntity.isLoop = isLoop; - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static createVideoPlayer(viewTag: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'createVideoPlayer', viewTag); - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static removeVideoPlayer(viewTag: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'removeVideoPlayer', viewTag); - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static setVideoPlayerRect(viewTag: number, x: number, y: number, w: number, h: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'setVideoPlayerRect', viewTag); - let viewRect: ViewRect = new ViewRect(x, y, w, h); - videoPlayMsgEntity.viewRect = viewRect; - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static play(viewTag: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'play', viewTag); - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - static pause(viewTag: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'pause', viewTag); - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static stop(viewTag: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'stop', viewTag); - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static setVisible(viewTag: number, visible: boolean) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'setVisible', viewTag); - videoPlayMsgEntity.visible = visible - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static requestFullscreen(viewTag: number, isFullScreen: boolean) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'requestFullscreen', viewTag); - videoPlayMsgEntity.isFullScreen = isFullScreen; - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static seekTo(viewTag: number, seekTo: number) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'seekTo', viewTag); - videoPlayMsgEntity.seekTo = seekTo; - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } - - static setKeepAspectRatioEnabled(viewTag: number, enable: boolean) : void { - let videoPlayMsgEntity: VideoPlayMsgEntity = new VideoPlayMsgEntity(VideoPlayer.MODULE_NAME, 'setKeepAspectRatioEnabled', viewTag); - videoPlayMsgEntity.keepAspectRatioEnabled = enable; - VideoPlayer.workerPort.postMessage(videoPlayMsgEntity); - } -} diff --git a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayerMsg.ets b/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayerMsg.ets deleted file mode 100644 index f11bdac82c9a..000000000000 --- a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/videoplayer/VideoPlayerMsg.ets +++ /dev/null @@ -1,145 +0,0 @@ -import Logger from '../../utils/Logger' -import { BusinessError } from '@ohos.base'; -import { GlobalContext,GlobalContextConstants } from "../../common/GlobalContext" -import { VideoPlayMsgEntity } from '../../entity/WorkerMsgEntity'; - -let log: Logger = new Logger(0x0001, "VideoPlayerMsg"); - -@Observed -export class VideoPlayerInfo { - // position - public x: number = 0; - public y: number = 0; - // size - public w: number = 0; - public h: number = 0; - // url - public url: string = '' - - public rawfile?: Resource; - public isUrl: boolean = false - // tag - public viewTag: number = 0 - - public isPlay: boolean = false - public isFullScreen: boolean = false - - // Whether to display - public visible: boolean = true - - public isLoop: boolean = false - - public objectFit: ImageFit = ImageFit.Auto - - public controller: VideoController = new VideoController() - - constructor(x: number, y: number, w: number, h: number, viewTag: number) { - this.x = x; - this.y = y; - this.w = w; - this.h = h; - this.viewTag = viewTag; - } -} - -export enum VideoEvent { - PLAYING = 0, - PAUSED, - STOPPED, - COMPLETED, -} - -export function handleVideoPlayMsg(eventData: VideoPlayMsgEntity) { - - switch (eventData.function) { - case "createVideoPlayer": { - let newVideoPlayerInfo = new VideoPlayerInfo(0, 0, 0, 0, eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_ARRAY).push(newVideoPlayerInfo); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).set(eventData.viewTag, newVideoPlayerInfo); - break; - } - case "removeVideoPlayer": { - let removeIndex = -1; - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_ARRAY).forEach((item:VideoPlayerInfo,index:number) => { - if (item.viewTag == eventData.viewTag) { - removeIndex = index; - } - }); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag).controller.requestFullscreen(false); //4.x已修复 - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_ARRAY).splice(removeIndex, 1); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).delete(eventData.viewTag); - break; - } - case "play": { - let videoPlayInfo :VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.controller.start(); - videoPlayInfo.isPlay = true; - break; - } - case "pause": { - let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.controller.pause(); - videoPlayInfo.isPlay = false; - break; - } - case "stop": { - let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.controller.stop(); - videoPlayInfo.isPlay = false; - break; - } - case "setURL": { - let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - if(eventData.isUrl == 0) { - videoPlayInfo.isUrl = false; - videoPlayInfo.rawfile = $rawfile(eventData.url); - } else { - videoPlayInfo.isUrl = true; - videoPlayInfo.url = eventData.url; - } - break; - } - case "setLooping": { - let videoPlayInfo: VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.isLoop = eventData.isLoop; - break; - } - case "setVideoPlayerRect": { - let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - try { - videoPlayInfo.x = px2vp(eventData.viewRect.x); - videoPlayInfo.y = px2vp(eventData.viewRect.y); - videoPlayInfo.w = px2vp(eventData.viewRect.w); - videoPlayInfo.h = px2vp(eventData.viewRect.h); - } catch (error) { - let e: BusinessError = error as BusinessError; - log.error('videoPlayerInfo ErrorCode: %{public}d, Message: %{public}s', e.code, e.message); - } - break; - } - case "setVisible": { - let videoPlayInfo:VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - if (videoPlayInfo.visible == eventData.visible) { - return; - } - videoPlayInfo.visible = eventData.visible; - break; - } - case "requestFullscreen": { - let videoPlayInfo: VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.controller.requestFullscreen(eventData.isFullScreen); - videoPlayInfo.isFullScreen = eventData.isFullScreen; - break; - } - case "seekTo": { - let videoPlayInfo: VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.controller.setCurrentTime(eventData.seekTo, SeekMode.Accurate); - break; - } - case "setKeepAspectRatioEnabled": { - let videoPlayInfo: VideoPlayerInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_INDEX_MAP).get(eventData.viewTag); - videoPlayInfo.objectFit = eventData.keepAspectRatioEnabled? ImageFit.Cover : ImageFit.Auto; - break; - } - } -} \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebView.ts b/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebView.ts deleted file mode 100644 index 872ec4ce70fe..000000000000 --- a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebView.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { ViewRect, WebViewMsgEntity } from '../../entity/WorkerMsgEntity'; - -export class WebView { - static MODULE_NAME: string = 'WebView'; - - private static workerPort; - - static init(workerPort) : void { - WebView.workerPort = workerPort; - } - - static createWebView(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'createWebView', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static removeWebView(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'removeWebView', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static setJavascriptInterfaceScheme(viewTag: number, jsInterfaceScheme: string) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'setJavascriptInterfaceScheme', viewTag); - webViewMsgEntity.jsInterfaceScheme = jsInterfaceScheme; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static loadData(viewTag: number, data: string, mimeType: string, encoding: string, baseURL: string) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'loadData', viewTag); - webViewMsgEntity.data = data; - webViewMsgEntity.mimeType = mimeType; - webViewMsgEntity.encoding = encoding; - webViewMsgEntity.baseURL = baseURL; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static loadURL(viewTag: number, url: string) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'loadURL', viewTag); - webViewMsgEntity.url = url; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static loadFile(viewTag: number, filePath: string) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'loadFile', viewTag); - webViewMsgEntity.filePath = filePath; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static stopLoading(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'stopLoading', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static reload(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'reload', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static canGoBack(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'canGoBack', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static canGoForward(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'canGoForward', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static goBack(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'goBack', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static goForward(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'goForward', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static setWebViewRect(viewTag: number, x: number, y: number, w: number, h: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'setWebViewRect', viewTag); - let viewRect: ViewRect = new ViewRect(x, y, w, h); - webViewMsgEntity.viewRect = viewRect; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static setVisible(viewTag: number, visible: boolean) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'setVisible', viewTag); - webViewMsgEntity.visible = visible; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static setOpacityWebView(viewTag: number, opacity: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'setOpacityWebView', viewTag); - webViewMsgEntity.opacity = opacity; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static setBackgroundTransparent(viewTag: number) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'setBackgroundTransparent', viewTag); - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static evaluateJS(viewTag: number, js: string) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'evaluateJS', viewTag); - webViewMsgEntity.js = js; - WebView.workerPort.postMessage(webViewMsgEntity); - } - - static setScalesPageToFit(viewTag: number, scalesPageToFit: boolean) : void { - let webViewMsgEntity: WebViewMsgEntity = new WebViewMsgEntity(WebView.MODULE_NAME, 'setScalesPageToFit', viewTag); - webViewMsgEntity.scalesPageToFit = scalesPageToFit; - WebView.workerPort.postMessage(webViewMsgEntity); - } -} \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebViewMsg.ets b/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebViewMsg.ets deleted file mode 100644 index de125a3331f5..000000000000 --- a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/components/webview/WebViewMsg.ets +++ /dev/null @@ -1,246 +0,0 @@ -import web_webview from '@ohos.web.webview' -import Logger from '../../utils/Logger'; -import { GlobalContext, GlobalContextConstants } from '../../common/GlobalContext'; -import { WebViewMsgEntity } from '../../entity/WorkerMsgEntity'; -import { BusinessError } from '@ohos.base'; - -let log: Logger = new Logger(0x0001, "WebViewMsg"); - -export class WebViewInfo { - public uniqueId: number = 0; - // position - public x: number = 0; - public y: number = 0; - // size - public w: number = 0; - public h: number = 0; - // url - public url: string = ''; - public isUrl: boolean = true; - public viewTag: number = 0 - public zoomAccess: boolean = true - public visible: boolean = true - public opacity: number = 1 - public backgroundColor: number = 0xffffff; - - public jsInterfaceScheme: string = ""; - - public controller: web_webview.WebviewController = new web_webview.WebviewController() - - constructor(x: number, y: number, w: number, h: number, viewTag: number) { - this.x = x; - this.y = y; - this.w = w; - this.h = h; - this.viewTag = viewTag - this.uniqueId = viewTag; - } -} - -function copyWebViewInfo(viewInfo: WebViewInfo): WebViewInfo { - let newViewInfo: WebViewInfo = new WebViewInfo(viewInfo.x, viewInfo.y, viewInfo.w, viewInfo.h, viewInfo.viewTag); - newViewInfo.url = viewInfo.url; - newViewInfo.isUrl = viewInfo.isUrl; - newViewInfo.zoomAccess = viewInfo.zoomAccess; - newViewInfo.visible = viewInfo.visible; - newViewInfo.controller = viewInfo.controller; - newViewInfo.opacity = viewInfo.opacity; - newViewInfo.backgroundColor = viewInfo.backgroundColor; - newViewInfo.jsInterfaceScheme = viewInfo.jsInterfaceScheme; - newViewInfo.uniqueId = 100000 - viewInfo.uniqueId; // support 50000 webView exist at the same time - return newViewInfo; -} - -function waitUtilControllerAttached(): Promise { - return new Promise((resolve, reject) => { - resolve(1); - }) -} - -export function handleWebViewMsg(eventData: WebViewMsgEntity) { - let index: number; - switch (eventData.function) { - case "createWebView": { - let view = new WebViewInfo(0, 0, 0, 0, eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY).push(view); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP) - .set(eventData.viewTag, GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY) - .length - 1); - break; - } - case "removeWebView": { - if (GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY).length > 0) { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY).splice(index, 1); - // Do not assume the invoking time of removeWebView. After an element is deleted, the following elements need to be advanced by one bit. - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP) - .forEach((value: number, key: number, map: Map) => { - if (value > index) { - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).set(key, value - 1); - } - }) - - // Delete the subscript mapping of the removed webView. - let tempInfoMap: Map = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP); - tempInfoMap.delete(eventData.viewTag); - } - break; - } - case "setJavascriptInterfaceScheme": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - webViewInfo.jsInterfaceScheme = eventData.jsInterfaceScheme; - break; - } - case "loadData": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - waitUtilControllerAttached().then(() => { - webViewInfo.controller.loadData(eventData.data, eventData.mimeType, eventData.encoding, eventData.baseURL) - }); - break; - } - case "loadURL": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index].url = eventData.url; - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index].isUrl = true; - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - waitUtilControllerAttached().then(() => { - webViewInfo.controller.loadUrl(eventData.url); - }) - break; - } - case "loadFile": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index].url = eventData.filePath; - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index].isUrl = false; - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - waitUtilControllerAttached().then(() => { - webViewInfo.controller.loadUrl($rawfile(eventData.filePath)); - }) - break; - } - case "stopLoading": - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index].controller.stop(); - break; - case "reload": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - waitUtilControllerAttached().then(() => { - webViewInfo.controller.refresh(); - }) - break; - } - case "canGoBack": - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let result: number = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .controller - .accessBackward(); - // todo The value needs to be sent back to the worker thread. - break; - case "canGoForward": - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - result = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .controller - .accessForward(); - // todo The value needs to be sent back to the worker thread. - break; - case "goBack": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - waitUtilControllerAttached().then(() => { - webViewInfo.controller.backward(); - }) - break; - } - case "goForward": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let webViewInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - waitUtilControllerAttached().then(() => { - webViewInfo.controller.forward(); - }) - break; - } - case "setWebViewRect": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - let tmpWebInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - tmpWebInfo.x = px2vp(eventData.viewRect.x); - tmpWebInfo.y = px2vp(eventData.viewRect.y); - tmpWebInfo.w = px2vp(eventData.viewRect.w); - tmpWebInfo.h = px2vp(eventData.viewRect.h); - let newViewInfo: WebViewInfo = copyWebViewInfo(tmpWebInfo); - let tempInfoArray: WebViewInfo[] = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY); - tempInfoArray[index] = newViewInfo; - break; - } - case "setVisible": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - if (GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .visible == eventData.visible) { - return; - } - let tmpWebInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - tmpWebInfo.visible = eventData.visible; - let newViewInfo: WebViewInfo = copyWebViewInfo(tmpWebInfo); - let tempInfoArray: WebViewInfo[] = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY); - tempInfoArray[index] = newViewInfo; - break; - } - case "setOpacityWebView": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - if (GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .opacity == eventData.opacity) { - return; - } - let tmpWebInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - tmpWebInfo.opacity = eventData.opacity; - let newViewInfo: WebViewInfo = copyWebViewInfo(tmpWebInfo); - let tempInfoArray: WebViewInfo[] = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY); - tempInfoArray[index] = newViewInfo; - break; - } - case "setBackgroundTransparent": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - if (GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .backgroundColor == Color.Transparent) { - return; - } - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .backgroundColor = Color.Transparent; - let newViewInfo: WebViewInfo = copyWebViewInfo(GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]); - let tempInfoArray: WebViewInfo[] = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY); - tempInfoArray[index] = newViewInfo; - break; - } - case "evaluateJS": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .controller - .runJavaScript(eventData.js, (error: BusinessError, result: string) => { - if (error) { - log.warn("webView run JavaScript error:%{public}s", JSON.stringify(error)); - return; - } - if (result) { - GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_WEB_RESULT, result) - log.debug("webView run JavaScript result is %{public}s:", result); - } - }) - break; - } - case "setScalesPageToFit": { - index = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP).get(eventData.viewTag); - if (GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index] - .zoomAccess == eventData.scalesPageToFit) { - return; - } - let tmpWebInfo: WebViewInfo = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY)[index]; - tmpWebInfo.zoomAccess == eventData.scalesPageToFit - let newViewInfo: WebViewInfo = copyWebViewInfo(tmpWebInfo); - let tempInfoArray: WebViewInfo[] = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY); - tempInfoArray[index] = newViewInfo; - } - break; - } -} \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/Result.ts b/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/Result.ts deleted file mode 100644 index dd9e38897da3..000000000000 --- a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/Result.ts +++ /dev/null @@ -1,16 +0,0 @@ -export class Result { - public static success(data){ - return { - "errCode": 0, - "errMsg": "", - "data": data, - }; - } - - public static error(errCode, errMsg) { - return { - "errCode": errCode, - "errMsg": errMsg, - }; - } -}; \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/TextInputDialogEntity.ts b/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/TextInputDialogEntity.ts deleted file mode 100644 index 39d272a0b68c..000000000000 --- a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/TextInputDialogEntity.ts +++ /dev/null @@ -1,7 +0,0 @@ -export class TextInputDialogEntity { - message : string; - - constructor(msg: string) { - this.message = msg; - } -} \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/WorkerMsgEntity.ts b/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/WorkerMsgEntity.ts deleted file mode 100644 index 608158d25be9..000000000000 --- a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/entity/WorkerMsgEntity.ts +++ /dev/null @@ -1,141 +0,0 @@ -export class ViewRect { - x: number - y: number - w: number - h: number - - constructor(x: number, y: number, w: number, h: number) { - this.x = x; - this.y = y; - this.w = w; - this.h = h; - } -} - -export class Color4B { - r: number - g: number - b: number - a: number - - constructor(r: number, g: number, b: number, a: number) { - this.r = r; - this.g = g; - this.b = b; - this.a = a; - } -} - -export class BaseWorkerMsgEntity { - module: string; - - function: string; - - constructor(module: string, func: string) { - this.module = module; - this.function = func; - } -} - -export class DialogMsgEntity extends BaseWorkerMsgEntity { - title: string; - - message: string; - - constructor(module: string, func: string) { - super(module, func); - } -} - -export class EditBoxMsgEntity extends BaseWorkerMsgEntity { - viewTag: number - - viewRect: ViewRect - - paddingW: number - paddingH: number - - visible: boolean - - text: string - fontSize: number - color: Color4B - fontPath: string - - placeHolderText: string - placeHolderSize: number - placeHolderColor: Color4B - placeHolderFontPath: string - - maxLength: number - - inputMode: number - - inputFlag: number - - constructor(module: string, func: string, viewTag?: number) { - super(module, func); - this.viewTag = viewTag; - } -} - -export class VideoPlayMsgEntity extends BaseWorkerMsgEntity { - viewTag: number - - url: string - isUrl: number - - isLoop: boolean - - viewRect: ViewRect - - visible: boolean - - isFullScreen: boolean - - seekTo: number - - keepAspectRatioEnabled: boolean - - constructor(module: string, func: string, viewTag: number) { - super(module, func); - this.viewTag = viewTag; - } -} - -export class WebViewMsgEntity extends BaseWorkerMsgEntity { - viewTag: number - - data: string - mimeType: string - encoding: string - baseURL: string - - url: string - - filePath: string - - viewRect: ViewRect - - visible: boolean - - opacity: number - - js: string - - scalesPageToFit: boolean - jsInterfaceScheme: string - - constructor(module: string, func: string, viewTag: number) { - super(module, func); - this.viewTag = viewTag; - } -} - -export class JumpMsgEntity extends BaseWorkerMsgEntity { - url: string; - - constructor(module: string, func: string) { - super(module, func); - } -} \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/napi/NapiHelper.ts b/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/napi/NapiHelper.ts deleted file mode 100644 index e70836332ec2..000000000000 --- a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/napi/NapiHelper.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { Dialog } from '../components/dialog/DialogWorker' -import StringUtils from '../utils/StringUtils' -import { JumpManager } from '../system/appJump/JumpManager' -import { DeviceUtils } from '../system/device/DeviceUtils' -import { ApplicationManager } from '../system/application/ApplicationManager' -import { CocosEditBox } from '../components/editbox/CocosEditBox' -import { WebView } from '../components/webview/WebView' -import { VideoPlayer } from '../components/videoplayer/VideoPlayer' -import Accelerometer from '../system/sensor/AccelerometerUtils' -import Preferences from '../preferences/Preferences' - -export class NapiHelper { - - static registerFunctions(registerFunc : Function) { - NapiHelper.registerOthers(registerFunc); - NapiHelper.registerDeviceUtils(registerFunc); - NapiHelper.registerEditBox(registerFunc); - NapiHelper.registerWebView(registerFunc); - NapiHelper.registerVideoPlay(registerFunc); - NapiHelper.registerSensor(registerFunc); - NapiHelper.registerPreferences(registerFunc); - } - - private static registerOthers(registerFunc : Function) { - registerFunc('DiaLog.showDialog', Dialog.showDialog); - registerFunc('DiaLog.showTextInputDialog', Dialog.showTextInputDialog); - registerFunc('DiaLog.hideTextInputDialog', Dialog.hideTextInputDialog); - registerFunc('StringUtils.getWidth', StringUtils.getWidth); - registerFunc('ApplicationManager.exit', ApplicationManager.exit); - registerFunc('ApplicationManager.getVersionName', ApplicationManager.getVersionName); - registerFunc('JumpManager.openUrl', JumpManager.openUrl); - } - - - private static registerDeviceUtils(registerFunc : Function) { - registerFunc('DeviceUtils.getDpi', DeviceUtils.getDpi); - registerFunc('DeviceUtils.getSystemLanguage', DeviceUtils.getSystemLanguage); - registerFunc('DeviceUtils.startVibration', DeviceUtils.startVibration); - registerFunc('DeviceUtils.setKeepScreenOn', DeviceUtils.setKeepScreenOn); - registerFunc('DeviceUtils.isRoundScreen', DeviceUtils.isRoundScreen); - registerFunc('DeviceUtils.hasSoftKeys', DeviceUtils.hasSoftKeys); - registerFunc('DeviceUtils.isCutoutEnable', DeviceUtils.isCutoutEnable); - registerFunc('DeviceUtils.initScreenInfo', DeviceUtils.initScreenInfo); - registerFunc('DeviceUtils.getOrientation', DeviceUtils.getOrientation); - registerFunc('DeviceUtils.getCutoutHeight', DeviceUtils.getCutoutHeight); - registerFunc('DeviceUtils.getCutoutWidth', DeviceUtils.getCutoutWidth); - } - - private static registerEditBox(registerFunc : Function) { - registerFunc('CocosEditBox.createCocosEditBox', CocosEditBox.createCocosEditBox); - registerFunc('CocosEditBox.removeCocosEditBox', CocosEditBox.removeCocosEditBox); - registerFunc('CocosEditBox.setCurrentText', CocosEditBox.setCurrentText); - registerFunc('CocosEditBox.setEditBoxViewRect', CocosEditBox.setEditBoxViewRect); - registerFunc('CocosEditBox.setEditBoxVisible', CocosEditBox.setEditBoxVisible); - registerFunc('CocosEditBox.setEditBoxPlaceHolder', CocosEditBox.setEditBoxPlaceHolder); - registerFunc('CocosEditBox.setEditBoxFontSize', CocosEditBox.setEditBoxFontSize); - registerFunc('CocosEditBox.setEditBoxFontColor', CocosEditBox.setEditBoxFontColor); - registerFunc('CocosEditBox.setEditBoxFontPath', CocosEditBox.setEditBoxFontPath); - registerFunc('CocosEditBox.setEditBoxPlaceHolderFontSize', CocosEditBox.setEditBoxPlaceHolderFontSize); - registerFunc('CocosEditBox.setEditBoxPlaceHolderFontColor', CocosEditBox.setEditBoxPlaceHolderFontColor); - registerFunc('CocosEditBox.setEditBoxPlaceHolderFontPath', CocosEditBox.setEditBoxPlaceHolderFontPath); - registerFunc('CocosEditBox.setEditBoxMaxLength', CocosEditBox.setEditBoxMaxLength); - registerFunc('CocosEditBox.setNativeInputMode', CocosEditBox.setNativeInputMode); - registerFunc('CocosEditBox.setNativeInputFlag', CocosEditBox.setNativeInputFlag); - registerFunc('CocosEditBox.hideAllEditBox', CocosEditBox.hideAllEditBox); - } - - private static registerWebView(registerFunc : Function) { - registerFunc('WebView.createWebView', WebView.createWebView); - registerFunc('WebView.removeWebView', WebView.removeWebView); - registerFunc('WebView.setJavascriptInterfaceScheme', WebView.setJavascriptInterfaceScheme); - registerFunc('WebView.loadData', WebView.loadData); - registerFunc('WebView.loadURL', WebView.loadURL); - registerFunc('WebView.loadFile', WebView.loadFile); - registerFunc('WebView.stopLoading', WebView.stopLoading); - registerFunc('WebView.reload', WebView.reload); - registerFunc('WebView.canGoBack', WebView.canGoBack); - registerFunc('WebView.canGoForward', WebView.canGoForward); - registerFunc('WebView.goBack', WebView.goBack); - registerFunc('WebView.goForward', WebView.goForward); - registerFunc('WebView.setWebViewRect', WebView.setWebViewRect); - registerFunc('WebView.setVisible', WebView.setVisible); - registerFunc('WebView.setOpacityWebView', WebView.setOpacityWebView); - registerFunc('WebView.setBackgroundTransparent', WebView.setBackgroundTransparent); - registerFunc('WebView.evaluateJS', WebView.evaluateJS); - registerFunc('WebView.setScalesPageToFit', WebView.setScalesPageToFit); - } - - private static registerVideoPlay(registerFunc : Function) { - registerFunc('VideoPlayer.createVideoPlayer', VideoPlayer.createVideoPlayer); - registerFunc('VideoPlayer.removeVideoPlayer', VideoPlayer.removeVideoPlayer); - registerFunc('VideoPlayer.setURL', VideoPlayer.setURL); - registerFunc('VideoPlayer.setLooping', VideoPlayer.setLooping); - registerFunc('VideoPlayer.setVideoPlayerRect', VideoPlayer.setVideoPlayerRect); - registerFunc('VideoPlayer.play', VideoPlayer.play); - registerFunc('VideoPlayer.pause', VideoPlayer.pause); - registerFunc('VideoPlayer.stop', VideoPlayer.stop); - registerFunc('VideoPlayer.setVisible', VideoPlayer.setVisible); - registerFunc('VideoPlayer.requestFullscreen', VideoPlayer.requestFullscreen); - registerFunc('VideoPlayer.seekTo', VideoPlayer.seekTo); - registerFunc('VideoPlayer.setKeepAspectRatioEnabled', VideoPlayer.setKeepAspectRatioEnabled); - } - - private static registerSensor(registerFunc : Function) { - registerFunc('Accelerometer.enable', Accelerometer.enable); - registerFunc('Accelerometer.disable', Accelerometer.disable); - } - - private static registerPreferences(registerFunc : Function) { - registerFunc('Preferences.get', Preferences.get); - registerFunc('Preferences.getAll', Preferences.getAll); - registerFunc('Preferences.put', Preferences.put); - registerFunc('Preferences.has', Preferences.has); - registerFunc('Preferences.delete', Preferences.delete); - registerFunc('Preferences.flush', Preferences.flush); - registerFunc('Preferences.clear', Preferences.clear); - } - -} diff --git a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/preferences/Preferences.ts b/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/preferences/Preferences.ts deleted file mode 100644 index e95e89b29d10..000000000000 --- a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/preferences/Preferences.ts +++ /dev/null @@ -1,218 +0,0 @@ -import Logger from '../utils/Logger'; -import data_preferences from '@ohos.data.preferences'; -import { BusinessError } from '@ohos.base'; -import common from '@ohos.app.ability.common'; -import { GlobalContext, GlobalContextConstants } from '../common/GlobalContext'; - -let log: Logger = new Logger(0x0001, "Preferences"); -let preferences: data_preferences.Preferences | null = null; -const PREFS_NAME: string = "Cocos2dxPreferences"; - -export default class Preferences { - - // 通过 preferencesName 获取Preferences实例 - static getPreferences(): data_preferences.Preferences { - let context: common.UIAbilityContext = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT); - try { - preferences = data_preferences.getPreferencesSync(context, {name: PREFS_NAME}); - log.info("Succeeded in getting preferences."); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to get preferences. code =" + code + ", message =" + message); - } - return preferences; - } - - /* - 通过 preferencesName 从缓存中移出指定的Preferences实例,若Preferences实例有对应的持久化文件,则同时删除其持久化文件。使用Promise异步回调。 - 调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 - */ - static deletePreferences(): void { - let context: common.UIAbilityContext = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT); - try { - data_preferences.deletePreferences(context, PREFS_NAME).then(() => { - log.info("Succeeded in deleting preferences."); - }); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to delete preferences. code =" + code + ", message =" + message); - } - } - - /* - 通过 preferencesName 从缓存中移出指定的Preferences实例,使用Promise异步回调。 - 应用首次调用getPreferences接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次getPreferences时不会再次从持久化文件中读取, - 直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。 - 调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 - */ - static removePreferencesFromCache(): void { - let context: common.UIAbilityContext = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT); - try { - data_preferences.removePreferencesFromCacheSync(context, PREFS_NAME); - log.info("Succeeded in removing preferences."); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to remove preferences. code =" + code + ", message =" + message); - } - } - - // 从缓存的Preferences实例中获取键对应的值,如果值为null或者非默认值类型,返回默认数据defValue - static get(key: string, defValue: data_preferences.ValueType): data_preferences.ValueType { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - let data = preferences.getSync(key, defValue); - log.info("Succeeded in getting value of 'startup'. Data: " + data); - return data; - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to get value of 'startup'. code =" + code + ", message =" + message); - return defValue; - } - } - - // 将数据写入缓存的Preferences实例中,可通过flush将Preferences实例持久化 - static put(key: string, value: data_preferences.ValueType): void { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - preferences.putSync(key, value); - log.info("Succeeded in put the key."); - Preferences.flush(); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to put. code =" + code + ", message =" + message); - } - } - - // 从缓存的Preferences实例中获取所有键值数据。 - static getAll(): string | undefined { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - let object = preferences.getAllSync(); - let allKeys = getObjKeys(object); - log.info('getAll keys = ' + allKeys); - log.info("getAll object = " + JSON.stringify(object)); - return JSON.stringify(object); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to getAll. code =" + code + ", message =" + message); - return undefined; - } - } - - // 检查缓存的Preferences实例中是否包含名为给定Key的存储键值对 - static has(key: string): boolean { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - let val = preferences.hasSync(key); - if (val) { - log.info("The key 'startup' is contained."); - return true; - } else { - log.info("The key 'startup' dose not contain."); - return false; - } - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to has. code =" + code + ", message =" + message); - return false; - } - } - - // 从缓存的Preferences实例中删除名为给定Key的存储键值对,可通过flush将Preferences实例持久化 - static delete(key: string): void { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - preferences.deleteSync(key); - log.info("Succeeded in deleting the key."); - Preferences.flush(); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to delete. code =" + code + ", message =" + message); - } - } - - // 将缓存的Preferences实例中的数据异步存储到用户首选项的持久化文件中,使用Promise异步回调。 - static flush(): void { - if (preferences === null) { - Preferences.getPreferences(); - } - preferences.flush().then(()=>{ - log.info("Succeeded in flushing."); - }); - } - - // 清除缓存的Preferences实例中的所有数据,可通过flush将Preferences实例持久化,使用Promise异步回调。 - static clear(): void { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - preferences.clearSync(); - log.info("Succeeded in clearing."); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to clear. code =" + code + ", message =" + message); - } - } - - - // 订阅数据变更,订阅的Key的值发生变更后,在执行flush方法后,触发callback回调。 - static onChange(cb: Function): void { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - preferences.on('change', (key: string) => { - log.info("The key " + key + " changed."); - cb(key); - }); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to flush. code =" + code + ", message =" + message); - } - } - - // 取消订阅数据变更。 - static offChange(cb: Function): void { - if (preferences === null) { - Preferences.getPreferences(); - } - try { - preferences.off('change', (key: string) => { - log.info("The key " + key + " changed."); - cb(key); - }); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - log.error("Failed to flush. code =" + code + ", message =" + message); - } - } -} - -// 由于ArkTS中无Object.keys,且无法使用for..in... -// 若报ArkTS问题,请将此方法单独抽离至一个ts文件中并暴露,在需要用到的ets文件中引入使用 -function getObjKeys(obj: Object): string[] { - let keys = Object.keys(obj); - return keys; -} \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManager.ts b/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManager.ts deleted file mode 100644 index dfa95dfaa5ab..000000000000 --- a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManager.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { ThreadWorkerGlobalScope } from '@ohos.worker'; -import { JumpMsgEntity } from '../../entity/WorkerMsgEntity'; - -export class JumpManager { - - static MODULE_NAME: string = 'JumpManager'; - - private static workerPort: ThreadWorkerGlobalScope; - - static init(workerPort: ThreadWorkerGlobalScope) : void { - JumpManager.workerPort = workerPort; - } - - static openUrl(url: string) : void { - let jumpMsgEntity: JumpMsgEntity = new JumpMsgEntity(JumpManager.MODULE_NAME, 'openUrl'); - jumpMsgEntity.url = url; - JumpManager.workerPort.postMessage(jumpMsgEntity); - } -} diff --git a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManagerMsg.ts b/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManagerMsg.ts deleted file mode 100644 index ea373af90811..000000000000 --- a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/appJump/JumpManagerMsg.ts +++ /dev/null @@ -1,31 +0,0 @@ -import type common from '@ohos.app.ability.common'; -import { GlobalContext, GlobalContextConstants } from '../../common/GlobalContext'; -import {Result} from "../../entity/Result" -import type { JumpMsgEntity } from '../../entity/WorkerMsgEntity'; -import Logger from '../../utils/Logger' - -let log: Logger = new Logger(0x0001, "JumpManagerMsg"); - -export function handleJumpManagerMsg(eventData: JumpMsgEntity) : void { - switch (eventData.function) { - case "openUrl": - openUrl(eventData.url); - break; - default: - log.error('%{public}s has not implement yet', eventData.function); - } -} - -function openUrl(url: string): void { - let context: common.UIAbilityContext = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT); - let wantInfo = { - 'action': 'ohos.want.action.viewData', - 'entities': ['entity.system.browsable'], - 'uri': url - } - context.startAbility(wantInfo).then(() => { - log.info('%{public}s', JSON.stringify(Result.success({}))); - }).catch((err) => { - log.error('openUrl : err : %{public}s', JSON.stringify(Result.error(-1, JSON.stringify(err))) ?? ''); - }); -} \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/application/ApplicationManager.ts b/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/application/ApplicationManager.ts deleted file mode 100644 index ffe0826a5f7a..000000000000 --- a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/application/ApplicationManager.ts +++ /dev/null @@ -1,55 +0,0 @@ -import bundleManager from '@ohos.bundle.bundleManager'; -import type { ThreadWorkerGlobalScope } from '@ohos.worker'; -import { BaseWorkerMsgEntity } from '../../entity/WorkerMsgEntity'; -import { common } from '@kit.AbilityKit'; -import { BusinessError } from '@kit.BasicServicesKit'; -import { GlobalContext, GlobalContextConstants } from '../../common/GlobalContext'; - -export class ApplicationManager { - static MODULE_NAME: string = 'ApplicationManager'; - - private static workerPort: ThreadWorkerGlobalScope; - - static init(workerPort: ThreadWorkerGlobalScope): void { - ApplicationManager.workerPort = workerPort; - } - - static exit(): void { - let workerMsg: BaseWorkerMsgEntity = new BaseWorkerMsgEntity(ApplicationManager.MODULE_NAME, 'exit'); - ApplicationManager.workerPort.postMessage(workerMsg); - } - - static getVersionName(): string { - let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; - return bundleManager.getBundleInfoForSelfSync(bundleFlags).versionName; - } -} - -export function handleApplicationMsg(eventData: BaseWorkerMsgEntity): void { - switch (eventData.function) { - case "exit": - terminateSelf(); - break; - default: - console.error('%{public}s has not implement yet', eventData.function); - } -} - -function terminateSelf(): void { - try { - let context: common.UIAbilityContext = - GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT); - context.terminateSelf((err: BusinessError) => { - if (err.code) { - console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`); - return; - } - console.info('terminateSelf succeed'); - }); - } catch (err) { - let code = (err as BusinessError).code; - let message = (err as BusinessError).message; - console.error(`terminateSelf failed, code is ${code}, message is ${message}`); - } -} - diff --git a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/device/DeviceUtils.ts b/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/device/DeviceUtils.ts deleted file mode 100644 index b778f1584810..000000000000 --- a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/device/DeviceUtils.ts +++ /dev/null @@ -1,164 +0,0 @@ -import display from '@ohos.display' -import i18n from '@ohos.i18n'; -import vibrator from '@ohos.vibrator'; -import Logger from '../../utils/Logger'; -import window from '@ohos.window'; -import { GlobalContext, GlobalContextConstants } from '../../common/GlobalContext'; -import { Rect } from '@ohos.application.AccessibilityExtensionAbility'; - -let log = new Logger(0x0001, "DeviceUtils"); - -export class DeviceUtils { - static MODULE_NAME: string = 'DeviceUtils'; - static _roundScreen: boolean = false; - static _hasSoftKeys: boolean = false; - static _isCutoutEnable: boolean = false; - static _cutoutLeft: number; - static _cutoutWidth: number; - static _cutoutTop: number; - static _cutoutHeight: number; - - static getDpi(): number { - return display.getDefaultDisplaySync().densityDPI; - } - - static getSystemLanguage(): string { - return i18n.System.getSystemLanguage(); - } - - static startVibration(time: number) { - try { - vibrator.startVibration({ - type: 'time', - duration: time * 1000, // Seconds to milliseconds - }, { - id: 0, - usage: 'unknown' - }, (error) => { - if (error) { - log.error('vibrate fail, error.code: %{public}d, error.message: %{public}s', error.code, error.message); - return; - } - }); - } catch (err) { - log.error('error.code: %{public}d, error.message: %{public}s', err.code, err.message); - } - } - - static setKeepScreenOn(value: boolean) { - let windowClass = null; - try { - window.getLastWindow(GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT), (err, data) => { //获取窗口实例 - if (err.code) { - log.error('Failed to obtain last window when setKeepScreenOn. Cause:%{public}s', JSON.stringify(err)); - return; - } - windowClass = data; - // Sets whether the screen is always on. - let keepScreenOnPromise = windowClass.setWindowKeepScreenOn(value); - Promise.all([keepScreenOnPromise]).then(() => { - log.info('Succeeded in setKeepScreenOn, value:%{public}s', value); - }).catch((err) => { - log.error('Failed to setKeepScreenOn, cause:%{public}s', JSON.stringify(err)); - }); - }); - } catch (exception) { - log.error('Failed to get or set the window when setKeepScreenOn, cause:%{public}s', JSON.stringify(exception)); - } - } - - static isRoundScreen() : boolean { - return DeviceUtils._roundScreen; - } - - static hasSoftKeys() : boolean { - return DeviceUtils._hasSoftKeys; - } - - static isCutoutEnable() : boolean { - return DeviceUtils._isCutoutEnable; - } - - static initScreenInfo() : void { - let windowClass = null; - try { - window.getLastWindow(GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT), (err, data) => { - if (err.code) { - log.error('Failed to obtain last window when initScreenInfo. Cause:%{public}s', JSON.stringify(err)); - return; - } - - windowClass = data; - let windowProperties: window.WindowProperties = windowClass.getWindowProperties(); - DeviceUtils._roundScreen = windowProperties.isRoundCorner; - let rect: Rect = windowProperties.windowRect; - if(rect.top + rect.height < display.getDefaultDisplaySync().height) { - DeviceUtils._hasSoftKeys = true; - } else { - DeviceUtils._hasSoftKeys = false; - } - }); - } catch (exception) { - log.error('Failed to get or set the window when initScreenInfo, cause:%{public}s', JSON.stringify(exception)); - } - - display.getDefaultDisplaySync().getCutoutInfo().then((data) => { - if(data.boundingRects.length == 0) { - DeviceUtils._isCutoutEnable = false; - return; - } - - DeviceUtils._isCutoutEnable = true; - DeviceUtils._cutoutLeft = data.boundingRects[0].left; - DeviceUtils._cutoutTop = data.boundingRects[0].top; - DeviceUtils._cutoutWidth = data.boundingRects[0].width; - DeviceUtils._cutoutHeight = data.boundingRects[0].height; - }).catch((err) => { - log.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); - }); - } - - static getOrientation() : number { - let orientation: display.Orientation = display.getDefaultDisplaySync().orientation; - - // If the system enumeration value changes, the processing logic in the C++ code needs to be changed. Therefore, the mapping is performed again. - if(orientation == display.Orientation.PORTRAIT) { - return 0; - } - - if(orientation == display.Orientation.LANDSCAPE) { - return 1; - } - - if(orientation == display.Orientation.PORTRAIT_INVERTED) { - return 2; - } - - if(orientation == display.Orientation.LANDSCAPE_INVERTED) { - return 3; - } - - return 4; - } - - static getCutoutHeight() : number { - if(DeviceUtils._cutoutHeight) { - let height = DeviceUtils._cutoutTop + DeviceUtils._cutoutHeight; - return height; - } - return 0; - } - - static getCutoutWidth() : number { - if(!DeviceUtils._cutoutWidth) { - return 0; - } - - let disPlayWidth = display.getDefaultDisplaySync().width; - if(DeviceUtils._cutoutLeft + DeviceUtils._cutoutWidth > disPlayWidth - DeviceUtils._cutoutLeft) { - return disPlayWidth - DeviceUtils._cutoutLeft; - } - - return DeviceUtils._cutoutLeft + DeviceUtils._cutoutWidth; - } -} \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/sensor/AccelerometerUtils.ts b/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/sensor/AccelerometerUtils.ts deleted file mode 100644 index 56309439f011..000000000000 --- a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/system/sensor/AccelerometerUtils.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { getContext } from "libnativerender.so"; -import { ContextType } from "../../common/Constants" -import sensor from '@ohos.sensor'; -import display from '@ohos.display'; -import {Result} from "../../entity/Result" -import Logger from '../../utils/Logger' - -let log: Logger = new Logger(0x0001, "AccelerometerUtils"); - -const accUtils = getContext(ContextType.SENSOR_API); - -export default class Accelerometer { - - private static instance = new Accelerometer(); - - static getInstance() : Accelerometer { - return Accelerometer.instance; - } - - static enable(intervalTime: number) : void { - try { - /* HarmonyOS allow multiple subscriptions, but the game only need one - so if the interval changed, cancel subscription and redo with the new interval */ - sensor.off(sensor.SensorId.ACCELEROMETER); - sensor.on(sensor.SensorId.ACCELEROMETER, function (data) { - let rotation = display.getDefaultDisplaySync().rotation; - if (rotation === 0) { - // Display device screen rotation 0° - accUtils.onAccelerometerCallBack(data.x, data.y, data.z, intervalTime); - } else if (rotation === 1) { - // Display device screen rotation 90° - accUtils.onAccelerometerCallBack(data.y, -data.x, data.z, intervalTime); - } else if (rotation === 2) { - // Display device screen rotation 180° - accUtils.onAccelerometerCallBack(-data.x, -data.y, data.z, intervalTime); - } else if (rotation === 3) { - // Display device screen rotation 270° - accUtils.onAccelerometerCallBack(-data.y, data.x, data.z, intervalTime); - } else { - log.error('Accelerometer init fail, err: %{public}s', JSON.stringify(Result.error(-1, 'unsupported rotation: ' + rotation))); - } - }, { interval: intervalTime }); - } catch (err) { - log.error('Accelerometer init fail, err: %{public}s', JSON.stringify(Result.error(-1, JSON.stringify(err))) ?? ''); - } - } - - static disable() : void { - try { - sensor.off(sensor.SensorId.ACCELEROMETER); - } catch (err) { - log.error('Accelerometer off fail, err: %{public}s', JSON.stringify(Result.error(-1, JSON.stringify(err))) ?? ''); - } - } -} \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/Logger.ts b/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/Logger.ts deleted file mode 100644 index 6277b0e1ab52..000000000000 --- a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/Logger.ts +++ /dev/null @@ -1,27 +0,0 @@ -import hilog from '@ohos.hilog' - -export default class Logger { - private domain: number - private prefix: string - - constructor(domain : number, prefix: string) { - this.domain = domain - this.prefix = prefix - } - - debug(format: string, ...args: any[]) { - hilog.debug(this.domain, this.prefix, format, args) - } - - info(format: string, ...args: any[]) { - hilog.info(this.domain, this.prefix, format, args) - } - - warn(format: string, ...args: any[]) { - hilog.warn(this.domain, this.prefix, format, args) - } - - error(format: string, ...args: any[]) { - hilog.error(this.domain, this.prefix, format, args) - } -} \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/StringUtils.ts b/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/StringUtils.ts deleted file mode 100644 index 4e3d20ec55e1..000000000000 --- a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/StringUtils.ts +++ /dev/null @@ -1,8 +0,0 @@ -import measure from '@ohos.measure'; - -export default class StringUtils { - - public static getWidth(text: string, fontSize: number, fontWeight: number): number { - return measure.measureText({ textContent: text, fontSize: fontSize + 'px', fontWeight: fontWeight }); - } -} \ No newline at end of file diff --git a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/WorkerMsgUtils.ets b/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/WorkerMsgUtils.ets deleted file mode 100644 index b9cac7106b18..000000000000 --- a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/ets/utils/WorkerMsgUtils.ets +++ /dev/null @@ -1,42 +0,0 @@ -import worker, { MessageEvents } from '@ohos.worker'; -import Logger from './Logger'; -import { handleEditBoxMsg } from '../components/editbox/EditBoxMsg' -import { handleWebViewMsg } from '../components/webview/WebViewMsg' -import { handleVideoPlayMsg } from '../components/videoplayer/VideoPlayerMsg' -import { handleDialogMsg } from '../components/dialog/DialogMsg' -import { handleJumpManagerMsg } from '../system/appJump/JumpManagerMsg' -import { handleApplicationMsg } from '../system/application/ApplicationManager' -import { BaseWorkerMsgEntity, DialogMsgEntity, EditBoxMsgEntity, JumpMsgEntity, VideoPlayMsgEntity, WebViewMsgEntity } from '../entity/WorkerMsgEntity'; - -export class WorkerMsgUtils { - static workPort = worker.workerPort; - static log : Logger = new Logger(0x0001, 'WorkerMsgUtils') - - static async recvWorkerThreadMessage(event: MessageEvents) { - let eventData: BaseWorkerMsgEntity = event.data; - WorkerMsgUtils.log.debug('mainThread receiveMsg, module:%{public}s, function:%{public}s', eventData.module, eventData.function); - - switch (eventData.module) { - case 'EditBox': - handleEditBoxMsg(eventData as EditBoxMsgEntity); - break; - case "Dialog": - handleDialogMsg(eventData as DialogMsgEntity); - break; - case 'WebView': - handleWebViewMsg(eventData as WebViewMsgEntity); - break; - case 'VideoPlay': - handleVideoPlayMsg(eventData as VideoPlayMsgEntity); - break; - case 'JumpManager': - handleJumpManagerMsg(eventData as JumpMsgEntity); - break; - case 'ApplicationManager': - handleApplicationMsg(eventData as BaseWorkerMsgEntity); - break; - default: - WorkerMsgUtils.log.error('%{public}s has not implement yet', eventData.module); - } - } -} diff --git a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/module.json5 b/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/module.json5 deleted file mode 100644 index daa1891126f5..000000000000 --- a/tests/lua-tests/project/proj.ohos/libSysCapabilities/src/main/module.json5 +++ /dev/null @@ -1,10 +0,0 @@ -{ - "module": { - "name": "libSysCapabilities", - "type": "har", - "deviceTypes": [ - "phone", - "tablet" - ] - } -} diff --git a/tests/lua-tests/project/proj.ohos/oh-package.json5 b/tests/lua-tests/project/proj.ohos/oh-package.json5 deleted file mode 100644 index 938694dd037a..000000000000 --- a/tests/lua-tests/project/proj.ohos/oh-package.json5 +++ /dev/null @@ -1,10 +0,0 @@ -{ - "modelVersion": "5.0.0", - "license": "ISC", - "devDependencies": {}, - "name": "proj.ohos", - "description": "example description", - "main": "", - "version": "1.0.0", - "dependencies": {} -} \ No newline at end of file diff --git a/tests/lua-tests/src/controller.lua b/tests/lua-tests/src/controller.lua index adce6e9afb8c..59423c1dc96b 100644 --- a/tests/lua-tests/src/controller.lua +++ b/tests/lua-tests/src/controller.lua @@ -1,7 +1,10 @@ - --- jit off +local currPlatform = cc.Application:getInstance():getTargetPlatform() +cc.PLATFORM_OS_OHOS = 12 +if (cc.PLATFORM_OS_OHOS == currPlatform) then local jit = require("jit") jit.off() + print("jit.off()") +end -- avoid memory leak collectgarbage("setpause", 100) collectgarbage("setstepmul", 5000) From 981f8114f436b81d942f8774baa716d2df0b3897 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=86=B0=E5=86=B0=E5=86=B0?= <418776654@qq.com> Date: Mon, 28 Apr 2025 21:53:41 +0800 Subject: [PATCH 2/2] code optimization MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 冰冰冰 <418776654@qq.com> --- cocos/platform/ohos/napi/helper/NapiHelper.h | 21 ++++++++++++++- cocos/platform/ohos/napi/plugin_manager.cpp | 7 ++++- .../ohos/napi/render/plugin_render.cpp | 26 ++++++++++++++++--- tests/cpp-tests/proj.ohos | 2 +- tests/js-tests/project/proj.ohos | 2 +- tests/lua-tests/project/proj.ohos | 2 +- 6 files changed, 51 insertions(+), 9 deletions(-) diff --git a/cocos/platform/ohos/napi/helper/NapiHelper.h b/cocos/platform/ohos/napi/helper/NapiHelper.h index ac662559af63..c7b48c9fe6c7 100644 --- a/cocos/platform/ohos/napi/helper/NapiHelper.h +++ b/cocos/platform/ohos/napi/helper/NapiHelper.h @@ -114,7 +114,11 @@ class JSFunction { napi_value jsArgs[sizeof...(Args)] = {NapiValueConverter::ToNapiValue(env, args)...}; napi_value return_val; status = napi_call_function(env, global, func, sizeof...(Args), jsArgs, &return_val); - + if (status == napi_pending_exception) { + LOGI("Caught invoke exception: napi_pending_exception"); + napi_value exception; + napi_get_and_clear_last_exception(env, &exception); + } ReturnType value; if (!NapiValueConverter::ToCppValue(env, return_val, value)) { // Handle error here @@ -136,6 +140,11 @@ class JSFunction { napi_value jsArgs[sizeof...(Args)] = {NapiValueConverter::ToNapiValue(env, args)...}; napi_value return_val; status = napi_call_function(env, global, func, sizeof...(Args), jsArgs, &return_val); + if (status == napi_pending_exception) { + LOGI("Caught invoke exception: napi_pending_exception"); + napi_value exception; + napi_get_and_clear_last_exception(env, &exception); + } } static void callFunctionWithParams(WorkParam *param) { @@ -167,6 +176,11 @@ class JSFunction { } if (status != napi_ok) { LOGI("XXXXXX:napi_call_function getClassObject != napi_ok %{public}d", status); + if (status == napi_pending_exception) { + LOGI("Caught invoke exception: napi_pending_exception"); + napi_value exception; + napi_get_and_clear_last_exception(env, &exception); + } } napi_value thenFunc = nullptr; @@ -187,6 +201,11 @@ class JSFunction { status = napi_call_function(env, promise, thenFunc, 1, &successFunc, &ret); if (status != napi_ok) { LOGI("XXXXXX:napi_call_function thenFunc failed, ret: %{public}d", status); + if (status == napi_pending_exception) { + LOGI("Caught invoke exception: napi_pending_exception"); + napi_value exception; + napi_get_and_clear_last_exception(env, &exception); + } } } // Callback Function Type diff --git a/cocos/platform/ohos/napi/plugin_manager.cpp b/cocos/platform/ohos/napi/plugin_manager.cpp index 768598c945a7..63655aba4116 100644 --- a/cocos/platform/ohos/napi/plugin_manager.cpp +++ b/cocos/platform/ohos/napi/plugin_manager.cpp @@ -59,7 +59,11 @@ napi_value NapiManager::GetContext(napi_env env, napi_callback_info info) { int64_t value; NAPI_CALL(env, napi_get_value_int64(env, args[0], &value)); - + napi_handle_scope scope = nullptr; + NAPI_CALL(env, napi_open_handle_scope(env, &scope)); + if(scope == nullptr){ + return nullptr; + } NAPI_CALL(env, napi_create_object(env, &exports)); switch (value) { @@ -160,6 +164,7 @@ napi_value NapiManager::GetContext(napi_env env, napi_callback_info info) { default: OHOS_LOGE("unknown type"); } + NAPI_CALL(env, napi_close_handle_scope(env, scope)); return exports; } diff --git a/cocos/platform/ohos/napi/render/plugin_render.cpp b/cocos/platform/ohos/napi/render/plugin_render.cpp index 1db076d0fe54..06d216da2cc0 100644 --- a/cocos/platform/ohos/napi/render/plugin_render.cpp +++ b/cocos/platform/ohos/napi/render/plugin_render.cpp @@ -1,3 +1,4 @@ +#include #include #include @@ -31,7 +32,7 @@ float mousePositionY = -1; bool isMouseLeftActive = false; double scrollDistance = 0; -std::unordered_map ohKeyMap = { +const std::unordered_map ohKeyMap = { {KEY_ESCAPE, cocos2d::EventKeyboard::KeyCode::KEY_ESCAPE}, {KEY_GRAVE, cocos2d::EventKeyboard::KeyCode::KEY_GRAVE}, {KEY_MINUS, cocos2d::EventKeyboard::KeyCode::KEY_MINUS}, @@ -61,7 +62,23 @@ std::unordered_map ohKeyMap = { {KEY_DPAD_UP, cocos2d::EventKeyboard::KeyCode::KEY_DPAD_UP}, {KEY_SYSRQ, cocos2d::EventKeyboard::KeyCode::KEY_PRINT}, {KEY_INSERT, cocos2d::EventKeyboard::KeyCode::KEY_INSERT}, - {KEY_FORWARD_DEL, cocos2d::EventKeyboard::KeyCode::KEY_DELETE} + {KEY_FORWARD_DEL, cocos2d::EventKeyboard::KeyCode::KEY_DELETE}, + {KEY_SCROLL_LOCK, cocos2d::EventKeyboard::KeyCode::KEY_SCROLL_LOCK}, + {KEY_MINUS, cocos2d::EventKeyboard::KeyCode::KEY_MINUS}, + {KEY_AT, cocos2d::EventKeyboard::KeyCode::KEY_AT}, + {KEY_PLUS, cocos2d::EventKeyboard::KeyCode::KEY_PLUS}, + {KEY_MENU, cocos2d::EventKeyboard::KeyCode::KEY_MENU}, + {KEY_BREAK, cocos2d::EventKeyboard::KeyCode::KEY_PAUSE}, + {KEY_MOVE_HOME, cocos2d::EventKeyboard::KeyCode::KEY_HOME}, + {KEY_MOVE_END, cocos2d::EventKeyboard::KeyCode::KEY_END}, + {KEY_PAGE_UP, cocos2d::EventKeyboard::KeyCode::KEY_PG_UP}, + {KEY_PAGE_DOWN, cocos2d::EventKeyboard::KeyCode::KEY_PG_DOWN}, + {KEY_NUMPAD_ADD, cocos2d::EventKeyboard::KeyCode::KEY_KP_PLUS}, + {KEY_NUMPAD_SUBTRACT, cocos2d::EventKeyboard::KeyCode::KEY_KP_MINUS}, + {KEY_NUMPAD_MULTIPLY, cocos2d::EventKeyboard::KeyCode::KEY_KP_MULTIPLY}, + {KEY_NUMPAD_DIVIDE, cocos2d::EventKeyboard::KeyCode::KEY_KP_DIVIDE}, + {KEY_NUMPAD_ENTER, cocos2d::EventKeyboard::KeyCode::KEY_KP_ENTER} + }; cocos2d::EventKeyboard::KeyCode ohKeyCodeToCocosKeyCode(OH_NativeXComponent_KeyCode ohKeyCode) @@ -81,8 +98,9 @@ cocos2d::EventKeyboard::KeyCode ohKeyCodeToCocosKeyCode(OH_NativeXComponent_KeyC if (ohKeyCode >= KEY_A && ohKeyCode <= KEY_Z) { // A - Z return cocos2d::EventKeyboard::KeyCode(int(cocos2d::EventKeyboard::KeyCode::KEY_A) + (ohKeyCode - KEY_A)); - } - return cocos2d::EventKeyboard::KeyCode(ohKeyCode); + } + OHOS_LOGW("Unmapped OH key code: %d", ohKeyCode); + return cocos2d::EventKeyboard::KeyCode::KEY_NONE; } void OnSurfaceCreatedCB(OH_NativeXComponent* component, void* window) diff --git a/tests/cpp-tests/proj.ohos b/tests/cpp-tests/proj.ohos index 98a643f46069..735b54750d59 160000 --- a/tests/cpp-tests/proj.ohos +++ b/tests/cpp-tests/proj.ohos @@ -1 +1 @@ -Subproject commit 98a643f46069806f94e210cd2e0386d9d112811d +Subproject commit 735b54750d593755d93bbd33988dad5121471ccb diff --git a/tests/js-tests/project/proj.ohos b/tests/js-tests/project/proj.ohos index 8d5e6a65a4b7..8914adb20376 160000 --- a/tests/js-tests/project/proj.ohos +++ b/tests/js-tests/project/proj.ohos @@ -1 +1 @@ -Subproject commit 8d5e6a65a4b7b5015fbb83ea16e86bdf771956fb +Subproject commit 8914adb203767eaddb1c043f08b2aa46691a2ddf diff --git a/tests/lua-tests/project/proj.ohos b/tests/lua-tests/project/proj.ohos index 75d72fc6133b..36f664bfaab6 160000 --- a/tests/lua-tests/project/proj.ohos +++ b/tests/lua-tests/project/proj.ohos @@ -1 +1 @@ -Subproject commit 75d72fc6133ba367c0e10617042c2bf910ca93fe +Subproject commit 36f664bfaab6fb1933d1e676c92850940c14fbfb