diff --git a/native/.github/workflows/clangtidy-android.yml b/native/.github/workflows/clangtidy-android.yml index e79b877892..a6bc886d4b 100644 --- a/native/.github/workflows/clangtidy-android.yml +++ b/native/.github/workflows/clangtidy-android.yml @@ -1,5 +1,9 @@ name: Clang Tidy - Android +# on: +# pull_request_target: +# types: [assigned, opened, edited, synchronize, reopened ,ready_for_review] + on: pull_request jobs: @@ -31,15 +35,15 @@ jobs: - exclude: 'cocos/editor-support/dragonbones/**' - exclude: 'cocos/base/etc1.*' - exclude: 'cocos/base/etc2.*' + - exclude: 'cocos/bindings/auto/**' + - exclude: 'cocos/bindings/manual/**' + - exclude: 'cocos/renderer/gfx-gles-common/**' + - exclude: 'cocos/bindings/jswrapper/v8/debugger/**' allChanges: - added|modified|deleted: '**' skipedDebug: - added|modified|deleted: '**' - exclude: 'cocos/editor-support/dragonbones/**' - - name: Install CMake & Clang Tidy - run: | - sudo apt install -y cmake llvm clang-tidy-11 - - name: Generate Compile database shell: bash run: | @@ -47,7 +51,6 @@ jobs: rm external/config.json git clone --branch $EXT_VERSION --depth 1 https://github.com/cocos-creator/engine-native-external external utils/generate_compile_commands_android.sh - - name: Generate clang-fix.yaml shell: bash if: ${{ steps.listchanged.outputs.source == 'true' }} @@ -57,9 +60,10 @@ jobs: if [[ "$FILTERED-xxx" == "-xxx" ]]; then echo "no source files match" else - clang-tidy-11 --format-style=file --export-fixes=clang-fixes.yaml $FILTERED + $ANDROID_NDK_HOME/toolchains/llvm/prebuilt/linux-x86_64/bin/clang-tidy --format-style=file --export-fixes=clang-fixes.yaml $FILTERED fi - name: clang-tidy-action + #uses: PatriceJiang/clang-tidy-action@github-api uses: PatriceJiang/clang-tidy-action@master if: hashFiles('clang-fixes.yaml') != '' with: diff --git a/native/.github/workflows/cmake.yml b/native/.github/workflows/cmake.yml index a8bf72f21f..5ae1ae959a 100644 --- a/native/.github/workflows/cmake.yml +++ b/native/.github/workflows/cmake.yml @@ -1,9 +1,9 @@ -name: Cmake Unit Test +name: Unit Test on: [push, pull_request] jobs: - camke-unit: + unit-test-with-cmake: # The CMake configure and build commands are platform agnostic and should work equally # well on Windows or Mac. You can convert this to a matrix build if you need # cross-platform coverage. diff --git a/native/.gitignore b/native/.gitignore index e10d3055a6..aad514e62e 100644 --- a/native/.gitignore +++ b/native/.gitignore @@ -172,3 +172,15 @@ build/* out CMakeSettings.json + +cocos/platform/ohos/libcocos/build/.transforms +cocos/platform/ohos/libcocos/build + +**/.gradle +**/.settings +**/.project + +.clangd/** + + +**/*~ diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index e3a21fb7b6..98637b022e 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -4,6 +4,7 @@ set(CC_PLATFORM_MAC_IOS 1) set(CC_PLATFORM_WINDOWS 2) set(CC_PLATFORM_ANDROID 3) set(CC_PLATFORM_MAC_OSX 4) +set(CC_PLATFORM_OHOS 5) set(CC_PLATFORM 1) if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") @@ -24,17 +25,23 @@ elseif(${CMAKE_SYSTEM_NAME} MATCHES "iOS") set(IOS TRUE) set(PLATFORM_FOLDER ios) set(CC_PLATFORM ${CC_PLATFORM_MAC_IOS}) +elseif(OHOS) + set(OHOS TRUE) + set(CC_PLATFORM ${CC_PLATFORM_OHOS}) + add_definitions(-D__OHOS__=1) + set(PLATFORM_FOLDER ohos) else() - message(FATAL_ERROR "Unsupported platform, CMake will exit") + message(FATAL_ERROR "Unsupported platform '${CMAKE_SYSTEM_NAME}', CMake will exit!") return() endif() # platform macros -add_definitions(-DCC_PLATFORM_WINDOWS=${CC_PLATFORM_WINDOWS} ) -add_definitions(-DCC_PLATFORM_MAC_OSX=${CC_PLATFORM_MAC_OSX} ) -add_definitions(-DCC_PLATFORM_MAC_IOS=${CC_PLATFORM_MAC_IOS} ) -add_definitions(-DCC_PLATFORM_ANDROID=${CC_PLATFORM_ANDROID} ) +add_definitions(-DCC_PLATFORM_WINDOWS=${CC_PLATFORM_WINDOWS}) +add_definitions(-DCC_PLATFORM_MAC_OSX=${CC_PLATFORM_MAC_OSX}) +add_definitions(-DCC_PLATFORM_MAC_IOS=${CC_PLATFORM_MAC_IOS}) +add_definitions(-DCC_PLATFORM_ANDROID=${CC_PLATFORM_ANDROID}) +add_definitions(-DCC_PLATFORM_OHOS=${CC_PLATFORM_OHOS}) add_definitions(-DCC_PLATFORM=${CC_PLATFORM}) # generators that are capable of organizing into a hierarchy of folders @@ -156,6 +163,11 @@ elseif(MACOSX OR IOS) set_if_undefined(CC_USE_VULKAN OFF) set_if_undefined(CC_USE_GLES3 OFF) set_if_undefined(CC_USE_GLES2 OFF) +elseif(OHOS) + set_if_undefined(CC_USE_METAL OFF) + set_if_undefined(CC_USE_VULKAN OFF) + set_if_undefined(CC_USE_GLES3 ON) + set_if_undefined(CC_USE_GLES2 OFF) endif() if(USE_PHYSICS_PHYSX) @@ -177,8 +189,12 @@ if(NOT USE_SOCKET) set(USE_WEBSOCKET_SERVER OFF) endif() +if(OHOS) + set(CC_USE_GLES2 OFF) +endif() + ## disable videoplay on non-mobile platforms -if(NOT ANDROID AND NOT IOS) +if(NOT ANDROID AND NOT IOS AND NOT OHOS) set(USE_VIDEO OFF) set(USE_WEBVIEW OFF) endif() @@ -226,7 +242,7 @@ inspect_values( if(NOT EXISTS ${CMAKE_CURRENT_LIST_DIR}/external/CMakeLists.txt) - message(FATAL_ERROR "Please download external libraries!") + message(FATAL_ERROR "Please download external libraries! File ${CMAKE_CURRENT_LIST_DIR}/external/CMakeLists.txt not exists!") endif() include(${CMAKE_CURRENT_LIST_DIR}/external/CMakeLists.txt) @@ -240,21 +256,21 @@ if(USE_AUDIO) ) if(WINDOWS) cocos_source_files( - cocos/audio/win32/AudioCache.cpp - cocos/audio/win32/AudioCache.h - cocos/audio/win32/AudioDecoder.cpp - cocos/audio/win32/AudioDecoder.h - cocos/audio/win32/AudioDecoderManager.cpp - cocos/audio/win32/AudioDecoderManager.h - cocos/audio/win32/AudioDecoderMp3.cpp - cocos/audio/win32/AudioDecoderMp3.h - cocos/audio/win32/AudioDecoderOgg.cpp - cocos/audio/win32/AudioDecoderOgg.h - cocos/audio/win32/AudioEngine-win32.cpp - cocos/audio/win32/AudioEngine-win32.h - cocos/audio/win32/AudioMacros.h - cocos/audio/win32/AudioPlayer.cpp - cocos/audio/win32/AudioPlayer.h + cocos/audio/oalsoft/AudioCache.cpp + cocos/audio/oalsoft/AudioCache.h + cocos/audio/oalsoft/AudioDecoder.cpp + cocos/audio/oalsoft/AudioDecoder.h + cocos/audio/oalsoft/AudioDecoderManager.cpp + cocos/audio/oalsoft/AudioDecoderManager.h + cocos/audio/oalsoft/AudioDecoderMp3.cpp + cocos/audio/oalsoft/AudioDecoderMp3.h + cocos/audio/oalsoft/AudioDecoderOgg.cpp + cocos/audio/oalsoft/AudioDecoderOgg.h + cocos/audio/oalsoft/AudioEngine-soft.cpp + cocos/audio/oalsoft/AudioEngine-soft.h + cocos/audio/oalsoft/AudioMacros.h + cocos/audio/oalsoft/AudioPlayer.cpp + cocos/audio/oalsoft/AudioPlayer.h ) elseif(ANDROID) cocos_source_files( @@ -322,6 +338,35 @@ if(USE_AUDIO) cocos/audio/android/utils/Utils.cpp cocos/audio/android/utils/Utils.h ) + elseif(OHOS) + cocos_source_files( + cocos/audio/oalsoft/AudioCache.cpp + cocos/audio/oalsoft/AudioCache.h + cocos/audio/oalsoft/AudioDecoderManager.cpp + cocos/audio/oalsoft/AudioDecoderManager.h + cocos/audio/oalsoft/AudioDecoder.cpp + cocos/audio/oalsoft/AudioDecoder.h + cocos/audio/oalsoft/AudioDecoderMp3.cpp + cocos/audio/oalsoft/AudioDecoderMp3.h + cocos/audio/oalsoft/AudioDecoderOgg.cpp + cocos/audio/oalsoft/AudioDecoderOgg.h + cocos/audio/oalsoft/AudioEngine-soft.cpp + cocos/audio/oalsoft/AudioEngine-soft.h + cocos/audio/oalsoft/AudioMacros.h + cocos/audio/oalsoft/AudioPlayer.cpp + cocos/audio/oalsoft/AudioPlayer.h + + cocos/audio/ohos/AudioDecoderWav.h + cocos/audio/ohos/AudioDecoderWav.cpp + # cocos/audio/ohos/AudioDecoderMp3.h + # cocos/audio/ohos/AudioDecoderMp3.cpp + cocos/audio/ohos/FsCallback.h + cocos/audio/ohos/FsCallback.cpp + + cocos/audio/android/tinysndfile.cpp + cocos/audio/android/tinysndfile.h + cocos/audio/android/audio_utils/primitives.c + ) elseif(APPLE) cocos_source_files( cocos/audio/apple/AudioDecoder.h @@ -523,11 +568,11 @@ if(APPLE) endif() endif() -if(ANDROID) +if(ANDROID OR OHOS) cocos_source_files( - cocos/network/Downloader-android.cpp - cocos/network/Downloader-android.h - cocos/network/HttpClient-android.cpp + cocos/network/Downloader-java.cpp + cocos/network/Downloader-java.h + cocos/network/HttpClient-java.cpp ) endif() @@ -583,26 +628,47 @@ if(WINDOWS) ) elseif(ANDROID) cocos_source_files( - cocos/platform/android/Application-android.cpp - cocos/platform/android/CanvasRenderingContext2D-android.cpp - cocos/platform/android/Device-android.cpp - cocos/platform/android/FileUtils-android.cpp - cocos/platform/android/FileUtils-android.h - cocos/platform/android/View.cpp - cocos/platform/android/View.h + cocos/platform/android/Application-android.cpp + cocos/platform/java/CanvasRenderingContext2D-java.cpp + cocos/platform/android/Device-android.cpp + cocos/platform/android/FileUtils-android.cpp + cocos/platform/android/FileUtils-android.h + cocos/platform/android/View.cpp + cocos/platform/android/View.h ) set(CC_JNI_SRC_FILES ${CWD}/cocos/platform/android/jni/JniCocosActivity.cpp ${CWD}/cocos/platform/android/jni/JniCocosActivity.h - ${CWD}/cocos/platform/android/jni/JniCocosTouchHandler.cpp - ${CWD}/cocos/platform/android/jni/JniCocosKeyCodeHandler.cpp + ${CWD}/cocos/platform/java/jni/JniCocosTouchHandler.cpp + ${CWD}/cocos/platform/java/jni/JniCocosKeyCodeHandler.cpp ${CWD}/cocos/platform/android/jni/JniCocosSurfaceView.cpp - ${CWD}/cocos/platform/android/jni/JniCocosOrientationHelper.cpp - ${CWD}/cocos/platform/android/jni/JniHelper.cpp - ${CWD}/cocos/platform/android/jni/JniHelper.h - ${CWD}/cocos/platform/android/jni/JniImp.cpp - ${CWD}/cocos/platform/android/jni/JniImp.h + ${CWD}/cocos/platform/java/jni/JniCocosOrientationHelper.cpp + ${CWD}/cocos/platform/java/jni/JniHelper.cpp + ${CWD}/cocos/platform/java/jni/JniHelper.h + ${CWD}/cocos/platform/java/jni/JniImp.cpp + ${CWD}/cocos/platform/java/jni/JniImp.h ) +elseif(OHOS) + cocos_source_files( + cocos/platform/ohos/Application-ohos.cpp + cocos/platform/java/CanvasRenderingContext2D-java.cpp + cocos/platform/ohos/Device-ohos.cpp + cocos/platform/ohos/FileUtils-ohos.cpp + cocos/platform/ohos/FileUtils-ohos.h + cocos/platform/ohos/View.cpp + cocos/platform/ohos/View.h + ) + set(CC_JNI_SRC_FILES + ${CWD}/cocos/platform/ohos/jni/JniCocosAbility.cpp + ${CWD}/cocos/platform/ohos/jni/JniCocosAbility.h + ${CWD}/cocos/platform/java/jni/JniHelper.cpp + ${CWD}/cocos/platform/java/jni/JniHelper.h + ${CWD}/cocos/platform/java/jni/JniImp.cpp + ${CWD}/cocos/platform/java/jni/JniImp.h + ${CWD}/cocos/platform/java/jni/JniCocosTouchHandler.cpp + ${CWD}/cocos/platform/java/jni/JniCocosKeyCodeHandler.cpp + ${CWD}/cocos/platform/java/jni/JniCocosOrientationHelper.cpp + ${CWD}/cocos/platform/ohos/jni/AbilityConsts.h) elseif(APPLE) cocos_source_files( cocos/platform/apple/FileUtils-apple.h @@ -835,12 +901,16 @@ cocos_source_files( ) if(CC_USE_GLES2 OR CC_USE_GLES3) -cocos_source_files( - cocos/renderer/gfx-gles-common/GLESCommandPool.h - cocos/renderer/gfx-gles-common/eglw.cpp - cocos/renderer/gfx-gles-common/gles2w.cpp - cocos/renderer/gfx-gles-common/gles3w.cpp -) + cocos_source_files( + cocos/renderer/gfx-gles-common/GLESCommandPool.h + cocos/renderer/gfx-gles-common/eglw.cpp + cocos/renderer/gfx-gles-common/gles2w.cpp + ) + if(CC_USE_GLES3) + cocos_source_files( + cocos/renderer/gfx-gles-common/gles3w.cpp + ) + endif() endif() if(CC_USE_GLES2) @@ -1532,6 +1602,12 @@ if(ANDROID) cocos/bindings/manual/JavaScriptJavaBridge.cpp cocos/bindings/manual/JavaScriptJavaBridge.h ) +elseif(OHOS) + cocos_source_files( + cocos/bindings/manual/jsb_platform_ohos.cpp + cocos/bindings/manual/JavaScriptJavaBridge.cpp + cocos/bindings/manual/JavaScriptJavaBridge.h + ) elseif(APPLE) cocos_source_files( NO_WERROR cocos/bindings/manual/jsb_platfrom_apple.mm @@ -1565,7 +1641,7 @@ if(USE_SE_V8) cocos/bindings/jswrapper/v8/debugger/base64.h NO_WERROR cocos/bindings/jswrapper/v8/debugger/env.cpp cocos/bindings/jswrapper/v8/debugger/env.h - NO_WERROR cocos/bindings/jswrapper/v8/debugger/http_parser.c + NO_WERROR cocos/bindings/jswrapper/v8/debugger/http_parser.cpp cocos/bindings/jswrapper/v8/debugger/http_parser.h NO_WERROR cocos/bindings/jswrapper/v8/debugger/inspector_agent.cpp cocos/bindings/jswrapper/v8/debugger/inspector_agent.h @@ -1654,7 +1730,7 @@ if(USE_EDIT_BOX) ) endif() -if(ANDROID OR IOS) +if(ANDROID OR IOS OR OHOS) if(USE_VIDEO) cocos_source_files( cocos/ui/videoplayer/VideoPlayer.h @@ -1662,7 +1738,7 @@ if(ANDROID OR IOS) endif() if(USE_WEBVIEW) cocos_source_files( - cocos/ui/webview/WebViewImpl-android.h + cocos/ui/webview/WebViewImpl-java.h cocos/ui/webview/WebViewImpl-ios.h cocos/ui/webview/WebView-inl.h cocos/ui/webview/WebView.h @@ -1678,7 +1754,7 @@ if(ANDROID) endif() if(USE_VIDEO) cocos_source_files( - cocos/ui/videoplayer/VideoPlayer-android.cpp + cocos/ui/videoplayer/VideoPlayer-java.cpp ) endif() if(USE_WEBVIEW) @@ -1686,10 +1762,26 @@ if(ANDROID) cocos/ui/webview/WebViewImpl-android.cpp ) endif() +elseif(OHOS) + if(USE_EDIT_BOX) + cocos_source_files( + cocos/ui/edit-box/EditBox-ohos.cpp + ) + endif() + if(USE_VIDEO) + cocos_source_files( + cocos/ui/videoplayer/VideoPlayer-java.cpp + ) + endif() + if(USE_WEBVIEW) + cocos_source_files( + cocos/ui/webview/WebViewImpl-ohos.cpp + ) + endif() elseif(MACOSX) if(USE_EDIT_BOX) cocos_source_files( - cocos/ui/edit-box/EditBox-mac.mm + cocos/ui/edit-box/EditBox-mac.mm ) endif() elseif(IOS) @@ -1736,18 +1828,20 @@ list(APPEND COCOS2D_SOURCE_LIST ${CC_EXTERNAL_SOURCES}) add_library(cocos2d ${COCOS2D_SOURCE_LIST}) -if(ANDROID) +if(ANDROID OR OHOS) enable_werror("${CC_JNI_SRC_FILES}") add_library(cocos2d_jni STATIC ${CC_JNI_SRC_FILES}) target_include_directories(cocos2d_jni PUBLIC ${CWD} ${CWD}/cocos ) - target_link_libraries(cocos2d_jni PUBLIC - android_platform - android - log - ) + if(ANDROID) + target_link_libraries(cocos2d_jni PUBLIC + android_platform + android + log + ) + endif() endif() # setup default flags @@ -1806,7 +1900,7 @@ target_include_directories(cocos2d ${CWD}/cocos ${CWD}/cocos/renderer ${CWD}/cocos/platform - ${CWD}/external/sources/khronos + ${CWD}/cocos/renderer/core ${CWD}/cocos/editor-support $<$:${CWD}/cocos/bindings/jswrapper> PRIVATE @@ -1817,6 +1911,13 @@ target_compile_definitions(cocos2d PRIVATE ${CC_EXTERNAL_PRIVATE_DEFINITIONS} ) +if(NOT OHOS) + target_include_directories(cocos2d PUBLIC + ${CWD}/external/sources/EGL + ${CWD}/external/sources/khronos + ) +endif() + if(WIN32) target_link_libraries(cocos2d PUBLIC @@ -1857,6 +1958,19 @@ if(ANDROID) ) endif() +if(OHOS) + target_link_libraries(cocos2d PUBLIC + hilog_ndk.z + EGL + GLESv3 + zgraphic.z + rawfile.z + z + OpenSLES + ${CC_EXTERNAL_LIBS} + ) +endif() + if(APPLE) target_compile_options(cocos2d PRIVATE diff --git a/native/cocos/audio/AudioEngine.cpp b/native/cocos/audio/AudioEngine.cpp index 6226a3d17a..a983cabb2b 100644 --- a/native/cocos/audio/AudioEngine.cpp +++ b/native/cocos/audio/AudioEngine.cpp @@ -25,21 +25,21 @@ ****************************************************************************/ #include "audio/include/AudioEngine.h" -#include "platform/FileUtils.h" -#include "base/Utils.h" #include "base/Log.h" +#include "base/Utils.h" +#include "platform/FileUtils.h" #include +#include #include #include -#include #if CC_PLATFORM == CC_PLATFORM_ANDROID #include "audio/android/AudioEngine-inl.h" #elif CC_PLATFORM == CC_PLATFORM_MAC_IOS || CC_PLATFORM == CC_PLATFORM_MAC_OSX #include "audio/apple/AudioEngine-inl.h" -#elif CC_PLATFORM == CC_PLATFORM_WINDOWS - #include "audio/win32/AudioEngine-win32.h" +#elif CC_PLATFORM == CC_PLATFORM_WINDOWS || CC_PLATFORM == CC_PLATFORM_OHOS + #include "audio/oalsoft/AudioEngine-soft.h" #elif CC_PLATFORM == CC_PLATFORM_WINRT #include "audio/winrt/AudioEngine-winrt.h" #elif CC_PLATFORM == CC_PLATFORM_LINUX @@ -54,38 +54,41 @@ #undef ERROR #endif // ERROR -using namespace cc; +using namespace cc; //NOLINT -const int AudioEngine::INVALID_AUDIO_ID = -1; -const float AudioEngine::TIME_UNKNOWN = -1.0f; +const int AudioEngine::INVALID_AUDIO_ID = -1; +const float AudioEngine::TIME_UNKNOWN = -1.0F; //audio file path,audio IDs -std::unordered_map> AudioEngine::_audioPathIDMap; +std::unordered_map> AudioEngine::sAudioPathIDMap; //profileName,ProfileHelper -std::unordered_map AudioEngine::_audioPathProfileHelperMap; -unsigned int AudioEngine::_maxInstances = MAX_AUDIOINSTANCES; -AudioEngine::ProfileHelper *AudioEngine::_defaultProfileHelper = nullptr; -std::unordered_map AudioEngine::_audioIDInfoMap; -AudioEngineImpl *AudioEngine::_audioEngineImpl = nullptr; +std::unordered_map AudioEngine::sAudioPathProfileHelperMap; +unsigned int AudioEngine::sMaxInstances = MAX_AUDIOINSTANCES; +AudioEngine::ProfileHelper * AudioEngine::sDefaultProfileHelper = nullptr; +std::unordered_map AudioEngine::sAudioIDInfoMap; +AudioEngineImpl * AudioEngine::sAudioEngineImpl = nullptr; -uint32_t AudioEngine::_onPauseListenerID = 0; -uint32_t AudioEngine::_onResumeListenerID = 0; -std::vector AudioEngine::_breakAudioID; +uint32_t AudioEngine::sOnPauseListenerID = 0; +uint32_t AudioEngine::sOnResumeListenerID = 0; +std::vector AudioEngine::sBreakAudioID; -AudioEngine::AudioEngineThreadPool *AudioEngine::s_threadPool = nullptr; -bool AudioEngine::_isEnabled = true; +AudioEngine::AudioEngineThreadPool *AudioEngine::sThreadPool = nullptr; +bool AudioEngine::sIsEnabled = true; AudioEngine::AudioInfo::AudioInfo() -: filePath(nullptr), profileHelper(nullptr), volume(1.0f), loop(false), duration(TIME_UNKNOWN), state(AudioState::INITIALIZING) { +: filePath(nullptr), + profileHelper(nullptr), + volume(1.0F), + loop(false), + duration(TIME_UNKNOWN), + state(AudioState::INITIALIZING) { } -AudioEngine::AudioInfo::~AudioInfo() { -} +AudioEngine::AudioInfo::~AudioInfo() = default; class AudioEngine::AudioEngineThreadPool { public: - AudioEngineThreadPool(int threads = 4) - : _stop(false) { + explicit AudioEngineThreadPool(int threads = 4) { for (int index = 0; index < threads; ++index) { _workers.emplace_back(std::thread(std::bind(&AudioEngineThreadPool::threadFunc, this))); } @@ -131,54 +134,54 @@ private: } } - std::vector _workers; + std::vector _workers; std::queue> _taskQueue; - std::mutex _queueMutex; + std::mutex _queueMutex; std::condition_variable _taskCondition; - bool _stop; + bool _stop{}; }; void AudioEngine::end() { stopAll(); - if (s_threadPool) { - delete s_threadPool; - s_threadPool = nullptr; + if (sThreadPool) { + delete sThreadPool; + sThreadPool = nullptr; } - delete _audioEngineImpl; - _audioEngineImpl = nullptr; + delete sAudioEngineImpl; + sAudioEngineImpl = nullptr; - delete _defaultProfileHelper; - _defaultProfileHelper = nullptr; + delete sDefaultProfileHelper; + sDefaultProfileHelper = nullptr; - if (_onPauseListenerID != 0) { - EventDispatcher::removeCustomEventListener(EVENT_COME_TO_BACKGROUND, _onPauseListenerID); - _onPauseListenerID = 0; + if (sOnPauseListenerID != 0) { + EventDispatcher::removeCustomEventListener(EVENT_COME_TO_BACKGROUND, sOnPauseListenerID); + sOnPauseListenerID = 0; } - if (_onResumeListenerID != 0) { - EventDispatcher::removeCustomEventListener(EVENT_COME_TO_FOREGROUND, _onResumeListenerID); - _onResumeListenerID = 0; + if (sOnResumeListenerID != 0) { + EventDispatcher::removeCustomEventListener(EVENT_COME_TO_FOREGROUND, sOnResumeListenerID); + sOnResumeListenerID = 0; } } bool AudioEngine::lazyInit() { - if (_audioEngineImpl == nullptr) { - _audioEngineImpl = new (std::nothrow) AudioEngineImpl(); - if (!_audioEngineImpl || !_audioEngineImpl->init()) { - delete _audioEngineImpl; - _audioEngineImpl = nullptr; + if (sAudioEngineImpl == nullptr) { + sAudioEngineImpl = new (std::nothrow) AudioEngineImpl(); + if (!sAudioEngineImpl || !sAudioEngineImpl->init()) { + delete sAudioEngineImpl; + sAudioEngineImpl = nullptr; return false; } - _onPauseListenerID = EventDispatcher::addCustomEventListener(EVENT_COME_TO_BACKGROUND, AudioEngine::onEnterBackground); - _onResumeListenerID = EventDispatcher::addCustomEventListener(EVENT_COME_TO_FOREGROUND, AudioEngine::onEnterForeground); + sOnPauseListenerID = EventDispatcher::addCustomEventListener(EVENT_COME_TO_BACKGROUND, AudioEngine::onEnterBackground); + sOnResumeListenerID = EventDispatcher::addCustomEventListener(EVENT_COME_TO_FOREGROUND, AudioEngine::onEnterForeground); } #if (CC_PLATFORM != CC_PLATFORM_ANDROID) - if (_audioEngineImpl && s_threadPool == nullptr) { - s_threadPool = new (std::nothrow) AudioEngineThreadPool(); + if (sAudioEngineImpl && sThreadPool == nullptr) { + sThreadPool = new (std::nothrow) AudioEngineThreadPool(); } #endif @@ -201,14 +204,14 @@ int AudioEngine::play2d(const std::string &filePath, bool loop, float volume, co break; } - auto profileHelper = _defaultProfileHelper; + auto profileHelper = sDefaultProfileHelper; if (profile && profile != &profileHelper->profile) { CC_ASSERT(!profile->name.empty()); - profileHelper = &_audioPathProfileHelperMap[profile->name]; + profileHelper = &sAudioPathProfileHelperMap[profile->name]; profileHelper->profile = *profile; } - if (_audioIDInfoMap.size() >= _maxInstances) { + if (sAudioIDInfoMap.size() >= sMaxInstances) { CC_LOG_INFO("Fail to play %s cause by limited max instance of AudioEngine", filePath.c_str()); break; } @@ -219,7 +222,7 @@ int AudioEngine::play2d(const std::string &filePath, bool loop, float volume, co } if (profileHelper->profile.minDelay > TIME_DELAY_PRECISION) { auto currTime = std::chrono::high_resolution_clock::now(); - auto delay = (float)std::chrono::duration_cast(currTime - profileHelper->lastPlayTime).count() / 1000000.0; + auto delay = static_cast(std::chrono::duration_cast(currTime - profileHelper->lastPlayTime).count()) / 1000000.0; if (profileHelper->lastPlayTime.time_since_epoch().count() != 0 && delay <= profileHelper->profile.minDelay) { CC_LOG_INFO("Fail to play %s cause by limited minimum delay", filePath.c_str()); break; @@ -227,20 +230,20 @@ int AudioEngine::play2d(const std::string &filePath, bool loop, float volume, co } } - if (volume < 0.0f) { - volume = 0.0f; - } else if (volume > 1.0f) { - volume = 1.0f; + if (volume < 0.0F) { + volume = 0.0F; + } else if (volume > 1.0F) { + volume = 1.0F; } - ret = _audioEngineImpl->play2d(filePath, loop, volume); + ret = sAudioEngineImpl->play2d(filePath, loop, volume); if (ret != INVALID_AUDIO_ID) { - _audioPathIDMap[filePath].push_back(ret); - auto it = _audioPathIDMap.find(filePath); + sAudioPathIDMap[filePath].push_back(ret); + auto it = sAudioPathIDMap.find(filePath); - auto &audioRef = _audioIDInfoMap[ret]; - audioRef.volume = volume; - audioRef.loop = loop; + auto &audioRef = sAudioIDInfoMap[ret]; + audioRef.volume = volume; + audioRef.loop = loop; audioRef.filePath = &it->first; if (profileHelper) { @@ -249,176 +252,176 @@ int AudioEngine::play2d(const std::string &filePath, bool loop, float volume, co } audioRef.profileHelper = profileHelper; } - } while (0); + } while (false); return ret; } void AudioEngine::setLoop(int audioID, bool loop) { - auto it = _audioIDInfoMap.find(audioID); - if (it != _audioIDInfoMap.end() && it->second.loop != loop) { - _audioEngineImpl->setLoop(audioID, loop); + auto it = sAudioIDInfoMap.find(audioID); + if (it != sAudioIDInfoMap.end() && it->second.loop != loop) { + sAudioEngineImpl->setLoop(audioID, loop); it->second.loop = loop; } } void AudioEngine::setVolume(int audioID, float volume) { - auto it = _audioIDInfoMap.find(audioID); - if (it != _audioIDInfoMap.end()) { - if (volume < 0.0f) { - volume = 0.0f; - } else if (volume > 1.0f) { - volume = 1.0f; + auto it = sAudioIDInfoMap.find(audioID); + if (it != sAudioIDInfoMap.end()) { + if (volume < 0.0F) { + volume = 0.0F; + } else if (volume > 1.0F) { + volume = 1.0F; } if (it->second.volume != volume) { - _audioEngineImpl->setVolume(audioID, volume); + sAudioEngineImpl->setVolume(audioID, volume); it->second.volume = volume; } } } void AudioEngine::pause(int audioID) { - auto it = _audioIDInfoMap.find(audioID); - if (it != _audioIDInfoMap.end() && it->second.state == AudioState::PLAYING) { - _audioEngineImpl->pause(audioID); + auto it = sAudioIDInfoMap.find(audioID); + if (it != sAudioIDInfoMap.end() && it->second.state == AudioState::PLAYING) { + sAudioEngineImpl->pause(audioID); it->second.state = AudioState::PAUSED; } } void AudioEngine::pauseAll() { - auto itEnd = _audioIDInfoMap.end(); - for (auto it = _audioIDInfoMap.begin(); it != itEnd; ++it) { + auto itEnd = sAudioIDInfoMap.end(); + for (auto it = sAudioIDInfoMap.begin(); it != itEnd; ++it) { if (it->second.state == AudioState::PLAYING) { - _audioEngineImpl->pause(it->first); + sAudioEngineImpl->pause(it->first); it->second.state = AudioState::PAUSED; } } } void AudioEngine::resume(int audioID) { - auto it = _audioIDInfoMap.find(audioID); - if (it != _audioIDInfoMap.end() && it->second.state == AudioState::PAUSED) { - _audioEngineImpl->resume(audioID); + auto it = sAudioIDInfoMap.find(audioID); + if (it != sAudioIDInfoMap.end() && it->second.state == AudioState::PAUSED) { + sAudioEngineImpl->resume(audioID); it->second.state = AudioState::PLAYING; } } void AudioEngine::resumeAll() { - auto itEnd = _audioIDInfoMap.end(); - for (auto it = _audioIDInfoMap.begin(); it != itEnd; ++it) { + auto itEnd = sAudioIDInfoMap.end(); + for (auto it = sAudioIDInfoMap.begin(); it != itEnd; ++it) { if (it->second.state == AudioState::PAUSED) { - _audioEngineImpl->resume(it->first); + sAudioEngineImpl->resume(it->first); it->second.state = AudioState::PLAYING; } } } -void AudioEngine::onEnterBackground(const CustomEvent &event) { - auto itEnd = _audioIDInfoMap.end(); - for (auto it = _audioIDInfoMap.begin(); it != itEnd; ++it) { +void AudioEngine::onEnterBackground(const CustomEvent & /*event*/) { + auto itEnd = sAudioIDInfoMap.end(); + for (auto it = sAudioIDInfoMap.begin(); it != itEnd; ++it) { if (it->second.state == AudioState::PLAYING) { - _audioEngineImpl->pause(it->first); - _breakAudioID.push_back(it->first); + sAudioEngineImpl->pause(it->first); + sBreakAudioID.push_back(it->first); } } #if CC_PLATFORM == CC_PLATFORM_ANDROID - if (_audioEngineImpl) { - _audioEngineImpl->onPause(); + if (sAudioEngineImpl) { + sAudioEngineImpl->onPause(); } #endif } -void AudioEngine::onEnterForeground(const CustomEvent &event) { - auto itEnd = _breakAudioID.end(); - for (auto it = _breakAudioID.begin(); it != itEnd; ++it) { - _audioEngineImpl->resume(*it); +void AudioEngine::onEnterForeground(const CustomEvent & /*event*/) { + auto itEnd = sBreakAudioID.end(); + for (auto it = sBreakAudioID.begin(); it != itEnd; ++it) { + sAudioEngineImpl->resume(*it); } - _breakAudioID.clear(); + sBreakAudioID.clear(); #if CC_PLATFORM == CC_PLATFORM_ANDROID - if (_audioEngineImpl) { - _audioEngineImpl->onResume(); + if (sAudioEngineImpl) { + sAudioEngineImpl->onResume(); } #endif } void AudioEngine::stop(int audioID) { - auto it = _audioIDInfoMap.find(audioID); - if (it != _audioIDInfoMap.end()) { - _audioEngineImpl->stop(audioID); + auto it = sAudioIDInfoMap.find(audioID); + if (it != sAudioIDInfoMap.end()) { + sAudioEngineImpl->stop(audioID); remove(audioID); } } void AudioEngine::remove(int audioID) { - auto it = _audioIDInfoMap.find(audioID); - if (it != _audioIDInfoMap.end()) { + auto it = sAudioIDInfoMap.find(audioID); + if (it != sAudioIDInfoMap.end()) { if (it->second.profileHelper) { it->second.profileHelper->audioIDs.remove(audioID); } - _audioPathIDMap[*it->second.filePath].remove(audioID); - _audioIDInfoMap.erase(audioID); + sAudioPathIDMap[*it->second.filePath].remove(audioID); + sAudioIDInfoMap.erase(audioID); } } void AudioEngine::stopAll() { - if (!_audioEngineImpl) { + if (!sAudioEngineImpl) { return; } - _audioEngineImpl->stopAll(); - auto itEnd = _audioIDInfoMap.end(); - for (auto it = _audioIDInfoMap.begin(); it != itEnd; ++it) { + sAudioEngineImpl->stopAll(); + auto itEnd = sAudioIDInfoMap.end(); + for (auto it = sAudioIDInfoMap.begin(); it != itEnd; ++it) { if (it->second.profileHelper) { it->second.profileHelper->audioIDs.remove(it->first); } } - _audioPathIDMap.clear(); - _audioIDInfoMap.clear(); + sAudioPathIDMap.clear(); + sAudioIDInfoMap.clear(); } void AudioEngine::uncache(const std::string &filePath) { - auto audioIDsIter = _audioPathIDMap.find(filePath); - if (audioIDsIter != _audioPathIDMap.end()) { + auto audioIDsIter = sAudioPathIDMap.find(filePath); + if (audioIDsIter != sAudioPathIDMap.end()) { //@Note: For safely iterating elements from the audioID list, we need to copy the list - // since 'AudioEngine::remove' may be invoked in '_audioEngineImpl->stop' synchronously. + // since 'AudioEngine::remove' may be invoked in 'sAudioEngineImpl->stop' synchronously. // If this happens, it will break the iteration, and crash will appear on some devices. std::list copiedIDs(audioIDsIter->second); for (int audioID : copiedIDs) { - _audioEngineImpl->stop(audioID); + sAudioEngineImpl->stop(audioID); - auto itInfo = _audioIDInfoMap.find(audioID); - if (itInfo != _audioIDInfoMap.end()) { + auto itInfo = sAudioIDInfoMap.find(audioID); + if (itInfo != sAudioIDInfoMap.end()) { if (itInfo->second.profileHelper) { itInfo->second.profileHelper->audioIDs.remove(audioID); } - _audioIDInfoMap.erase(audioID); + sAudioIDInfoMap.erase(audioID); } } - _audioPathIDMap.erase(filePath); + sAudioPathIDMap.erase(filePath); } - if (_audioEngineImpl) { - _audioEngineImpl->uncache(filePath); + if (sAudioEngineImpl) { + sAudioEngineImpl->uncache(filePath); } } void AudioEngine::uncacheAll() { - if (!_audioEngineImpl) { + if (!sAudioEngineImpl) { return; } stopAll(); - _audioEngineImpl->uncacheAll(); + sAudioEngineImpl->uncacheAll(); } float AudioEngine::getDuration(int audioID) { - auto it = _audioIDInfoMap.find(audioID); - if (it != _audioIDInfoMap.end() && it->second.state != AudioState::INITIALIZING) { + auto it = sAudioIDInfoMap.find(audioID); + if (it != sAudioIDInfoMap.end() && it->second.state != AudioState::INITIALIZING) { if (it->second.duration == TIME_UNKNOWN) { - it->second.duration = _audioEngineImpl->getDuration(audioID); + it->second.duration = sAudioEngineImpl->getDuration(audioID); } return it->second.duration; } @@ -429,40 +432,40 @@ float AudioEngine::getDuration(int audioID) { float AudioEngine::getDurationFromFile(const std::string &filePath) { lazyInit(); - if (_audioEngineImpl) { - return _audioEngineImpl->getDurationFromFile(filePath); + if (sAudioEngineImpl) { + return sAudioEngineImpl->getDurationFromFile(filePath); } return TIME_UNKNOWN; } bool AudioEngine::setCurrentTime(int audioID, float time) { - auto it = _audioIDInfoMap.find(audioID); - if (it != _audioIDInfoMap.end() && it->second.state != AudioState::INITIALIZING) { - return _audioEngineImpl->setCurrentTime(audioID, time); + auto it = sAudioIDInfoMap.find(audioID); + if (it != sAudioIDInfoMap.end() && it->second.state != AudioState::INITIALIZING) { + return sAudioEngineImpl->setCurrentTime(audioID, time); } return false; } float AudioEngine::getCurrentTime(int audioID) { - auto it = _audioIDInfoMap.find(audioID); - if (it != _audioIDInfoMap.end() && it->second.state != AudioState::INITIALIZING) { - return _audioEngineImpl->getCurrentTime(audioID); + auto it = sAudioIDInfoMap.find(audioID); + if (it != sAudioIDInfoMap.end() && it->second.state != AudioState::INITIALIZING) { + return sAudioEngineImpl->getCurrentTime(audioID); } - return 0.0f; + return 0.0F; } void AudioEngine::setFinishCallback(int audioID, const std::function &callback) { - auto it = _audioIDInfoMap.find(audioID); - if (it != _audioIDInfoMap.end()) { - _audioEngineImpl->setFinishCallback(audioID, callback); + auto it = sAudioIDInfoMap.find(audioID); + if (it != sAudioIDInfoMap.end()) { + sAudioEngineImpl->setFinishCallback(audioID, callback); } } bool AudioEngine::setMaxAudioInstance(int maxInstances) { if (maxInstances > 0 && maxInstances <= MAX_AUDIOINSTANCES) { - _maxInstances = maxInstances; + sMaxInstances = maxInstances; return true; } @@ -470,8 +473,8 @@ bool AudioEngine::setMaxAudioInstance(int maxInstances) { } bool AudioEngine::isLoop(int audioID) { - auto tmpIterator = _audioIDInfoMap.find(audioID); - if (tmpIterator != _audioIDInfoMap.end()) { + auto tmpIterator = sAudioIDInfoMap.find(audioID); + if (tmpIterator != sAudioIDInfoMap.end()) { return tmpIterator->second.loop; } @@ -480,18 +483,18 @@ bool AudioEngine::isLoop(int audioID) { } float AudioEngine::getVolume(int audioID) { - auto tmpIterator = _audioIDInfoMap.find(audioID); - if (tmpIterator != _audioIDInfoMap.end()) { + auto tmpIterator = sAudioIDInfoMap.find(audioID); + if (tmpIterator != sAudioIDInfoMap.end()) { return tmpIterator->second.volume; } CC_LOG_INFO("AudioEngine::getVolume-->The audio instance %d is non-existent", audioID); - return 0.0f; + return 0.0F; } AudioEngine::AudioState AudioEngine::getState(int audioID) { - auto tmpIterator = _audioIDInfoMap.find(audioID); - if (tmpIterator != _audioIDInfoMap.end()) { + auto tmpIterator = sAudioIDInfoMap.find(audioID); + if (tmpIterator != sAudioIDInfoMap.end()) { return tmpIterator->second.state; } @@ -499,8 +502,8 @@ AudioEngine::AudioState AudioEngine::getState(int audioID) { } AudioProfile *AudioEngine::getProfile(int audioID) { - auto it = _audioIDInfoMap.find(audioID); - if (it != _audioIDInfoMap.end()) { + auto it = sAudioIDInfoMap.find(audioID); + if (it != sAudioIDInfoMap.end()) { return &it->second.profileHelper->profile; } @@ -508,23 +511,22 @@ AudioProfile *AudioEngine::getProfile(int audioID) { } AudioProfile *AudioEngine::getDefaultProfile() { - if (_defaultProfileHelper == nullptr) { - _defaultProfileHelper = new (std::nothrow) ProfileHelper(); + if (sDefaultProfileHelper == nullptr) { + sDefaultProfileHelper = new (std::nothrow) ProfileHelper(); } - return &_defaultProfileHelper->profile; + return &sDefaultProfileHelper->profile; } AudioProfile *AudioEngine::getProfile(const std::string &name) { - auto it = _audioPathProfileHelperMap.find(name); - if (it != _audioPathProfileHelperMap.end()) { + auto it = sAudioPathProfileHelperMap.find(name); + if (it != sAudioPathProfileHelperMap.end()) { return &it->second.profile; - } else { - return nullptr; } + return nullptr; } -void AudioEngine::preload(const std::string &filePath, std::function callback) { +void AudioEngine::preload(const std::string &filePath, const std::function &callback) { if (!isEnabled()) { callback(false); return; @@ -532,7 +534,7 @@ void AudioEngine::preload(const std::string &filePath, std::functionisFileExist(filePath)) { if (callback) { callback(false); @@ -540,32 +542,32 @@ void AudioEngine::preload(const std::string &filePath, std::functionpreload(filePath, callback); + sAudioEngineImpl->preload(filePath, callback); } } void AudioEngine::addTask(const std::function &task) { lazyInit(); - if (_audioEngineImpl && s_threadPool) { - s_threadPool->addTask(task); + if (sAudioEngineImpl && sThreadPool) { + sThreadPool->addTask(task); } } int AudioEngine::getPlayingAudioCount() { - return static_cast(_audioIDInfoMap.size()); + return static_cast(sAudioIDInfoMap.size()); } void AudioEngine::setEnabled(bool isEnabled) { - if (_isEnabled != isEnabled) { - _isEnabled = isEnabled; + if (sIsEnabled != isEnabled) { + sIsEnabled = isEnabled; - if (!_isEnabled) { + if (!sIsEnabled) { stopAll(); } } } bool AudioEngine::isEnabled() { - return _isEnabled; + return sIsEnabled; } diff --git a/native/cocos/audio/android/AudioDecoderWav.cpp b/native/cocos/audio/android/AudioDecoderWav.cpp index ff925662c9..032a362894 100644 --- a/native/cocos/audio/android/AudioDecoderWav.cpp +++ b/native/cocos/audio/android/AudioDecoderWav.cpp @@ -29,7 +29,7 @@ THE SOFTWARE. #include "audio/android/tinysndfile.h" #include "platform/FileUtils.h" -#include +#include namespace cc { @@ -37,18 +37,17 @@ AudioDecoderWav::AudioDecoderWav() { ALOGV("Create AudioDecoderWav"); } -AudioDecoderWav::~AudioDecoderWav() { -} +AudioDecoderWav::~AudioDecoderWav() = default; -void *AudioDecoderWav::onWavOpen(const char *path, void *user) { +void *AudioDecoderWav::onWavOpen(const char * /*path*/, void *user) { return user; } -int AudioDecoderWav::onWavSeek(void *datasource, long offset, int whence) { - return AudioDecoder::fileSeek(datasource, (int64_t)offset, whence); +int AudioDecoderWav::onWavSeek(void *datasource, long offset, int whence) { //NOLINT(google-runtime-int) + return AudioDecoder::fileSeek(datasource, static_cast(offset), whence); } -int AudioDecoderWav::onWavClose(void *datasource) { +int AudioDecoderWav::onWavClose(void * /*datasource*/) { return 0; } @@ -61,44 +60,47 @@ bool AudioDecoderWav::decodeToPcm() { SF_INFO info; snd_callbacks cb; - cb.open = onWavOpen; - cb.read = AudioDecoder::fileRead; - cb.seek = onWavSeek; + cb.open = onWavOpen; + cb.read = AudioDecoder::fileRead; + cb.seek = onWavSeek; cb.close = onWavClose; - cb.tell = AudioDecoder::fileTell; + cb.tell = AudioDecoder::fileTell; - SNDFILE *handle = NULL; - bool ret = false; + SNDFILE *handle = nullptr; + bool ret = false; do { handle = sf_open_read(_url.c_str(), &info, &cb, this); - if (handle == nullptr) + if (handle == nullptr) { break; + } - if (info.frames == 0) + if (info.frames == 0) { break; + } ALOGD("wav info: frames: %d, samplerate: %d, channels: %d, format: %d", info.frames, info.samplerate, info.channels, info.format); - size_t bufSize = sizeof(short) * info.frames * info.channels; - unsigned char *buf = (unsigned char *)malloc(bufSize); - sf_count_t readFrames = sf_readf_short(handle, (short *)buf, info.frames); + size_t bufSize = sizeof(int16_t) * info.frames * info.channels; + auto * buf = static_cast(malloc(bufSize)); + sf_count_t readFrames = sf_readf_short(handle, reinterpret_cast(buf), info.frames); assert(readFrames == info.frames); _result.pcmBuffer->insert(_result.pcmBuffer->end(), buf, buf + bufSize); - _result.numChannels = info.channels; - _result.sampleRate = info.samplerate; + _result.numChannels = info.channels; + _result.sampleRate = info.samplerate; _result.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; _result.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; - _result.channelMask = _result.numChannels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT); - _result.endianness = SL_BYTEORDER_LITTLEENDIAN; - _result.numFrames = info.frames; - _result.duration = 1.0f * info.frames / _result.sampleRate; + _result.channelMask = _result.numChannels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT); + _result.endianness = SL_BYTEORDER_LITTLEENDIAN; + _result.numFrames = info.frames; + _result.duration = static_cast(1.0F * info.frames / _result.sampleRate); //NOLINT free(buf); ret = true; } while (false); - if (handle != NULL) + if (handle != nullptr) { sf_close(handle); + } return ret; } diff --git a/native/cocos/audio/android/AudioEngine-inl.cpp b/native/cocos/audio/android/AudioEngine-inl.cpp index 53dd8788d5..be5fef56bc 100644 --- a/native/cocos/audio/android/AudioEngine-inl.cpp +++ b/native/cocos/audio/android/AudioEngine-inl.cpp @@ -28,57 +28,57 @@ #include // for native asset manager -#include #include #include -#include #include -#include +#include #include +#include +#include #include "audio/include/AudioEngine.h" -#include "platform/Application.h" +#include "base/Log.h" #include "base/Scheduler.h" #include "base/UTF8.h" -#include "base/Log.h" +#include "platform/Application.h" #include "platform/android/FileUtils-android.h" -#include "platform/android/jni/JniImp.h" -#include "platform/android/jni/JniHelper.h" +#include "platform/java/jni/JniHelper.h" +#include "platform/java/jni/JniImp.h" +#include "audio/android/AudioPlayerProvider.h" #include "audio/android/IAudioPlayer.h" #include "audio/android/ICallerThreadUtils.h" -#include "audio/android/AudioPlayerProvider.h" -#include "audio/android/cutils/log.h" #include "audio/android/UrlAudioPlayer.h" +#include "audio/android/cutils/log.h" -#include "cocos/bindings/event/EventDispatcher.h" #include "cocos/bindings/event/CustomEventTypes.h" +#include "cocos/bindings/event/EventDispatcher.h" -using namespace cc; +using namespace cc; //NOLINT // Audio focus values synchronized with which in cocos/platform/android/java/src/com/cocos/lib/CocosNativeActivity.java namespace { -AudioEngineImpl *__impl = nullptr; -int outputSampleRate = 44100; -int bufferSizeInFrames = 192; +AudioEngineImpl *gAudioImpl = nullptr; +int outputSampleRate = 44100; +int bufferSizeInFrames = 192; void getAudioInfo() { - JNIEnv *env = JniHelper::getEnv(); - jclass audioSystem = env->FindClass("android/media/AudioSystem"); - jmethodID method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputSamplingRate", "()I"); - outputSampleRate = env->CallStaticIntMethod(audioSystem, method); - method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputFrameCount", "()I"); - bufferSizeInFrames = env->CallStaticIntMethod(audioSystem, method); + JNIEnv * env = JniHelper::getEnv(); + jclass audioSystem = env->FindClass("android/media/AudioSystem"); + jmethodID method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputSamplingRate", "()I"); + outputSampleRate = env->CallStaticIntMethod(audioSystem, method); + method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputFrameCount", "()I"); + bufferSizeInFrames = env->CallStaticIntMethod(audioSystem, method); } } // namespace class CallerThreadUtils : public ICallerThreadUtils { public: - virtual void performFunctionInCallerThread(const std::function &func) { + void performFunctionInCallerThread(const std::function &func) override { Application::getInstance()->getScheduler()->performFunctionInCocosThread(func); }; - virtual std::thread::id getCallerThreadId() { + std::thread::id getCallerThreadId() override { return _tid; }; @@ -90,12 +90,16 @@ private: std::thread::id _tid; }; -static CallerThreadUtils __callerThreadUtils; +static CallerThreadUtils gCallerThreadUtils; static int fdGetter(const std::string &url, off_t *start, off_t *length) { int fd = -1; if (cc::FileUtilsAndroid::getObbFile() != nullptr) { - fd = getObbAssetFileDescriptorJNI(url.c_str(), start, length); + int64_t startV; + int64_t lenV; + fd = getObbAssetFileDescriptorJNI(url, &startV, &lenV); + *start = static_cast(startV); + *length = static_cast(lenV); } if (fd <= 0) { auto asset = AAssetManager_open(cc::FileUtilsAndroid::getAssetManager(), url.c_str(), AASSET_MODE_UNKNOWN); @@ -113,9 +117,14 @@ static int fdGetter(const std::string &url, off_t *start, off_t *length) { //==================================================== AudioEngineImpl::AudioEngineImpl() -: _engineObject(nullptr), _engineEngine(nullptr), _outputMixObject(nullptr), _audioPlayerProvider(nullptr), _audioIDIndex(0), _lazyInitLoop(true) { - __callerThreadUtils.setCallerThreadId(std::this_thread::get_id()); - __impl = this; +: _engineObject(nullptr), + _engineEngine(nullptr), + _outputMixObject(nullptr), + _audioPlayerProvider(nullptr), + _audioIDIndex(0), + _lazyInitLoop(true) { + gCallerThreadUtils.setCallerThreadId(std::this_thread::get_id()); + gAudioImpl = this; getAudioInfo(); } @@ -132,13 +141,12 @@ AudioEngineImpl::~AudioEngineImpl() { (*_engineObject)->Destroy(_engineObject); } - __impl = nullptr; + gAudioImpl = nullptr; } bool AudioEngineImpl::init() { bool ret = false; do { - // create engine auto result = slCreateEngine(&_engineObject, 0, nullptr, 0, nullptr, nullptr); if (SL_RESULT_SUCCESS != result) { @@ -162,8 +170,8 @@ bool AudioEngineImpl::init() { // create output mix const SLInterfaceID outputMixIIDs[] = {}; - const SLboolean outputMixReqs[] = {}; - result = (*_engineEngine)->CreateOutputMix(_engineEngine, &_outputMixObject, 0, outputMixIIDs, outputMixReqs); + const SLboolean outputMixReqs[] = {}; + result = (*_engineEngine)->CreateOutputMix(_engineEngine, &_outputMixObject, 0, outputMixIIDs, outputMixReqs); if (SL_RESULT_SUCCESS != result) { CC_LOG_ERROR("create output mix fail"); break; @@ -176,7 +184,7 @@ bool AudioEngineImpl::init() { break; } - _audioPlayerProvider = new AudioPlayerProvider(_engineEngine, _outputMixObject, outputSampleRate, bufferSizeInFrames, fdGetter, &__callerThreadUtils); + _audioPlayerProvider = new AudioPlayerProvider(_engineEngine, _outputMixObject, outputSampleRate, bufferSizeInFrames, fdGetter, &gCallerThreadUtils); ret = true; } while (false); @@ -195,8 +203,9 @@ int AudioEngineImpl::play2d(const std::string &filePath, bool loop, float volume auto audioId = AudioEngine::INVALID_AUDIO_ID; do { - if (_engineEngine == nullptr || _audioPlayerProvider == nullptr) + if (_engineEngine == nullptr || _audioPlayerProvider == nullptr) { break; + } auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); @@ -242,9 +251,9 @@ int AudioEngineImpl::play2d(const std::string &filePath, bool loop, float volume return AudioEngine::INVALID_AUDIO_ID; } - AudioEngine::_audioIDInfoMap[audioId].state = AudioEngine::AudioState::PLAYING; + AudioEngine::sAudioIDInfoMap[audioId].state = AudioEngine::AudioState::PLAYING; - } while (0); + } while (false); return audioId; } @@ -315,7 +324,7 @@ float AudioEngineImpl::getDuration(int audioID) { auto player = iter->second; return player->getDuration(); } - return 0.0f; + return 0.0F; } float AudioEngineImpl::getDurationFromFile(const std::string &filePath) { @@ -332,7 +341,7 @@ float AudioEngineImpl::getCurrentTime(int audioID) { auto player = iter->second; return player->getPosition(); } - return 0.0f; + return 0.0F; } bool AudioEngineImpl::setCurrentTime(int audioID, float time) { @@ -351,7 +360,7 @@ void AudioEngineImpl::setFinishCallback(int audioID, const std::function &callback) { if (_audioPlayerProvider != nullptr) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); - _audioPlayerProvider->preloadEffect(fullPath, [callback](bool succeed, PcmData data) { + _audioPlayerProvider->preloadEffect(fullPath, [callback](bool succeed, const PcmData & /*data*/) { if (callback != nullptr) { callback(succeed); } diff --git a/native/cocos/audio/android/AudioEngine-inl.h b/native/cocos/audio/android/AudioEngine-inl.h index 68985d92fc..620651dbd2 100644 --- a/native/cocos/audio/android/AudioEngine-inl.h +++ b/native/cocos/audio/android/AudioEngine-inl.h @@ -24,18 +24,18 @@ ****************************************************************************/ #pragma once - #include - #include - #include - #include - #include +#include +#include +#include +#include +#include - #include "base/Ref.h" - #include "base/Utils.h" +#include "base/Ref.h" +#include "base/Utils.h" - #define MAX_AUDIOINSTANCES 13 +#define MAX_AUDIOINSTANCES 13 - #define ERRORLOG(msg) log("fun:%s,line:%d,msg:%s", __func__, __LINE__, #msg) +#define ERRORLOG(msg) log("fun:%s,line:%d,msg:%s", __func__, __LINE__, #msg) namespace cc { @@ -49,21 +49,21 @@ class AudioEngineImpl; class AudioEngineImpl : public cc::Ref { public: AudioEngineImpl(); - ~AudioEngineImpl(); + ~AudioEngineImpl() override; - bool init(); - int play2d(const std::string &fileFullPath, bool loop, float volume); - void setVolume(int audioID, float volume); - void setLoop(int audioID, bool loop); - void pause(int audioID); - void resume(int audioID); - void stop(int audioID); - void stopAll(); + bool init(); + int play2d(const std::string &filePath, bool loop, float volume); + void setVolume(int audioID, float volume); + void setLoop(int audioID, bool loop); + void pause(int audioID); + void resume(int audioID); + void stop(int audioID); + void stopAll(); float getDuration(int audioID); - float getDurationFromFile(const std::string &fileFullPath); + float getDurationFromFile(const std::string &filePath); float getCurrentTime(int audioID); - bool setCurrentTime(int audioID, float time); - void setFinishCallback(int audioID, const std::function &callback); + bool setCurrentTime(int audioID, float time); + void setFinishCallback(int audioID, const std::function &callback); void uncache(const std::string &filePath); void uncacheAll(); @@ -83,7 +83,7 @@ private: SLObjectItf _outputMixObject; //audioID,AudioInfo - std::unordered_map _audioPlayers; + std::unordered_map _audioPlayers; std::unordered_map> _callbackMap; // UrlAudioPlayers which need to resumed while entering foreground @@ -96,4 +96,4 @@ private: bool _lazyInitLoop; }; -} +} // namespace cc diff --git a/native/cocos/audio/android/AudioPlayerProvider.cpp b/native/cocos/audio/android/AudioPlayerProvider.cpp index aa8190d44a..23469c2083 100644 --- a/native/cocos/audio/android/AudioPlayerProvider.cpp +++ b/native/cocos/audio/android/AudioPlayerProvider.cpp @@ -25,27 +25,28 @@ THE SOFTWARE. #define LOG_TAG "AudioPlayerProvider" -#include "base/ThreadPool.h" #include "audio/android/AudioPlayerProvider.h" -#include "audio/android/UrlAudioPlayer.h" -#include "audio/android/PcmAudioPlayer.h" #include "audio/android/AudioDecoder.h" #include "audio/android/AudioDecoderProvider.h" #include "audio/android/AudioMixerController.h" -#include "audio/android/PcmAudioService.h" #include "audio/android/ICallerThreadUtils.h" +#include "audio/android/PcmAudioPlayer.h" +#include "audio/android/PcmAudioService.h" +#include "audio/android/UrlAudioPlayer.h" #include "audio/android/utils/Utils.h" +#include "base/ThreadPool.h" #include -#include #include // for std::find_if +#include +#include namespace cc { static int getSystemAPILevel() { - static int __systemApiLevel = -1; - if (__systemApiLevel > 0) { - return __systemApiLevel; + static int sSystemApiLevel = -1; + if (sSystemApiLevel > 0) { + return sSystemApiLevel; } int apiLevel = getSDKVersion(); @@ -54,16 +55,16 @@ static int getSystemAPILevel() { } else { ALOGE("Fail to get Android API level!"); } - __systemApiLevel = apiLevel; + sSystemApiLevel = apiLevel; return apiLevel; } struct AudioFileIndicator { std::string extension; - int smallSizeIndicator; + int smallSizeIndicator; }; -static AudioFileIndicator __audioFileIndicator[] = { +static AudioFileIndicator gAudioFileIndicator[] = { {"default", 128000}, // If we could not handle the audio format, return default value, the position should be first. {".wav", 1024000}, {".ogg", 128000}, @@ -71,8 +72,8 @@ static AudioFileIndicator __audioFileIndicator[] = { AudioPlayerProvider::AudioPlayerProvider(SLEngineItf engineItf, SLObjectItf outputMixObject, int deviceSampleRate, int bufferSizeInFrames, - const FdGetterCallback &fdGetterCallback, - ICallerThreadUtils *callerThreadUtils) + const FdGetterCallback &fdGetterCallback, //NOLINT(modernize-pass-by-value) + ICallerThreadUtils * callerThreadUtils) : _engineItf(engineItf), _outputMixObject(outputMixObject), _deviceSampleRate(deviceSampleRate), _bufferSizeInFrames(bufferSizeInFrames), _fdGetterCallback(fdGetterCallback), _callerThreadUtils(callerThreadUtils), _pcmAudioService(nullptr), _mixController(nullptr), _threadPool(LegacyThreadPool::newCachedThreadPool(1, 8, 5, 2, 2)) { ALOGI("deviceSampleRate: %d, bufferSizeInFrames: %d", _deviceSampleRate, _bufferSizeInFrames); if (getSystemAPILevel() >= 17) { @@ -123,22 +124,22 @@ IAudioPlayer *AudioPlayerProvider::getAudioPlayer(const std::string &audioFilePa if (info.isValid()) { if (isSmallFile(info)) { // 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); + auto pcmData = std::make_shared(); + auto isSucceed = std::make_shared(false); auto isReturnFromCache = std::make_shared(false); auto isPreloadFinished = std::make_shared(false); std::thread::id threadId = std::this_thread::get_id(); - void *infoPtr = &info; - std::string url = info.url; + void * infoPtr = &info; + std::string url = info.url; preloadEffect( info, [infoPtr, url, threadId, pcmData, isSucceed, isReturnFromCache, isPreloadFinished](bool succeed, PcmData data) { // If the callback is in the same thread as caller's, it means that we found it // in the cache *isReturnFromCache = std::this_thread::get_id() == threadId; - *pcmData = data; - *isSucceed = succeed; + *pcmData = std::move(data); + *isSucceed = succeed; *isPreloadFinished = true; ALOGV("FileInfo (%p), Set isSucceed flag: %d, path: %s", infoPtr, succeed, url.c_str()); }, @@ -195,7 +196,7 @@ void AudioPlayerProvider::preloadEffect(const std::string &audioFilePath, const auto info = getFileInfo(audioFilePath); preloadEffect( - info, [this, cb, audioFilePath](bool succeed, PcmData data) { + info, [this, cb, audioFilePath](bool succeed, const PcmData &data) { _callerThreadUtils->performFunctionInCallerThread([this, succeed, data, cb]() { cb(succeed, data); }); @@ -235,7 +236,7 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload if (preloadIter != _preloadCallbackMap.end()) { ALOGV("audio (%s) is being preloaded, add to callback vector!", audioFilePath.c_str()); PreloadCallbackParam param; - param.callback = cb; + param.callback = cb; param.isPreloadInPlay2d = isPreloadInPlay2d; preloadIter->second.push_back(std::move(param)); return; @@ -254,18 +255,18 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload _pcmCacheMutex.unlock(); PreloadCallbackParam param; - param.callback = cb; + param.callback = cb; param.isPreloadInPlay2d = isPreloadInPlay2d; std::vector callbacks; callbacks.push_back(std::move(param)); _preloadCallbackMap.insert(std::make_pair(audioFilePath, std::move(callbacks))); } - _threadPool->pushTask([this, audioFilePath](int tid) { + _threadPool->pushTask([this, audioFilePath](int /*tid*/) { ALOGV("AudioPlayerProvider::preloadEffect: (%s)", audioFilePath.c_str()); - PcmData d; + PcmData d; AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(_engineItf, audioFilePath, _bufferSizeInFrames, _deviceSampleRate, _fdGetterCallback); - bool ret = decoder != nullptr && decoder->start(); + bool ret = decoder != nullptr && decoder->start(); if (ret) { d = decoder->getResult(); std::lock_guard lk(_pcmCacheMutex); @@ -277,7 +278,7 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload ALOGV("decode %s", (ret ? "succeed" : "failed")); std::lock_guard lk(_preloadCallbackMutex); - auto &&preloadIter = _preloadCallbackMap.find(audioFilePath); + auto && preloadIter = _preloadCallbackMap.find(audioFilePath); if (preloadIter != _preloadCallbackMap.end()) { auto &¶ms = preloadIter->second; ALOGV("preload (%s) callback count: %d", audioFilePath.c_str(), (int)params.size()); @@ -302,13 +303,14 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo( const std::string &audioFilePath) { AudioFileInfo info; - long fileSize = 0; - off_t start = 0, length = 0; - int assetFd = -1; + long fileSize = 0; //NOLINT(google-runtime-int) + off_t start = 0; + off_t length = 0; + int assetFd = -1; if (audioFilePath[0] != '/') { std::string relativePath; - size_t position = audioFilePath.find("@assets/"); + size_t position = audioFilePath.find("@assets/"); if (0 == position) { // "@assets/" is at the beginning of the path and we don't want it @@ -336,42 +338,42 @@ AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo( } } - info.url = audioFilePath; + info.url = audioFilePath; info.assetFd = std::make_shared(assetFd); - info.start = start; - info.length = fileSize; + info.start = start; + info.length = fileSize; ALOGV("(%s) file size: %ld", audioFilePath.c_str(), fileSize); return info; } -bool AudioPlayerProvider::isSmallFile(const AudioFileInfo &info) { +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. - AudioFileInfo &audioFileInfo = const_cast(info); - size_t judgeCount = sizeof(__audioFileIndicator) / sizeof(__audioFileIndicator[0]); - size_t pos = audioFileInfo.url.rfind("."); + auto & audioFileInfo = const_cast(info); + size_t judgeCount = sizeof(gAudioFileIndicator) / sizeof(gAudioFileIndicator[0]); + size_t pos = audioFileInfo.url.rfind('.'); std::string extension; if (pos != std::string::npos) { extension = audioFileInfo.url.substr(pos); } - auto iter = std::find_if(std::begin(__audioFileIndicator), std::end(__audioFileIndicator), + auto iter = std::find_if(std::begin(gAudioFileIndicator), std::end(gAudioFileIndicator), [&extension](const AudioFileIndicator &judge) -> bool { return judge.extension == extension; }); - if (iter != std::end(__audioFileIndicator)) { + if (iter != std::end(gAudioFileIndicator)) { // ALOGV("isSmallFile: found: %s: ", iter->extension.c_str()); return info.length < iter->smallSizeIndicator; } // ALOGV("isSmallFile: not found return default value"); - return info.length < __audioFileIndicator[0].smallSizeIndicator; + return info.length < gAudioFileIndicator[0].smallSizeIndicator; } float AudioPlayerProvider::getDurationFromFile(const std::string &filePath) { std::lock_guard lk(_pcmCacheMutex); - auto iter = _pcmCache.find(filePath); + auto iter = _pcmCache.find(filePath); if (iter != _pcmCache.end()) { return iter->second.duration; } @@ -380,7 +382,7 @@ float AudioPlayerProvider::getDurationFromFile(const std::string &filePath) { void AudioPlayerProvider::clearPcmCache(const std::string &audioFilePath) { std::lock_guard lk(_pcmCacheMutex); - auto iter = _pcmCache.find(audioFilePath); + auto iter = _pcmCache.find(audioFilePath); if (iter != _pcmCache.end()) { ALOGV("clear pcm cache: (%s)", audioFilePath.c_str()); _pcmCache.erase(iter); @@ -395,7 +397,7 @@ void AudioPlayerProvider::clearAllPcmCaches() { } PcmAudioPlayer *AudioPlayerProvider::obtainPcmAudioPlayer(const std::string &url, - const PcmData &pcmData) { + const PcmData & pcmData) { PcmAudioPlayer *pcmPlayer = nullptr; if (pcmData.isValid()) { pcmPlayer = new (std::nothrow) PcmAudioPlayer(_mixController, _callerThreadUtils); @@ -416,8 +418,8 @@ UrlAudioPlayer *AudioPlayerProvider::createUrlAudioPlayer( } SLuint32 locatorType = info.assetFd->getFd() > 0 ? SL_DATALOCATOR_ANDROIDFD : SL_DATALOCATOR_URI; - auto urlPlayer = new (std::nothrow) UrlAudioPlayer(_engineItf, _outputMixObject, _callerThreadUtils); - bool ret = urlPlayer->prepare(info.url, locatorType, info.assetFd, info.start, info.length); + auto urlPlayer = new (std::nothrow) UrlAudioPlayer(_engineItf, _outputMixObject, _callerThreadUtils); + bool ret = urlPlayer->prepare(info.url, locatorType, info.assetFd, info.start, info.length); if (!ret) { SL_SAFE_DELETE(urlPlayer); } diff --git a/native/cocos/audio/android/AudioPlayerProvider.h b/native/cocos/audio/android/AudioPlayerProvider.h index e737d2d72e..088a648e0c 100644 --- a/native/cocos/audio/android/AudioPlayerProvider.h +++ b/native/cocos/audio/android/AudioPlayerProvider.h @@ -29,9 +29,9 @@ THE SOFTWARE. #include "audio/android/OpenSLHelper.h" #include "audio/android/PcmData.h" -#include -#include #include +#include +#include namespace cc { // Manage PcmAudioPlayer& UrlAudioPlayer @@ -54,11 +54,11 @@ public: IAudioPlayer *getAudioPlayer(const std::string &audioFilePath); - typedef std::function PreloadCallback; + using PreloadCallback = std::function; void preloadEffect(const std::string &audioFilePath, const PreloadCallback &cb); float getDurationFromFile(const std::string &filePath); - void clearPcmCache(const std::string &audioFilePath); + void clearPcmCache(const std::string &audioFilePath); void clearAllPcmCaches(); @@ -68,13 +68,13 @@ public: private: struct AudioFileInfo { - std::string url; + std::string url; std::shared_ptr assetFd; - off_t start; - off_t length; + off_t start{}; + off_t length; AudioFileInfo() - : assetFd(nullptr), start(0), length(0){}; + : assetFd(nullptr) {} inline bool isValid() const { return !url.empty() && length > 0; @@ -92,28 +92,28 @@ private: bool isSmallFile(const AudioFileInfo &info); private: - SLEngineItf _engineItf; - SLObjectItf _outputMixObject; - int _deviceSampleRate; - int _bufferSizeInFrames; - FdGetterCallback _fdGetterCallback; + SLEngineItf _engineItf; + SLObjectItf _outputMixObject; + int _deviceSampleRate; + int _bufferSizeInFrames; + FdGetterCallback _fdGetterCallback; ICallerThreadUtils *_callerThreadUtils; std::unordered_map _pcmCache; - std::mutex _pcmCacheMutex; + std::mutex _pcmCacheMutex; struct PreloadCallbackParam { PreloadCallback callback; - bool isPreloadInPlay2d; + bool isPreloadInPlay2d; }; std::unordered_map> _preloadCallbackMap; - std::mutex _preloadCallbackMutex; + std::mutex _preloadCallbackMutex; - std::mutex _preloadWaitMutex; + std::mutex _preloadWaitMutex; std::condition_variable _preloadWaitCond; - PcmAudioService *_pcmAudioService; + PcmAudioService * _pcmAudioService; AudioMixerController *_mixController; LegacyThreadPool *_threadPool; diff --git a/native/cocos/audio/android/tinysndfile.cpp b/native/cocos/audio/android/tinysndfile.cpp index b9ba6d9e2c..6c6ecd759f 100644 --- a/native/cocos/audio/android/tinysndfile.cpp +++ b/native/cocos/audio/android/tinysndfile.cpp @@ -18,14 +18,16 @@ #include "audio/android/tinysndfile.h" #include "audio/android/audio_utils/include/audio_utils/primitives.h" -#include "audio/android/cutils/log.h" + +#include "base/Log.h" // #ifdef HAVE_STDERR // #include // #endif -#include -#include +#include +#include +#include #ifndef HAVE_STDERR #define HAVE_STDERR @@ -35,15 +37,15 @@ #define WAVE_FORMAT_IEEE_FLOAT 3 #define WAVE_FORMAT_EXTENSIBLE 0xFFFE -static snd_callbacks __defaultCallback; -static int __inited = 0; +static snd_callbacks sDefaultCallback; +static int sInited = 0; struct SNDFILE_ { - uint8_t *temp; // realloc buffer used for shrinking 16 bits to 8 bits and byte-swapping - void *stream; - size_t bytesPerFrame; - size_t remaining; // frames unread for SFM_READ, frames written for SFM_WRITE - SF_INFO info; + uint8_t * temp; // realloc buffer used for shrinking 16 bits to 8 bits and byte-swapping + void * stream; + size_t bytesPerFrame; + size_t remaining; // frames unread for SFM_READ, frames written for SFM_WRITE + SF_INFO info; snd_callbacks callback; }; @@ -55,113 +57,113 @@ static unsigned little4u(unsigned char *ptr) { return (ptr[3] << 24) + (ptr[2] << 16) + (ptr[1] << 8) + ptr[0]; } -static int isLittleEndian(void) { - static const short one = 1; - return *((const char *)&one) == 1; +static int isLittleEndian() { + static const uint16_t ONE = 1; + return *(reinterpret_cast(&ONE)) == 1; } // "swab" conflicts with OS X -static void my_swab(short *ptr, size_t numToSwap) { +static void my_swab(int16_t *ptr, size_t numToSwap) { //NOLINT(readability-identifier-naming) while (numToSwap > 0) { - *ptr = little2u((unsigned char *)ptr); + *ptr = static_cast(little2u(reinterpret_cast(ptr))); --numToSwap; ++ptr; } } -static void *open_func(const char *path, void *user) { +static void *open_func(const char *path, void * /*user*/) { //NOLINT(readability-identifier-naming) return fopen(path, "rb"); } -static size_t read_func(void *ptr, size_t size, size_t nmemb, void *datasource) { - return fread(ptr, size, nmemb, (FILE *)datasource); +static size_t read_func(void *ptr, size_t size, size_t nmemb, void *datasource) { //NOLINT(readability-identifier-naming) + return fread(ptr, size, nmemb, static_cast(datasource)); } -static int seek_func(void *datasource, long offset, int whence) { - return fseek((FILE *)datasource, offset, whence); +static int seek_func(void *datasource, long offset, int whence) { //NOLINT(google-runtime-int,readability-identifier-naming) + return fseek(static_cast(datasource), offset, whence); } -static int close_func(void *datasource) { - return fclose((FILE *)datasource); +static int close_func(void *datasource) { //NOLINT(readability-identifier-naming) + return fclose(static_cast(datasource)); } -static long tell_func(void *datasource) { - return ftell((FILE *)datasource); +static long tell_func(void *datasource) { //NOLINT(google-runtime-int,readability-identifier-naming) + return ftell(static_cast(datasource)); } static void lazyInit() { - if (__inited == 0) { - __defaultCallback.open = open_func; - __defaultCallback.read = read_func; - __defaultCallback.seek = seek_func; - __defaultCallback.close = close_func; - __defaultCallback.tell = tell_func; - __inited = 1; + if (sInited == 0) { + sDefaultCallback.open = open_func; + sDefaultCallback.read = read_func; + sDefaultCallback.seek = seek_func; + sDefaultCallback.close = close_func; + sDefaultCallback.tell = tell_func; + sInited = 1; } } -SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks *cb, void *user) { +SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks *cb, void *user) { //NOLINT(readability-identifier-naming) lazyInit(); - if (path == NULL || info == NULL) { + if (path == nullptr || info == nullptr) { #ifdef HAVE_STDERR - ALOGE("path=%p info=%p\n", path, info); + CC_LOG_ERROR("path=%p info=%p\n", path, info); #endif - return NULL; + return nullptr; } - SNDFILE *handle = (SNDFILE *)malloc(sizeof(SNDFILE)); - handle->temp = NULL; + auto *handle = static_cast(malloc(sizeof(SNDFILE))); + handle->temp = nullptr; handle->info.format = SF_FORMAT_WAV; - if (cb != NULL) { + if (cb != nullptr) { handle->callback = *cb; } else { - handle->callback = __defaultCallback; + handle->callback = sDefaultCallback; } void *stream = handle->callback.open(path, user); - if (stream == NULL) { + if (stream == nullptr) { #ifdef HAVE_STDERR - ALOGE("fopen %s failed errno %d\n", path, errno); + CC_LOG_ERROR("fopen %s failed errno %d\n", path, errno); #endif free(handle); - return NULL; + return nullptr; } handle->stream = stream; // don't attempt to parse all valid forms, just the most common ones unsigned char wav[12]; - size_t actual; - unsigned riffSize; - size_t remaining; - int hadFmt = 0; - int hadData = 0; - long dataTell = 0L; + size_t actual; + unsigned riffSize; + size_t remaining; + int hadFmt = 0; + int hadData = 0; + long dataTell = 0L; //NOLINT(google-runtime-int) actual = handle->callback.read(wav, sizeof(char), sizeof(wav), stream); if (actual < 12) { #ifdef HAVE_STDERR - ALOGE("actual %zu < 44\n", actual); + CC_LOG_ERROR("actual %zu < 44\n", actual); #endif goto close; } - if (memcmp(wav, "RIFF", 4)) { + if (memcmp(wav, "RIFF", 4)) { //NOLINT(bugprone-suspicious-string-compare) #ifdef HAVE_STDERR - ALOGE("wav != RIFF\n"); + CC_LOG_ERROR("wav != RIFF\n"); #endif goto close; } riffSize = little4u(&wav[4]); if (riffSize < 4) { #ifdef HAVE_STDERR - ALOGE("riffSize %u < 4\n", riffSize); + CC_LOG_ERROR("riffSize %u < 4\n", riffSize); #endif goto close; } - if (memcmp(&wav[8], "WAVE", 4)) { + if (memcmp(&wav[8], "WAVE", 4)) { //NOLINT(bugprone-suspicious-string-compare) #ifdef HAVE_STDERR - ALOGE("missing WAVE\n"); + CC_LOG_ERROR("missing WAVE\n"); #endif goto close; } @@ -172,7 +174,7 @@ SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks *cb, void * actual = handle->callback.read(chunk, sizeof(char), sizeof(chunk), stream); if (actual != sizeof(chunk)) { #ifdef HAVE_STDERR - ALOGE("actual %zu != %zu\n", actual, sizeof(chunk)); + CC_LOG_ERROR("actual %zu != %zu\n", actual, sizeof(chunk)); #endif goto close; } @@ -180,20 +182,20 @@ SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks *cb, void * unsigned chunkSize = little4u(&chunk[4]); if (chunkSize > remaining) { #ifdef HAVE_STDERR - ALOGE("chunkSize %u > remaining %zu\n", chunkSize, remaining); + CC_LOG_ERROR("chunkSize %u > remaining %zu\n", chunkSize, remaining); #endif goto close; } if (!memcmp(&chunk[0], "fmt ", 4)) { if (hadFmt) { #ifdef HAVE_STDERR - ALOGE("multiple fmt\n"); + CC_LOG_ERROR("multiple fmt\n"); #endif goto close; } if (chunkSize < 2) { #ifdef HAVE_STDERR - ALOGE("chunkSize %u < 2\n", chunkSize); + CC_LOG_ERROR("chunkSize %u < 2\n", chunkSize); #endif goto close; } @@ -201,12 +203,12 @@ SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks *cb, void * actual = handle->callback.read(fmt, sizeof(char), 2, stream); if (actual != 2) { #ifdef HAVE_STDERR - ALOGE("actual %zu != 2\n", actual); + CC_LOG_ERROR("actual %zu != 2\n", actual); #endif goto close; } - unsigned format = little2u(&fmt[0]); - size_t minSize = 0; + unsigned format = little2u(&fmt[0]); + size_t minSize = 0; switch (format) { case WAVE_FORMAT_PCM: case WAVE_FORMAT_IEEE_FLOAT: @@ -217,38 +219,38 @@ SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks *cb, void * break; default: #ifdef HAVE_STDERR - ALOGE("unsupported format %u\n", format); + CC_LOG_ERROR("unsupported format %u\n", format); #endif goto close; } if (chunkSize < minSize) { #ifdef HAVE_STDERR - ALOGE("chunkSize %u < minSize %zu\n", chunkSize, minSize); + CC_LOG_ERROR("chunkSize %u < minSize %zu\n", chunkSize, minSize); #endif goto close; } actual = handle->callback.read(&fmt[2], sizeof(char), minSize - 2, stream); if (actual != minSize - 2) { #ifdef HAVE_STDERR - ALOGE("actual %zu != %zu\n", actual, minSize - 16); + CC_LOG_ERROR("actual %zu != %zu\n", actual, minSize - 16); #endif goto close; } if (chunkSize > minSize) { - handle->callback.seek(stream, (long)(chunkSize - minSize), SEEK_CUR); + handle->callback.seek(stream, static_cast(chunkSize - minSize), SEEK_CUR); //NOLINT(google-runtime-int) } unsigned channels = little2u(&fmt[2]); // IDEA: FCC_8 if (channels != 1 && channels != 2 && channels != 4 && channels != 6 && channels != 8) { #ifdef HAVE_STDERR - ALOGE("unsupported channels %u\n", channels); + CC_LOG_ERROR("unsupported channels %u\n", channels); #endif goto close; } unsigned samplerate = little4u(&fmt[4]); if (samplerate == 0) { #ifdef HAVE_STDERR - ALOGE("samplerate %u == 0\n", samplerate); + CC_LOG_ERROR("samplerate %u == 0\n", samplerate); #endif goto close; } @@ -258,14 +260,14 @@ SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks *cb, void * if (bitsPerSample != 8 && bitsPerSample != 16 && bitsPerSample != 24 && bitsPerSample != 32) { #ifdef HAVE_STDERR - ALOGE("bitsPerSample %u != 8 or 16 or 24 or 32\n", bitsPerSample); + CC_LOG_ERROR("bitsPerSample %u != 8 or 16 or 24 or 32\n", bitsPerSample); #endif goto close; } - unsigned bytesPerFrame = (bitsPerSample >> 3) * channels; - handle->bytesPerFrame = bytesPerFrame; - handle->info.samplerate = samplerate; - handle->info.channels = channels; + unsigned bytesPerFrame = (bitsPerSample >> 3) * channels; + handle->bytesPerFrame = bytesPerFrame; + handle->info.samplerate = static_cast(samplerate); + handle->info.channels = static_cast(channels); switch (bitsPerSample) { case 8: handle->info.format |= SF_FORMAT_PCM_U8; @@ -277,59 +279,60 @@ SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks *cb, void * handle->info.format |= SF_FORMAT_PCM_24; break; case 32: - if (format == WAVE_FORMAT_IEEE_FLOAT) + if (format == WAVE_FORMAT_IEEE_FLOAT) { handle->info.format |= SF_FORMAT_FLOAT; - else + } else { handle->info.format |= SF_FORMAT_PCM_32; + } break; } hadFmt = 1; } else if (!memcmp(&chunk[0], "data", 4)) { if (!hadFmt) { #ifdef HAVE_STDERR - ALOGE("data not preceded by fmt\n"); + CC_LOG_ERROR("data not preceded by fmt\n"); #endif goto close; } if (hadData) { #ifdef HAVE_STDERR - ALOGE("multiple data\n"); + CC_LOG_ERROR("multiple data\n"); #endif goto close; } - handle->remaining = chunkSize / handle->bytesPerFrame; + handle->remaining = chunkSize / handle->bytesPerFrame; handle->info.frames = handle->remaining; - dataTell = handle->callback.tell(stream); + dataTell = handle->callback.tell(stream); if (chunkSize > 0) { - handle->callback.seek(stream, (long)chunkSize, SEEK_CUR); + handle->callback.seek(stream, static_cast(chunkSize), SEEK_CUR); //NOLINT(google-runtime-int) } hadData = 1; } else if (!memcmp(&chunk[0], "fact", 4)) { // ignore fact if (chunkSize > 0) { - handle->callback.seek(stream, (long)chunkSize, SEEK_CUR); + handle->callback.seek(stream, static_cast(chunkSize), SEEK_CUR); //NOLINT(google-runtime-int) } } else { // ignore unknown chunk #ifdef HAVE_STDERR - ALOGE("ignoring unknown chunk %c%c%c%c\n", - chunk[0], chunk[1], chunk[2], chunk[3]); + CC_LOG_ERROR("ignoring unknown chunk %c%c%c%c\n", + chunk[0], chunk[1], chunk[2], chunk[3]); #endif if (chunkSize > 0) { - handle->callback.seek(stream, (long)chunkSize, SEEK_CUR); + handle->callback.seek(stream, static_cast(chunkSize), SEEK_CUR); //NOLINT(google-runtime-int) } } remaining -= chunkSize; } if (remaining > 0) { #ifdef HAVE_STDERR - ALOGE("partial chunk at end of RIFF, remaining %zu\n", remaining); + CC_LOG_ERROR("partial chunk at end of RIFF, remaining %zu\n", remaining); #endif goto close; } if (!hadData) { #ifdef HAVE_STDERR - ALOGE("missing data\n"); + CC_LOG_ERROR("missing data\n"); #endif goto close; } @@ -340,32 +343,53 @@ SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks *cb, void * close: free(handle); handle->callback.close(stream); - return NULL; + return nullptr; } -void sf_close(SNDFILE *handle) { - if (handle == NULL) +void sf_close(SNDFILE *handle) { //NOLINT(readability-identifier-naming) + if (handle == nullptr) { return; + } free(handle->temp); (void)handle->callback.close(handle->stream); free(handle); } -sf_count_t sf_readf_short(SNDFILE *handle, short *ptr, sf_count_t desiredFrames) { - if (handle == NULL || ptr == NULL || !handle->remaining || +off_t sf_seek(SNDFILE *handle, int offset, int whence) { //NOLINT(readability-identifier-naming) + if (whence == SEEK_SET) { + assert(offset >= 0 && offset <= handle->info.frames); + } else if (whence == SEEK_CUR) { + offset += sf_tell(handle); + assert(offset >= 0 && offset <= handle->info.frames); + } else if (whence == SEEK_END) { + offset += handle->info.frames; + assert(offset >= 0 && offset <= handle->info.frames); + } else { + assert(false); // base whence value + } + handle->remaining = handle->info.frames - offset; + return offset; +} + +off_t sf_tell(SNDFILE *handle) { //NOLINT(readability-identifier-naming) + return handle->info.frames - handle->remaining; +} + +sf_count_t sf_readf_short(SNDFILE *handle, int16_t *ptr, sf_count_t desiredFrames) { //NOLINT(readability-identifier-naming) + if (handle == nullptr || ptr == nullptr || !handle->remaining || desiredFrames <= 0) { return 0; } - if (handle->remaining < (size_t)desiredFrames) { + if (handle->remaining < static_cast(desiredFrames)) { desiredFrames = handle->remaining; } // does not check for numeric overflow - size_t desiredBytes = desiredFrames * handle->bytesPerFrame; - size_t actualBytes; - void *temp = NULL; + size_t desiredBytes = desiredFrames * handle->bytesPerFrame; + size_t actualBytes; + void * temp = nullptr; unsigned format = handle->info.format & SF_FORMAT_SUBMASK; if (format == SF_FORMAT_PCM_32 || format == SF_FORMAT_FLOAT || format == SF_FORMAT_PCM_24) { - temp = malloc(desiredBytes); + temp = malloc(desiredBytes); actualBytes = handle->callback.read(temp, sizeof(char), desiredBytes, handle->stream); } else { actualBytes = handle->callback.read(ptr, sizeof(char), desiredBytes, handle->stream); @@ -374,26 +398,27 @@ sf_count_t sf_readf_short(SNDFILE *handle, short *ptr, sf_count_t desiredFrames) handle->remaining -= actualFrames; switch (format) { case SF_FORMAT_PCM_U8: - memcpy_to_i16_from_u8(ptr, (unsigned char *)ptr, actualFrames * handle->info.channels); + memcpy_to_i16_from_u8(ptr, reinterpret_cast(ptr), actualFrames * handle->info.channels); break; case SF_FORMAT_PCM_16: - if (!isLittleEndian()) + if (!isLittleEndian()) { my_swab(ptr, actualFrames * handle->info.channels); + } break; case SF_FORMAT_PCM_32: - memcpy_to_i16_from_i32(ptr, (const int *)temp, actualFrames * handle->info.channels); + memcpy_to_i16_from_i32(ptr, static_cast(temp), actualFrames * handle->info.channels); free(temp); break; case SF_FORMAT_FLOAT: - memcpy_to_i16_from_float(ptr, (const float *)temp, actualFrames * handle->info.channels); + memcpy_to_i16_from_float(ptr, static_cast(temp), actualFrames * handle->info.channels); free(temp); break; case SF_FORMAT_PCM_24: - memcpy_to_i16_from_p24(ptr, (const uint8_t *)temp, actualFrames * handle->info.channels); + memcpy_to_i16_from_p24(ptr, static_cast(temp), actualFrames * handle->info.channels); free(temp); break; default: - memset(ptr, 0, actualFrames * handle->info.channels * sizeof(short)); + memset(ptr, 0, actualFrames * handle->info.channels * sizeof(int16_t)); break; } return actualFrames; @@ -402,7 +427,7 @@ sf_count_t sf_readf_short(SNDFILE *handle, short *ptr, sf_count_t desiredFrames) /* sf_count_t sf_readf_float(SNDFILE *handle, float *ptr, sf_count_t desiredFrames) { - if (handle == NULL || ptr == NULL || !handle->remaining || + if (handle == nullptr || ptr == nullptr || !handle->remaining || desiredFrames <= 0) { return 0; } @@ -412,7 +437,7 @@ sf_count_t sf_readf_float(SNDFILE *handle, float *ptr, sf_count_t desiredFrames) // does not check for numeric overflow size_t desiredBytes = desiredFrames * handle->bytesPerFrame; size_t actualBytes; - void *temp = NULL; + void *temp = nullptr; unsigned format = handle->info.format & SF_FORMAT_SUBMASK; if (format == SF_FORMAT_PCM_16 || format == SF_FORMAT_PCM_U8 || format == SF_FORMAT_PCM_24) { temp = malloc(desiredBytes); @@ -432,7 +457,7 @@ sf_count_t sf_readf_float(SNDFILE *handle, float *ptr, sf_count_t desiredFrames) free(temp); break; case SF_FORMAT_PCM_16: - memcpy_to_float_from_i16(ptr, (const short *) temp, actualFrames * handle->info.channels); + memcpy_to_float_from_i16(ptr, (const int16_t *) temp, actualFrames * handle->info.channels); free(temp); break; case SF_FORMAT_PCM_32: @@ -453,7 +478,7 @@ sf_count_t sf_readf_float(SNDFILE *handle, float *ptr, sf_count_t desiredFrames) sf_count_t sf_readf_int(SNDFILE *handle, int *ptr, sf_count_t desiredFrames) { - if (handle == NULL || ptr == NULL || !handle->remaining || + if (handle == nullptr || ptr == nullptr || !handle->remaining || desiredFrames <= 0) { return 0; } @@ -462,7 +487,7 @@ sf_count_t sf_readf_int(SNDFILE *handle, int *ptr, sf_count_t desiredFrames) } // does not check for numeric overflow size_t desiredBytes = desiredFrames * handle->bytesPerFrame; - void *temp = NULL; + void *temp = nullptr; unsigned format = handle->info.format & SF_FORMAT_SUBMASK; size_t actualBytes; if (format == SF_FORMAT_PCM_16 || format == SF_FORMAT_PCM_U8 || format == SF_FORMAT_PCM_24) { @@ -483,7 +508,7 @@ sf_count_t sf_readf_int(SNDFILE *handle, int *ptr, sf_count_t desiredFrames) free(temp); break; case SF_FORMAT_PCM_16: - memcpy_to_i32_from_i16(ptr, (const short *) temp, actualFrames * handle->info.channels); + memcpy_to_i32_from_i16(ptr, (const int16_t *) temp, actualFrames * handle->info.channels); free(temp); break; case SF_FORMAT_PCM_32: diff --git a/native/cocos/audio/android/tinysndfile.h b/native/cocos/audio/android/tinysndfile.h index d90c7500a0..4651350bd3 100644 --- a/native/cocos/audio/android/tinysndfile.h +++ b/native/cocos/audio/android/tinysndfile.h @@ -22,23 +22,23 @@ // The API should be familiar to clients of similar libraries, but there is // no guarantee that it will stay exactly source-code compatible with other libraries. -#include #include +#include __BEGIN_DECLS // visible to clients -typedef int sf_count_t; +using sf_count_t = int; -typedef struct { +using SF_INFO = struct { sf_count_t frames; - int samplerate; - int channels; - int format; -} SF_INFO; + int samplerate; + int channels; + int format; +}; // opaque to clients -typedef struct SNDFILE_ SNDFILE; +using SNDFILE = struct SNDFILE_; // Format #define SF_FORMAT_TYPEMASK 1 @@ -50,25 +50,28 @@ typedef struct SNDFILE_ SNDFILE; #define SF_FORMAT_PCM_32 8 #define SF_FORMAT_PCM_24 10 -typedef struct { +using snd_callbacks = struct { void *(*open)(const char *path, void *user); size_t (*read)(void *ptr, size_t size, size_t nmemb, void *datasource); - int (*seek)(void *datasource, long offset, int whence); + int (*seek)(void *datasource, long offset, int whence); //NOLINT(google-runtime-int) int (*close)(void *datasource); - long (*tell)(void *datasource); -} snd_callbacks; + long (*tell)(void *datasource); //NOLINT(google-runtime-int) +}; // Open stream -SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks *cb, void *user); +SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks *cb, void *user); //NOLINT(readability-identifier-naming) // Close stream -void sf_close(SNDFILE *handle); +void sf_close(SNDFILE *handle); //NOLINT(readability-identifier-naming) // Read interleaved frames and return actual number of frames read -sf_count_t sf_readf_short(SNDFILE *handle, short *ptr, sf_count_t desired); +sf_count_t sf_readf_short(SNDFILE *handle, int16_t *ptr, sf_count_t desired); //NOLINT(readability-identifier-naming) /* sf_count_t sf_readf_float(SNDFILE *handle, float *ptr, sf_count_t desired); sf_count_t sf_readf_int(SNDFILE *handle, int *ptr, sf_count_t desired); */ +off_t sf_seek(SNDFILE *handle, int offset, int whence); //NOLINT(readability-identifier-naming) +off_t sf_tell(SNDFILE *handle); //NOLINT(readability-identifier-naming) + __END_DECLS diff --git a/native/cocos/audio/apple/AudioEngine-inl.h b/native/cocos/audio/apple/AudioEngine-inl.h index 9a4b734af4..7570236dbe 100644 --- a/native/cocos/audio/apple/AudioEngine-inl.h +++ b/native/cocos/audio/apple/AudioEngine-inl.h @@ -27,12 +27,12 @@ #ifndef __AUDIO_ENGINE_INL_H_ #define __AUDIO_ENGINE_INL_H_ -#include #include +#include -#include "base/Ref.h" #include "audio/apple/AudioCache.h" #include "audio/apple/AudioPlayer.h" +#include "base/Ref.h" namespace cc { class Scheduler; @@ -44,28 +44,28 @@ public: AudioEngineImpl(); ~AudioEngineImpl(); - bool init(); - int play2d(const std::string &fileFullPath, bool loop, float volume); - void setVolume(int audioID, float volume); - void setLoop(int audioID, bool loop); - bool pause(int audioID); - bool resume(int audioID); - void stop(int audioID); - void stopAll(); + bool init(); + int play2d(const std::string &fileFullPath, bool loop, float volume); + void setVolume(int audioID, float volume); + void setLoop(int audioID, bool loop); + bool pause(int audioID); + bool resume(int audioID); + void stop(int audioID); + void stopAll(); float getDuration(int audioID); float getDurationFromFile(const std::string &fileFullPath); float getCurrentTime(int audioID); - bool setCurrentTime(int audioID, float time); - void setFinishCallback(int audioID, const std::function &callback); + bool setCurrentTime(int audioID, float time); + void setFinishCallback(int audioID, const std::function &callback); - void uncache(const std::string &filePath); - void uncacheAll(); + void uncache(const std::string &filePath); + void uncacheAll(); AudioCache *preload(const std::string &filePath, std::function callback); - void update(float dt); + void update(float dt); private: - bool _checkAudioIdValid(int audioID); - void _play2d(AudioCache *cache, int audioID); + bool checkAudioIdValid(int audioID); + void play2dImpl(AudioCache *cache, int audioID); ALuint findValidSource(); static ALvoid myAlSourceNotificationCallback(ALuint sid, ALuint notificationID, ALvoid *userData); @@ -80,11 +80,11 @@ private: //audioID,AudioInfo std::unordered_map _audioPlayers; - std::mutex _threadMutex; + std::mutex _threadMutex; bool _lazyInitLoop; - int _currentAudioID; + int _currentAudioID; std::weak_ptr _scheduler; }; } // namespace cc diff --git a/native/cocos/audio/apple/AudioEngine-inl.mm b/native/cocos/audio/apple/AudioEngine-inl.mm index 2a692d310b..03ec5d8942 100644 --- a/native/cocos/audio/apple/AudioEngine-inl.mm +++ b/native/cocos/audio/apple/AudioEngine-inl.mm @@ -381,7 +381,7 @@ int AudioEngineImpl::play2d(const std::string &filePath, bool loop, float volume _audioPlayers[_currentAudioID] = player; _threadMutex.unlock(); - audioCache->addPlayCallback(std::bind(&AudioEngineImpl::_play2d, this, audioCache, _currentAudioID)); + audioCache->addPlayCallback(std::bind(&AudioEngineImpl::play2dImpl, this, audioCache, _currentAudioID)); if (_lazyInitLoop) { _lazyInitLoop = false; @@ -393,7 +393,7 @@ int AudioEngineImpl::play2d(const std::string &filePath, bool loop, float volume return _currentAudioID++; } -void AudioEngineImpl::_play2d(AudioCache *cache, int audioID) { +void AudioEngineImpl::play2dImpl(AudioCache *cache, int audioID) { //Note: It may bn in sub thread or main thread :( if (!*cache->_isDestroyed && cache->_state == AudioCache::State::READY) { _threadMutex.lock(); @@ -401,15 +401,15 @@ void AudioEngineImpl::_play2d(AudioCache *cache, int audioID) { if (playerIt != _audioPlayers.end() && playerIt->second->play2d()) { if (auto sche = _scheduler.lock()) { sche->performFunctionInCocosThread([audioID]() { - if (AudioEngine::_audioIDInfoMap.find(audioID) != AudioEngine::_audioIDInfoMap.end()) { - AudioEngine::_audioIDInfoMap[audioID].state = AudioEngine::AudioState::PLAYING; + if (AudioEngine::sAudioIDInfoMap.find(audioID) != AudioEngine::sAudioIDInfoMap.end()) { + AudioEngine::sAudioIDInfoMap[audioID].state = AudioEngine::AudioState::PLAYING; } }); } } _threadMutex.unlock(); } else { - ALOGD("AudioEngineImpl::_play2d, cache was destroyed or not ready!"); + ALOGD("AudioEngineImpl::play2dImpl, cache was destroyed or not ready!"); auto iter = _audioPlayers.find(audioID); if (iter != _audioPlayers.end()) { iter->second->_removeByAudioEngine = true; @@ -428,7 +428,7 @@ ALuint AudioEngineImpl::findValidSource() { } void AudioEngineImpl::setVolume(int audioID, float volume) { - if (!_checkAudioIdValid(audioID)) { + if (!checkAudioIdValid(audioID)) { return; } auto player = _audioPlayers[audioID]; @@ -445,7 +445,7 @@ void AudioEngineImpl::setVolume(int audioID, float volume) { } void AudioEngineImpl::setLoop(int audioID, bool loop) { - if (!_checkAudioIdValid(audioID)) { + if (!checkAudioIdValid(audioID)) { return; } auto player = _audioPlayers[audioID]; @@ -471,7 +471,7 @@ void AudioEngineImpl::setLoop(int audioID, bool loop) { } bool AudioEngineImpl::pause(int audioID) { - if (!_checkAudioIdValid(audioID)) { + if (!checkAudioIdValid(audioID)) { return false; } bool ret = true; @@ -487,7 +487,7 @@ bool AudioEngineImpl::pause(int audioID) { } bool AudioEngineImpl::resume(int audioID) { - if (!_checkAudioIdValid(audioID)) { + if (!checkAudioIdValid(audioID)) { return false; } bool ret = true; @@ -503,7 +503,7 @@ bool AudioEngineImpl::resume(int audioID) { } void AudioEngineImpl::stop(int audioID) { - if (!_checkAudioIdValid(audioID)) { + if (!checkAudioIdValid(audioID)) { return; } auto player = _audioPlayers[audioID]; @@ -523,7 +523,7 @@ void AudioEngineImpl::stopAll() { } float AudioEngineImpl::getDuration(int audioID) { - if (!_checkAudioIdValid(audioID)) { + if (!checkAudioIdValid(audioID)) { return 0.0f; } auto player = _audioPlayers[audioID]; @@ -545,7 +545,7 @@ float AudioEngineImpl::getDurationFromFile(const std::string &filePath) { } float AudioEngineImpl::getCurrentTime(int audioID) { - if (!_checkAudioIdValid(audioID)) { + if (!checkAudioIdValid(audioID)) { return 0.0f; } float ret = 0.0f; @@ -567,7 +567,7 @@ float AudioEngineImpl::getCurrentTime(int audioID) { } bool AudioEngineImpl::setCurrentTime(int audioID, float time) { - if (!_checkAudioIdValid(audioID)) { + if (!checkAudioIdValid(audioID)) { return false; } bool ret = false; @@ -602,7 +602,7 @@ bool AudioEngineImpl::setCurrentTime(int audioID, float time) { } void AudioEngineImpl::setFinishCallback(int audioID, const std::function &callback) { - if (!_checkAudioIdValid(audioID)) { + if (!checkAudioIdValid(audioID)) { return; } _audioPlayers[audioID]->_finishCallbak = callback; @@ -633,7 +633,7 @@ void AudioEngineImpl::update(float dt) { std::string filePath; if (player->_finishCallbak) { - auto &audioInfo = AudioEngine::_audioIDInfoMap[audioID]; + auto &audioInfo = AudioEngine::sAudioIDInfoMap[audioID]; filePath = *audioInfo.filePath; } @@ -674,6 +674,6 @@ void AudioEngineImpl::uncacheAll() { _audioCaches.clear(); } -bool AudioEngineImpl::_checkAudioIdValid(int audioID) { +bool AudioEngineImpl::checkAudioIdValid(int audioID) { return _audioPlayers.find(audioID) != _audioPlayers.end(); } diff --git a/native/cocos/audio/include/AudioEngine.h b/native/cocos/audio/include/AudioEngine.h index 206df41c22..27d7ac004e 100644 --- a/native/cocos/audio/include/AudioEngine.h +++ b/native/cocos/audio/include/AudioEngine.h @@ -26,17 +26,17 @@ #pragma once -#include "base/Macros.h" #include "audio/include/Export.h" +#include "base/Macros.h" -#include "bindings/event/EventDispatcher.h" #include "bindings/event/CustomEventTypes.h" +#include "bindings/event/EventDispatcher.h" +#include #include #include #include #include -#include #ifdef ERROR #undef ERROR @@ -59,19 +59,17 @@ public: //Profile name can't be empty. std::string name; //The maximum number of simultaneous audio instance. - unsigned int maxInstances; + unsigned int maxInstances{}; /* Minimum delay in between sounds */ - double minDelay; + double minDelay{}; /** * Default constructor * * @lua new */ - AudioProfile() - : maxInstances(0), minDelay(0.0) { - } + AudioProfile() = default; }; class AudioEngineImpl; @@ -127,7 +125,7 @@ public: * * @see `AudioProfile` */ - static int play2d(const std::string &filePath, bool loop = false, float volume = 1.0f, const AudioProfile *profile = nullptr); + static int play2d(const std::string &filePath, bool loop = false, float volume = 1.0F, const AudioProfile *profile = nullptr); /** * Sets whether an audio instance loop or not. @@ -195,10 +193,10 @@ public: * Sets the current playback position of an audio instance. * * @param audioID An audioID returned by the play2d function. - * @param sec The offset in seconds from the start to seek to. + * @param time The offset in seconds from the start to seek to. * @return */ - static bool setCurrentTime(int audioID, float sec); + static bool setCurrentTime(int audioID, float time); /** * Gets the current playback position of an audio instance. @@ -243,7 +241,7 @@ public: /** * Gets the maximum number of simultaneous audio instance of AudioEngine. */ - static int getMaxAudioInstance() { return _maxInstances; } + static int getMaxAudioInstance() { return static_cast(sMaxInstances); } /** * Sets the maximum number of simultaneous audio instance for AudioEngine. @@ -254,7 +252,7 @@ public: /** * Uncache the audio data from internal buffer. - * AudioEngine cache audio data on ios,mac, and win32 platform. + * AudioEngine cache audio data on ios,mac, and oalsoft platform. * * @warning This can lead to stop related audio first. * @param filePath Audio file path. @@ -295,7 +293,7 @@ public: * @param filePath The file path of an audio. * @param callback A callback which will be called after loading is finished. */ - static void preload(const std::string &filePath, std::function callback); + static void preload(const std::string &filePath, const std::function &callback); /** * Gets playing audio count. @@ -323,17 +321,16 @@ protected: std::chrono::high_resolution_clock::time_point lastPlayTime; - ProfileHelper() { - } + ProfileHelper() = default; }; struct AudioInfo { const std::string *filePath; - ProfileHelper *profileHelper; + ProfileHelper * profileHelper; - float volume; - bool loop; - float duration; + float volume; + bool loop; + float duration; AudioState state; AudioInfo(); @@ -341,35 +338,35 @@ protected: private: AudioInfo(const AudioInfo &info); - AudioInfo(AudioInfo &&info); + AudioInfo(AudioInfo &&info) noexcept; AudioInfo &operator=(const AudioInfo &info); - AudioInfo &operator=(AudioInfo &&info); + AudioInfo &operator=(AudioInfo &&info) noexcept; }; //audioID,audioAttribute - static std::unordered_map _audioIDInfoMap; + static std::unordered_map sAudioIDInfoMap; //audio file path,audio IDs - static std::unordered_map> _audioPathIDMap; + static std::unordered_map> sAudioPathIDMap; //profileName,ProfileHelper - static std::unordered_map _audioPathProfileHelperMap; + static std::unordered_map sAudioPathProfileHelperMap; - static unsigned int _maxInstances; + static unsigned int sMaxInstances; - static ProfileHelper *_defaultProfileHelper; + static ProfileHelper *sDefaultProfileHelper; - static AudioEngineImpl *_audioEngineImpl; + static AudioEngineImpl *sAudioEngineImpl; class AudioEngineThreadPool; - static AudioEngineThreadPool *s_threadPool; + static AudioEngineThreadPool *sThreadPool; - static bool _isEnabled; + static bool sIsEnabled; private: - static uint32_t _onPauseListenerID; - static uint32_t _onResumeListenerID; - static std::vector _breakAudioID; + static uint32_t sOnPauseListenerID; + static uint32_t sOnResumeListenerID; + static std::vector sBreakAudioID; static void onEnterBackground(const CustomEvent &); static void onEnterForeground(const CustomEvent &); diff --git a/native/cocos/audio/win32/AudioCache.cpp b/native/cocos/audio/oalsoft/AudioCache.cpp similarity index 85% rename from native/cocos/audio/win32/AudioCache.cpp rename to native/cocos/audio/oalsoft/AudioCache.cpp index 5341387637..22e50cafd5 100644 --- a/native/cocos/audio/win32/AudioCache.cpp +++ b/native/cocos/audio/oalsoft/AudioCache.cpp @@ -26,13 +26,13 @@ #define LOG_TAG "AudioCache" -#include "audio/win32/AudioCache.h" +#include "audio/oalsoft/AudioCache.h" #include -#include "platform/Application.h" #include "base/Scheduler.h" +#include "platform/Application.h" -#include "audio/win32/AudioDecoderManager.h" -#include "audio/win32/AudioDecoder.h" +#include "audio/oalsoft/AudioDecoder.h" +#include "audio/oalsoft/AudioDecoderManager.h" #define VERY_VERY_VERBOSE_LOGGING #ifdef VERY_VERY_VERBOSE_LOGGING @@ -44,19 +44,19 @@ #endif namespace { -unsigned int __idIndex = 0; +unsigned int gIdIndex = 0; } #define INVALID_AL_BUFFER_ID 0xFFFFFFFF #define PCMDATA_CACHEMAXSIZE 1048576 -using namespace cc; +using namespace cc; //NOLINT AudioCache::AudioCache() -: _format(-1), _sampleRate(0), _duration(0.0f), _totalFrames(0), _framesRead(0), _alBufferId(INVALID_AL_BUFFER_ID), _pcmData(nullptr), _queBufferFrames(0), _state(State::INITIAL), _isDestroyed(std::make_shared(false)), _id(++__idIndex), _isLoadingFinished(false), _isSkipReadDataTask(false) { +: _format(-1), _sampleRate(0), _duration(0.0F), _totalFrames(0), _framesRead(0), _alBufferId(INVALID_AL_BUFFER_ID), _pcmData(nullptr), _queBufferFrames(0), _state(State::INITIAL), _isDestroyed(std::make_shared(false)), _id(++gIdIndex), _isLoadingFinished(false), _isSkipReadDataTask(false) { ALOGVV("AudioCache() %p, id=%u", this, _id); for (int i = 0; i < QUEUEBUFFER_NUM; ++i) { - _queBuffers[i] = nullptr; + _queBuffers[i] = nullptr; _queBufferSize[i] = 0; } } @@ -91,8 +91,8 @@ AudioCache::~AudioCache() { } if (_queBufferFrames > 0) { - for (int index = 0; index < QUEUEBUFFER_NUM; ++index) { - free(_queBuffers[index]); + for (auto &buffer : _queBuffers) { + free(buffer); } } ALOGVV("~AudioCache() %p, id=%u, end", this, _id); @@ -107,32 +107,33 @@ void AudioCache::readDataTask(unsigned int selfId) { AudioDecoder *decoder = AudioDecoderManager::createDecoder(_fileFullPath.c_str()); do { - if (decoder == nullptr || !decoder->open(_fileFullPath.c_str())) + if (decoder == nullptr || !decoder->open(_fileFullPath.c_str())) { break; + } const uint32_t originalTotalFrames = decoder->getTotalFrames(); - const uint32_t bytesPerFrame = decoder->getBytesPerFrame(); - const uint32_t sampleRate = decoder->getSampleRate(); - const uint32_t channelCount = decoder->getChannelCount(); + const uint32_t bytesPerFrame = decoder->getBytesPerFrame(); + const uint32_t sampleRate = decoder->getSampleRate(); + const uint32_t channelCount = decoder->getChannelCount(); - uint32_t totalFrames = originalTotalFrames; - uint32_t dataSize = totalFrames * bytesPerFrame; + uint32_t totalFrames = originalTotalFrames; + uint32_t dataSize = totalFrames * bytesPerFrame; uint32_t remainingFrames = totalFrames; - uint32_t adjustFrames = 0; + uint32_t adjustFrames = 0; - _format = channelCount > 1 ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16; - _sampleRate = (ALsizei)sampleRate; - _duration = 1.0f * totalFrames / sampleRate; + _format = channelCount > 1 ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16; + _sampleRate = static_cast(sampleRate); + _duration = 1.0F * totalFrames / sampleRate; _totalFrames = totalFrames; if (dataSize <= PCMDATA_CACHEMAXSIZE) { - uint32_t framesRead = 0; + uint32_t framesRead = 0; const uint32_t framesToReadOnce = std::min(totalFrames, static_cast(sampleRate * QUEUEBUFFER_TIME_STEP * QUEUEBUFFER_NUM)); std::vector adjustFrameBuf; if (decoder->seek(totalFrames)) { - char *tmpBuf = (char *)malloc(framesToReadOnce * bytesPerFrame); + auto *tmpBuf = static_cast(malloc(framesToReadOnce * bytesPerFrame)); adjustFrameBuf.reserve(framesToReadOnce * bytesPerFrame); // Adjust total frames by setting position to the end of frames and try to read more data. @@ -160,7 +161,7 @@ void AudioCache::readDataTask(unsigned int selfId) { // Reset to frame 0 BREAK_IF_ERR_LOG(!decoder->seek(0), "AudioDecoder::seek(0) failed!"); - _pcmData = (char *)malloc(dataSize); + _pcmData = static_cast(malloc(dataSize)); CC_ASSERT(_pcmData); memset(_pcmData, 0x00, dataSize); @@ -176,15 +177,17 @@ void AudioCache::readDataTask(unsigned int selfId) { break; } - if (*_isDestroyed) + if (*_isDestroyed) { break; + } framesRead = decoder->readFixedFrames(std::min(framesToReadOnce, remainingFrames), _pcmData + _framesRead * bytesPerFrame); _framesRead += framesRead; remainingFrames -= framesRead; - if (*_isDestroyed) + if (*_isDestroyed) { break; + } uint32_t frames = 0; while (!*_isDestroyed && _framesRead < originalTotalFrames) { @@ -193,14 +196,16 @@ void AudioCache::readDataTask(unsigned int selfId) { frames = originalTotalFrames - _framesRead; } framesRead = decoder->read(frames, _pcmData + _framesRead * bytesPerFrame); - if (framesRead == 0) + if (framesRead == 0) { break; + } _framesRead += framesRead; remainingFrames -= framesRead; } - if (*_isDestroyed) + if (*_isDestroyed) { break; + } if (_framesRead < originalTotalFrames) { memset(_pcmData + _framesRead * bytesPerFrame, 0x00, (totalFrames - _framesRead) * bytesPerFrame); @@ -209,7 +214,7 @@ void AudioCache::readDataTask(unsigned int selfId) { _framesRead += adjustFrames; - alBufferData(_alBufferId, _format, _pcmData, (ALsizei)dataSize, (ALsizei)sampleRate); + alBufferData(_alBufferId, _format, _pcmData, static_cast(dataSize), static_cast(sampleRate)); _state = State::READY; } else { @@ -219,7 +224,7 @@ void AudioCache::readDataTask(unsigned int selfId) { const uint32_t queBufferBytes = _queBufferFrames * bytesPerFrame; for (int index = 0; index < QUEUEBUFFER_NUM; ++index) { - _queBuffers[index] = (char *)malloc(queBufferBytes); + _queBuffers[index] = static_cast(malloc(queBufferBytes)); _queBufferSize[index] = queBufferBytes; decoder->readFixedFrames(_queBufferFrames, _queBuffers[index]); @@ -312,7 +317,7 @@ void AudioCache::invokingLoadCallbacks() { } auto isDestroyed = _isDestroyed; - auto scheduler = Application::getInstance()->getScheduler(); + auto scheduler = Application::getInstance()->getScheduler(); scheduler->performFunctionInCocosThread([&, isDestroyed]() { if (*isDestroyed) { ALOGV("invokingLoadCallbacks perform in cocos thread, AudioCache (%p) was destroyed!", this); diff --git a/native/cocos/audio/win32/AudioCache.h b/native/cocos/audio/oalsoft/AudioCache.h similarity index 94% rename from native/cocos/audio/win32/AudioCache.h rename to native/cocos/audio/oalsoft/AudioCache.h index 5f8e4d4408..16eb0c52f6 100644 --- a/native/cocos/audio/win32/AudioCache.h +++ b/native/cocos/audio/oalsoft/AudioCache.h @@ -26,18 +26,20 @@ #pragma once -#include -#include -#include -#include #include -#ifdef OPENAL_PLAIN_INCLUDES +#include +#include +#include +#include +#if defined(OPENAL_PLAIN_INCLUDES) #include -#else +#elif CC_PLATFORM == CC_PLATFORM_WINDOWS #include +#elif CC_PLATFORM == CC_PLATFORM_OHOS + #include #endif +#include "audio/oalsoft/AudioMacros.h" #include "base/Macros.h" -#include "audio/win32/AudioMacros.h" namespace cc { class AudioEngineImpl; diff --git a/native/cocos/audio/win32/AudioDecoder.cpp b/native/cocos/audio/oalsoft/AudioDecoder.cpp similarity index 87% rename from native/cocos/audio/win32/AudioDecoder.cpp rename to native/cocos/audio/oalsoft/AudioDecoder.cpp index a5af94a6ed..f2879f2822 100644 --- a/native/cocos/audio/win32/AudioDecoder.cpp +++ b/native/cocos/audio/oalsoft/AudioDecoder.cpp @@ -22,18 +22,24 @@ 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 "audio/win32/AudioDecoder.h" -#include "audio/win32/AudioMacros.h" + ****************************************************************************/ +#include "audio/oalsoft/AudioDecoder.h" +#include "audio/oalsoft/AudioMacros.h" #include "platform/FileUtils.h" +#ifdef LOG_TAG + #undef LOG_TAG +#endif #define LOG_TAG "AudioDecoder" namespace cc { AudioDecoder::AudioDecoder() -: _isOpened(false), _totalFrames(0), _bytesPerFrame(0), _sampleRate(0), _channelCount(0) { +: _isOpened(false), + _totalFrames(0), + _bytesPerFrame(0), + _sampleRate(0), + _channelCount(0) { } AudioDecoder::~AudioDecoder() { @@ -44,7 +50,7 @@ bool AudioDecoder::isOpened() const { } uint32_t AudioDecoder::readFixedFrames(uint32_t framesToRead, char *pcmBuf) { - uint32_t framesRead = 0; + uint32_t framesRead = 0; uint32_t framesReadOnce = 0; do { framesReadOnce = read(framesToRead - framesRead, pcmBuf + framesRead * _bytesPerFrame); diff --git a/native/cocos/audio/win32/AudioDecoder.h b/native/cocos/audio/oalsoft/AudioDecoder.h similarity index 95% rename from native/cocos/audio/win32/AudioDecoder.h rename to native/cocos/audio/oalsoft/AudioDecoder.h index 69ba19c285..2db62b15e1 100644 --- a/native/cocos/audio/win32/AudioDecoder.h +++ b/native/cocos/audio/oalsoft/AudioDecoder.h @@ -26,9 +26,13 @@ #pragma once -#include +#include -#include "vorbis/vorbisfile.h" +#if CC_PLATFORM == CC_PLATFORM_WINDOWS + #include "vorbis/vorbisfile.h" +#elif CC_PLATFORM == CC_PLATFORM_OHOS + #include "ivorbisfile.h" +#endif namespace cc { @@ -108,12 +112,14 @@ protected: AudioDecoder(); virtual ~AudioDecoder(); - bool _isOpened; + bool _isOpened; uint32_t _totalFrames; uint32_t _bytesPerFrame; uint32_t _sampleRate; uint32_t _channelCount; + void *_fsHooks = nullptr; + friend class AudioDecoderManager; }; diff --git a/native/cocos/audio/win32/AudioDecoderManager.cpp b/native/cocos/audio/oalsoft/AudioDecoderManager.cpp similarity index 82% rename from native/cocos/audio/win32/AudioDecoderManager.cpp rename to native/cocos/audio/oalsoft/AudioDecoderManager.cpp index 7cc0a752b7..a58bd7b415 100644 --- a/native/cocos/audio/win32/AudioDecoderManager.cpp +++ b/native/cocos/audio/oalsoft/AudioDecoderManager.cpp @@ -26,17 +26,17 @@ #define LOG_TAG "AudioDecoderManager" -#include "audio/win32/AudioDecoderManager.h" -#include "audio/win32/AudioDecoderOgg.h" -#include "audio/win32/AudioDecoderMp3.h" -#include "audio/win32/AudioMacros.h" +#include "audio/oalsoft/AudioDecoderManager.h" +#include "audio/oalsoft/AudioDecoderMp3.h" +#include "audio/oalsoft/AudioDecoderOgg.h" +#if CC_PLATFORM == CC_PLATFORM_OHOS + #include "audio/ohos/AudioDecoderWav.h" +#endif +#include "audio/oalsoft/AudioMacros.h" #include "platform/FileUtils.h" -#include "mpg123/mpg123.h" namespace cc { -static bool __mp3Inited = false; - bool AudioDecoderManager::init() { return true; } @@ -49,10 +49,18 @@ AudioDecoder *AudioDecoderManager::createDecoder(const char *path) { std::string suffix = FileUtils::getInstance()->getFileExtension(path); if (suffix == ".ogg") { return new (std::nothrow) AudioDecoderOgg(); - } else if (suffix == ".mp3") { + } + + if (suffix == ".mp3") { return new (std::nothrow) AudioDecoderMp3(); } +#if CC_PLATFORM == CC_PLATFORM_OHOS + if (suffix == ".wav") { + return new (std::nothrow) AudioDecoderWav(); + } +#endif + return nullptr; } diff --git a/native/cocos/audio/win32/AudioDecoderManager.h b/native/cocos/audio/oalsoft/AudioDecoderManager.h similarity index 100% rename from native/cocos/audio/win32/AudioDecoderManager.h rename to native/cocos/audio/oalsoft/AudioDecoderManager.h diff --git a/native/cocos/audio/win32/AudioDecoderMp3.cpp b/native/cocos/audio/oalsoft/AudioDecoderMp3.cpp similarity index 73% rename from native/cocos/audio/win32/AudioDecoderMp3.cpp rename to native/cocos/audio/oalsoft/AudioDecoderMp3.cpp index 5101bea81e..891a52e321 100644 --- a/native/cocos/audio/win32/AudioDecoderMp3.cpp +++ b/native/cocos/audio/oalsoft/AudioDecoderMp3.cpp @@ -22,26 +22,37 @@ 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 "audio/win32/AudioDecoderMp3.h" -#include "audio/win32/AudioMacros.h" + ****************************************************************************/ +#include "audio/oalsoft/AudioDecoderMp3.h" +#include "audio/oalsoft/AudioMacros.h" #include "platform/FileUtils.h" -#include "mpg123/mpg123.h" +#if CC_PLATFORM == CC_PLATFORM_WINDOWS + #include "mpg123/mpg123.h" +#elif CC_PLATFORM == CC_PLATFORM_OHOS + #include "cocos/platform/ohos/FileUtils-ohos.h" + #include "mpg123.h" + #include +#endif +#include +#include + +#ifdef LOG_TAG + #undef LOG_TAG +#endif #define LOG_TAG "AudioDecoderMp3" namespace cc { -static bool __mp3Inited = false; +static bool sMp3Inited = false; bool AudioDecoderMp3::lazyInit() { bool ret = true; - if (!__mp3Inited) { + if (!sMp3Inited) { int error = mpg123_init(); if (error == MPG123_OK) { - __mp3Inited = true; + sMp3Inited = true; } else { ALOGE("Basic setup goes wrong: %s", mpg123_plain_strerror(error)); ret = false; @@ -51,14 +62,13 @@ bool AudioDecoderMp3::lazyInit() { } void AudioDecoderMp3::destroy() { - if (__mp3Inited) { + if (sMp3Inited) { mpg123_exit(); - __mp3Inited = false; + sMp3Inited = false; } } -AudioDecoderMp3::AudioDecoderMp3() -: _mpg123handle(nullptr) { +AudioDecoderMp3::AudioDecoderMp3() { lazyInit(); } @@ -69,24 +79,29 @@ AudioDecoderMp3::~AudioDecoderMp3() { bool AudioDecoderMp3::open(const char *path) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(path); - long rate = 0; - int error = MPG123_OK; - int mp3Encoding = 0; - int channel = 0; + long rate = 0; //NOLINT(google-runtime-int) + int error = MPG123_OK; + int mp3Encoding = 0; + int channel = 0; do { _mpg123handle = mpg123_new(nullptr, &error); if (nullptr == _mpg123handle) { ALOGE("Basic setup goes wrong: %s", mpg123_plain_strerror(error)); break; } - +#if CC_PLATFORM_OHOS == CC_PLATFORM + auto *fu = static_cast(FileUtils::getInstance()); + _fdAndDeleter = fu->getFd(fullPath); + if (mpg123_open_fd(_mpg123handle, _fdAndDeleter.first) != MPG123_OK || mpg123_getformat(_mpg123handle, &rate, &channel, &mp3Encoding) != MPG123_OK) { +#else if (mpg123_open(_mpg123handle, FileUtils::getInstance()->getSuitableFOpen(fullPath).c_str()) != MPG123_OK || mpg123_getformat(_mpg123handle, &rate, &channel, &mp3Encoding) != MPG123_OK) { +#endif ALOGE("Trouble with mpg123: %s\n", mpg123_strerror(_mpg123handle)); break; } _channelCount = channel; - _sampleRate = rate; + _sampleRate = rate; if (mp3Encoding == MPG123_ENC_SIGNED_16) { _bytesPerFrame = 2 * _channelCount; @@ -126,12 +141,18 @@ void AudioDecoderMp3::close() { } _isOpened = false; } +#if CC_PLATFORM_OHOS == CC_PLATFORM + if (_fdAndDeleter.second) { + _fdAndDeleter.second(); + _fdAndDeleter.second = nullptr; + } +#endif } uint32_t AudioDecoderMp3::read(uint32_t framesToRead, char *pcmBuf) { - int bytesToRead = framesToRead * _bytesPerFrame; - size_t bytesRead = 0; - int err = mpg123_read(_mpg123handle, (unsigned char *)pcmBuf, bytesToRead, &bytesRead); + size_t bytesToRead = framesToRead * _bytesPerFrame; + size_t bytesRead = 0; + int err = mpg123_read(_mpg123handle, reinterpret_cast(pcmBuf), bytesToRead, &bytesRead); if (err == MPG123_ERR) { ALOGE("Trouble with mpg123: %s\n", mpg123_strerror(_mpg123handle)); return 0; @@ -143,10 +164,7 @@ uint32_t AudioDecoderMp3::read(uint32_t framesToRead, char *pcmBuf) { bool AudioDecoderMp3::seek(uint32_t frameOffset) { off_t offset = mpg123_seek(_mpg123handle, frameOffset, SEEK_SET); //ALOGD("mpg123_seek return: %d", (int)offset); - if (offset >= 0 && offset == frameOffset) { - return true; - } - return false; + return offset >= 0 && offset == frameOffset; } uint32_t AudioDecoderMp3::tell() const { diff --git a/native/cocos/audio/win32/AudioDecoderMp3.h b/native/cocos/audio/oalsoft/AudioDecoderMp3.h similarity index 85% rename from native/cocos/audio/win32/AudioDecoderMp3.h rename to native/cocos/audio/oalsoft/AudioDecoderMp3.h index 21a903be5f..992ff3eab3 100644 --- a/native/cocos/audio/win32/AudioDecoderMp3.h +++ b/native/cocos/audio/oalsoft/AudioDecoderMp3.h @@ -26,7 +26,9 @@ #pragma once -#include "audio/win32/AudioDecoder.h" +#include "audio/oalsoft/AudioDecoder.h" + +#include struct mpg123_handle_struct; @@ -41,13 +43,13 @@ public: * @brief Opens an audio file specified by a file path. * @return true if succeed, otherwise false. */ - virtual bool open(const char *path) override; + bool open(const char *path) override; /** * @brief Closes opened audio file. * @note The method will also be automatically invoked in the destructor. */ - virtual void close() override; + void close() override; /** * @brief Reads audio frames of PCM format. @@ -55,29 +57,33 @@ public: * @param pcmBuf The buffer to hold the frames to be read, its size should be >= |framesToRead| * _bytesPerFrame. * @return The number of frames actually read, it's probably less than 'framesToRead'. Returns 0 means reach the end of file. */ - virtual uint32_t read(uint32_t framesToRead, char *pcmBuf) override; + uint32_t read(uint32_t framesToRead, char *pcmBuf) override; /** * @brief Sets frame offest to be read. * @param frameOffset The frame offest to be set. * @return true if succeed, otherwise false */ - virtual bool seek(uint32_t frameOffset) override; + bool seek(uint32_t frameOffset) override; /** * @brief Tells the current frame offset. * @return The current frame offset. */ - virtual uint32_t tell() const override; + uint32_t tell() const override; protected: AudioDecoderMp3(); - ~AudioDecoderMp3(); + ~AudioDecoderMp3() override; static bool lazyInit(); static void destroy(); - struct mpg123_handle_struct *_mpg123handle; + struct mpg123_handle_struct *_mpg123handle = nullptr; + +#if CC_PLATFORM_OHOS == CC_PLATFORM + std::pair> _fdAndDeleter; +#endif friend class AudioDecoderManager; }; diff --git a/native/cocos/audio/win32/AudioDecoderOgg.cpp b/native/cocos/audio/oalsoft/AudioDecoderOgg.cpp similarity index 58% rename from native/cocos/audio/win32/AudioDecoderOgg.cpp rename to native/cocos/audio/oalsoft/AudioDecoderOgg.cpp index 4830182337..546e9801b0 100644 --- a/native/cocos/audio/win32/AudioDecoderOgg.cpp +++ b/native/cocos/audio/oalsoft/AudioDecoderOgg.cpp @@ -22,18 +22,34 @@ 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 "audio/win32/AudioDecoderOgg.h" -#include "audio/win32/AudioMacros.h" + ****************************************************************************/ +#include "audio/oalsoft/AudioDecoderOgg.h" +#include "audio/oalsoft/AudioMacros.h" #include "platform/FileUtils.h" +#if CC_PLATFORM == CC_PLATFORM_OHOS + #include "audio/ohos/FsCallback.h" +namespace { +int ohosSeek_wrap(void *source, ogg_int64_t offset, int whence) { //NOLINT + return cc::ohosSeek(source, static_cast(offset), whence); //NOLINT +} + +ov_callbacks ogg_callbacks = { //NOLINT + static_cast(cc::ohosRead), + static_cast(ohosSeek_wrap), + static_cast(cc::ohosClose), + static_cast(cc::ohosTell)}; //NOLINT +} // namespace +#endif + +#ifdef LOG_TAG + #undef LOG_TAG +#endif #define LOG_TAG "AudioDecoderOgg" namespace cc { -AudioDecoderOgg::AudioDecoderOgg() { -} +AudioDecoderOgg::AudioDecoderOgg() = default; AudioDecoderOgg::~AudioDecoderOgg() { close(); @@ -41,14 +57,19 @@ AudioDecoderOgg::~AudioDecoderOgg() { bool AudioDecoderOgg::open(const char *path) { std::string fullPath = FileUtils::getInstance()->fullPathForFilename(path); +#if CC_PLATFORM == CC_PLATFORM_WINDOWS if (0 == ov_fopen(FileUtils::getInstance()->getSuitableFOpen(fullPath).c_str(), &_vf)) { +#elif CC_PLATFORM == CC_PLATFORM_OHOS + auto *fp = cc::ohosOpen(FileUtils::getInstance()->getSuitableFOpen(fullPath).c_str(), this); + if (0 == ov_open_callbacks(fp, &_vf, nullptr, 0, ogg_callbacks)) { +#endif // header vorbis_info *vi = ov_info(&_vf, -1); - _sampleRate = static_cast(vi->rate); - _channelCount = vi->channels; - _bytesPerFrame = vi->channels * sizeof(short); - _totalFrames = static_cast(ov_pcm_total(&_vf, -1)); - _isOpened = true; + _sampleRate = static_cast(vi->rate); + _channelCount = vi->channels; + _bytesPerFrame = vi->channels * sizeof(int16_t); + _totalFrames = static_cast(ov_pcm_total(&_vf, -1)); + _isOpened = true; return true; } return false; @@ -62,9 +83,14 @@ void AudioDecoderOgg::close() { } uint32_t AudioDecoderOgg::read(uint32_t framesToRead, char *pcmBuf) { - int currentSection = 0; - int bytesToRead = framesToRead * _bytesPerFrame; - long bytesRead = ov_read(&_vf, pcmBuf, bytesToRead, 0, 2, 1, ¤tSection); + int currentSection = 0; + auto bytesToRead = framesToRead * _bytesPerFrame; +#if CC_PLATFORM == CC_PLATFORM_WINDOWS + auto bytesRead = ov_read(&_vf, pcmBuf, bytesToRead, 0, 2, 1, ¤tSection); +#elif CC_PLATFORM == CC_PLATFORM_OHOS + int bitstream = 0; + auto bytesRead = ov_read(&_vf, pcmBuf, bytesToRead, &bitstream); +#endif return static_cast(bytesRead / _bytesPerFrame); } diff --git a/native/cocos/audio/win32/AudioDecoderOgg.h b/native/cocos/audio/oalsoft/AudioDecoderOgg.h similarity index 85% rename from native/cocos/audio/win32/AudioDecoderOgg.h rename to native/cocos/audio/oalsoft/AudioDecoderOgg.h index 74dbe95c04..2db4fbda2b 100644 --- a/native/cocos/audio/win32/AudioDecoderOgg.h +++ b/native/cocos/audio/oalsoft/AudioDecoderOgg.h @@ -26,9 +26,13 @@ #pragma once -#include "audio/win32/AudioDecoder.h" +#include "audio/oalsoft/AudioDecoder.h" -#include "vorbis/vorbisfile.h" +#if CC_PLATFORM == CC_PLATFORM_WINDOWS + #include "vorbis/vorbisfile.h" +#elif CC_PLATFORM == CC_PLATFORM_OHOS + #include "ivorbisfile.h" +#endif namespace cc { @@ -41,13 +45,13 @@ public: * @brief Opens an audio file specified by a file path. * @return true if succeed, otherwise false. */ - virtual bool open(const char *path) override; + bool open(const char *path) override; /** * @brief Closes opened audio file. * @note The method will also be automatically invoked in the destructor. */ - virtual void close() override; + void close() override; /** * @brief Reads audio frames of PCM format. @@ -55,24 +59,24 @@ public: * @param pcmBuf The buffer to hold the frames to be read, its size should be >= |framesToRead| * _bytesPerFrame. * @return The number of frames actually read, it's probably less than 'framesToRead'. Returns 0 means reach the end of file. */ - virtual uint32_t read(uint32_t framesToRead, char *pcmBuf) override; + uint32_t read(uint32_t framesToRead, char *pcmBuf) override; /** * @brief Sets frame offest to be read. * @param frameOffset The frame offest to be set. * @return true if succeed, otherwise false */ - virtual bool seek(uint32_t frameOffset) override; + bool seek(uint32_t frameOffset) override; /** * @brief Tells the current frame offset. * @return The current frame offset. */ - virtual uint32_t tell() const override; + uint32_t tell() const override; protected: AudioDecoderOgg(); - ~AudioDecoderOgg(); + ~AudioDecoderOgg() override; OggVorbis_File _vf; diff --git a/native/cocos/audio/win32/AudioEngine-win32.cpp b/native/cocos/audio/oalsoft/AudioEngine-soft.cpp similarity index 74% rename from native/cocos/audio/win32/AudioEngine-win32.cpp rename to native/cocos/audio/oalsoft/AudioEngine-soft.cpp index 8a5021a95e..bd70e03364 100644 --- a/native/cocos/audio/win32/AudioEngine-win32.cpp +++ b/native/cocos/audio/oalsoft/AudioEngine-soft.cpp @@ -22,26 +22,29 @@ 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 "AudioEngine-OALSOFT" -#define LOG_TAG "AudioEngine-Win32" - -#include "audio/win32/AudioEngine-win32.h" +#include "audio/oalsoft/AudioEngine-soft.h" #ifdef OPENAL_PLAIN_INCLUDES #include "alc.h" #include "alext.h" -#else +#elif CC_PLATFORM == CC_PLATFORM_WINDOWS #include "OpenalSoft/alc.h" #include "OpenalSoft/alext.h" +#elif CC_PLATFORM == CC_PLATFORM_OHOS + #include "AL/alc.h" + #include "AL/alext.h" #endif #include "audio/include/AudioEngine.h" -#include "platform/Application.h" +#include "audio/oalsoft/AudioDecoderManager.h" #include "base/Scheduler.h" +#include "platform/Application.h" #include "platform/FileUtils.h" -#include "audio/win32/AudioDecoderManager.h" -#include +#if CC_PLATFORM == CC_PLATFORM_WINDOWS + #include // log, CC_LOG_DEBUG aren't threadsafe, since we uses sub threads for parsing pcm data, threadsafe log output // is needed. Define the following macros (ALOGV, ALOGD, ALOGI, ALOGW, ALOGE) for threadsafe log output. @@ -49,8 +52,8 @@ //IDEA: Move _winLog, winLog to a separated file static void _winLog(const char *format, va_list args) { static const int MAX_LOG_LENGTH = 16 * 1024; - int bufferSize = MAX_LOG_LENGTH; - char *buf = nullptr; + int bufferSize = MAX_LOG_LENGTH; + char * buf = nullptr; do { buf = new (std::nothrow) char[bufferSize]; @@ -69,10 +72,10 @@ static void _winLog(const char *format, va_list args) { strcat(buf, "\n"); - int pos = 0; - int len = strlen(buf); - char tempBuf[MAX_LOG_LENGTH + 1] = {0}; - WCHAR wszBuf[MAX_LOG_LENGTH + 1] = {0}; + int pos = 0; + int len = strlen(buf); + char tempBuf[MAX_LOG_LENGTH + 1] = {0}; + WCHAR wszBuf[MAX_LOG_LENGTH + 1] = {0}; do { std::copy(buf + pos, buf + pos + MAX_LOG_LENGTH, tempBuf); @@ -89,20 +92,29 @@ static void _winLog(const char *format, va_list args) { delete[] buf; } +#ifndef audioLog void audioLog(const char *format, ...) { va_list args; va_start(args, format); _winLog(format, args); va_end(args); } +#endif -using namespace cc; +#else -static ALCdevice *s_ALDevice = nullptr; -static ALCcontext *s_ALContext = nullptr; + #define audioLog(...) CC_LOG_DEBUG(__VA_ARGS__) + +#endif + +using namespace cc; //NOLINT + +static ALCdevice * sALDevice = nullptr; +static ALCcontext *sALContext = nullptr; AudioEngineImpl::AudioEngineImpl() -: _lazyInitLoop(true), _currentAudioID(0) { +: _lazyInitLoop(true), + _currentAudioID(0) { } AudioEngineImpl::~AudioEngineImpl() { @@ -110,19 +122,19 @@ AudioEngineImpl::~AudioEngineImpl() { sche->unschedule("AudioEngine", this); } - if (s_ALContext) { + if (sALContext) { alDeleteSources(MAX_AUDIOINSTANCES, _alSources); _audioCaches.clear(); alcMakeContextCurrent(nullptr); - alcDestroyContext(s_ALContext); - s_ALContext = nullptr; + alcDestroyContext(sALContext); + sALContext = nullptr; } - if (s_ALDevice) { - alcCloseDevice(s_ALDevice); - s_ALDevice = nullptr; + if (sALDevice) { + alcCloseDevice(sALDevice); + sALDevice = nullptr; } AudioDecoderManager::destroy(); @@ -131,42 +143,42 @@ AudioEngineImpl::~AudioEngineImpl() { bool AudioEngineImpl::init() { bool ret = false; do { - s_ALDevice = alcOpenDevice(nullptr); + sALDevice = alcOpenDevice(nullptr); - if (s_ALDevice) { + if (sALDevice) { alGetError(); - s_ALContext = alcCreateContext(s_ALDevice, nullptr); - alcMakeContextCurrent(s_ALContext); + sALContext = alcCreateContext(sALDevice, nullptr); + alcMakeContextCurrent(sALContext); alGenSources(MAX_AUDIOINSTANCES, _alSources); auto alError = alGetError(); if (alError != AL_NO_ERROR) { - ALOGE("%s:generating sources failed! error = %x\n", __FUNCTION__, alError); + CC_LOG_ERROR("%s:generating sources failed! error = %x\n", __FUNCTION__, alError); break; } - for (int i = 0; i < MAX_AUDIOINSTANCES; ++i) { - _alSourceUsed[_alSources[i]] = false; + for (unsigned int src : _alSources) { + _alSourceUsed[src] = false; } _scheduler = Application::getInstance()->getScheduler(); - ret = AudioDecoderManager::init(); - ALOGI("OpenAL was initialized successfully!"); + ret = AudioDecoderManager::init(); + CC_LOG_DEBUG("OpenAL was initialized successfully!"); } } while (false); return ret; } -AudioCache *AudioEngineImpl::preload(const std::string &filePath, std::function callback) { +AudioCache *AudioEngineImpl::preload(const std::string &filePath, const std::function &callback) { AudioCache *audioCache = nullptr; auto it = _audioCaches.find(filePath); if (it == _audioCaches.end()) { - audioCache = &_audioCaches[filePath]; - audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath); - unsigned int cacheId = audioCache->_id; - auto isCacheDestroyed = audioCache->_isDestroyed; + audioCache = &_audioCaches[filePath]; + audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath); + unsigned int cacheId = audioCache->_id; + auto isCacheDestroyed = audioCache->_isDestroyed; AudioEngine::addTask([audioCache, cacheId, isCacheDestroyed]() { if (*isCacheDestroyed) { ALOGV("AudioCache (id=%u) was destroyed, no need to launch readDataTask.", cacheId); @@ -186,14 +198,14 @@ AudioCache *AudioEngineImpl::preload(const std::string &filePath, std::function< } int AudioEngineImpl::play2d(const std::string &filePath, bool loop, float volume) { - if (s_ALDevice == nullptr) { + if (sALDevice == nullptr) { return AudioEngine::INVALID_AUDIO_ID; } - bool sourceFlag = false; - ALuint alSource = 0; - for (int i = 0; i < MAX_AUDIOINSTANCES; ++i) { - alSource = _alSources[i]; + bool sourceFlag = false; + ALuint alSource = 0; + for (unsigned int src : _alSources) { + alSource = src; if (!_alSourceUsed[alSource]) { sourceFlag = true; @@ -210,8 +222,8 @@ int AudioEngineImpl::play2d(const std::string &filePath, bool loop, float volume } player->_alSource = alSource; - player->_loop = loop; - player->_volume = volume; + player->_loop = loop; + player->_volume = volume; auto audioCache = preload(filePath, nullptr); if (audioCache == nullptr) { @@ -226,19 +238,19 @@ int AudioEngineImpl::play2d(const std::string &filePath, bool loop, float volume _alSourceUsed[alSource] = true; - audioCache->addPlayCallback(std::bind(&AudioEngineImpl::_play2d, this, audioCache, _currentAudioID)); + audioCache->addPlayCallback(std::bind(&AudioEngineImpl::play2dImpl, this, audioCache, _currentAudioID)); if (_lazyInitLoop) { _lazyInitLoop = false; if (auto sche = _scheduler.lock()) { - sche->schedule(CC_CALLBACK_1(AudioEngineImpl::update, this), this, 0.05f, false, "AudioEngine"); + sche->schedule(CC_CALLBACK_1(AudioEngineImpl::update, this), this, 0.05F, false, "AudioEngine"); } } return _currentAudioID++; } -void AudioEngineImpl::_play2d(AudioCache *cache, int audioID) { +void AudioEngineImpl::play2dImpl(AudioCache *cache, int audioID) { //Note: It may bn in sub thread or main thread :( if (!*cache->_isDestroyed && cache->_state == AudioCache::State::READY) { _threadMutex.lock(); @@ -246,15 +258,15 @@ void AudioEngineImpl::_play2d(AudioCache *cache, int audioID) { if (playerIt != _audioPlayers.end() && playerIt->second->play2d()) { if (auto sche = _scheduler.lock()) { sche->performFunctionInCocosThread([audioID]() { - if (AudioEngine::_audioIDInfoMap.find(audioID) != AudioEngine::_audioIDInfoMap.end()) { - AudioEngine::_audioIDInfoMap[audioID].state = AudioEngine::AudioState::PLAYING; + if (AudioEngine::sAudioIDInfoMap.find(audioID) != AudioEngine::sAudioIDInfoMap.end()) { + AudioEngine::sAudioIDInfoMap[audioID].state = AudioEngine::AudioState::PLAYING; } }); } } _threadMutex.unlock(); } else { - ALOGD("AudioEngineImpl::_play2d, cache was destroyed or not ready!"); + CC_LOG_DEBUG("AudioEngineImpl::play2dImpl, cache was destroyed or not ready!"); auto iter = _audioPlayers.find(audioID); if (iter != _audioPlayers.end()) { iter->second->_removeByAudioEngine = true; @@ -263,10 +275,10 @@ void AudioEngineImpl::_play2d(AudioCache *cache, int audioID) { } void AudioEngineImpl::setVolume(int audioID, float volume) { - if (!_checkAudioIdValid(audioID)) { + if (!checkAudioIdValid(audioID)) { return; } - auto player = _audioPlayers[audioID]; + auto player = _audioPlayers[audioID]; player->_volume = volume; if (player->_ready) { @@ -280,7 +292,7 @@ void AudioEngineImpl::setVolume(int audioID, float volume) { } void AudioEngineImpl::setLoop(int audioID, bool loop) { - if (!_checkAudioIdValid(audioID)) { + if (!checkAudioIdValid(audioID)) { return; } auto player = _audioPlayers[audioID]; @@ -306,7 +318,7 @@ void AudioEngineImpl::setLoop(int audioID, bool loop) { } bool AudioEngineImpl::pause(int audioID) { - if (!_checkAudioIdValid(audioID)) { + if (!checkAudioIdValid(audioID)) { return false; } bool ret = true; @@ -322,7 +334,7 @@ bool AudioEngineImpl::pause(int audioID) { } bool AudioEngineImpl::resume(int audioID) { - if (!_checkAudioIdValid(audioID)) { + if (!checkAudioIdValid(audioID)) { return false; } bool ret = true; @@ -338,7 +350,7 @@ bool AudioEngineImpl::resume(int audioID) { } void AudioEngineImpl::stop(int audioID) { - if (!_checkAudioIdValid(audioID)) { + if (!checkAudioIdValid(audioID)) { return; } auto player = _audioPlayers[audioID]; @@ -348,7 +360,7 @@ void AudioEngineImpl::stop(int audioID) { // _alSourceUsed[player->_alSource] = false; // Call 'update' method to cleanup immediately since the schedule may be cancelled without any notification. - update(0.0f); + update(0.0F); } void AudioEngineImpl::stopAll() { @@ -363,19 +375,18 @@ void AudioEngineImpl::stopAll() { // } // Call 'update' method to cleanup immediately since the schedule may be cancelled without any notification. - update(0.0f); + update(0.0F); } float AudioEngineImpl::getDuration(int audioID) { - if (!_checkAudioIdValid(audioID)) { - return 0.0f; + if (!checkAudioIdValid(audioID)) { + return 0.0F; } auto player = _audioPlayers[audioID]; if (player->_ready) { return player->_audioCache->_duration; - } else { - return AudioEngine::TIME_UNKNOWN; } + return AudioEngine::TIME_UNKNOWN; } float AudioEngineImpl::getDurationFromFile(const std::string &filePath) { @@ -389,11 +400,11 @@ float AudioEngineImpl::getDurationFromFile(const std::string &filePath) { } float AudioEngineImpl::getCurrentTime(int audioID) { - if (!_checkAudioIdValid(audioID)) { - return 0.0f; + if (!checkAudioIdValid(audioID)) { + return 0.0F; } - float ret = 0.0f; - auto player = _audioPlayers[audioID]; + float ret = 0.0F; + auto player = _audioPlayers[audioID]; if (player->_ready) { if (player->_streamingSource) { ret = player->getTime(); @@ -411,10 +422,10 @@ float AudioEngineImpl::getCurrentTime(int audioID) { } bool AudioEngineImpl::setCurrentTime(int audioID, float time) { - if (!_checkAudioIdValid(audioID)) { + if (!checkAudioIdValid(audioID)) { return false; } - bool ret = false; + bool ret = false; auto player = _audioPlayers[audioID]; do { @@ -425,44 +436,45 @@ bool AudioEngineImpl::setCurrentTime(int audioID, float time) { if (player->_streamingSource) { ret = player->setTime(time); break; - } else { - if (player->_audioCache->_framesRead != player->_audioCache->_totalFrames && - (time * player->_audioCache->_sampleRate) > player->_audioCache->_framesRead) { - ALOGE("%s: audio id = %d", __FUNCTION__, audioID); - break; - } - - alSourcef(player->_alSource, AL_SEC_OFFSET, time); - - auto error = alGetError(); - if (error != AL_NO_ERROR) { - ALOGE("%s: audio id = %d, error = %x", __FUNCTION__, audioID, error); - } - ret = true; } - } while (0); + + if (player->_audioCache->_framesRead != player->_audioCache->_totalFrames && + (time * player->_audioCache->_sampleRate) > player->_audioCache->_framesRead) { + ALOGE("%s: audio id = %d", __FUNCTION__, audioID); + break; + } + + alSourcef(player->_alSource, AL_SEC_OFFSET, time); + + auto error = alGetError(); + if (error != AL_NO_ERROR) { + ALOGE("%s: audio id = %d, error = %x", __FUNCTION__, audioID, error); + } + ret = true; + + } while (false); return ret; } void AudioEngineImpl::setFinishCallback(int audioID, const std::function &callback) { - if (!_checkAudioIdValid(audioID)) { + if (!checkAudioIdValid(audioID)) { return; } _audioPlayers[audioID]->_finishCallbak = callback; } -void AudioEngineImpl::update(float dt) { - ALint sourceState; - int audioID; +void AudioEngineImpl::update(float /*dt*/) { + ALint sourceState; + int audioID; AudioPlayer *player; - ALuint alSource; + ALuint alSource; // ALOGV("AudioPlayer count: %d", (int)_audioPlayers.size()); for (auto it = _audioPlayers.begin(); it != _audioPlayers.end();) { - audioID = it->first; - player = it->second; + audioID = it->first; + player = it->second; alSource = player->_alSource; alGetSourcei(alSource, AL_SOURCE_STATE, &sourceState); @@ -474,11 +486,10 @@ void AudioEngineImpl::update(float dt) { delete player; _alSourceUsed[alSource] = false; } else if (player->_ready && sourceState == AL_STOPPED) { - std::string filePath; if (player->_finishCallbak) { - auto &audioInfo = AudioEngine::_audioIDInfoMap[audioID]; - filePath = *audioInfo.filePath; + auto &audioInfo = AudioEngine::sAudioIDInfoMap[audioID]; + filePath = *audioInfo.filePath; } AudioEngine::remove(audioID); @@ -513,6 +524,6 @@ void AudioEngineImpl::uncacheAll() { _audioCaches.clear(); } -bool AudioEngineImpl::_checkAudioIdValid(int audioID) { +bool AudioEngineImpl::checkAudioIdValid(int audioID) { return _audioPlayers.find(audioID) != _audioPlayers.end(); } diff --git a/native/cocos/audio/win32/AudioEngine-win32.h b/native/cocos/audio/oalsoft/AudioEngine-soft.h similarity index 67% rename from native/cocos/audio/win32/AudioEngine-win32.h rename to native/cocos/audio/oalsoft/AudioEngine-soft.h index cc67e2d9ce..d3b52eca92 100644 --- a/native/cocos/audio/win32/AudioEngine-win32.h +++ b/native/cocos/audio/oalsoft/AudioEngine-soft.h @@ -28,9 +28,9 @@ #include +#include "audio/oalsoft/AudioCache.h" +#include "audio/oalsoft/AudioPlayer.h" #include "base/Ref.h" -#include "audio/win32/AudioCache.h" -#include "audio/win32/AudioPlayer.h" namespace cc { @@ -41,30 +41,30 @@ class Scheduler; class CC_DLL AudioEngineImpl : public cc::Ref { public: AudioEngineImpl(); - ~AudioEngineImpl(); + ~AudioEngineImpl() override; - bool init(); - int play2d(const std::string &fileFullPath, bool loop, float volume); - void setVolume(int audioID, float volume); - void setLoop(int audioID, bool loop); - bool pause(int audioID); - bool resume(int audioID); - void stop(int audioID); - void stopAll(); + bool init(); + int play2d(const std::string &filePath, bool loop, float volume); + void setVolume(int audioID, float volume); + void setLoop(int audioID, bool loop); + bool pause(int audioID); + bool resume(int audioID); + void stop(int audioID); + void stopAll(); float getDuration(int audioID); - float getDurationFromFile(const std::string &fileFullPath); + float getDurationFromFile(const std::string &filePath); float getCurrentTime(int audioID); - bool setCurrentTime(int audioID, float time); - void setFinishCallback(int audioID, const std::function &callback); + bool setCurrentTime(int audioID, float time); + void setFinishCallback(int audioID, const std::function &callback); - void uncache(const std::string &filePath); - void uncacheAll(); - AudioCache *preload(const std::string &filePath, std::function callback); - void update(float dt); + void uncache(const std::string &filePath); + void uncacheAll(); + AudioCache *preload(const std::string &filePath, const std::function &callback); + void update(float dt); private: - bool _checkAudioIdValid(int audioID); - void _play2d(AudioCache *cache, int audioID); + bool checkAudioIdValid(int audioID); + void play2dImpl(AudioCache *cache, int audioID); ALuint _alSources[MAX_AUDIOINSTANCES]; @@ -76,11 +76,11 @@ private: //audioID,AudioInfo std::unordered_map _audioPlayers; - std::mutex _threadMutex; + std::mutex _threadMutex; bool _lazyInitLoop; - int _currentAudioID; + int _currentAudioID; std::weak_ptr _scheduler; }; } // namespace cc diff --git a/native/cocos/audio/win32/AudioMacros.h b/native/cocos/audio/oalsoft/AudioMacros.h similarity index 95% rename from native/cocos/audio/win32/AudioMacros.h rename to native/cocos/audio/oalsoft/AudioMacros.h index 1ac8704df2..97ad88c7dc 100644 --- a/native/cocos/audio/win32/AudioMacros.h +++ b/native/cocos/audio/oalsoft/AudioMacros.h @@ -26,6 +26,8 @@ #pragma once +#include "base/Log.h" + #define QUEUEBUFFER_NUM (3) #define QUEUEBUFFER_TIME_STEP (0.1f) @@ -34,7 +36,7 @@ //IDEA:Move the definition of the following macros to a separated file. -void audioLog(const char *format, ...); +#define audioLog(...) CC_LOG_DEBUG(__VA_ARGS__) #define QUOTEME_(x) #x #define QUOTEME(x) QUOTEME_(x) @@ -70,6 +72,6 @@ void audioLog(const char *format, ...); #define BREAK_IF_ERR_LOG(condition, fmt, ...) \ if (!!(condition)) { \ - ALOGE("(" QUOTEME(condition) ") failed, message: " fmt, ##__VA_ARGS__); \ + CC_LOG_DEBUG("(" QUOTEME(condition) ") failed, message: " fmt, ##__VA_ARGS__); \ break; \ } diff --git a/native/cocos/audio/win32/AudioPlayer.cpp b/native/cocos/audio/oalsoft/AudioPlayer.cpp similarity index 76% rename from native/cocos/audio/win32/AudioPlayer.cpp rename to native/cocos/audio/oalsoft/AudioPlayer.cpp index 1d47aae0d0..fbc8484307 100644 --- a/native/cocos/audio/win32/AudioPlayer.cpp +++ b/native/cocos/audio/oalsoft/AudioPlayer.cpp @@ -26,35 +26,36 @@ #define LOG_TAG "AudioPlayer" -#if CC_PLATFORM == CC_PLATFORM_WINDOWS - #include "audio/win32/AudioPlayer.h" - #include "audio/win32/AudioCache.h" - #include "platform/FileUtils.h" - #include "audio/win32/AudioDecoderManager.h" - #include "audio/win32/Audiodecoder.h" +#include "audio/oalsoft/AudioPlayer.h" +#include "audio/oalsoft/AudioCache.h" +#include "audio/oalsoft/AudioDecoder.h" +#include "audio/oalsoft/AudioDecoderManager.h" - #define VERY_VERY_VERBOSE_LOGGING - #ifdef VERY_VERY_VERBOSE_LOGGING - #define ALOGVV ALOGV - #else - #define ALOGVV(...) \ - do { \ - } while (false) - #endif +#include "base/Log.h" -using namespace cc; +using namespace cc; //NOLINT namespace { -unsigned int __idIndex = 0; +unsigned int gIdIndex = 0; } AudioPlayer::AudioPlayer() -: _audioCache(nullptr), _finishCallbak(nullptr), _isDestroyed(false), _removeByAudioEngine(false), _ready(false), _currTime(0.0f), _streamingSource(false), _rotateBufferThread(nullptr), _timeDirty(false), _isRotateThreadExited(false), _id(++__idIndex) { +: _audioCache(nullptr), + _finishCallbak(nullptr), + _isDestroyed(false), + _removeByAudioEngine(false), + _ready(false), + _currTime(0.0F), + _streamingSource(false), + _rotateBufferThread(nullptr), + _timeDirty(false), + _isRotateThreadExited(false), + _id(++gIdIndex) { memset(_bufferIds, 0, sizeof(_bufferIds)); } AudioPlayer::~AudioPlayer() { - ALOGVV("~AudioPlayer() (%p), id=%u", this, _id); + CC_LOG_DEBUG("~AudioPlayer() (%p), id=%u", this, _id); destroy(); if (_streamingSource) { @@ -63,17 +64,18 @@ AudioPlayer::~AudioPlayer() { } void AudioPlayer::destroy() { - if (_isDestroyed) + if (_isDestroyed) { return; + } - ALOGVV("AudioPlayer::destroy begin, id=%u", _id); + CC_LOG_DEBUG("AudioPlayer::destroy begin, id=%u", _id); _isDestroyed = true; do { if (_audioCache != nullptr) { if (_audioCache->_state == AudioCache::State::INITIAL) { - ALOGV("AudioPlayer::destroy, id=%u, cache isn't ready!", _id); + CC_LOG_INFO("AudioPlayer::destroy, id=%u, cache isn't ready!", _id); break; } @@ -99,22 +101,22 @@ void AudioPlayer::destroy() { delete _rotateBufferThread; _rotateBufferThread = nullptr; - ALOGVV("rotateBufferThread exited!"); + CC_LOG_DEBUG("rotateBufferThread exited!"); } } } while (false); - ALOGVV("Before alSourceStop"); + CC_LOG_DEBUG("Before alSourceStop"); alSourceStop(_alSource); CHECK_AL_ERROR_DEBUG(); - ALOGVV("Before alSourcei"); - alSourcei(_alSource, AL_BUFFER, NULL); + CC_LOG_DEBUG("Before alSourcei"); + alSourcei(_alSource, AL_BUFFER, 0); CHECK_AL_ERROR_DEBUG(); _removeByAudioEngine = true; _ready = false; - ALOGVV("AudioPlayer::destroy end, id=%u", _id); + CC_LOG_DEBUG("AudioPlayer::destroy end, id=%u", _id); } void AudioPlayer::setCache(AudioCache *cache) { @@ -123,7 +125,7 @@ void AudioPlayer::setCache(AudioCache *cache) { bool AudioPlayer::play2d() { _play2dMutex.lock(); - ALOGV("AudioPlayer::play2d, _alSource: %u, player id=%u", _alSource, _id); + CC_LOG_INFO("AudioPlayer::play2d, _alSource: %u, player id=%u", _alSource, _id); /*********************************************************************/ /* Note that it may be in sub thread or in main thread. **/ @@ -131,13 +133,13 @@ bool AudioPlayer::play2d() { bool ret = false; do { if (_audioCache->_state != AudioCache::State::READY) { - ALOGE("alBuffer isn't ready for play!"); + CC_LOG_ERROR("alBuffer isn't ready for play!"); break; } alSourcei(_alSource, AL_BUFFER, 0); CHECK_AL_ERROR_DEBUG(); - alSourcef(_alSource, AL_PITCH, 1.0f); + alSourcef(_alSource, AL_PITCH, 1.0F); CHECK_AL_ERROR_DEBUG(); alSourcef(_alSource, AL_GAIN, _volume); CHECK_AL_ERROR_DEBUG(); @@ -155,7 +157,8 @@ bool AudioPlayer::play2d() { auto alError = alGetError(); if (alError == AL_NO_ERROR) { for (int index = 0; index < QUEUEBUFFER_NUM; ++index) { - alBufferData(_bufferIds[index], _audioCache->_format, _audioCache->_queBuffers[index], _audioCache->_queBufferSize[index], _audioCache->_sampleRate); + alBufferData(_bufferIds[index], _audioCache->_format, _audioCache->_queBuffers[index], + _audioCache->_queBufferSize[index], _audioCache->_sampleRate); } CHECK_AL_ERROR_DEBUG(); } else { @@ -167,13 +170,15 @@ bool AudioPlayer::play2d() { { std::unique_lock lk(_sleepMutex); - if (_isDestroyed) + if (_isDestroyed) { break; + } if (_streamingSource) { alSourceQueueBuffers(_alSource, QUEUEBUFFER_NUM, _bufferIds); CHECK_AL_ERROR_DEBUG(); - _rotateBufferThread = new std::thread(&AudioPlayer::rotateBufferThread, this, _audioCache->_queBufferFrames * QUEUEBUFFER_NUM + 1); + _rotateBufferThread = new std::thread(&AudioPlayer::rotateBufferThread, this, + _audioCache->_queBufferFrames * QUEUEBUFFER_NUM + 1); } else { alSourcei(_alSource, AL_BUFFER, _audioCache->_alBufferId); CHECK_AL_ERROR_DEBUG(); @@ -191,12 +196,13 @@ bool AudioPlayer::play2d() { ALint state; alGetSourcei(_alSource, AL_SOURCE_STATE, &state); if (state != AL_PLAYING) { - ALOGE("state isn't playing, %d, %s, cache id=%u, player id=%u", state, _audioCache->_fileFullPath.c_str(), _audioCache->_id, _id); + ALOGE("state isn't playing, %d, %s, cache id=%u, player id=%u", state, _audioCache->_fileFullPath.c_str(), + _audioCache->_id, _id); //abort playing if the state is incorrect break; } _ready = true; - ret = true; + ret = true; } while (false); if (!ret) { @@ -208,15 +214,15 @@ bool AudioPlayer::play2d() { } void AudioPlayer::rotateBufferThread(int offsetFrame) { - char *tmpBuffer = nullptr; - AudioDecoder *decoder = AudioDecoderManager::createDecoder(_audioCache->_fileFullPath.c_str()); + char * tmpBuffer = nullptr; + AudioDecoder *decoder = AudioDecoderManager::createDecoder(_audioCache->_fileFullPath.c_str()); do { BREAK_IF(decoder == nullptr || !decoder->open(_audioCache->_fileFullPath.c_str())); - uint32_t framesRead = 0; + uint32_t framesRead = 0; const uint32_t framesToRead = _audioCache->_queBufferFrames; - const uint32_t bufferSize = framesToRead * decoder->getBytesPerFrame(); - tmpBuffer = (char *)malloc(bufferSize); + const uint32_t bufferSize = framesToRead * decoder->getBytesPerFrame(); + tmpBuffer = static_cast(malloc(bufferSize)); memset(tmpBuffer, 0, bufferSize); if (offsetFrame != 0) { @@ -224,8 +230,8 @@ void AudioPlayer::rotateBufferThread(int offsetFrame) { } ALint sourceState; - ALint bufferProcessed = 0; - bool needToExitThread = false; + ALint bufferProcessed = 0; + bool needToExitThread = false; while (!_isDestroyed) { alGetSourcei(_alSource, AL_SOURCE_STATE, &sourceState); @@ -234,14 +240,14 @@ void AudioPlayer::rotateBufferThread(int offsetFrame) { while (bufferProcessed > 0) { bufferProcessed--; if (_timeDirty) { - _timeDirty = false; + _timeDirty = false; offsetFrame = static_cast(_currTime * decoder->getSampleRate()); decoder->seek(offsetFrame); } else { _currTime += QUEUEBUFFER_TIME_STEP; if (_currTime > _audioCache->_duration) { if (_loop) { - _currTime = 0.0f; + _currTime = 0.0F; } else { _currTime = _audioCache->_duration; } @@ -262,7 +268,8 @@ void AudioPlayer::rotateBufferThread(int offsetFrame) { ALuint bid; alSourceUnqueueBuffers(_alSource, 1, &bid); - alBufferData(bid, _audioCache->_format, tmpBuffer, framesRead * decoder->getBytesPerFrame(), decoder->getSampleRate()); + alBufferData(bid, _audioCache->_format, tmpBuffer, framesRead * decoder->getBytesPerFrame(), + decoder->getSampleRate()); alSourceQueueBuffers(_alSource, 1, &bid); } } @@ -277,14 +284,14 @@ void AudioPlayer::rotateBufferThread(int offsetFrame) { } while (false); - ALOGV("Exit rotate buffer thread ..."); + CC_LOG_INFO("Exit rotate buffer thread ..."); if (decoder != nullptr) { decoder->close(); } AudioDecoderManager::destroyDecoder(decoder); free(tmpBuffer); _isRotateThreadExited = true; - ALOGV("%s exited.\n", __FUNCTION__); + CC_LOG_INFO("%s exited.\n", __FUNCTION__); } bool AudioPlayer::setLoop(bool loop) { @@ -297,14 +304,11 @@ bool AudioPlayer::setLoop(bool loop) { } bool AudioPlayer::setTime(float time) { - if (!_isDestroyed && time >= 0.0f && time < _audioCache->_duration) { - - _currTime = time; + if (!_isDestroyed && time >= 0.0F && time < _audioCache->_duration) { + _currTime = time; _timeDirty = true; return true; } return false; } - -#endif diff --git a/native/cocos/audio/win32/AudioPlayer.h b/native/cocos/audio/oalsoft/AudioPlayer.h similarity index 96% rename from native/cocos/audio/win32/AudioPlayer.h rename to native/cocos/audio/oalsoft/AudioPlayer.h index b2e438c6f4..d9fbddf720 100644 --- a/native/cocos/audio/win32/AudioPlayer.h +++ b/native/cocos/audio/oalsoft/AudioPlayer.h @@ -26,15 +26,17 @@ #pragma once -#include #include -#include -#include #include +#include +#include +#include #ifdef OPENAL_PLAIN_INCLUDES #include -#else +#elif CC_PLATFORM == CC_PLATFORM_WINDOWS #include +#elif CC_PLATFORM == CC_PLATFORM_OHOS + #include #endif #include "base/Macros.h" diff --git a/native/cocos/audio/ohos/AudioDecoderWav.cpp b/native/cocos/audio/ohos/AudioDecoderWav.cpp new file mode 100644 index 0000000000..49c9ffc9a4 --- /dev/null +++ b/native/cocos/audio/ohos/AudioDecoderWav.cpp @@ -0,0 +1,87 @@ +/**************************************************************************** +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 "AudioDecoderWav" + +#include "audio/ohos/AudioDecoderWav.h" +#include "audio/ohos/FsCallback.h" +#include "base/Log.h" + +namespace { +snd_callbacks wavCallbacks = { + .open = cc::ohosOpen, + .read = cc::ohosRead, + .seek = cc::ohosSeek, + .close = cc::ohosClose, + .tell = cc::ohosTell, +}; +} + +namespace cc { + +AudioDecoderWav::AudioDecoderWav() { + CC_LOG_DEBUG("Create AudioDecoderWav"); +} + +AudioDecoderWav::~AudioDecoderWav() { + close(); +} + +bool AudioDecoderWav::open(const char *path) { + _sndHandle = sf_open_read(path, &_sndInfo, &wavCallbacks, this); + _isOpened = (_sndHandle != nullptr) && _sndInfo.frames > 0; + if (!_isOpened) return false; + + _channelCount = _sndInfo.channels; + _sampleRate = _sndInfo.samplerate; + _bytesPerFrame = 2 * _channelCount; // short + _totalFrames = _sndInfo.frames; + return true; +} + +void AudioDecoderWav::close() { + if (_sndHandle) { + sf_close(_sndHandle); + _sndHandle = nullptr; + } + _isOpened = false; +} + +uint32_t AudioDecoderWav::read(uint32_t framesToRead, char *pcmBuf) { + auto *output = reinterpret_cast(pcmBuf); + auto actualFrames = sf_readf_short(_sndHandle, output, framesToRead); + return actualFrames / _bytesPerFrame; +} + +bool AudioDecoderWav::seek(uint32_t frameOffset) { + off_t offset = sf_seek(_sndHandle, frameOffset, SEEK_SET); + return offset >= 0 && offset == frameOffset; +} + +uint32_t AudioDecoderWav::tell() const { + return sf_tell(_sndHandle); +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/audio/ohos/AudioDecoderWav.h b/native/cocos/audio/ohos/AudioDecoderWav.h new file mode 100644 index 0000000000..0492b508d2 --- /dev/null +++ b/native/cocos/audio/ohos/AudioDecoderWav.h @@ -0,0 +1,49 @@ +/**************************************************************************** +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 "audio/android/tinysndfile.h" +#include "audio/oalsoft/AudioDecoder.h" + +namespace cc { + +class AudioDecoderWav : public AudioDecoder { +public: + AudioDecoderWav(); + ~AudioDecoderWav() override; + + bool open(const char *path) override; + void close() override; + uint32_t read(uint32_t framesToRead, char *pcmBuf) override; + bool seek(uint32_t frameOffset) override; + uint32_t tell() const override; + +private: + SF_INFO _sndInfo; + SNDFILE *_sndHandle{}; +}; + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/audio/ohos/FsCallback.cpp b/native/cocos/audio/ohos/FsCallback.cpp new file mode 100644 index 0000000000..b6759bc120 --- /dev/null +++ b/native/cocos/audio/ohos/FsCallback.cpp @@ -0,0 +1,73 @@ +#include "cocos/audio/ohos/FsCallback.h" + +#include +#include +#include "cocos/platform/ohos/FileUtils-ohos.h" + +namespace { +inline cc::FileUtilsOHOS *getFU() { + return static_cast(cc::FileUtils::getInstance()); +} + +struct FatFd { + union { + FILE * fp; + RawFile *rf; + } file; + void *user; + bool isRawFile; +}; +} // namespace + +namespace cc { +void *ohosOpen(const char *path, void *user) { + bool isRawfile = false; + const auto newPath = getFU()->expandPath(path, &isRawfile); + auto * ret = new FatFd(); + if (isRawfile) { + ret->file.rf = OpenRawFile(cc::FileUtilsOHOS::getResourceManager(), newPath.c_str()); + } else { + ret->file.fp = fopen(newPath.c_str(), "rb"); + } + ret->user = user; + ret->isRawFile = isRawfile; + return ret; +} + +size_t ohosRead(void *ptr, size_t size, size_t nmemb, void *datasource) { + auto *fatFd = static_cast(datasource); + if (fatFd->isRawFile) { + return ReadRawFile(fatFd->file.rf, ptr, size * nmemb) / size; + } + return fread(ptr, size, nmemb, fatFd->file.fp); +} + +int ohosSeek(void *datasource, long offset, int whence) { //NOLINT(google-runtime-int) + auto *fatFd = static_cast(datasource); + if (fatFd->isRawFile) { + return SeekRawFile(fatFd->file.rf, offset, whence); + } + return fseek(fatFd->file.fp, offset, whence); +} + +int ohosClose(void *datasource) { + auto *fatFd = static_cast(datasource); + int code = 0; + if (fatFd->isRawFile) { + CloseRawFile(fatFd->file.rf); + code = 0; + } else { + code = fclose(fatFd->file.fp); + } + delete fatFd; + return code; +} + +long ohosTell(void *datasource) { //NOLINT(google-runtime-int) + auto *fatFd = static_cast(datasource); + if (fatFd->isRawFile) { + return GetRawFileOffset(fatFd->file.rf); + } + return ftell(fatFd->file.fp); +} +} // namespace cc \ No newline at end of file diff --git a/native/cocos/audio/ohos/FsCallback.h b/native/cocos/audio/ohos/FsCallback.h new file mode 100644 index 0000000000..f0d8a9ec6c --- /dev/null +++ b/native/cocos/audio/ohos/FsCallback.h @@ -0,0 +1,16 @@ +#pragma once + +#include + +namespace cc { +void *ohosOpen(const char *path, void *user); + +size_t ohosRead(void *ptr, size_t size, size_t nmemb, void *datasource); + +int ohosSeek(void *datasource, long offset, int whence); //NOLINT(google-runtime-int) + +int ohosClose(void *datasource); + +long ohosTell(void *datasource); //NOLINT(google-runtime-int) + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/base/Data.cpp b/native/cocos/base/Data.cpp index 601f1915b2..3e1d3c109e 100644 --- a/native/cocos/base/Data.cpp +++ b/native/cocos/base/Data.cpp @@ -56,7 +56,9 @@ Data::~Data() { Data &Data::operator=(const Data &other) { // CC_LOG_INFO("In the copy assignment of Data."); - copy(other._bytes, other._size); + if (this != &other) { + copy(other._bytes, other._size); + } return *this; } @@ -93,7 +95,7 @@ void Data::copy(const unsigned char *bytes, ssize_t size) { if (size > 0) { _size = size; - _bytes = (unsigned char *)malloc(sizeof(unsigned char) * _size); + _bytes = static_cast(malloc(sizeof(unsigned char) * _size)); memcpy(_bytes, bytes, _size); } } @@ -104,6 +106,15 @@ void Data::fastSet(unsigned char *bytes, ssize_t size) { _size = size; } +void Data::resize(ssize_t size) { + assert(size); + if (_size == size) { + return; + } + _size = size; + _bytes = static_cast(realloc(_bytes, sizeof(unsigned char) * _size)); +} + void Data::clear() { free(_bytes); _bytes = nullptr; diff --git a/native/cocos/base/Data.h b/native/cocos/base/Data.h index f395aae3ac..e345e62939 100644 --- a/native/cocos/base/Data.h +++ b/native/cocos/base/Data.h @@ -27,9 +27,9 @@ #pragma once -#include "base/Macros.h" #include // for ssize_t on android #include // for ssize_t on linux +#include "base/Macros.h" /** * @addtogroup base @@ -107,6 +107,8 @@ public: */ void fastSet(unsigned char *bytes, ssize_t size); + void resize(ssize_t size); + /** * Clears data, free buffer and reset data size. */ @@ -142,7 +144,7 @@ public: unsigned char *takeBuffer(ssize_t *size = nullptr); private: - void move(Data &other); + void move(Data &other); //NOLINT private: unsigned char *_bytes; diff --git a/native/cocos/base/Log.cpp b/native/cocos/base/Log.cpp index c99f20bb16..5ce48b3aff 100755 --- a/native/cocos/base/Log.cpp +++ b/native/cocos/base/Log.cpp @@ -47,29 +47,31 @@ #elif (CC_PLATFORM == CC_PLATFORM_ANDROID) #include +#elif CC_PLATFORM == CC_PLATFORM_OHOS + #include #endif namespace cc { #define LOG_USE_TIMESTAMP #if (CC_DEBUG == 1) -LogLevel Log::_logLevel = LogLevel::LEVEL_DEBUG; +LogLevel Log::slogLevel = LogLevel::LEVEL_DEBUG; #else -LogLevel Log::_logLevel = LogLevel::INFO; +LogLevel Log::slogLevel = LogLevel::INFO; #endif -FILE * Log::_logFile = nullptr; +FILE * Log::slogFile = nullptr; const std::vector LOG_LEVEL_DESCS{"FATAL", "ERROR", "WARN", "INFO", "DEBUG"}; void Log::setLogFile(const std::string &filename) { #if (CC_PLATFORM == CC_PLATFORM_WINDOWS) - if (_logFile) { - fclose(_logFile); + if (slogFile) { + fclose(slogFile); } - _logFile = fopen(filename.c_str(), "w"); + slogFile = fopen(filename.c_str(), "w"); - if (_logFile) { + if (slogFile) { String msg; msg += "------------------------------------------------------\n"; @@ -88,16 +90,16 @@ void Log::setLogFile(const std::string &filename) { msg += "------------------------------------------------------\n"; - fputs(msg.c_str(), _logFile); - fflush(_logFile); + fputs(msg.c_str(), slogFile); + fflush(slogFile); } #endif } void Log::close() { - if (_logFile) { - fclose(_logFile); - _logFile = nullptr; + if (slogFile) { + fclose(slogFile); + slogFile = nullptr; } } @@ -121,8 +123,8 @@ void Log::logMessage(LogType type, LogLevel level, const char *formats, ...) { va_start(args, formats); // p += StringUtil::vprintf(p, last, formats, args); - int count = (int)(last - p); - int ret = vsnprintf(p, count, formats, args); + ptrdiff_t count = (last - p); + int ret = vsnprintf(p, count, formats, args); if (ret >= count - 1) { p += (count - 1); } else if (ret >= 0) { @@ -134,9 +136,9 @@ void Log::logMessage(LogType type, LogLevel level, const char *formats, ...) { *p++ = '\n'; *p = 0; - if (_logFile) { - fputs(buff, _logFile); - fflush(_logFile); + if (slogFile) { + fputs(buff, slogFile); + fflush(slogFile); } #if (CC_PLATFORM == CC_PLATFORM_WINDOWS) @@ -169,6 +171,27 @@ void Log::logMessage(LogType type, LogLevel level, const char *formats, ...) { } __android_log_write(priority, (type == LogType::KERNEL ? "Cocos" : "CocosScript"), buff); +#elif (CC_PLATFORM == CC_PLATFORM_OHOS) + const char *typeStr = (type == LogType::KERNEL ? "Cocos %{public}s" : "CocosScript %{public}s"); + switch (level) { + case LogLevel::LEVEL_DEBUG: + HILOG_DEBUG(LOG_APP, typeStr, (const char *)buff); + break; + case LogLevel::INFO: + HILOG_INFO(LOG_APP, typeStr, buff); + break; + case LogLevel::WARN: + HILOG_WARN(LOG_APP, typeStr, buff); + break; + case LogLevel::ERR: + HILOG_ERROR(LOG_APP, typeStr, buff); + break; + case LogLevel::FATAL: + HILOG_FATAL(LOG_APP, typeStr, buff); + break; + default: + HILOG_DEBUG(LOG_APP, typeStr, buff); + } #else fputs(buff, stdout); #endif diff --git a/native/cocos/base/Log.h b/native/cocos/base/Log.h index b807529b20..6e45be6da0 100755 --- a/native/cocos/base/Log.h +++ b/native/cocos/base/Log.h @@ -25,8 +25,8 @@ #pragma once -#include "Macros.h" #include +#include "Macros.h" namespace cc { @@ -47,30 +47,30 @@ enum class LogLevel { class CC_DLL Log { public: - static LogLevel _logLevel; // for read only + static LogLevel slogLevel; // for read only - static CC_INLINE void setLogLevel(LogLevel level) { _logLevel = level; } - static CC_INLINE FILE *getLogFile() { return _logFile; } + static CC_INLINE void setLogLevel(LogLevel level) { slogLevel = level; } + static CC_INLINE FILE *getLogFile() { return slogFile; } static void setLogFile(const std::string &filename); static void close(); static void logMessage(LogType type, LogLevel level, const char *formats, ...); private: - static FILE *_logFile; + static FILE *slogFile; }; } // namespace cc #define CC_LOG_DEBUG(formats, ...) \ - if (cc::Log::_logLevel >= cc::LogLevel::LEVEL_DEBUG) cc::Log::logMessage(cc::LogType::KERNEL, cc::LogLevel::LEVEL_DEBUG, formats, ##__VA_ARGS__) + if (cc::Log::slogLevel >= cc::LogLevel::LEVEL_DEBUG) cc::Log::logMessage(cc::LogType::KERNEL, cc::LogLevel::LEVEL_DEBUG, formats, ##__VA_ARGS__) #define CC_LOG_INFO(formats, ...) \ - if (cc::Log::_logLevel >= cc::LogLevel::INFO) cc::Log::logMessage(cc::LogType::KERNEL, cc::LogLevel::INFO, formats, ##__VA_ARGS__) + if (cc::Log::slogLevel >= cc::LogLevel::INFO) cc::Log::logMessage(cc::LogType::KERNEL, cc::LogLevel::INFO, formats, ##__VA_ARGS__) #define CC_LOG_WARNING(formats, ...) \ - if (cc::Log::_logLevel >= cc::LogLevel::WARN) cc::Log::logMessage(cc::LogType::KERNEL, cc::LogLevel::WARN, formats, ##__VA_ARGS__) + if (cc::Log::slogLevel >= cc::LogLevel::WARN) cc::Log::logMessage(cc::LogType::KERNEL, cc::LogLevel::WARN, formats, ##__VA_ARGS__) #define DO_CC_LOG_ERROR(formats, ...) \ - if (cc::Log::_logLevel >= cc::LogLevel::ERR) cc::Log::logMessage(cc::LogType::KERNEL, cc::LogLevel::ERR, formats, ##__VA_ARGS__) + if (cc::Log::slogLevel >= cc::LogLevel::ERR) cc::Log::logMessage(cc::LogType::KERNEL, cc::LogLevel::ERR, formats, ##__VA_ARGS__) #define CC_LOG_FATAL(formats, ...) \ - if (cc::Log::_logLevel >= cc::LogLevel::FATAL) cc::Log::logMessage(cc::LogType::KERNEL, cc::LogLevel::FATAL, formats, ##__VA_ARGS__) + if (cc::Log::slogLevel >= cc::LogLevel::FATAL) cc::Log::logMessage(cc::LogType::KERNEL, cc::LogLevel::FATAL, formats, ##__VA_ARGS__) #define CC_LOG_ERROR(formats, ...) \ do { \ diff --git a/native/cocos/base/Macros.h b/native/cocos/base/Macros.h index 3a29228986..b50c9ffb89 100644 --- a/native/cocos/base/Macros.h +++ b/native/cocos/base/Macros.h @@ -52,6 +52,14 @@ typedef SSIZE_T ssize_t; "%s function:%s line:%d", \ __FILE__, __FUNCTION__, __LINE__); \ } +#elif (CC_PLATFORM == CC_PLATFORM_OHOS) + #include + #define CC_ASSERT(cond) \ + if (!(cond)) { \ + HILOG_ERROR(LOG_APP, \ + "assert %{public}s function:%{public}s line:%{public}d", \ + __FILE__, __FUNCTION__, __LINE__); \ + } #else #include #define CC_ASSERT(cond) assert(cond) diff --git a/native/cocos/base/StringUtil.h b/native/cocos/base/StringUtil.h index 7a559d1a0b..3fd93531c4 100755 --- a/native/cocos/base/StringUtil.h +++ b/native/cocos/base/StringUtil.h @@ -33,9 +33,9 @@ namespace cc { class CC_DLL StringUtil { public: - static int vprintf(char *buf, const char *last, const char *fmt, va_list args); - static int printf(char *buf, const char *last, const char *fmt, ...); - static String format(const char *fmt, ...); + static int vprintf(char *buf, const char *last, const char *fmt, va_list args); + static int printf(char *buf, const char *last, const char *fmt, ...); + static String format(const char *fmt, ...); static StringArray split(const String &str, const String &delims, uint maxSplits = 0); }; diff --git a/native/cocos/base/UTF8.cpp b/native/cocos/base/UTF8.cpp index 6606b25b7b..7a22549b01 100644 --- a/native/cocos/base/UTF8.cpp +++ b/native/cocos/base/UTF8.cpp @@ -35,7 +35,7 @@ namespace cc { -namespace StringUtils { +namespace StringUtils { //NOLINT std::string format(const char *format, ...) { #define CC_MAX_STRING_LENGTH (1024 * 100) @@ -45,7 +45,7 @@ std::string format(const char *format, ...) { va_list ap; va_start(ap, format); - char *buf = (char *)malloc(CC_MAX_STRING_LENGTH); + char *buf = static_cast(malloc(CC_MAX_STRING_LENGTH)); if (buf != nullptr) { vsnprintf(buf, CC_MAX_STRING_LENGTH, format, ap); ret = buf; @@ -83,7 +83,7 @@ unsigned int getIndexOfLastNotChar16(const std::vector &str, char16_t * * Return value: the trimmed string. * */ -static void trimUTF16VectorFromIndex(std::vector &str, int index) { +static void trimUTF16VectorFromIndex(std::vector &str, int index) { //NOLINT int size = static_cast(str.size()); if (index >= size || index < 0) { return; @@ -171,7 +171,7 @@ bool utfConvert( } // See: http://unicode.org/faq/utf_bom.html#gen6 - static const int mostBytesPerCharacter = 4; + constexpr int mostBytesPerCharacter = 4; const size_t maxNumberOfChars = from.length(); // all UTFs at most one element represents one character. const size_t numberOfOut = maxNumberOfChars * mostBytesPerCharacter / sizeof(To); @@ -194,9 +194,9 @@ bool utfConvert( return true; }; -CC_DLL void UTF8LooseFix(const std::string &in, std::string &out) { - const UTF8 *p = (const UTF8 *)in.c_str(); - const UTF8 *end = (const UTF8 *)(in.c_str() + in.size()); +CC_DLL void UTF8LooseFix(const std::string &in, std::string &out) { //NOLINT + const auto *p = reinterpret_cast(in.c_str()); + const auto *end = reinterpret_cast(in.c_str() + in.size()); unsigned ucharLen = 0; while (p < end) { ucharLen = getNumBytesForUTF8(*p); @@ -211,36 +211,36 @@ CC_DLL void UTF8LooseFix(const std::string &in, std::string &out) { } } -bool UTF8ToUTF16(const std::string &utf8, std::u16string &outUtf16) { +bool UTF8ToUTF16(const std::string &utf8, std::u16string &outUtf16) { //NOLINT return utfConvert(utf8, outUtf16, ConvertUTF8toUTF16); } -bool UTF8ToUTF32(const std::string &utf8, std::u32string &outUtf32) { +bool UTF8ToUTF32(const std::string &utf8, std::u32string &outUtf32) { //NOLINT return utfConvert(utf8, outUtf32, ConvertUTF8toUTF32); } -bool UTF16ToUTF8(const std::u16string &utf16, std::string &outUtf8) { +bool UTF16ToUTF8(const std::u16string &utf16, std::string &outUtf8) { //NOLINT return utfConvert(utf16, outUtf8, ConvertUTF16toUTF8); } -bool UTF16ToUTF32(const std::u16string &utf16, std::u32string &outUtf32) { +bool UTF16ToUTF32(const std::u16string &utf16, std::u32string &outUtf32) { //NOLINT return utfConvert(utf16, outUtf32, ConvertUTF16toUTF32); } -bool UTF32ToUTF8(const std::u32string &utf32, std::string &outUtf8) { +bool UTF32ToUTF8(const std::u32string &utf32, std::string &outUtf8) { //NOLINT return utfConvert(utf32, outUtf8, ConvertUTF32toUTF8); } -bool UTF32ToUTF16(const std::u32string &utf32, std::u16string &outUtf16) { +bool UTF32ToUTF16(const std::u32string &utf32, std::u16string &outUtf16) { //NOLINT return utfConvert(utf32, outUtf16, ConvertUTF32toUTF16); } -#if (CC_PLATFORM == CC_PLATFORM_ANDROID) +#if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) std::string getStringUTFCharsJNI(JNIEnv *env, jstring srcjStr, bool *ret) { std::string utf8Str; - auto * unicodeChar = static_cast(env->GetStringChars(srcjStr, nullptr)); + auto * unicodeChar = static_cast(env->GetStringChars(srcjStr, nullptr)); size_t unicodeCharLength = env->GetStringLength(srcjStr); - const std::u16string unicodeStr((const char16_t *)unicodeChar, unicodeCharLength); + const std::u16string unicodeStr(reinterpret_cast(unicodeChar), unicodeCharLength); bool flag = UTF16ToUTF8(unicodeStr, utf8Str); if (ret) { @@ -265,7 +265,7 @@ jstring newStringUTFJNI(JNIEnv *env, const std::string &utf8Str, bool *ret) { if (!flag) { utf16Str.clear(); } - jstring stringText = env->NewString((const jchar *)utf16Str.data(), utf16Str.length()); + jstring stringText = env->NewString(reinterpret_cast(utf16Str.data()), utf16Str.length()); return stringText; } #endif @@ -274,8 +274,8 @@ std::vector getChar16VectorFromUTF16String(const std::u16string &utf16 return std::vector(utf16.begin(), utf16.end()); } -long getCharacterCountInUTF8String(const std::string &utf8) { - return getUTF8StringLength((const UTF8 *)utf8.c_str()); +long getCharacterCountInUTF8String(const std::string &utf8) { //NOLINT + return getUTF8StringLength(reinterpret_cast(utf8.c_str())); } StringUTF8::StringUTF8(const std::string &newStr) { @@ -289,7 +289,7 @@ std::size_t StringUTF8::length() const { void StringUTF8::replace(const std::string &newStr) { _str.clear(); if (!newStr.empty()) { - UTF8 *sequenceUtf8 = (UTF8 *)newStr.c_str(); + const auto *sequenceUtf8 = reinterpret_cast(newStr.c_str()); int lengthString = getUTF8StringLength(sequenceUtf8); @@ -302,7 +302,7 @@ void StringUTF8::replace(const std::string &newStr) { std::size_t lengthChar = getNumBytesForUTF8(*sequenceUtf8); CharUTF8 charUTF8; - charUTF8._char.append((char *)sequenceUtf8, lengthChar); + charUTF8._char.append(reinterpret_cast(sequenceUtf8), lengthChar); sequenceUtf8 += lengthChar; _str.push_back(charUTF8); diff --git a/native/cocos/base/UTF8.h b/native/cocos/base/UTF8.h index a75d866118..38fe82ddea 100644 --- a/native/cocos/base/UTF8.h +++ b/native/cocos/base/UTF8.h @@ -27,18 +27,18 @@ #pragma once -#include "base/Macros.h" #include #include #include +#include "base/Macros.h" -#if (CC_PLATFORM == CC_PLATFORM_ANDROID) - #include "platform/android/jni/JniHelper.h" +#if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) + #include "platform/java/jni/JniHelper.h" #endif namespace cc { -namespace StringUtils { +namespace StringUtils { //NOLINT template std::string toString(T arg) { @@ -69,49 +69,49 @@ std::string CC_DLL format(const char *format, ...) CC_FORMAT_PRINTF(1, 2); * } * @endcode */ -CC_DLL bool UTF8ToUTF16(const std::string &inUtf8, std::u16string &outUtf16); +CC_DLL bool UTF8ToUTF16(const std::string &inUtf8, std::u16string &outUtf16); //NOLINT /** * @brief Same as \a UTF8ToUTF16 but converts form UTF8 to UTF32. * * @see UTF8ToUTF16 */ -CC_DLL bool UTF8ToUTF32(const std::string &inUtf8, std::u32string &outUtf32); +CC_DLL bool UTF8ToUTF32(const std::string &inUtf8, std::u32string &outUtf32); //NOLINT /** * @brief Same as \a UTF8ToUTF16 but converts form UTF16 to UTF8. * * @see UTF8ToUTF16 */ -CC_DLL bool UTF16ToUTF8(const std::u16string &inUtf16, std::string &outUtf8); +CC_DLL bool UTF16ToUTF8(const std::u16string &inUtf16, std::string &outUtf8); //NOLINT /** * @brief Same as \a UTF8ToUTF16 but converts form UTF16 to UTF32. * * @see UTF8ToUTF16 */ -CC_DLL bool UTF16ToUTF32(const std::u16string &inUtf16, std::u32string &outUtf32); +CC_DLL bool UTF16ToUTF32(const std::u16string &inUtf16, std::u32string &outUtf32); //NOLINT /** * @brief Same as \a UTF8ToUTF16 but converts form UTF32 to UTF8. * * @see UTF8ToUTF16 */ -CC_DLL bool UTF32ToUTF8(const std::u32string &inUtf32, std::string &outUtf8); +CC_DLL bool UTF32ToUTF8(const std::u32string &inUtf32, std::string &outUtf8); //NOLINT /** * @brief Same as \a UTF8ToUTF16 but converts form UTF32 to UTF16. * * @see UTF8ToUTF16 */ -CC_DLL bool UTF32ToUTF16(const std::u32string &inUtf32, std::u16string &outUtf16); +CC_DLL bool UTF32ToUTF16(const std::u32string &inUtf32, std::u16string &outUtf16); //NOLINT /** * @brief Skip some bad char code. */ -CC_DLL void UTF8LooseFix(const std::string &in, std::string &out); +CC_DLL void UTF8LooseFix(const std::string &in, std::string &out); //NOLINT -#if (CC_PLATFORM == CC_PLATFORM_ANDROID) +#if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) /** * @brief convert jstring to utf8 std::string, same function with env->getStringUTFChars. @@ -137,7 +137,7 @@ CC_DLL jstring newStringUTFJNI(JNIEnv *env, const std::string &utf8Str, bool *re /** * @brief Trims the unicode spaces at the end of char16_t vector. */ -CC_DLL void trimUTF16Vector(std::vector &str); +CC_DLL void trimUTF16Vector(std::vector &str); //NOLINT /** * @brief Whether the character is a whitespace character. @@ -165,7 +165,7 @@ CC_DLL bool isCJKUnicode(char16_t ch); * @param utf8 An UTF-8 encoded string. * @returns The length of the string in characters. */ -CC_DLL long getCharacterCountInUTF8String(const std::string &utf8); +CC_DLL long getCharacterCountInUTF8String(const std::string &utf8); //NOLINT /** * @brief Gets the index of the last character that is not equal to the character given. diff --git a/native/cocos/base/Utils.h b/native/cocos/base/Utils.h index 1f1c68e724..5a832c8354 100644 --- a/native/cocos/base/Utils.h +++ b/native/cocos/base/Utils.h @@ -27,10 +27,14 @@ #pragma once -#include "base/Macros.h" -#include "base/TypeDef.h" +#include #include #include +#include "base/Macros.h" +#include "base/TypeDef.h" +/** @file ccUtils.h +Misc free functions +*/ namespace cc { namespace utils { diff --git a/native/cocos/bindings/auto/jsb_webview_auto.cpp b/native/cocos/bindings/auto/jsb_webview_auto.cpp index b09c0a65af..c452166aa6 100644 --- a/native/cocos/bindings/auto/jsb_webview_auto.cpp +++ b/native/cocos/bindings/auto/jsb_webview_auto.cpp @@ -24,28 +24,27 @@ ****************************************************************************/ #include "cocos/bindings/auto/jsb_webview_auto.h" -#if (USE_WEBVIEW > 0) && (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_MAC_IOS) -#include "cocos/bindings/manual/jsb_conversions.h" -#include "cocos/bindings/manual/jsb_global.h" -#include "ui/webview/WebView.h" +#if USE_WEBVIEW > 0 + #include "cocos/bindings/manual/jsb_conversions.h" + #include "cocos/bindings/manual/jsb_global.h" + #include "ui/webview/WebView.h" -#ifndef JSB_ALLOC -#define JSB_ALLOC(kls, ...) new (std::nothrow) kls(__VA_ARGS__) -#endif + #ifndef JSB_ALLOC + #define JSB_ALLOC(kls, ...) new (std::nothrow) kls(__VA_ARGS__) + #endif -#ifndef JSB_FREE -#define JSB_FREE(ptr) delete ptr -#endif + #ifndef JSB_FREE + #define JSB_FREE(ptr) delete ptr + #endif se::Object* __jsb_cc_WebView_proto = nullptr; -se::Class* __jsb_cc_WebView_class = nullptr; +se::Class* __jsb_cc_WebView_class = nullptr; -static bool js_webview_WebView_canGoBack(se::State& s) -{ +static bool js_webview_WebView_canGoBack(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_canGoBack : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { bool result = cobj->canGoBack(); ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); @@ -58,13 +57,12 @@ static bool js_webview_WebView_canGoBack(se::State& s) } SE_BIND_FUNC(js_webview_WebView_canGoBack) -static bool js_webview_WebView_canGoForward(se::State& s) -{ +static bool js_webview_WebView_canGoForward(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_canGoForward : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { bool result = cobj->canGoForward(); ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); @@ -77,13 +75,12 @@ static bool js_webview_WebView_canGoForward(se::State& s) } SE_BIND_FUNC(js_webview_WebView_canGoForward) -static bool js_webview_WebView_evaluateJS(se::State& s) -{ +static bool js_webview_WebView_evaluateJS(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_evaluateJS : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { HolderType arg0 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); @@ -96,13 +93,12 @@ static bool js_webview_WebView_evaluateJS(se::State& s) } SE_BIND_FUNC(js_webview_WebView_evaluateJS) -static bool js_webview_WebView_getOnDidFailLoading(se::State& s) -{ +static bool js_webview_WebView_getOnDidFailLoading(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_getOnDidFailLoading : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { cc::WebView::ccWebViewCallback result = cobj->getOnDidFailLoading(); ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); @@ -115,13 +111,12 @@ static bool js_webview_WebView_getOnDidFailLoading(se::State& s) } SE_BIND_FUNC(js_webview_WebView_getOnDidFailLoading) -static bool js_webview_WebView_getOnDidFinishLoading(se::State& s) -{ +static bool js_webview_WebView_getOnDidFinishLoading(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_getOnDidFinishLoading : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { cc::WebView::ccWebViewCallback result = cobj->getOnDidFinishLoading(); ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); @@ -134,13 +129,12 @@ static bool js_webview_WebView_getOnDidFinishLoading(se::State& s) } SE_BIND_FUNC(js_webview_WebView_getOnDidFinishLoading) -static bool js_webview_WebView_getOnJSCallback(se::State& s) -{ +static bool js_webview_WebView_getOnJSCallback(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_getOnJSCallback : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { cc::WebView::ccWebViewCallback result = cobj->getOnJSCallback(); ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); @@ -153,15 +147,14 @@ static bool js_webview_WebView_getOnJSCallback(se::State& s) } SE_BIND_FUNC(js_webview_WebView_getOnJSCallback) -static bool js_webview_WebView_getOnShouldStartLoading(se::State& s) -{ +static bool js_webview_WebView_getOnShouldStartLoading(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_getOnShouldStartLoading : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { - std::function result = cobj->getOnShouldStartLoading(); + std::function result = cobj->getOnShouldStartLoading(); ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/); SE_PRECONDITION2(ok, false, "js_webview_WebView_getOnShouldStartLoading : Error processing arguments"); SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); @@ -172,12 +165,11 @@ static bool js_webview_WebView_getOnShouldStartLoading(se::State& s) } SE_BIND_FUNC(js_webview_WebView_getOnShouldStartLoading) -static bool js_webview_WebView_goBack(se::State& s) -{ +static bool js_webview_WebView_goBack(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_goBack : Invalid Native Object"); const auto& args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 0) { cobj->goBack(); return true; @@ -187,12 +179,11 @@ static bool js_webview_WebView_goBack(se::State& s) } SE_BIND_FUNC(js_webview_WebView_goBack) -static bool js_webview_WebView_goForward(se::State& s) -{ +static bool js_webview_WebView_goForward(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_goForward : Invalid Native Object"); const auto& args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 0) { cobj->goForward(); return true; @@ -202,15 +193,14 @@ static bool js_webview_WebView_goForward(se::State& s) } SE_BIND_FUNC(js_webview_WebView_goForward) -static bool js_webview_WebView_loadData(se::State& s) -{ +static bool js_webview_WebView_loadData(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_loadData : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 4) { - HolderType arg0 = {}; + HolderType arg0 = {}; HolderType arg1 = {}; HolderType arg2 = {}; HolderType arg3 = {}; @@ -227,13 +217,12 @@ static bool js_webview_WebView_loadData(se::State& s) } SE_BIND_FUNC(js_webview_WebView_loadData) -static bool js_webview_WebView_loadFile(se::State& s) -{ +static bool js_webview_WebView_loadFile(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_loadFile : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { HolderType arg0 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); @@ -246,13 +235,12 @@ static bool js_webview_WebView_loadFile(se::State& s) } SE_BIND_FUNC(js_webview_WebView_loadFile) -static bool js_webview_WebView_loadHTMLString(se::State& s) -{ +static bool js_webview_WebView_loadHTMLString(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_loadHTMLString : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { HolderType arg0 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); @@ -274,13 +262,12 @@ static bool js_webview_WebView_loadHTMLString(se::State& s) } SE_BIND_FUNC(js_webview_WebView_loadHTMLString) -static bool js_webview_WebView_loadURL(se::State& s) -{ +static bool js_webview_WebView_loadURL(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_loadURL : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { HolderType arg0 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); @@ -293,12 +280,11 @@ static bool js_webview_WebView_loadURL(se::State& s) } SE_BIND_FUNC(js_webview_WebView_loadURL) -static bool js_webview_WebView_reload(se::State& s) -{ +static bool js_webview_WebView_reload(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_reload : Invalid Native Object"); const auto& args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 0) { cobj->reload(); return true; @@ -308,13 +294,12 @@ static bool js_webview_WebView_reload(se::State& s) } SE_BIND_FUNC(js_webview_WebView_reload) -static bool js_webview_WebView_setBackgroundTransparent(se::State& s) -{ +static bool js_webview_WebView_setBackgroundTransparent(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_setBackgroundTransparent : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { HolderType arg0 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); @@ -327,13 +312,12 @@ static bool js_webview_WebView_setBackgroundTransparent(se::State& s) } SE_BIND_FUNC(js_webview_WebView_setBackgroundTransparent) -static bool js_webview_WebView_setBounces(se::State& s) -{ +static bool js_webview_WebView_setBounces(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_setBounces : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { HolderType arg0 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); @@ -346,13 +330,12 @@ static bool js_webview_WebView_setBounces(se::State& s) } SE_BIND_FUNC(js_webview_WebView_setBounces) -static bool js_webview_WebView_setFrame(se::State& s) -{ +static bool js_webview_WebView_setFrame(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_setFrame : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 4) { HolderType arg0 = {}; HolderType arg1 = {}; @@ -371,13 +354,12 @@ static bool js_webview_WebView_setFrame(se::State& s) } SE_BIND_FUNC(js_webview_WebView_setFrame) -static bool js_webview_WebView_setJavascriptInterfaceScheme(se::State& s) -{ +static bool js_webview_WebView_setJavascriptInterfaceScheme(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_setJavascriptInterfaceScheme : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { HolderType arg0 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); @@ -390,46 +372,41 @@ static bool js_webview_WebView_setJavascriptInterfaceScheme(se::State& s) } SE_BIND_FUNC(js_webview_WebView_setJavascriptInterfaceScheme) -static bool js_webview_WebView_setOnDidFailLoading(se::State& s) -{ +static bool js_webview_WebView_setOnDidFailLoading(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_setOnDidFailLoading : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { - HolderType, true> arg0 = {}; + HolderType, true> arg0 = {}; do { - if (args[0].isObject() && args[0].toObject()->isFunction()) - { + if (args[0].isObject() && args[0].toObject()->isFunction()) { se::Value jsThis(s.thisObject()); se::Value jsFunc(args[0]); jsThis.toObject()->attachObject(jsFunc.toObject()); auto lambda = [=](cc::WebView* larg0, const std::string& larg1) -> void { se::ScriptEngine::getInstance()->clearException(); se::AutoHandleScope hs; - + CC_UNUSED bool ok = true; se::ValueArray args; args.resize(2); ok &= nativevalue_to_se(larg0, args[0], nullptr /*ctx*/); ok &= nativevalue_to_se(larg1, args[1], nullptr /*ctx*/); - se::Value rval; + se::Value rval; se::Object* thisObj = jsThis.isObject() ? jsThis.toObject() : nullptr; se::Object* funcObj = jsFunc.toObject(); - bool succeed = funcObj->call(args, thisObj, &rval); + bool succeed = funcObj->call(args, thisObj, &rval); if (!succeed) { se::ScriptEngine::getInstance()->clearException(); } }; arg0.data = lambda; - } - else - { + } else { arg0.data = nullptr; } - } while(false) - ; + } while (false); SE_PRECONDITION2(ok, false, "js_webview_WebView_setOnDidFailLoading : Error processing arguments"); cobj->setOnDidFailLoading(arg0.value()); return true; @@ -439,46 +416,41 @@ static bool js_webview_WebView_setOnDidFailLoading(se::State& s) } SE_BIND_FUNC(js_webview_WebView_setOnDidFailLoading) -static bool js_webview_WebView_setOnDidFinishLoading(se::State& s) -{ +static bool js_webview_WebView_setOnDidFinishLoading(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_setOnDidFinishLoading : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { - HolderType, true> arg0 = {}; + HolderType, true> arg0 = {}; do { - if (args[0].isObject() && args[0].toObject()->isFunction()) - { + if (args[0].isObject() && args[0].toObject()->isFunction()) { se::Value jsThis(s.thisObject()); se::Value jsFunc(args[0]); jsThis.toObject()->attachObject(jsFunc.toObject()); auto lambda = [=](cc::WebView* larg0, const std::string& larg1) -> void { se::ScriptEngine::getInstance()->clearException(); se::AutoHandleScope hs; - + CC_UNUSED bool ok = true; se::ValueArray args; args.resize(2); ok &= nativevalue_to_se(larg0, args[0], nullptr /*ctx*/); ok &= nativevalue_to_se(larg1, args[1], nullptr /*ctx*/); - se::Value rval; + se::Value rval; se::Object* thisObj = jsThis.isObject() ? jsThis.toObject() : nullptr; se::Object* funcObj = jsFunc.toObject(); - bool succeed = funcObj->call(args, thisObj, &rval); + bool succeed = funcObj->call(args, thisObj, &rval); if (!succeed) { se::ScriptEngine::getInstance()->clearException(); } }; arg0.data = lambda; - } - else - { + } else { arg0.data = nullptr; } - } while(false) - ; + } while (false); SE_PRECONDITION2(ok, false, "js_webview_WebView_setOnDidFinishLoading : Error processing arguments"); cobj->setOnDidFinishLoading(arg0.value()); return true; @@ -488,46 +460,41 @@ static bool js_webview_WebView_setOnDidFinishLoading(se::State& s) } SE_BIND_FUNC(js_webview_WebView_setOnDidFinishLoading) -static bool js_webview_WebView_setOnJSCallback(se::State& s) -{ +static bool js_webview_WebView_setOnJSCallback(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_setOnJSCallback : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { - HolderType, true> arg0 = {}; + HolderType, true> arg0 = {}; do { - if (args[0].isObject() && args[0].toObject()->isFunction()) - { + if (args[0].isObject() && args[0].toObject()->isFunction()) { se::Value jsThis(s.thisObject()); se::Value jsFunc(args[0]); jsThis.toObject()->attachObject(jsFunc.toObject()); auto lambda = [=](cc::WebView* larg0, const std::string& larg1) -> void { se::ScriptEngine::getInstance()->clearException(); se::AutoHandleScope hs; - + CC_UNUSED bool ok = true; se::ValueArray args; args.resize(2); ok &= nativevalue_to_se(larg0, args[0], nullptr /*ctx*/); ok &= nativevalue_to_se(larg1, args[1], nullptr /*ctx*/); - se::Value rval; + se::Value rval; se::Object* thisObj = jsThis.isObject() ? jsThis.toObject() : nullptr; se::Object* funcObj = jsFunc.toObject(); - bool succeed = funcObj->call(args, thisObj, &rval); + bool succeed = funcObj->call(args, thisObj, &rval); if (!succeed) { se::ScriptEngine::getInstance()->clearException(); } }; arg0.data = lambda; - } - else - { + } else { arg0.data = nullptr; } - } while(false) - ; + } while (false); SE_PRECONDITION2(ok, false, "js_webview_WebView_setOnJSCallback : Error processing arguments"); cobj->setOnJSCallback(arg0.value()); return true; @@ -537,34 +504,32 @@ static bool js_webview_WebView_setOnJSCallback(se::State& s) } SE_BIND_FUNC(js_webview_WebView_setOnJSCallback) -static bool js_webview_WebView_setOnShouldStartLoading(se::State& s) -{ +static bool js_webview_WebView_setOnShouldStartLoading(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_setOnShouldStartLoading : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { - HolderType, true> arg0 = {}; + HolderType, true> arg0 = {}; do { - if (args[0].isObject() && args[0].toObject()->isFunction()) - { + if (args[0].isObject() && args[0].toObject()->isFunction()) { se::Value jsThis(s.thisObject()); se::Value jsFunc(args[0]); jsThis.toObject()->attachObject(jsFunc.toObject()); auto lambda = [=](cc::WebView* larg0, const std::string& larg1) -> bool { se::ScriptEngine::getInstance()->clearException(); se::AutoHandleScope hs; - + CC_UNUSED bool ok = true; se::ValueArray args; args.resize(2); ok &= nativevalue_to_se(larg0, args[0], nullptr /*ctx*/); ok &= nativevalue_to_se(larg1, args[1], nullptr /*ctx*/); - se::Value rval; + se::Value rval; se::Object* thisObj = jsThis.isObject() ? jsThis.toObject() : nullptr; se::Object* funcObj = jsFunc.toObject(); - bool succeed = funcObj->call(args, thisObj, &rval); + bool succeed = funcObj->call(args, thisObj, &rval); if (!succeed) { se::ScriptEngine::getInstance()->clearException(); } @@ -574,13 +539,10 @@ static bool js_webview_WebView_setOnShouldStartLoading(se::State& s) return result; }; arg0.data = lambda; - } - else - { + } else { arg0.data = nullptr; } - } while(false) - ; + } while (false); SE_PRECONDITION2(ok, false, "js_webview_WebView_setOnShouldStartLoading : Error processing arguments"); cobj->setOnShouldStartLoading(arg0.value()); return true; @@ -590,13 +552,12 @@ static bool js_webview_WebView_setOnShouldStartLoading(se::State& s) } SE_BIND_FUNC(js_webview_WebView_setOnShouldStartLoading) -static bool js_webview_WebView_setScalesPageToFit(se::State& s) -{ +static bool js_webview_WebView_setScalesPageToFit(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_setScalesPageToFit : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { HolderType arg0 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); @@ -609,13 +570,12 @@ static bool js_webview_WebView_setScalesPageToFit(se::State& s) } SE_BIND_FUNC(js_webview_WebView_setScalesPageToFit) -static bool js_webview_WebView_setVisible(se::State& s) -{ +static bool js_webview_WebView_setVisible(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_setVisible : Invalid Native Object"); - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { HolderType arg0 = {}; ok &= sevalue_to_native(args[0], &arg0, s.thisObject()); @@ -628,12 +588,11 @@ static bool js_webview_WebView_setVisible(se::State& s) } SE_BIND_FUNC(js_webview_WebView_setVisible) -static bool js_webview_WebView_stopLoading(se::State& s) -{ +static bool js_webview_WebView_stopLoading(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_webview_WebView_stopLoading : Invalid Native Object"); const auto& args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 0) { cobj->stopLoading(); return true; @@ -643,11 +602,10 @@ static bool js_webview_WebView_stopLoading(se::State& s) } SE_BIND_FUNC(js_webview_WebView_stopLoading) -static bool js_webview_WebView_create(se::State& s) -{ - const auto& args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; +static bool js_webview_WebView_create(se::State& s) { + const auto& args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { auto result = cc::WebView::create(); result->retain(); @@ -661,30 +619,24 @@ static bool js_webview_WebView_create(se::State& s) } SE_BIND_FUNC(js_webview_WebView_create) - - -static bool js_cc_WebView_finalize(se::State& s) -{ +static bool js_cc_WebView_finalize(se::State& s) { // destructor is skipped return true; } SE_BIND_FINALIZE_FUNC(js_cc_WebView_finalize) -static bool js_cc_WebView_destroy(se::State& s) -{ +static bool js_cc_WebView_destroy(se::State& s) { cc::WebView* cobj = SE_THIS_OBJECT(s); cobj->release(); auto objIter = se::NativePtrToObjectMap::find(SE_THIS_OBJECT(s)); - if(objIter != se::NativePtrToObjectMap::end()) - { + if (objIter != se::NativePtrToObjectMap::end()) { objIter->second->clearPrivateData(true); } return true; } SE_BIND_FUNC(js_cc_WebView_destroy) -bool js_register_webview_WebView(se::Object* obj) -{ +bool js_register_webview_WebView(se::Object* obj) { auto cls = se::Class::create("WebView", obj, nullptr, nullptr); cls->defineFunction("canGoBack", _SE(js_webview_WebView_canGoBack)); @@ -724,12 +676,10 @@ bool js_register_webview_WebView(se::Object* obj) se::ScriptEngine::getInstance()->clearException(); return true; } -bool register_all_webview(se::Object* obj) -{ +bool register_all_webview(se::Object* obj) { // Get the ns se::Value nsVal; - if (!obj->getProperty("jsb", &nsVal)) - { + if (!obj->getProperty("jsb", &nsVal)) { se::HandleObject jsobj(se::Object::createPlainObject()); nsVal.setObject(jsobj); obj->setProperty("jsb", nsVal); diff --git a/native/cocos/bindings/auto/jsb_webview_auto.h b/native/cocos/bindings/auto/jsb_webview_auto.h index 586a70ad04..59696bba65 100644 --- a/native/cocos/bindings/auto/jsb_webview_auto.h +++ b/native/cocos/bindings/auto/jsb_webview_auto.h @@ -25,14 +25,14 @@ #pragma once #include "base/Config.h" -#if (USE_WEBVIEW > 0) && (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_MAC_IOS) -#include -#include "cocos/bindings/jswrapper/SeApi.h" -#include "cocos/bindings/manual/jsb_conversions.h" -#include "cocos/ui/webview/WebView.h" +#if USE_WEBVIEW > 0 + #include + #include "cocos/bindings/jswrapper/SeApi.h" + #include "cocos/bindings/manual/jsb_conversions.h" + #include "cocos/ui/webview/WebView.h" extern se::Object* __jsb_cc_WebView_proto; -extern se::Class* __jsb_cc_WebView_class; +extern se::Class* __jsb_cc_WebView_class; bool js_register_cc_WebView(se::Object* obj); bool register_all_webview(se::Object* obj); diff --git a/native/cocos/bindings/dop/jsb_dop.cpp b/native/cocos/bindings/dop/jsb_dop.cpp index 96b1b68545..8463d9c5a2 100644 --- a/native/cocos/bindings/dop/jsb_dop.cpp +++ b/native/cocos/bindings/dop/jsb_dop.cpp @@ -163,6 +163,7 @@ static bool js_ObjectPool_bind(se::State &s) { // NOLINT return true; } SE_REPORT_ERROR("jsb_ObjectPool_bind: wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; } SE_BIND_FUNC(js_ObjectPool_bind) diff --git a/native/cocos/bindings/jswrapper/config.h b/native/cocos/bindings/jswrapper/config.h index b4612db88c..4b110440fe 100644 --- a/native/cocos/bindings/jswrapper/config.h +++ b/native/cocos/bindings/jswrapper/config.h @@ -63,7 +63,15 @@ #define LOG_TAG "jswrapper" #define SE_LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) #define SE_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) - +#elif __OHOS__ + #if 1 + #include "cocos/base/Log.h" + #define SE_LOGD(...) CC_LOG_DEBUG(__VA_ARGS__) + #define SE_LOGE(...) CC_LOG_ERROR(__VA_ARGS__) + #else + #define SE_LOGD(...) + #define SE_LOGE(...) + #endif #elif defined(_WIN32) && defined(_WINDOWS) #ifndef QUOTEME_ @@ -98,7 +106,7 @@ void seLogE(const char *format, ...); #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) - #define __POSIX__ + #define __POSIX__ //NOLINT #endif @@ -109,7 +117,7 @@ void seLogE(const char *format, ...); #define __SSIZE_T typedef SSIZE_T ssize_t; #define _SSIZE_T_DEFINED // libuv also defines ssize_t, use the one defined here. - #endif // __SSIZE_T + #endif // __SSIZE_T #endif // #if defined(_WIN32) && defined(_WINDOWS) diff --git a/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp b/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp index 41a52e48cb..cc692250e8 100644 --- a/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp +++ b/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp @@ -47,11 +47,11 @@ #define EXPOSE_GC "__jsb_gc__" -unsigned int __jsbStackFrameLimit = 20; +const unsigned int JSB_STACK_FRAME_LIMIT = 20; #ifdef CC_DEBUG -unsigned int __jsbInvocationCount = 0; -std::map __jsbFunctionInvokedRecords; +unsigned int jsbInvocationCount = 0; +std::map jsbFunctionInvokedRecords; #endif #define RETRUN_VAL_IF_FAIL(cond, val) \ @@ -59,38 +59,39 @@ std::map __jsbFunctionInvokedRecords; namespace se { -Class *__jsb_CCPrivateData_class = nullptr; +Class *__jsb_CCPrivateData_class = nullptr; //NOLINT(readability-identifier-naming) namespace { -ScriptEngine *__instance = nullptr; +ScriptEngine *gSriptEngineInstance = nullptr; -void __log(const v8::FunctionCallbackInfo &info) { +void seLogCallback(const v8::FunctionCallbackInfo &info) { if (info[0]->IsString()) { v8::String::Utf8Value utf8(v8::Isolate::GetCurrent(), info[0]); SE_LOGD("JS: %s\n", *utf8); } } -void __forceGC(const v8::FunctionCallbackInfo &info) { +void seForceGC(const v8::FunctionCallbackInfo & /*info*/) { ScriptEngine::getInstance()->garbageCollect(); } std::string stackTraceToString(v8::Local stack) { std::string stackStr; - if (stack.IsEmpty()) + if (stack.IsEmpty()) { return stackStr; + } char tmp[100] = {0}; for (int i = 0, e = stack->GetFrameCount(); i < e; ++i) { - v8::Local frame = stack->GetFrame(v8::Isolate::GetCurrent(), i); - v8::Local script = frame->GetScriptName(); - std::string scriptName; + v8::Local frame = stack->GetFrame(v8::Isolate::GetCurrent(), i); + v8::Local script = frame->GetScriptName(); + std::string scriptName; if (!script.IsEmpty()) { scriptName = *v8::String::Utf8Value(v8::Isolate::GetCurrent(), script); } v8::Local func = frame->GetFunctionName(); - std::string funcName; + std::string funcName; if (!func.IsEmpty()) { funcName = *v8::String::Utf8Value(v8::Isolate::GetCurrent(), func); } @@ -114,27 +115,28 @@ std::string stackTraceToString(v8::Local stack) { return stackStr; } -se::Value __oldConsoleLog; -se::Value __oldConsoleDebug; -se::Value __oldConsoleInfo; -se::Value __oldConsoleWarn; -se::Value __oldConsoleError; -se::Value __oldConsoleAssert; +se::Value oldConsoleLog; +se::Value oldConsoleDebug; +se::Value oldConsoleInfo; +se::Value oldConsoleWarn; +se::Value oldConsoleError; +se::Value oldConsoleAssert; -bool JSB_console_format_log(State &s, const char *prefix, int msgIndex = 0) { - if (msgIndex < 0) +bool jsbConsoleFormatLog(State &state, const char *prefix, int msgIndex = 0) { //NOLINT(google-runtime-references) + if (msgIndex < 0) { return false; + } - const auto &args = s.args(); - int argc = (int)args.size(); + const auto &args = state.args(); + int argc = static_cast(args.size()); if ((argc - msgIndex) == 1) { std::string msg = args[msgIndex].toStringForce(); SE_LOGD("JS: %s%s\n", prefix, msg.c_str()); } else if (argc > 1) { std::string msg = args[msgIndex].toStringForce(); - size_t pos; + size_t pos; for (int i = (msgIndex + 1); i < argc; ++i) { - pos = msg.find("%"); + pos = msg.find('%'); if (pos != std::string::npos && pos != (msg.length() - 1) && (msg[pos + 1] == 'd' || msg[pos + 1] == 's' || msg[pos + 1] == 'f')) { msg.replace(pos, 2, args[i].toStringForce()); } else { @@ -148,52 +150,52 @@ bool JSB_console_format_log(State &s, const char *prefix, int msgIndex = 0) { return true; } -bool JSB_console_log(State &s) { - JSB_console_format_log(s, ""); - __oldConsoleLog.toObject()->call(s.args(), s.thisObject()); +bool jsbConsoleLog(State &s) { //NOLINT(google-runtime-references) + jsbConsoleFormatLog(s, ""); + oldConsoleLog.toObject()->call(s.args(), s.thisObject()); return true; } -SE_BIND_FUNC(JSB_console_log) +SE_BIND_FUNC(jsbConsoleLog) -bool JSB_console_debug(State &s) { - JSB_console_format_log(s, "[DEBUG]: "); - __oldConsoleDebug.toObject()->call(s.args(), s.thisObject()); +bool jsbConsoleDebug(State &s) { //NOLINT(google-runtime-references) + jsbConsoleFormatLog(s, "[DEBUG]: "); + oldConsoleDebug.toObject()->call(s.args(), s.thisObject()); return true; } -SE_BIND_FUNC(JSB_console_debug) +SE_BIND_FUNC(jsbConsoleDebug) -bool JSB_console_info(State &s) { - JSB_console_format_log(s, "[INFO]: "); - __oldConsoleInfo.toObject()->call(s.args(), s.thisObject()); +bool jsbConsoleInfo(State &s) { //NOLINT(google-runtime-references) + jsbConsoleFormatLog(s, "[INFO]: "); + oldConsoleInfo.toObject()->call(s.args(), s.thisObject()); return true; } -SE_BIND_FUNC(JSB_console_info) +SE_BIND_FUNC(jsbConsoleInfo) -bool JSB_console_warn(State &s) { - JSB_console_format_log(s, "[WARN]: "); - __oldConsoleWarn.toObject()->call(s.args(), s.thisObject()); +bool jsbConsoleWarn(State &s) { //NOLINT(google-runtime-references) + jsbConsoleFormatLog(s, "[WARN]: "); + oldConsoleWarn.toObject()->call(s.args(), s.thisObject()); return true; } -SE_BIND_FUNC(JSB_console_warn) +SE_BIND_FUNC(jsbConsoleWarn) -bool JSB_console_error(State &s) { - JSB_console_format_log(s, "[ERROR]: "); - __oldConsoleError.toObject()->call(s.args(), s.thisObject()); +bool jsbConsoleError(State &s) { //NOLINT(google-runtime-references) + jsbConsoleFormatLog(s, "[ERROR]: "); + oldConsoleError.toObject()->call(s.args(), s.thisObject()); return true; } -SE_BIND_FUNC(JSB_console_error) +SE_BIND_FUNC(jsbConsoleError) -bool JSB_console_assert(State &s) { +bool jsbConsoleAssert(State &s) { //NOLINT(google-runtime-references) const auto &args = s.args(); if (!args.empty()) { if (args[0].isBoolean() && !args[0].toBoolean()) { - JSB_console_format_log(s, "[ASSERT]: ", 1); - __oldConsoleAssert.toObject()->call(s.args(), s.thisObject()); + jsbConsoleFormatLog(s, "[ASSERT]: ", 1); + oldConsoleAssert.toObject()->call(s.args(), s.thisObject()); } } return true; } -SE_BIND_FUNC(JSB_console_assert) +SE_BIND_FUNC(jsbConsoleAssert) /* * The unique V8 platform instance @@ -201,8 +203,8 @@ SE_BIND_FUNC(JSB_console_assert) class ScriptEngineV8Context { public: ScriptEngineV8Context() { - _platform = v8::platform::NewDefaultPlatform().release(); - v8::V8::InitializePlatform(_platform); + platform = v8::platform::NewDefaultPlatform().release(); + v8::V8::InitializePlatform(platform); std::string flags; //NOTICE: spaces are required between flags @@ -213,7 +215,7 @@ public: flags.append(" --jitless"); #endif if (!flags.empty()) { - v8::V8::SetFlagsFromString(flags.c_str(), (int)flags.length()); + v8::V8::SetFlagsFromString(flags.c_str(), static_cast(flags.length())); } bool ok = v8::V8::Initialize(); @@ -221,15 +223,14 @@ public: } ~ScriptEngineV8Context() { - v8::V8::Dispose(); v8::V8::ShutdownPlatform(); - delete _platform; + delete platform; } - v8::Platform *_platform = nullptr; + v8::Platform *platform = nullptr; }; -ScriptEngineV8Context *_sharedV8 = nullptr; +ScriptEngineV8Context *gSharedV8 = nullptr; } // namespace @@ -253,29 +254,30 @@ void ScriptEngine::onFatalErrorCallback(const char *location, const char *messag getInstance()->callExceptionCallback(location, message, "(no stack information)"); } -void ScriptEngine::onOOMErrorCallback(const char *location, bool is_heap_oom) { +void ScriptEngine::onOOMErrorCallback(const char *location, bool isHeapOom) { std::string errorStr = "[OOM ERROR] location: "; errorStr += location; std::string message; message = "is heap out of memory: "; - if (is_heap_oom) + if (isHeapOom) { message += "true"; - else + } else { message += "false"; + } errorStr += ", " + message; SE_LOGE("%s\n", errorStr.c_str()); getInstance()->callExceptionCallback(location, message.c_str(), "(no stack information)"); } -void ScriptEngine::onMessageCallback(v8::Local message, v8::Local data) { - ScriptEngine *thiz = getInstance(); - v8::Local msg = message->Get(); - Value msgVal; +void ScriptEngine::onMessageCallback(v8::Local message, v8::Local /*data*/) { + ScriptEngine * thiz = getInstance(); + v8::Local msg = message->Get(); + Value msgVal; internal::jsToSeValue(v8::Isolate::GetCurrent(), msg, &msgVal); assert(msgVal.isString()); v8::ScriptOrigin origin = message->GetScriptOrigin(); - Value resouceNameVal; + Value resouceNameVal; internal::jsToSeValue(v8::Isolate::GetCurrent(), origin.ResourceName(), &resouceNameVal); Value line; internal::jsToSeValue(v8::Isolate::GetCurrent(), origin.ResourceLineOffset(), &line); @@ -316,12 +318,13 @@ void ScriptEngine::onMessageCallback(v8::Local message, v8::Local_isolate; - v8::HandleScope scope(isolate); + v8::Isolate * isolate = getInstance()->_isolate; + v8::HandleScope scope(isolate); std::stringstream ss; - auto event = msg.GetEvent(); - auto value = msg.GetValue(); - const char *eventName = "[invalidatePromiseEvent]"; + auto event = msg.GetEvent(); + auto value = msg.GetValue(); + auto promiseName = msg.GetPromise()->GetConstructorName(); + const char * eventName = "[invalidatePromiseEvent]"; if (event == v8::kPromiseRejectWithNoHandler) { eventName = "unhandledRejectedPromise"; @@ -337,7 +340,57 @@ void ScriptEngine::onPromiseRejectCallback(v8::PromiseRejectMessage msg) { // prepend error object to stack message v8::Local str = value->ToString(isolate->GetCurrentContext()).ToLocalChecked(); v8::String::Utf8Value valueUtf8(isolate, str); - ss << *valueUtf8 << std::endl; + auto * strp = *valueUtf8; + auto len = valueUtf8.length(); + if (strp == nullptr) { + ss << "value: null" << std::endl; + auto tn = value->TypeOf(isolate); + v8::String::Utf8Value tnUtf8(isolate, tn); + strp = *tnUtf8; + if (strp) { + ss << " type: " << strp << std::endl; + } + if (value->IsObject()) { + v8::MaybeLocal json = v8::JSON::Stringify(isolate->GetCurrentContext(), value); + if (!json.IsEmpty()) { + v8::String::Utf8Value jsonStr(isolate, json.ToLocalChecked()); + strp = *jsonStr; + if (strp) { + ss << " obj: " << strp << std::endl; + } else { + ss << " obj: null" << std::endl; + } + } else { + v8::Local obj = value->ToObject(isolate->GetCurrentContext()).ToLocalChecked(); + v8::Local attrNames = obj->GetOwnPropertyNames(isolate->GetCurrentContext()).ToLocalChecked(); + + if (!attrNames.IsEmpty()) { + uint32_t size = attrNames->Length(); + + for (uint32_t i = 0; i < size; i++) { + se::Value e; + v8::Local attrName = attrNames->Get(isolate->GetCurrentContext(), i) + .ToLocalChecked() + ->ToString(isolate->GetCurrentContext()) + .ToLocalChecked(); + v8::String::Utf8Value attrUtf8(isolate, attrName); + strp = *attrUtf8; + ss << " obj.property " << strp << std::endl; + } + ss << " obj: JSON.parse failed!" << std::endl; + } + } + } + + } else { + ss << *valueUtf8 << std::endl; + } + + v8::String::Utf8Value valuePromiseConstructor(isolate, promiseName); + strp = *valuePromiseConstructor; + if (strp) { + ss << "PromiseConstructor " << strp; + } } auto stackStr = getInstance()->getCurrentStackTrace(); @@ -347,7 +400,7 @@ void ScriptEngine::onPromiseRejectCallback(v8::PromiseRejectMessage msg) { } void ScriptEngine::privateDataFinalize(void *nativeObj) { - internal::PrivateData *p = (internal::PrivateData *)nativeObj; + auto *p = static_cast(nativeObj); Object::nativeObjectFinalizeHook(p->data); @@ -359,16 +412,17 @@ void ScriptEngine::privateDataFinalize(void *nativeObj) { } ScriptEngine *ScriptEngine::getInstance() { - if (__instance == nullptr) { - __instance = new ScriptEngine(); + if (gSriptEngineInstance == nullptr) { + gSriptEngineInstance = new ScriptEngine(); } - return __instance; + return gSriptEngineInstance; } void ScriptEngine::destroyInstance() { - delete __instance; - __instance = nullptr; + gSriptEngineInstance->cleanup(); + delete gSriptEngineInstance; + gSriptEngineInstance = nullptr; } ScriptEngine::ScriptEngine() @@ -388,14 +442,12 @@ ScriptEngine::ScriptEngine() _isInCleanup(false), _isErrorHandleWorking(false) { - if (!_sharedV8) { - _sharedV8 = new ScriptEngineV8Context(); + if (!gSharedV8) { + gSharedV8 = new ScriptEngineV8Context(); } } -ScriptEngine::~ScriptEngine() { - cleanup(); -} +ScriptEngine::~ScriptEngine() = default; bool ScriptEngine::init() { cleanup(); @@ -408,13 +460,13 @@ bool ScriptEngine::init() { hook(); } _beforeInitHookArray.clear(); - v8::Isolate::CreateParams create_params; - create_params.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator(); - _isolate = v8::Isolate::New(create_params); + v8::Isolate::CreateParams createParams; + createParams.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator(); + _isolate = v8::Isolate::New(createParams); v8::HandleScope hs(_isolate); _isolate->Enter(); - _isolate->SetCaptureStackTraceForUncaughtExceptions(true, __jsbStackFrameLimit, v8::StackTrace::kOverview); + _isolate->SetCaptureStackTraceForUncaughtExceptions(true, JSB_STACK_FRAME_LIMIT, v8::StackTrace::kOverview); _isolate->SetFatalErrorHandler(onFatalErrorCallback); _isolate->SetOOMErrorHandler(onOOMErrorCallback); @@ -437,29 +489,29 @@ bool ScriptEngine::init() { se::Value consoleVal; if (_globalObj->getProperty("console", &consoleVal) && consoleVal.isObject()) { - consoleVal.toObject()->getProperty("log", &__oldConsoleLog); - consoleVal.toObject()->defineFunction("log", _SE(JSB_console_log)); + consoleVal.toObject()->getProperty("log", &oldConsoleLog); + consoleVal.toObject()->defineFunction("log", _SE(jsbConsoleLog)); - consoleVal.toObject()->getProperty("debug", &__oldConsoleDebug); - consoleVal.toObject()->defineFunction("debug", _SE(JSB_console_debug)); + consoleVal.toObject()->getProperty("debug", &oldConsoleDebug); + consoleVal.toObject()->defineFunction("debug", _SE(jsbConsoleDebug)); - consoleVal.toObject()->getProperty("info", &__oldConsoleInfo); - consoleVal.toObject()->defineFunction("info", _SE(JSB_console_info)); + consoleVal.toObject()->getProperty("info", &oldConsoleInfo); + consoleVal.toObject()->defineFunction("info", _SE(jsbConsoleInfo)); - consoleVal.toObject()->getProperty("warn", &__oldConsoleWarn); - consoleVal.toObject()->defineFunction("warn", _SE(JSB_console_warn)); + consoleVal.toObject()->getProperty("warn", &oldConsoleWarn); + consoleVal.toObject()->defineFunction("warn", _SE(jsbConsoleWarn)); - consoleVal.toObject()->getProperty("error", &__oldConsoleError); - consoleVal.toObject()->defineFunction("error", _SE(JSB_console_error)); + consoleVal.toObject()->getProperty("error", &oldConsoleError); + consoleVal.toObject()->defineFunction("error", _SE(jsbConsoleError)); - consoleVal.toObject()->getProperty("assert", &__oldConsoleAssert); - consoleVal.toObject()->defineFunction("assert", _SE(JSB_console_assert)); + consoleVal.toObject()->getProperty("assert", &oldConsoleAssert); + consoleVal.toObject()->defineFunction("assert", _SE(jsbConsoleAssert)); } _globalObj->setProperty("scriptEngineType", se::Value("V8")); - _globalObj->defineFunction("log", __log); - _globalObj->defineFunction("forceGC", __forceGC); + _globalObj->defineFunction("log", seLogCallback); + _globalObj->defineFunction("forceGC", seForceGC); _globalObj->getProperty(EXPOSE_GC, &_gcFuncValue); if (_gcFuncValue.isObject() && _gcFuncValue.toObject()->isFunction()) { @@ -484,8 +536,9 @@ bool ScriptEngine::init() { } void ScriptEngine::cleanup() { - if (!_isValid) + if (!_isValid) { return; + } SE_LOGD("ScriptEngine::cleanup begin ...\n"); _isInCleanup = true; @@ -502,12 +555,12 @@ void ScriptEngine::cleanup() { Class::cleanup(); garbageCollect(); - __oldConsoleLog.setUndefined(); - __oldConsoleDebug.setUndefined(); - __oldConsoleInfo.setUndefined(); - __oldConsoleWarn.setUndefined(); - __oldConsoleError.setUndefined(); - __oldConsoleAssert.setUndefined(); + oldConsoleLog.setUndefined(); + oldConsoleDebug.setUndefined(); + oldConsoleInfo.setUndefined(); + oldConsoleWarn.setUndefined(); + oldConsoleError.setUndefined(); + oldConsoleAssert.setUndefined(); #if SE_ENABLE_INSPECTOR @@ -534,9 +587,9 @@ void ScriptEngine::cleanup() { } _isolate->Dispose(); - _isolate = nullptr; + _isolate = nullptr; _globalObj = nullptr; - _isValid = false; + _isValid = false; _registerCallbackArray.clear(); @@ -584,8 +637,9 @@ void ScriptEngine::addPermanentRegisterCallback(RegisterCallback cb) { } bool ScriptEngine::start() { - if (!init()) + if (!init()) { return false; + } se::AutoHandleScope hs; @@ -594,33 +648,35 @@ bool ScriptEngine::start() { #if SE_ENABLE_INSPECTOR // V8 inspector stuff, most code are taken from NodeJS. _isolateData = node::CreateIsolateData(_isolate, uv_default_loop()); - _env = node::CreateEnvironment(_isolateData, _context.Get(_isolate), 0, nullptr, 0, nullptr); + _env = node::CreateEnvironment(_isolateData, _context.Get(_isolate), 0, nullptr, 0, nullptr); node::DebugOptions options; options.set_wait_for_connect(_isWaitForConnect); // the program will be hung up until debug attach if _isWaitForConnect = true options.set_inspector_enabled(true); - options.set_port((int)_debuggerServerPort); - options.set_host_name(_debuggerServerAddr.c_str()); - bool ok = _env->inspector_agent()->Start(_sharedV8->_platform, "", options); + options.set_port(static_cast(_debuggerServerPort)); + options.set_host_name(_debuggerServerAddr); + bool ok = _env->inspector_agent()->Start(gSharedV8->platform, "", options); assert(ok); #endif } // - bool ok = false; + bool ok = false; _startTime = std::chrono::steady_clock::now(); for (auto cb : _permRegisterCallbackArray) { ok = cb(_globalObj); assert(ok); - if (!ok) + if (!ok) { break; + } } for (auto cb : _registerCallbackArray) { ok = cb(_globalObj); assert(ok); - if (!ok) + if (!ok) { break; + } } // After ScriptEngine is started, _registerCallbackArray isn't needed. Therefore, clear it here. @@ -630,13 +686,13 @@ bool ScriptEngine::start() { } void ScriptEngine::garbageCollect() { - int objSize = __objectMap ? (int)__objectMap->size() : -1; + int objSize = __objectMap ? static_cast(__objectMap->size()) : -1; SE_LOGD("GC begin ..., (js->native map) size: %d, all objects: %d\n", (int)NativePtrToObjectMap::size(), objSize); if (_gcFunc == nullptr) { const double kLongIdlePauseInSeconds = 1.0; _isolate->ContextDisposedNotification(); - _isolate->IdleNotificationDeadline(_sharedV8->_platform->MonotonicallyIncreasingTime() + kLongIdlePauseInSeconds); + _isolate->IdleNotificationDeadline(gSharedV8->platform->MonotonicallyIncreasingTime() + kLongIdlePauseInSeconds); // By sending a low memory notifications, we will try hard to collect all // garbage and will therefore also invoke all weak callbacks of actually // unreachable persistent handles. @@ -644,7 +700,7 @@ void ScriptEngine::garbageCollect() { } else { _gcFunc->call({}, nullptr); } - objSize = __objectMap ? (int)__objectMap->size() : -1; + objSize = __objectMap ? static_cast(__objectMap->size()) : -1; SE_LOGD("GC end ..., (js->native map) size: %d, all objects: %d\n", (int)NativePtrToObjectMap::size(), objSize); } @@ -653,7 +709,7 @@ bool ScriptEngine::isGarbageCollecting() { return _isGarbageCollecting; } -void ScriptEngine::_setGarbageCollecting(bool isGarbageCollecting) { +void ScriptEngine::_setGarbageCollecting(bool isGarbageCollecting) { //NOLINT(readability-identifier-naming) _isGarbageCollecting = isGarbageCollecting; } @@ -669,18 +725,20 @@ bool ScriptEngine::evalString(const char *script, ssize_t length /* = -1 */, Val } assert(script != nullptr); - if (length < 0) + if (length < 0) { length = strlen(script); + } - if (fileName == nullptr) + if (fileName == nullptr) { fileName = "(no filename)"; + } // Fix the source url is too long displayed in Chrome debugger. - std::string sourceUrl = fileName; - static const std::string prefixKey = "/temp/quick-scripts/"; - size_t prefixPos = sourceUrl.find(prefixKey); + std::string sourceUrl = fileName; + static const std::string PREFIX_KEY = "/temp/quick-scripts/"; + size_t prefixPos = sourceUrl.find(PREFIX_KEY); if (prefixPos != std::string::npos) { - sourceUrl = sourceUrl.substr(prefixPos + prefixKey.length()); + sourceUrl = sourceUrl.substr(prefixPos + PREFIX_KEY.length()); } #if CC_PLATFORM == CC_PLATFORM_MAC_OSX @@ -690,18 +748,20 @@ bool ScriptEngine::evalString(const char *script, ssize_t length /* = -1 */, Val #endif // It is needed, or will crash if invoked from non C++ context, such as invoked from objective-c context(for example, handler of UIKit). - v8::HandleScope handle_scope(_isolate); + v8::HandleScope handleScope(_isolate); - std::string scriptStr(script, length); + std::string scriptStr(script, length); v8::MaybeLocal source = v8::String::NewFromUtf8(_isolate, scriptStr.c_str(), v8::NewStringType::kNormal); - if (source.IsEmpty()) + if (source.IsEmpty()) { return false; + } v8::MaybeLocal originStr = v8::String::NewFromUtf8(_isolate, sourceUrl.c_str(), v8::NewStringType::kNormal); - if (originStr.IsEmpty()) + if (originStr.IsEmpty()) { return false; + } - v8::ScriptOrigin origin(originStr.ToLocalChecked()); + v8::ScriptOrigin origin(originStr.ToLocalChecked()); v8::MaybeLocal maybeScript = v8::Script::Compile(_context.Get(_isolate), source.ToLocalChecked(), &origin); bool success = false; @@ -709,7 +769,7 @@ bool ScriptEngine::evalString(const char *script, ssize_t length /* = -1 */, Val if (!maybeScript.IsEmpty()) { v8::TryCatch block(_isolate); - v8::Local v8Script = maybeScript.ToLocalChecked(); + v8::Local v8Script = maybeScript.ToLocalChecked(); v8::MaybeLocal maybeResult = v8Script->Run(_context.Get(_isolate)); if (!maybeResult.IsEmpty()) { @@ -736,11 +796,12 @@ bool ScriptEngine::evalString(const char *script, ssize_t length /* = -1 */, Val } std::string ScriptEngine::getCurrentStackTrace() { - if (!_isValid) + if (!_isValid) { return std::string(); + } - v8::HandleScope hs(_isolate); - v8::Local stack = v8::StackTrace::CurrentStackTrace(_isolate, __jsbStackFrameLimit, v8::StackTrace::kOverview); + v8::HandleScope hs(_isolate); + v8::Local stack = v8::StackTrace::CurrentStackTrace(_isolate, JSB_STACK_FRAME_LIMIT, v8::StackTrace::kOverview); return stackTraceToString(stack); } @@ -752,33 +813,33 @@ const ScriptEngine::FileOperationDelegate &ScriptEngine::getFileOperationDelegat return _fileOperationDelegate; } -bool ScriptEngine::saveByteCodeToFile(const std::string &path, const std::string &path_bc) { +bool ScriptEngine::saveByteCodeToFile(const std::string &path, const std::string &pathBc) { bool success = false; - auto fu = cc::FileUtils::getInstance(); + auto fu = cc::FileUtils::getInstance(); - if (path_bc.length() > 3 && path_bc.substr(path_bc.length() - 3) != ".bc") { + if (pathBc.length() > 3 && pathBc.substr(pathBc.length() - 3) != ".bc") { SE_LOGE("ScriptEngine::generateByteCode bytecode file path should endwith \".bc\"\n"); ; return false; } - if (fu->isFileExist(path_bc)) { + if (fu->isFileExist(pathBc)) { SE_LOGE("ScriptEngine::generateByteCode file already exists, it will be rewrite!\n"); } //create directory for .bc file { - int last_sep = (int)path_bc.size() - 1; - while (last_sep >= 0 && path_bc[last_sep] != '/') { - last_sep -= 1; + auto lastSep = static_cast(pathBc.size()) - 1; + while (lastSep >= 0 && pathBc[lastSep] != '/') { + lastSep -= 1; } - if (last_sep == 0) { + if (lastSep == 0) { SE_LOGE("ScriptEngine::generateByteCode no directory component found in path %s\n", path.c_str()); return false; } - std::string path_bc_dir = path_bc.substr(0, last_sep); - success = fu->createDirectory(path_bc_dir); + std::string pathBcDir = pathBc.substr(0, lastSep); + success = fu->createDirectory(pathBcDir); if (!success) { SE_LOGE("ScriptEngine::generateByteCode failed to create bytecode for %s\n", path.c_str()); return success; @@ -786,60 +847,60 @@ bool ScriptEngine::saveByteCodeToFile(const std::string &path, const std::string } // load script file - std::string scriptBuffer = _fileOperationDelegate.onGetStringFromFile(path); - v8::Local code = v8::String::NewFromUtf8(_isolate, scriptBuffer.c_str(), v8::NewStringType::kNormal, (int)scriptBuffer.length()).ToLocalChecked(); - v8::Local scriptPath = v8::String::NewFromUtf8(_isolate, path.data(), v8::NewStringType::kNormal).ToLocalChecked(); + std::string scriptBuffer = _fileOperationDelegate.onGetStringFromFile(path); + v8::Local code = v8::String::NewFromUtf8(_isolate, scriptBuffer.c_str(), v8::NewStringType::kNormal, static_cast(scriptBuffer.length())).ToLocalChecked(); + v8::Local scriptPath = v8::String::NewFromUtf8(_isolate, path.data(), v8::NewStringType::kNormal).ToLocalChecked(); // create unbound script - v8::ScriptOrigin origin(scriptPath); - v8::ScriptCompiler::Source source(code, origin); - v8::Local parsing_context = v8::Local::New(_isolate, _context); - v8::Context::Scope parsing_scope(parsing_context); - v8::TryCatch tryCatch(_isolate); - v8::Local v8_script = v8::ScriptCompiler::CompileUnboundScript(_isolate, &source, v8::ScriptCompiler::kEagerCompile) - .ToLocalChecked(); + v8::ScriptOrigin origin(scriptPath); + v8::ScriptCompiler::Source source(code, origin); + v8::Local parsingContext = v8::Local::New(_isolate, _context); + v8::Context::Scope parsingScope(parsingContext); + v8::TryCatch tryCatch(_isolate); + v8::Local v8Script = v8::ScriptCompiler::CompileUnboundScript(_isolate, &source, v8::ScriptCompiler::kEagerCompile) + .ToLocalChecked(); // create CachedData - v8::ScriptCompiler::CachedData *cd = v8::ScriptCompiler::CreateCodeCache(v8_script); + v8::ScriptCompiler::CachedData *cd = v8::ScriptCompiler::CreateCodeCache(v8Script); // save to file cc::Data writeData; writeData.copy(cd->data, cd->length); - success = fu->writeDataToFile(writeData, path_bc); + success = fu->writeDataToFile(writeData, pathBc); if (!success) { - SE_LOGE("ScriptEngine::generateByteCode write %s\n", path_bc.c_str()); + SE_LOGE("ScriptEngine::generateByteCode write %s\n", pathBc.c_str()); } return success; } -bool ScriptEngine::runByteCodeFile(const std::string &path_bc, Value *ret /* = nullptr */) { +bool ScriptEngine::runByteCodeFile(const std::string &pathBc, Value *ret /* = nullptr */) { auto fu = cc::FileUtils::getInstance(); cc::Data cachedData; - fu->getContents(path_bc, &cachedData); + fu->getContents(pathBc, &cachedData); // read origin source file length from .bc file - uint8_t *p = cachedData.getBytes() + 8; - int filesize = p[0] + (p[1] << 8) + (p[2] << 16) + (p[3] << 24); + uint8_t *p = cachedData.getBytes() + 8; + int filesize = p[0] + (p[1] << 8) + (p[2] << 16) + (p[3] << 24); { // fix bytecode - v8::HandleScope scope(_isolate); - v8::Local dummyBytecodeSource = v8::String::NewFromUtf8(_isolate, "\" \"", v8::NewStringType::kNormal).ToLocalChecked(); - v8::ScriptCompiler::Source dummySource(dummyBytecodeSource); - v8::Local dummyFunction = v8::ScriptCompiler::CompileUnboundScript(_isolate, &dummySource, v8::ScriptCompiler::kEagerCompile).ToLocalChecked(); - v8::ScriptCompiler::CachedData *dummyData = v8::ScriptCompiler::CreateCodeCache(dummyFunction); + v8::HandleScope scope(_isolate); + v8::Local dummyBytecodeSource = v8::String::NewFromUtf8(_isolate, "\" \"", v8::NewStringType::kNormal).ToLocalChecked(); + v8::ScriptCompiler::Source dummySource(dummyBytecodeSource); + v8::Local dummyFunction = v8::ScriptCompiler::CompileUnboundScript(_isolate, &dummySource, v8::ScriptCompiler::kEagerCompile).ToLocalChecked(); + v8::ScriptCompiler::CachedData *dummyData = v8::ScriptCompiler::CreateCodeCache(dummyFunction); memcpy(p + 4, dummyData->data + 12, 4); // delete dummyData; //NOTE: managed by v8 } // setup ScriptOrigin - v8::Local scriptPath = v8::String::NewFromUtf8(_isolate, path_bc.data(), v8::NewStringType::kNormal).ToLocalChecked(); - v8::Local offset = v8::Int32::New(_isolate, 0); - v8::Local column = v8::Int32::New(_isolate, 0); + v8::Local scriptPath = v8::String::NewFromUtf8(_isolate, pathBc.data(), v8::NewStringType::kNormal).ToLocalChecked(); + v8::Local offset = v8::Int32::New(_isolate, 0); + v8::Local column = v8::Int32::New(_isolate, 0); v8::Local crossOrigin = v8::Boolean::New(_isolate, true); ; v8::ScriptOrigin origin(scriptPath, offset, column, crossOrigin); // restore CacheData - v8::ScriptCompiler::CachedData *v8_cache_data = new v8::ScriptCompiler::CachedData(cachedData.getBytes(), (int)cachedData.getSize()); + auto * v8CacheData = new v8::ScriptCompiler::CachedData(cachedData.getBytes(), static_cast(cachedData.getSize())); v8::Local dummyCode; // generate dummy code @@ -847,40 +908,40 @@ bool ScriptEngine::runByteCodeFile(const std::string &path_bc, Value *ret /* = n std::vector codeBuffer; codeBuffer.resize(filesize + 1); std::fill(codeBuffer.begin(), codeBuffer.end(), ' '); - codeBuffer[0] = '\"'; + codeBuffer[0] = '\"'; codeBuffer[filesize - 1] = '\"'; - codeBuffer[filesize] = '\0'; - dummyCode = v8::String::NewFromUtf8(_isolate, codeBuffer.data(), v8::NewStringType::kNormal, filesize).ToLocalChecked(); + codeBuffer[filesize] = '\0'; + dummyCode = v8::String::NewFromUtf8(_isolate, codeBuffer.data(), v8::NewStringType::kNormal, filesize).ToLocalChecked(); assert(dummyCode->Length() == filesize); } - v8::ScriptCompiler::Source source(dummyCode, origin, v8_cache_data); + v8::ScriptCompiler::Source source(dummyCode, origin, v8CacheData); if (source.GetCachedData() == nullptr) { - SE_LOGE("ScriptEngine::runByteCodeFile can not load cacheData for %s", path_bc.c_str()); + SE_LOGE("ScriptEngine::runByteCodeFile can not load cacheData for %s", pathBc.c_str()); return false; } - v8::TryCatch tryCatch(_isolate); - v8::Local v8_script = v8::ScriptCompiler::CompileUnboundScript(_isolate, &source, v8::ScriptCompiler::kConsumeCodeCache) - .ToLocalChecked(); + v8::TryCatch tryCatch(_isolate); + v8::Local v8Script = v8::ScriptCompiler::CompileUnboundScript(_isolate, &source, v8::ScriptCompiler::kConsumeCodeCache) + .ToLocalChecked(); - if (v8_script.IsEmpty()) { - SE_LOGE("ScriptEngine::runByteCodeFile can not compile %s!\n", path_bc.c_str()); + if (v8Script.IsEmpty()) { + SE_LOGE("ScriptEngine::runByteCodeFile can not compile %s!\n", pathBc.c_str()); return false; } if (source.GetCachedData()->rejected) { - SE_LOGE("ScriptEngine::runByteCodeFile cache rejected %s!\n", path_bc.c_str()); + SE_LOGE("ScriptEngine::runByteCodeFile cache rejected %s!\n", pathBc.c_str()); return false; } - v8::Local runnable_script = v8_script->BindToCurrentContext(); - v8::MaybeLocal result = runnable_script->Run(_context.Get(_isolate)); + v8::Local runnableScript = v8Script->BindToCurrentContext(); + v8::MaybeLocal result = runnableScript->Run(_context.Get(_isolate)); if (result.IsEmpty()) { - SE_LOGE("ScriptEngine::runByteCodeFile script %s, failed!\n", path_bc.c_str()); + SE_LOGE("ScriptEngine::runByteCodeFile script %s, failed!\n", pathBc.c_str()); return false; } @@ -888,7 +949,7 @@ bool ScriptEngine::runByteCodeFile(const std::string &path_bc, Value *ret /* = n internal::jsToSeValue(_isolate, result.ToLocalChecked(), ret); } - SE_LOGE("ScriptEngine::runByteCodeFile success %s!\n", path_bc.c_str()); + SE_LOGE("ScriptEngine::runByteCodeFile success %s!\n", pathBc.c_str()); return true; } @@ -931,14 +992,14 @@ void ScriptEngine::setJSExceptionCallback(const ExceptionCallback &cb) { _jsExceptionCallback = cb; } -v8::Local ScriptEngine::_getContext() const { +v8::Local ScriptEngine::_getContext() const { //NOLINT(readability-identifier-naming) return _context.Get(_isolate); } void ScriptEngine::enableDebugger(const std::string &serverAddr, uint32_t port, bool isWait) { _debuggerServerAddr = serverAddr; _debuggerServerPort = port; - _isWaitForConnect = isWait; + _isWaitForConnect = isWait; } bool ScriptEngine::isDebuggerEnabled() const { diff --git a/native/cocos/bindings/jswrapper/v8/ScriptEngine.h b/native/cocos/bindings/jswrapper/v8/ScriptEngine.h index e8c56e8898..ab016a940b 100644 --- a/native/cocos/bindings/jswrapper/v8/ScriptEngine.h +++ b/native/cocos/bindings/jswrapper/v8/ScriptEngine.h @@ -30,8 +30,8 @@ #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8 - #include "Base.h" #include "../Value.h" + #include "Base.h" #include @@ -52,7 +52,7 @@ class Object; class Class; class Value; -extern Class *__jsb_CCPrivateData_class; +extern Class *__jsb_CCPrivateData_class; //NOLINT /** * A stack-allocated class that governs a number of local handles. @@ -65,8 +65,7 @@ public: AutoHandleScope() : _handleScope(v8::Isolate::GetCurrent()) { } - ~AutoHandleScope() { - } + ~AutoHandleScope() = default; private: v8::HandleScope _handleScope; @@ -94,7 +93,7 @@ public: */ Object *getGlobalObject() const; - typedef bool (*RegisterCallback)(Object *); + using RegisterCallback = bool (*)(Object *); /** * @brief Adds a callback for registering a native binding module. @@ -160,21 +159,21 @@ public: /** * @brief Executes a utf-8 string buffer which contains JavaScript code. - * @param[in] scriptStr A utf-8 string buffer, if it isn't null-terminated, parameter `length` should be assigned and > 0. + * @param[in] script A utf-8 string buffer, if it isn't null-terminated, parameter `length` should be assigned and > 0. * @param[in] length The length of parameter `scriptStr`, it will be set to string length internally if passing < 0 and parameter `scriptStr` is null-terminated. - * @param[in] rval The se::Value that results from evaluating script. Passing nullptr if you don't care about the result. + * @param[in] ret The se::Value that results from evaluating script. Passing nullptr if you don't care about the result. * @param[in] fileName A string containing a URL for the script's source file. This is used by debuggers and when reporting exceptions. Pass NULL if you do not care to include source file information. * @return true if succeed, otherwise false. */ - bool evalString(const char *scriptStr, ssize_t length = -1, Value *rval = nullptr, const char *fileName = nullptr); + bool evalString(const char *script, ssize_t length = -1, Value *ret = nullptr, const char *fileName = nullptr); /** * @brief Compile script file into v8::ScriptCompiler::CachedData and save to file. - * @param[in] scriptPath The path of script file. - * @param[in] outputPath The location where bytecode file should be written to. The path should be ends with ".bc", which indicates a bytecode file. + * @param[in] path The path of script file. + * @param[in] pathBc The location where bytecode file should be written to. The path should be ends with ".bc", which indicates a bytecode file. * @return true if succeed, otherwise false. */ - bool saveByteCodeToFile(const std::string &scriptPath, const std::string &outputPath); + bool saveByteCodeToFile(const std::string &path, const std::string &pathBc); /** * @brief Grab a snapshot of the current JavaScript execution stack. @@ -225,10 +224,10 @@ public: /** * @brief Executes a file which contains JavaScript code. * @param[in] path Script file path. - * @param[in] rval The se::Value that results from evaluating script. Passing nullptr if you don't care about the result. + * @param[in] ret The se::Value that results from evaluating script. Passing nullptr if you don't care about the result. * @return true if succeed, otherwise false. */ - bool runScript(const std::string &path, Value *rval = nullptr); + bool runScript(const std::string &path, Value *ret = nullptr); /** * @brief Tests whether script engine is doing garbage collection. @@ -302,10 +301,10 @@ public: uint32_t getVMId() const { return _vmId; } // Private API used in wrapper - void _retainScriptObject(void *owner, void *target); - void _releaseScriptObject(void *owner, void *target); - v8::Local _getContext() const; - void _setGarbageCollecting(bool isGarbageCollecting); + void _retainScriptObject(void *owner, void *target); //NOLINT(readability-identifier-naming) + void _releaseScriptObject(void *owner, void *target); //NOLINT(readability-identifier-naming) + v8::Local _getContext() const; //NOLINT(readability-identifier-naming) + void _setGarbageCollecting(bool isGarbageCollecting); //NOLINT(readability-identifier-naming) // private: ScriptEngine(); @@ -313,7 +312,7 @@ private: static void privateDataFinalize(void *nativeObj); static void onFatalErrorCallback(const char *location, const char *message); - static void onOOMErrorCallback(const char *location, bool is_heap_oom); + static void onOOMErrorCallback(const char *location, bool isHeapOom); static void onMessageCallback(v8::Local message, v8::Local data); static void onPromiseRejectCallback(v8::PromiseRejectMessage msg); @@ -323,28 +322,28 @@ private: * @param[in] ret The se::Value that results from evaluating script. Passing nullptr if you don't care about the result. * @return true if succeed, otherwise false. */ - bool runByteCodeFile(const std::string &path_bc, Value *ret /* = nullptr */); + bool runByteCodeFile(const std::string &pathBc, Value *ret /* = nullptr */); void callExceptionCallback(const char *, const char *, const char *); std::chrono::steady_clock::time_point _startTime; - std::vector _registerCallbackArray; - std::vector _permRegisterCallbackArray; - std::vector> _beforeInitHookArray; - std::vector> _afterInitHookArray; - std::vector> _beforeCleanupHookArray; - std::vector> _afterCleanupHookArray; + std::vector _registerCallbackArray; + std::vector _permRegisterCallbackArray; + std::vector> _beforeInitHookArray; + std::vector> _afterInitHookArray; + std::vector> _beforeCleanupHookArray; + std::vector> _afterCleanupHookArray; v8::Persistent _context; - v8::Isolate *_isolate; + v8::Isolate * _isolate; v8::HandleScope *_handleScope; - Object *_globalObj; - Value _gcFuncValue; - Object *_gcFunc = nullptr; + Object * _globalObj; + Value _gcFuncValue; + Object * _gcFunc = nullptr; FileOperationDelegate _fileOperationDelegate; - ExceptionCallback _nativeExceptionCallback = nullptr; - ExceptionCallback _jsExceptionCallback = nullptr; + ExceptionCallback _nativeExceptionCallback = nullptr; + ExceptionCallback _jsExceptionCallback = nullptr; #if SE_ENABLE_INSPECTOR node::Environment *_env; @@ -354,8 +353,8 @@ private: std::thread::id _engineThreadId; std::string _debuggerServerAddr; - uint32_t _debuggerServerPort; - bool _isWaitForConnect; + uint32_t _debuggerServerPort; + bool _isWaitForConnect; uint32_t _vmId; diff --git a/native/cocos/bindings/jswrapper/v8/debugger/http_parser.c b/native/cocos/bindings/jswrapper/v8/debugger/http_parser.c deleted file mode 100644 index f5bdf62a9a..0000000000 --- a/native/cocos/bindings/jswrapper/v8/debugger/http_parser.c +++ /dev/null @@ -1,2473 +0,0 @@ -/* Based on src/http/ngx_http_parse.c from NGINX copyright Igor Sysoev - * - * Additional changes are licensed under the same terms as NGINX and - * copyright Joyent, Inc. and other Node contributors. All rights reserved. - * - * 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 "http_parser.h" - -#if (SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8) && SE_ENABLE_INSPECTOR - -#include -#include -#include -#include -#include -#include - -#ifndef ULLONG_MAX -# define ULLONG_MAX ((uint64_t) -1) /* 2^64-1 */ -#endif - -#ifndef MIN -# define MIN(a,b) ((a) < (b) ? (a) : (b)) -#endif - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) -#endif - -#ifndef BIT_AT -# define BIT_AT(a, i) \ - (!!((unsigned int) (a)[(unsigned int) (i) >> 3] & \ - (1 << ((unsigned int) (i) & 7)))) -#endif - -#ifndef ELEM_AT -# define ELEM_AT(a, i, v) ((unsigned int) (i) < ARRAY_SIZE(a) ? (a)[(i)] : (v)) -#endif - -#define SET_ERRNO(e) \ -do { \ - parser->http_errno = (e); \ -} while(0) - -#define CURRENT_STATE() p_state -#define UPDATE_STATE(V) p_state = (enum state) (V); -#define RETURN(V) \ -do { \ - parser->state = CURRENT_STATE(); \ - return (V); \ -} while (0); -#define REEXECUTE() \ - goto reexecute; \ - - -#ifdef __GNUC__ -# define LIKELY(X) __builtin_expect(!!(X), 1) -# define UNLIKELY(X) __builtin_expect(!!(X), 0) -#else -# define LIKELY(X) (X) -# define UNLIKELY(X) (X) -#endif - - -/* Run the notify callback FOR, returning ER if it fails */ -#define CALLBACK_NOTIFY_(FOR, ER) \ -do { \ - assert(HTTP_PARSER_ERRNO(parser) == HPE_OK); \ - \ - if (LIKELY(settings->on_##FOR)) { \ - parser->state = CURRENT_STATE(); \ - if (UNLIKELY(0 != settings->on_##FOR(parser))) { \ - SET_ERRNO(HPE_CB_##FOR); \ - } \ - UPDATE_STATE(parser->state); \ - \ - /* We either errored above or got paused; get out */ \ - if (UNLIKELY(HTTP_PARSER_ERRNO(parser) != HPE_OK)) { \ - return (ER); \ - } \ - } \ -} while (0) - -/* Run the notify callback FOR and consume the current byte */ -#define CALLBACK_NOTIFY(FOR) CALLBACK_NOTIFY_(FOR, p - data + 1) - -/* Run the notify callback FOR and don't consume the current byte */ -#define CALLBACK_NOTIFY_NOADVANCE(FOR) CALLBACK_NOTIFY_(FOR, p - data) - -/* Run data callback FOR with LEN bytes, returning ER if it fails */ -#define CALLBACK_DATA_(FOR, LEN, ER) \ -do { \ - assert(HTTP_PARSER_ERRNO(parser) == HPE_OK); \ - \ - if (FOR##_mark) { \ - if (LIKELY(settings->on_##FOR)) { \ - parser->state = CURRENT_STATE(); \ - if (UNLIKELY(0 != \ - settings->on_##FOR(parser, FOR##_mark, (LEN)))) { \ - SET_ERRNO(HPE_CB_##FOR); \ - } \ - UPDATE_STATE(parser->state); \ - \ - /* We either errored above or got paused; get out */ \ - if (UNLIKELY(HTTP_PARSER_ERRNO(parser) != HPE_OK)) { \ - return (ER); \ - } \ - } \ - FOR##_mark = NULL; \ - } \ -} while (0) - -/* Run the data callback FOR and consume the current byte */ -#define CALLBACK_DATA(FOR) \ - CALLBACK_DATA_(FOR, p - FOR##_mark, p - data + 1) - -/* Run the data callback FOR and don't consume the current byte */ -#define CALLBACK_DATA_NOADVANCE(FOR) \ - CALLBACK_DATA_(FOR, p - FOR##_mark, p - data) - -/* Set the mark FOR; non-destructive if mark is already set */ -#define MARK(FOR) \ -do { \ - if (!FOR##_mark) { \ - FOR##_mark = p; \ - } \ -} while (0) - -/* Don't allow the total size of the HTTP headers (including the status - * line) to exceed HTTP_MAX_HEADER_SIZE. This check is here to protect - * embedders against denial-of-service attacks where the attacker feeds - * us a never-ending header that the embedder keeps buffering. - * - * This check is arguably the responsibility of embedders but we're doing - * it on the embedder's behalf because most won't bother and this way we - * make the web a little safer. HTTP_MAX_HEADER_SIZE is still far bigger - * than any reasonable request or response so this should never affect - * day-to-day operation. - */ -#define COUNT_HEADER_SIZE(V) \ -do { \ - parser->nread += (V); \ - if (UNLIKELY(parser->nread > (HTTP_MAX_HEADER_SIZE))) { \ - SET_ERRNO(HPE_HEADER_OVERFLOW); \ - goto error; \ - } \ -} while (0) - - -#define PROXY_CONNECTION "proxy-connection" -#define CONNECTION "connection" -#define CONTENT_LENGTH "content-length" -#define TRANSFER_ENCODING "transfer-encoding" -#define UPGRADE "upgrade" -#define CHUNKED "chunked" -#define KEEP_ALIVE "keep-alive" -#define CLOSE "close" - - -static const char *method_strings[] = - { -#define XX(num, name, string) #string, - HTTP_METHOD_MAP(XX) -#undef XX - }; - - -/* Tokens as defined by rfc 2616. Also lowercases them. - * token = 1* - * separators = "(" | ")" | "<" | ">" | "@" - * | "," | ";" | ":" | "\" | <"> - * | "/" | "[" | "]" | "?" | "=" - * | "{" | "}" | SP | HT - */ -static const char tokens[256] = { -/* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */ - 0, 0, 0, 0, 0, 0, 0, 0, -/* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */ - 0, 0, 0, 0, 0, 0, 0, 0, -/* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */ - 0, 0, 0, 0, 0, 0, 0, 0, -/* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */ - 0, 0, 0, 0, 0, 0, 0, 0, -/* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */ - 0, '!', 0, '#', '$', '%', '&', '\'', -/* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */ - 0, 0, '*', '+', 0, '-', '.', 0, -/* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */ - '0', '1', '2', '3', '4', '5', '6', '7', -/* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */ - '8', '9', 0, 0, 0, 0, 0, 0, -/* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */ - 0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', -/* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */ - 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', -/* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */ - 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', -/* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */ - 'x', 'y', 'z', 0, 0, 0, '^', '_', -/* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */ - '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', -/* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */ - 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', -/* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */ - 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', -/* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */ - 'x', 'y', 'z', 0, '|', 0, '~', 0 }; - - -static const int8_t unhex[256] = - {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 - ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 - ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 - , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1 - ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1 - ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 - ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1 - ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 - }; - - -#if HTTP_PARSER_STRICT -# define T(v) 0 -#else -# define T(v) v -#endif - - -static const uint8_t normal_url_char[32] = { -/* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */ - 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0, -/* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */ - 0 | T(2) | 0 | 0 | T(16) | 0 | 0 | 0, -/* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */ - 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0, -/* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */ - 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0, -/* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */ - 0 | 2 | 4 | 0 | 16 | 32 | 64 | 128, -/* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */ - 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, -/* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */ - 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, -/* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */ - 1 | 2 | 4 | 8 | 16 | 32 | 64 | 0, -/* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */ - 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, -/* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */ - 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, -/* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */ - 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, -/* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */ - 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, -/* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */ - 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, -/* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */ - 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, -/* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */ - 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, -/* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */ - 1 | 2 | 4 | 8 | 16 | 32 | 64 | 0, }; - -#undef T - -enum state - { s_dead = 1 /* important that this is > 0 */ - - , s_start_req_or_res - , s_res_or_resp_H - , s_start_res - , s_res_H - , s_res_HT - , s_res_HTT - , s_res_HTTP - , s_res_first_http_major - , s_res_http_major - , s_res_first_http_minor - , s_res_http_minor - , s_res_first_status_code - , s_res_status_code - , s_res_status_start - , s_res_status - , s_res_line_almost_done - - , s_start_req - - , s_req_method - , s_req_spaces_before_url - , s_req_schema - , s_req_schema_slash - , s_req_schema_slash_slash - , s_req_server_start - , s_req_server - , s_req_server_with_at - , s_req_path - , s_req_query_string_start - , s_req_query_string - , s_req_fragment_start - , s_req_fragment - , s_req_http_start - , s_req_http_H - , s_req_http_HT - , s_req_http_HTT - , s_req_http_HTTP - , s_req_first_http_major - , s_req_http_major - , s_req_first_http_minor - , s_req_http_minor - , s_req_line_almost_done - - , s_header_field_start - , s_header_field - , s_header_value_discard_ws - , s_header_value_discard_ws_almost_done - , s_header_value_discard_lws - , s_header_value_start - , s_header_value - , s_header_value_lws - - , s_header_almost_done - - , s_chunk_size_start - , s_chunk_size - , s_chunk_parameters - , s_chunk_size_almost_done - - , s_headers_almost_done - , s_headers_done - - /* Important: 's_headers_done' must be the last 'header' state. All - * states beyond this must be 'body' states. It is used for overflow - * checking. See the PARSING_HEADER() macro. - */ - - , s_chunk_data - , s_chunk_data_almost_done - , s_chunk_data_done - - , s_body_identity - , s_body_identity_eof - - , s_message_done - }; - - -#define PARSING_HEADER(state) (state <= s_headers_done) - - -enum header_states - { h_general = 0 - , h_C - , h_CO - , h_CON - - , h_matching_connection - , h_matching_proxy_connection - , h_matching_content_length - , h_matching_transfer_encoding - , h_matching_upgrade - - , h_connection - , h_content_length - , h_transfer_encoding - , h_upgrade - - , h_matching_transfer_encoding_chunked - , h_matching_connection_token_start - , h_matching_connection_keep_alive - , h_matching_connection_close - , h_matching_connection_upgrade - , h_matching_connection_token - - , h_transfer_encoding_chunked - , h_connection_keep_alive - , h_connection_close - , h_connection_upgrade - }; - -enum http_host_state - { - s_http_host_dead = 1 - , s_http_userinfo_start - , s_http_userinfo - , s_http_host_start - , s_http_host_v6_start - , s_http_host - , s_http_host_v6 - , s_http_host_v6_end - , s_http_host_v6_zone_start - , s_http_host_v6_zone - , s_http_host_port_start - , s_http_host_port -}; - -/* Macros for character classes; depends on strict-mode */ -#define CR '\r' -#define LF '\n' -#define LOWER(c) (unsigned char)(c | 0x20) -#define IS_ALPHA(c) (LOWER(c) >= 'a' && LOWER(c) <= 'z') -#define IS_NUM(c) ((c) >= '0' && (c) <= '9') -#define IS_ALPHANUM(c) (IS_ALPHA(c) || IS_NUM(c)) -#define IS_HEX(c) (IS_NUM(c) || (LOWER(c) >= 'a' && LOWER(c) <= 'f')) -#define IS_MARK(c) ((c) == '-' || (c) == '_' || (c) == '.' || \ - (c) == '!' || (c) == '~' || (c) == '*' || (c) == '\'' || (c) == '(' || \ - (c) == ')') -#define IS_USERINFO_CHAR(c) (IS_ALPHANUM(c) || IS_MARK(c) || (c) == '%' || \ - (c) == ';' || (c) == ':' || (c) == '&' || (c) == '=' || (c) == '+' || \ - (c) == '$' || (c) == ',') - -#define STRICT_TOKEN(c) (tokens[(unsigned char)c]) - -#if HTTP_PARSER_STRICT -#define TOKEN(c) (tokens[(unsigned char)c]) -#define IS_URL_CHAR(c) (BIT_AT(normal_url_char, (unsigned char)c)) -#define IS_HOST_CHAR(c) (IS_ALPHANUM(c) || (c) == '.' || (c) == '-') -#else -#define TOKEN(c) ((c == ' ') ? ' ' : tokens[(unsigned char)c]) -#define IS_URL_CHAR(c) \ - (BIT_AT(normal_url_char, (unsigned char)c) || ((c) & 0x80)) -#define IS_HOST_CHAR(c) \ - (IS_ALPHANUM(c) || (c) == '.' || (c) == '-' || (c) == '_') -#endif - -/** - * Verify that a char is a valid visible (printable) US-ASCII - * character or %x80-FF - **/ -#define IS_HEADER_CHAR(ch) \ - (ch == CR || ch == LF || ch == 9 || ((unsigned char)ch > 31 && ch != 127)) - -#define start_state (parser->type == HTTP_REQUEST ? s_start_req : s_start_res) - - -#if HTTP_PARSER_STRICT -# define STRICT_CHECK(cond) \ -do { \ - if (cond) { \ - SET_ERRNO(HPE_STRICT); \ - goto error; \ - } \ -} while (0) -# define NEW_MESSAGE() (http_should_keep_alive(parser) ? start_state : s_dead) -#else -# define STRICT_CHECK(cond) -# define NEW_MESSAGE() start_state -#endif - - -/* Map errno values to strings for human-readable output */ -#define HTTP_STRERROR_GEN(n, s) { "HPE_" #n, s }, -static struct { - const char *name; - const char *description; -} http_strerror_tab[] = { - HTTP_ERRNO_MAP(HTTP_STRERROR_GEN) -}; -#undef HTTP_STRERROR_GEN - -int http_message_needs_eof(const http_parser *parser); - -/* Our URL parser. - * - * This is designed to be shared by http_parser_execute() for URL validation, - * hence it has a state transition + byte-for-byte interface. In addition, it - * is meant to be embedded in http_parser_parse_url(), which does the dirty - * work of turning state transitions URL components for its API. - * - * This function should only be invoked with non-space characters. It is - * assumed that the caller cares about (and can detect) the transition between - * URL and non-URL states by looking for these. - */ -static enum state -parse_url_char(enum state s, const char ch) -{ - if (ch == ' ' || ch == '\r' || ch == '\n') { - return s_dead; - } - -#if HTTP_PARSER_STRICT - if (ch == '\t' || ch == '\f') { - return s_dead; - } -#endif - - switch (s) { - case s_req_spaces_before_url: - /* Proxied requests are followed by scheme of an absolute URI (alpha). - * All methods except CONNECT are followed by '/' or '*'. - */ - - if (ch == '/' || ch == '*') { - return s_req_path; - } - - if (IS_ALPHA(ch)) { - return s_req_schema; - } - - break; - - case s_req_schema: - if (IS_ALPHA(ch)) { - return s; - } - - if (ch == ':') { - return s_req_schema_slash; - } - - break; - - case s_req_schema_slash: - if (ch == '/') { - return s_req_schema_slash_slash; - } - - break; - - case s_req_schema_slash_slash: - if (ch == '/') { - return s_req_server_start; - } - - break; - - case s_req_server_with_at: - if (ch == '@') { - return s_dead; - } - - /* FALLTHROUGH */ - case s_req_server_start: - case s_req_server: - if (ch == '/') { - return s_req_path; - } - - if (ch == '?') { - return s_req_query_string_start; - } - - if (ch == '@') { - return s_req_server_with_at; - } - - if (IS_USERINFO_CHAR(ch) || ch == '[' || ch == ']') { - return s_req_server; - } - - break; - - case s_req_path: - if (IS_URL_CHAR(ch)) { - return s; - } - - switch (ch) { - case '?': - return s_req_query_string_start; - - case '#': - return s_req_fragment_start; - } - - break; - - case s_req_query_string_start: - case s_req_query_string: - if (IS_URL_CHAR(ch)) { - return s_req_query_string; - } - - switch (ch) { - case '?': - /* allow extra '?' in query string */ - return s_req_query_string; - - case '#': - return s_req_fragment_start; - } - - break; - - case s_req_fragment_start: - if (IS_URL_CHAR(ch)) { - return s_req_fragment; - } - - switch (ch) { - case '?': - return s_req_fragment; - - case '#': - return s; - } - - break; - - case s_req_fragment: - if (IS_URL_CHAR(ch)) { - return s; - } - - switch (ch) { - case '?': - case '#': - return s; - } - - break; - - default: - break; - } - - /* We should never fall out of the switch above unless there's an error */ - return s_dead; -} - -size_t http_parser_execute (http_parser *parser, - const http_parser_settings *settings, - const char *data, - size_t len) -{ - char c, ch; - int8_t unhex_val; - const char *p = data; - const char *header_field_mark = 0; - const char *header_value_mark = 0; - const char *url_mark = 0; - const char *body_mark = 0; - const char *status_mark = 0; - enum state p_state = (enum state) parser->state; - const unsigned int lenient = parser->lenient_http_headers; - - /* We're in an error state. Don't bother doing anything. */ - if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { - return 0; - } - - if (len == 0) { - switch (CURRENT_STATE()) { - case s_body_identity_eof: - /* Use of CALLBACK_NOTIFY() here would erroneously return 1 byte read if - * we got paused. - */ - CALLBACK_NOTIFY_NOADVANCE(message_complete); - return 0; - - case s_dead: - case s_start_req_or_res: - case s_start_res: - case s_start_req: - return 0; - - default: - SET_ERRNO(HPE_INVALID_EOF_STATE); - return 1; - } - } - - - if (CURRENT_STATE() == s_header_field) - header_field_mark = data; - if (CURRENT_STATE() == s_header_value) - header_value_mark = data; - switch (CURRENT_STATE()) { - case s_req_path: - case s_req_schema: - case s_req_schema_slash: - case s_req_schema_slash_slash: - case s_req_server_start: - case s_req_server: - case s_req_server_with_at: - case s_req_query_string_start: - case s_req_query_string: - case s_req_fragment_start: - case s_req_fragment: - url_mark = data; - break; - case s_res_status: - status_mark = data; - break; - default: - break; - } - - for (p=data; p != data + len; p++) { - ch = *p; - - if (PARSING_HEADER(CURRENT_STATE())) - COUNT_HEADER_SIZE(1); - -reexecute: - switch (CURRENT_STATE()) { - - case s_dead: - /* this state is used after a 'Connection: close' message - * the parser will error out if it reads another message - */ - if (LIKELY(ch == CR || ch == LF)) - break; - - SET_ERRNO(HPE_CLOSED_CONNECTION); - goto error; - - case s_start_req_or_res: - { - if (ch == CR || ch == LF) - break; - parser->flags = 0; - parser->content_length = ULLONG_MAX; - - if (ch == 'H') { - UPDATE_STATE(s_res_or_resp_H); - - CALLBACK_NOTIFY(message_begin); - } else { - parser->type = HTTP_REQUEST; - UPDATE_STATE(s_start_req); - REEXECUTE(); - } - - break; - } - - case s_res_or_resp_H: - if (ch == 'T') { - parser->type = HTTP_RESPONSE; - UPDATE_STATE(s_res_HT); - } else { - if (UNLIKELY(ch != 'E')) { - SET_ERRNO(HPE_INVALID_CONSTANT); - goto error; - } - - parser->type = HTTP_REQUEST; - parser->method = HTTP_HEAD; - parser->index = 2; - UPDATE_STATE(s_req_method); - } - break; - - case s_start_res: - { - parser->flags = 0; - parser->content_length = ULLONG_MAX; - - switch (ch) { - case 'H': - UPDATE_STATE(s_res_H); - break; - - case CR: - case LF: - break; - - default: - SET_ERRNO(HPE_INVALID_CONSTANT); - goto error; - } - - CALLBACK_NOTIFY(message_begin); - break; - } - - case s_res_H: - STRICT_CHECK(ch != 'T'); - UPDATE_STATE(s_res_HT); - break; - - case s_res_HT: - STRICT_CHECK(ch != 'T'); - UPDATE_STATE(s_res_HTT); - break; - - case s_res_HTT: - STRICT_CHECK(ch != 'P'); - UPDATE_STATE(s_res_HTTP); - break; - - case s_res_HTTP: - STRICT_CHECK(ch != '/'); - UPDATE_STATE(s_res_first_http_major); - break; - - case s_res_first_http_major: - if (UNLIKELY(ch < '0' || ch > '9')) { - SET_ERRNO(HPE_INVALID_VERSION); - goto error; - } - - parser->http_major = ch - '0'; - UPDATE_STATE(s_res_http_major); - break; - - /* major HTTP version or dot */ - case s_res_http_major: - { - if (ch == '.') { - UPDATE_STATE(s_res_first_http_minor); - break; - } - - if (!IS_NUM(ch)) { - SET_ERRNO(HPE_INVALID_VERSION); - goto error; - } - - parser->http_major *= 10; - parser->http_major += ch - '0'; - - if (UNLIKELY(parser->http_major > 999)) { - SET_ERRNO(HPE_INVALID_VERSION); - goto error; - } - - break; - } - - /* first digit of minor HTTP version */ - case s_res_first_http_minor: - if (UNLIKELY(!IS_NUM(ch))) { - SET_ERRNO(HPE_INVALID_VERSION); - goto error; - } - - parser->http_minor = ch - '0'; - UPDATE_STATE(s_res_http_minor); - break; - - /* minor HTTP version or end of request line */ - case s_res_http_minor: - { - if (ch == ' ') { - UPDATE_STATE(s_res_first_status_code); - break; - } - - if (UNLIKELY(!IS_NUM(ch))) { - SET_ERRNO(HPE_INVALID_VERSION); - goto error; - } - - parser->http_minor *= 10; - parser->http_minor += ch - '0'; - - if (UNLIKELY(parser->http_minor > 999)) { - SET_ERRNO(HPE_INVALID_VERSION); - goto error; - } - - break; - } - - case s_res_first_status_code: - { - if (!IS_NUM(ch)) { - if (ch == ' ') { - break; - } - - SET_ERRNO(HPE_INVALID_STATUS); - goto error; - } - parser->status_code = ch - '0'; - UPDATE_STATE(s_res_status_code); - break; - } - - case s_res_status_code: - { - if (!IS_NUM(ch)) { - switch (ch) { - case ' ': - UPDATE_STATE(s_res_status_start); - break; - case CR: - UPDATE_STATE(s_res_line_almost_done); - break; - case LF: - UPDATE_STATE(s_header_field_start); - break; - default: - SET_ERRNO(HPE_INVALID_STATUS); - goto error; - } - break; - } - - parser->status_code *= 10; - parser->status_code += ch - '0'; - - if (UNLIKELY(parser->status_code > 999)) { - SET_ERRNO(HPE_INVALID_STATUS); - goto error; - } - - break; - } - - case s_res_status_start: - { - if (ch == CR) { - UPDATE_STATE(s_res_line_almost_done); - break; - } - - if (ch == LF) { - UPDATE_STATE(s_header_field_start); - break; - } - - MARK(status); - UPDATE_STATE(s_res_status); - parser->index = 0; - break; - } - - case s_res_status: - if (ch == CR) { - UPDATE_STATE(s_res_line_almost_done); - CALLBACK_DATA(status); - break; - } - - if (ch == LF) { - UPDATE_STATE(s_header_field_start); - CALLBACK_DATA(status); - break; - } - - break; - - case s_res_line_almost_done: - STRICT_CHECK(ch != LF); - UPDATE_STATE(s_header_field_start); - break; - - case s_start_req: - { - if (ch == CR || ch == LF) - break; - parser->flags = 0; - parser->content_length = ULLONG_MAX; - - if (UNLIKELY(!IS_ALPHA(ch))) { - SET_ERRNO(HPE_INVALID_METHOD); - goto error; - } - - parser->method = (enum http_method) 0; - parser->index = 1; - switch (ch) { - case 'A': parser->method = HTTP_ACL; break; - case 'B': parser->method = HTTP_BIND; break; - case 'C': parser->method = HTTP_CONNECT; /* or COPY, CHECKOUT */ break; - case 'D': parser->method = HTTP_DELETE; break; - case 'G': parser->method = HTTP_GET; break; - case 'H': parser->method = HTTP_HEAD; break; - case 'L': parser->method = HTTP_LOCK; /* or LINK */ break; - case 'M': parser->method = HTTP_MKCOL; /* or MOVE, MKACTIVITY, MERGE, M-SEARCH, MKCALENDAR */ break; - case 'N': parser->method = HTTP_NOTIFY; break; - case 'O': parser->method = HTTP_OPTIONS; break; - case 'P': parser->method = HTTP_POST; - /* or PROPFIND|PROPPATCH|PUT|PATCH|PURGE */ - break; - case 'R': parser->method = HTTP_REPORT; /* or REBIND */ break; - case 'S': parser->method = HTTP_SUBSCRIBE; /* or SEARCH */ break; - case 'T': parser->method = HTTP_TRACE; break; - case 'U': parser->method = HTTP_UNLOCK; /* or UNSUBSCRIBE, UNBIND, UNLINK */ break; - default: - SET_ERRNO(HPE_INVALID_METHOD); - goto error; - } - UPDATE_STATE(s_req_method); - - CALLBACK_NOTIFY(message_begin); - - break; - } - - case s_req_method: - { - const char *matcher; - if (UNLIKELY(ch == '\0')) { - SET_ERRNO(HPE_INVALID_METHOD); - goto error; - } - - matcher = method_strings[parser->method]; - if (ch == ' ' && matcher[parser->index] == '\0') { - UPDATE_STATE(s_req_spaces_before_url); - } else if (ch == matcher[parser->index]) { - ; /* nada */ - } else if (IS_ALPHA(ch)) { - - switch (parser->method << 16 | parser->index << 8 | ch) { -#define XX(meth, pos, ch, new_meth) \ - case (HTTP_##meth << 16 | pos << 8 | ch): \ - parser->method = HTTP_##new_meth; break; - - XX(POST, 1, 'U', PUT) - XX(POST, 1, 'A', PATCH) - XX(CONNECT, 1, 'H', CHECKOUT) - XX(CONNECT, 2, 'P', COPY) - XX(MKCOL, 1, 'O', MOVE) - XX(MKCOL, 1, 'E', MERGE) - XX(MKCOL, 2, 'A', MKACTIVITY) - XX(MKCOL, 3, 'A', MKCALENDAR) - XX(SUBSCRIBE, 1, 'E', SEARCH) - XX(REPORT, 2, 'B', REBIND) - XX(POST, 1, 'R', PROPFIND) - XX(PROPFIND, 4, 'P', PROPPATCH) - XX(PUT, 2, 'R', PURGE) - XX(LOCK, 1, 'I', LINK) - XX(UNLOCK, 2, 'S', UNSUBSCRIBE) - XX(UNLOCK, 2, 'B', UNBIND) - XX(UNLOCK, 3, 'I', UNLINK) -#undef XX - - default: - SET_ERRNO(HPE_INVALID_METHOD); - goto error; - } - } else if (ch == '-' && - parser->index == 1 && - parser->method == HTTP_MKCOL) { - parser->method = HTTP_MSEARCH; - } else { - SET_ERRNO(HPE_INVALID_METHOD); - goto error; - } - - ++parser->index; - break; - } - - case s_req_spaces_before_url: - { - if (ch == ' ') break; - - MARK(url); - if (parser->method == HTTP_CONNECT) { - UPDATE_STATE(s_req_server_start); - } - - UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch)); - if (UNLIKELY(CURRENT_STATE() == s_dead)) { - SET_ERRNO(HPE_INVALID_URL); - goto error; - } - - break; - } - - case s_req_schema: - case s_req_schema_slash: - case s_req_schema_slash_slash: - case s_req_server_start: - { - switch (ch) { - /* No whitespace allowed here */ - case ' ': - case CR: - case LF: - SET_ERRNO(HPE_INVALID_URL); - goto error; - default: - UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch)); - if (UNLIKELY(CURRENT_STATE() == s_dead)) { - SET_ERRNO(HPE_INVALID_URL); - goto error; - } - } - - break; - } - - case s_req_server: - case s_req_server_with_at: - case s_req_path: - case s_req_query_string_start: - case s_req_query_string: - case s_req_fragment_start: - case s_req_fragment: - { - switch (ch) { - case ' ': - UPDATE_STATE(s_req_http_start); - CALLBACK_DATA(url); - break; - case CR: - case LF: - parser->http_major = 0; - parser->http_minor = 9; - UPDATE_STATE((ch == CR) ? - s_req_line_almost_done : - s_header_field_start); - CALLBACK_DATA(url); - break; - default: - UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch)); - if (UNLIKELY(CURRENT_STATE() == s_dead)) { - SET_ERRNO(HPE_INVALID_URL); - goto error; - } - } - break; - } - - case s_req_http_start: - switch (ch) { - case 'H': - UPDATE_STATE(s_req_http_H); - break; - case ' ': - break; - default: - SET_ERRNO(HPE_INVALID_CONSTANT); - goto error; - } - break; - - case s_req_http_H: - STRICT_CHECK(ch != 'T'); - UPDATE_STATE(s_req_http_HT); - break; - - case s_req_http_HT: - STRICT_CHECK(ch != 'T'); - UPDATE_STATE(s_req_http_HTT); - break; - - case s_req_http_HTT: - STRICT_CHECK(ch != 'P'); - UPDATE_STATE(s_req_http_HTTP); - break; - - case s_req_http_HTTP: - STRICT_CHECK(ch != '/'); - UPDATE_STATE(s_req_first_http_major); - break; - - /* first digit of major HTTP version */ - case s_req_first_http_major: - if (UNLIKELY(ch < '1' || ch > '9')) { - SET_ERRNO(HPE_INVALID_VERSION); - goto error; - } - - parser->http_major = ch - '0'; - UPDATE_STATE(s_req_http_major); - break; - - /* major HTTP version or dot */ - case s_req_http_major: - { - if (ch == '.') { - UPDATE_STATE(s_req_first_http_minor); - break; - } - - if (UNLIKELY(!IS_NUM(ch))) { - SET_ERRNO(HPE_INVALID_VERSION); - goto error; - } - - parser->http_major *= 10; - parser->http_major += ch - '0'; - - if (UNLIKELY(parser->http_major > 999)) { - SET_ERRNO(HPE_INVALID_VERSION); - goto error; - } - - break; - } - - /* first digit of minor HTTP version */ - case s_req_first_http_minor: - if (UNLIKELY(!IS_NUM(ch))) { - SET_ERRNO(HPE_INVALID_VERSION); - goto error; - } - - parser->http_minor = ch - '0'; - UPDATE_STATE(s_req_http_minor); - break; - - /* minor HTTP version or end of request line */ - case s_req_http_minor: - { - if (ch == CR) { - UPDATE_STATE(s_req_line_almost_done); - break; - } - - if (ch == LF) { - UPDATE_STATE(s_header_field_start); - break; - } - - /* XXX allow spaces after digit? */ - - if (UNLIKELY(!IS_NUM(ch))) { - SET_ERRNO(HPE_INVALID_VERSION); - goto error; - } - - parser->http_minor *= 10; - parser->http_minor += ch - '0'; - - if (UNLIKELY(parser->http_minor > 999)) { - SET_ERRNO(HPE_INVALID_VERSION); - goto error; - } - - break; - } - - /* end of request line */ - case s_req_line_almost_done: - { - if (UNLIKELY(ch != LF)) { - SET_ERRNO(HPE_LF_EXPECTED); - goto error; - } - - UPDATE_STATE(s_header_field_start); - break; - } - - case s_header_field_start: - { - if (ch == CR) { - UPDATE_STATE(s_headers_almost_done); - break; - } - - if (ch == LF) { - /* they might be just sending \n instead of \r\n so this would be - * the second \n to denote the end of headers*/ - UPDATE_STATE(s_headers_almost_done); - REEXECUTE(); - } - - c = TOKEN(ch); - - if (UNLIKELY(!c)) { - SET_ERRNO(HPE_INVALID_HEADER_TOKEN); - goto error; - } - - MARK(header_field); - - parser->index = 0; - UPDATE_STATE(s_header_field); - - switch (c) { - case 'c': - parser->header_state = h_C; - break; - - case 'p': - parser->header_state = h_matching_proxy_connection; - break; - - case 't': - parser->header_state = h_matching_transfer_encoding; - break; - - case 'u': - parser->header_state = h_matching_upgrade; - break; - - default: - parser->header_state = h_general; - break; - } - break; - } - - case s_header_field: - { - const char* start = p; - for (; p != data + len; p++) { - ch = *p; - c = TOKEN(ch); - - if (!c) - break; - - switch (parser->header_state) { - case h_general: - break; - - case h_C: - parser->index++; - parser->header_state = (c == 'o' ? h_CO : h_general); - break; - - case h_CO: - parser->index++; - parser->header_state = (c == 'n' ? h_CON : h_general); - break; - - case h_CON: - parser->index++; - switch (c) { - case 'n': - parser->header_state = h_matching_connection; - break; - case 't': - parser->header_state = h_matching_content_length; - break; - default: - parser->header_state = h_general; - break; - } - break; - - /* connection */ - - case h_matching_connection: - parser->index++; - if (parser->index > sizeof(CONNECTION)-1 - || c != CONNECTION[parser->index]) { - parser->header_state = h_general; - } else if (parser->index == sizeof(CONNECTION)-2) { - parser->header_state = h_connection; - } - break; - - /* proxy-connection */ - - case h_matching_proxy_connection: - parser->index++; - if (parser->index > sizeof(PROXY_CONNECTION)-1 - || c != PROXY_CONNECTION[parser->index]) { - parser->header_state = h_general; - } else if (parser->index == sizeof(PROXY_CONNECTION)-2) { - parser->header_state = h_connection; - } - break; - - /* content-length */ - - case h_matching_content_length: - parser->index++; - if (parser->index > sizeof(CONTENT_LENGTH)-1 - || c != CONTENT_LENGTH[parser->index]) { - parser->header_state = h_general; - } else if (parser->index == sizeof(CONTENT_LENGTH)-2) { - if (parser->flags & F_CONTENTLENGTH) { - SET_ERRNO(HPE_UNEXPECTED_CONTENT_LENGTH); - goto error; - } - parser->header_state = h_content_length; - parser->flags |= F_CONTENTLENGTH; - } - break; - - /* transfer-encoding */ - - case h_matching_transfer_encoding: - parser->index++; - if (parser->index > sizeof(TRANSFER_ENCODING)-1 - || c != TRANSFER_ENCODING[parser->index]) { - parser->header_state = h_general; - } else if (parser->index == sizeof(TRANSFER_ENCODING)-2) { - parser->header_state = h_transfer_encoding; - } - break; - - /* upgrade */ - - case h_matching_upgrade: - parser->index++; - if (parser->index > sizeof(UPGRADE)-1 - || c != UPGRADE[parser->index]) { - parser->header_state = h_general; - } else if (parser->index == sizeof(UPGRADE)-2) { - parser->header_state = h_upgrade; - } - break; - - case h_connection: - case h_content_length: - case h_transfer_encoding: - case h_upgrade: - if (ch != ' ') parser->header_state = h_general; - break; - - default: - assert(0 && "Unknown header_state"); - break; - } - } - - COUNT_HEADER_SIZE(p - start); - - if (p == data + len) { - --p; - break; - } - - if (ch == ':') { - UPDATE_STATE(s_header_value_discard_ws); - CALLBACK_DATA(header_field); - break; - } - - SET_ERRNO(HPE_INVALID_HEADER_TOKEN); - goto error; - } - - case s_header_value_discard_ws: - if (ch == ' ' || ch == '\t') break; - - if (ch == CR) { - UPDATE_STATE(s_header_value_discard_ws_almost_done); - break; - } - - if (ch == LF) { - UPDATE_STATE(s_header_value_discard_lws); - break; - } - - /* FALLTHROUGH */ - - case s_header_value_start: - { - MARK(header_value); - - UPDATE_STATE(s_header_value); - parser->index = 0; - - c = LOWER(ch); - - switch (parser->header_state) { - case h_upgrade: - parser->flags |= F_UPGRADE; - parser->header_state = h_general; - break; - - case h_transfer_encoding: - /* looking for 'Transfer-Encoding: chunked' */ - if ('c' == c) { - parser->header_state = h_matching_transfer_encoding_chunked; - } else { - parser->header_state = h_general; - } - break; - - case h_content_length: - if (UNLIKELY(!IS_NUM(ch))) { - SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); - goto error; - } - - parser->content_length = ch - '0'; - break; - - case h_connection: - /* looking for 'Connection: keep-alive' */ - if (c == 'k') { - parser->header_state = h_matching_connection_keep_alive; - /* looking for 'Connection: close' */ - } else if (c == 'c') { - parser->header_state = h_matching_connection_close; - } else if (c == 'u') { - parser->header_state = h_matching_connection_upgrade; - } else { - parser->header_state = h_matching_connection_token; - } - break; - - /* Multi-value `Connection` header */ - case h_matching_connection_token_start: - break; - - default: - parser->header_state = h_general; - break; - } - break; - } - - case s_header_value: - { - const char* start = p; - enum header_states h_state = (enum header_states) parser->header_state; - for (; p != data + len; p++) { - ch = *p; - if (ch == CR) { - UPDATE_STATE(s_header_almost_done); - parser->header_state = h_state; - CALLBACK_DATA(header_value); - break; - } - - if (ch == LF) { - UPDATE_STATE(s_header_almost_done); - COUNT_HEADER_SIZE(p - start); - parser->header_state = h_state; - CALLBACK_DATA_NOADVANCE(header_value); - REEXECUTE(); - } - - if (!lenient && !IS_HEADER_CHAR(ch)) { - SET_ERRNO(HPE_INVALID_HEADER_TOKEN); - goto error; - } - - c = LOWER(ch); - - switch (h_state) { - case h_general: - { - const char* p_cr; - const char* p_lf; - size_t limit = data + len - p; - - limit = MIN(limit, HTTP_MAX_HEADER_SIZE); - - p_cr = (const char*) memchr(p, CR, limit); - p_lf = (const char*) memchr(p, LF, limit); - if (p_cr != NULL) { - if (p_lf != NULL && p_cr >= p_lf) - p = p_lf; - else - p = p_cr; - } else if (UNLIKELY(p_lf != NULL)) { - p = p_lf; - } else { - p = data + len; - } - --p; - - break; - } - - case h_connection: - case h_transfer_encoding: - assert(0 && "Shouldn't get here."); - break; - - case h_content_length: - { - uint64_t t; - - if (ch == ' ') break; - - if (UNLIKELY(!IS_NUM(ch))) { - SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); - parser->header_state = h_state; - goto error; - } - - t = parser->content_length; - t *= 10; - t += ch - '0'; - - /* Overflow? Test against a conservative limit for simplicity. */ - if (UNLIKELY((ULLONG_MAX - 10) / 10 < parser->content_length)) { - SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); - parser->header_state = h_state; - goto error; - } - - parser->content_length = t; - break; - } - - /* Transfer-Encoding: chunked */ - case h_matching_transfer_encoding_chunked: - parser->index++; - if (parser->index > sizeof(CHUNKED)-1 - || c != CHUNKED[parser->index]) { - h_state = h_general; - } else if (parser->index == sizeof(CHUNKED)-2) { - h_state = h_transfer_encoding_chunked; - } - break; - - case h_matching_connection_token_start: - /* looking for 'Connection: keep-alive' */ - if (c == 'k') { - h_state = h_matching_connection_keep_alive; - /* looking for 'Connection: close' */ - } else if (c == 'c') { - h_state = h_matching_connection_close; - } else if (c == 'u') { - h_state = h_matching_connection_upgrade; - } else if (STRICT_TOKEN(c)) { - h_state = h_matching_connection_token; - } else if (c == ' ' || c == '\t') { - /* Skip lws */ - } else { - h_state = h_general; - } - break; - - /* looking for 'Connection: keep-alive' */ - case h_matching_connection_keep_alive: - parser->index++; - if (parser->index > sizeof(KEEP_ALIVE)-1 - || c != KEEP_ALIVE[parser->index]) { - h_state = h_matching_connection_token; - } else if (parser->index == sizeof(KEEP_ALIVE)-2) { - h_state = h_connection_keep_alive; - } - break; - - /* looking for 'Connection: close' */ - case h_matching_connection_close: - parser->index++; - if (parser->index > sizeof(CLOSE)-1 || c != CLOSE[parser->index]) { - h_state = h_matching_connection_token; - } else if (parser->index == sizeof(CLOSE)-2) { - h_state = h_connection_close; - } - break; - - /* looking for 'Connection: upgrade' */ - case h_matching_connection_upgrade: - parser->index++; - if (parser->index > sizeof(UPGRADE) - 1 || - c != UPGRADE[parser->index]) { - h_state = h_matching_connection_token; - } else if (parser->index == sizeof(UPGRADE)-2) { - h_state = h_connection_upgrade; - } - break; - - case h_matching_connection_token: - if (ch == ',') { - h_state = h_matching_connection_token_start; - parser->index = 0; - } - break; - - case h_transfer_encoding_chunked: - if (ch != ' ') h_state = h_general; - break; - - case h_connection_keep_alive: - case h_connection_close: - case h_connection_upgrade: - if (ch == ',') { - if (h_state == h_connection_keep_alive) { - parser->flags |= F_CONNECTION_KEEP_ALIVE; - } else if (h_state == h_connection_close) { - parser->flags |= F_CONNECTION_CLOSE; - } else if (h_state == h_connection_upgrade) { - parser->flags |= F_CONNECTION_UPGRADE; - } - h_state = h_matching_connection_token_start; - parser->index = 0; - } else if (ch != ' ') { - h_state = h_matching_connection_token; - } - break; - - default: - UPDATE_STATE(s_header_value); - h_state = h_general; - break; - } - } - parser->header_state = h_state; - - COUNT_HEADER_SIZE(p - start); - - if (p == data + len) - --p; - break; - } - - case s_header_almost_done: - { - if (UNLIKELY(ch != LF)) { - SET_ERRNO(HPE_LF_EXPECTED); - goto error; - } - - UPDATE_STATE(s_header_value_lws); - break; - } - - case s_header_value_lws: - { - if (ch == ' ' || ch == '\t') { - UPDATE_STATE(s_header_value_start); - REEXECUTE(); - } - - /* finished the header */ - switch (parser->header_state) { - case h_connection_keep_alive: - parser->flags |= F_CONNECTION_KEEP_ALIVE; - break; - case h_connection_close: - parser->flags |= F_CONNECTION_CLOSE; - break; - case h_transfer_encoding_chunked: - parser->flags |= F_CHUNKED; - break; - case h_connection_upgrade: - parser->flags |= F_CONNECTION_UPGRADE; - break; - default: - break; - } - - UPDATE_STATE(s_header_field_start); - REEXECUTE(); - } - - case s_header_value_discard_ws_almost_done: - { - STRICT_CHECK(ch != LF); - UPDATE_STATE(s_header_value_discard_lws); - break; - } - - case s_header_value_discard_lws: - { - if (ch == ' ' || ch == '\t') { - UPDATE_STATE(s_header_value_discard_ws); - break; - } else { - switch (parser->header_state) { - case h_connection_keep_alive: - parser->flags |= F_CONNECTION_KEEP_ALIVE; - break; - case h_connection_close: - parser->flags |= F_CONNECTION_CLOSE; - break; - case h_connection_upgrade: - parser->flags |= F_CONNECTION_UPGRADE; - break; - case h_transfer_encoding_chunked: - parser->flags |= F_CHUNKED; - break; - default: - break; - } - - /* header value was empty */ - MARK(header_value); - UPDATE_STATE(s_header_field_start); - CALLBACK_DATA_NOADVANCE(header_value); - REEXECUTE(); - } - } - - case s_headers_almost_done: - { - STRICT_CHECK(ch != LF); - - if (parser->flags & F_TRAILING) { - /* End of a chunked request */ - UPDATE_STATE(s_message_done); - CALLBACK_NOTIFY_NOADVANCE(chunk_complete); - REEXECUTE(); - } - - /* Cannot use chunked encoding and a content-length header together - per the HTTP specification. */ - if ((parser->flags & F_CHUNKED) && - (parser->flags & F_CONTENTLENGTH)) { - SET_ERRNO(HPE_UNEXPECTED_CONTENT_LENGTH); - goto error; - } - - UPDATE_STATE(s_headers_done); - - /* Set this here so that on_headers_complete() callbacks can see it */ - parser->upgrade = - ((parser->flags & (F_UPGRADE | F_CONNECTION_UPGRADE)) == - (F_UPGRADE | F_CONNECTION_UPGRADE) || - parser->method == HTTP_CONNECT); - - /* Here we call the headers_complete callback. This is somewhat - * different than other callbacks because if the user returns 1, we - * will interpret that as saying that this message has no body. This - * is needed for the annoying case of recieving a response to a HEAD - * request. - * - * We'd like to use CALLBACK_NOTIFY_NOADVANCE() here but we cannot, so - * we have to simulate it by handling a change in errno below. - */ - if (settings->on_headers_complete) { - switch (settings->on_headers_complete(parser)) { - case 0: - break; - - case 2: - parser->upgrade = 1; - - case 1: - parser->flags |= F_SKIPBODY; - break; - - default: - SET_ERRNO(HPE_CB_headers_complete); - RETURN(p - data); /* Error */ - } - } - - if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { - RETURN(p - data); - } - - REEXECUTE(); - } - - case s_headers_done: - { - int hasBody; - STRICT_CHECK(ch != LF); - - parser->nread = 0; - - hasBody = parser->flags & F_CHUNKED || - (parser->content_length > 0 && parser->content_length != ULLONG_MAX); - if (parser->upgrade && (parser->method == HTTP_CONNECT || - (parser->flags & F_SKIPBODY) || !hasBody)) { - /* Exit, the rest of the message is in a different protocol. */ - UPDATE_STATE(NEW_MESSAGE()); - CALLBACK_NOTIFY(message_complete); - RETURN((p - data) + 1); - } - - if (parser->flags & F_SKIPBODY) { - UPDATE_STATE(NEW_MESSAGE()); - CALLBACK_NOTIFY(message_complete); - } else if (parser->flags & F_CHUNKED) { - /* chunked encoding - ignore Content-Length header */ - UPDATE_STATE(s_chunk_size_start); - } else { - if (parser->content_length == 0) { - /* Content-Length header given but zero: Content-Length: 0\r\n */ - UPDATE_STATE(NEW_MESSAGE()); - CALLBACK_NOTIFY(message_complete); - } else if (parser->content_length != ULLONG_MAX) { - /* Content-Length header given and non-zero */ - UPDATE_STATE(s_body_identity); - } else { - if (!http_message_needs_eof(parser)) { - /* Assume content-length 0 - read the next */ - UPDATE_STATE(NEW_MESSAGE()); - CALLBACK_NOTIFY(message_complete); - } else { - /* Read body until EOF */ - UPDATE_STATE(s_body_identity_eof); - } - } - } - - break; - } - - case s_body_identity: - { - uint64_t to_read = MIN(parser->content_length, - (uint64_t) ((data + len) - p)); - - assert(parser->content_length != 0 - && parser->content_length != ULLONG_MAX); - - /* The difference between advancing content_length and p is because - * the latter will automaticaly advance on the next loop iteration. - * Further, if content_length ends up at 0, we want to see the last - * byte again for our message complete callback. - */ - MARK(body); - parser->content_length -= to_read; - p += to_read - 1; - - if (parser->content_length == 0) { - UPDATE_STATE(s_message_done); - - /* Mimic CALLBACK_DATA_NOADVANCE() but with one extra byte. - * - * The alternative to doing this is to wait for the next byte to - * trigger the data callback, just as in every other case. The - * problem with this is that this makes it difficult for the test - * harness to distinguish between complete-on-EOF and - * complete-on-length. It's not clear that this distinction is - * important for applications, but let's keep it for now. - */ - CALLBACK_DATA_(body, p - body_mark + 1, p - data); - REEXECUTE(); - } - - break; - } - - /* read until EOF */ - case s_body_identity_eof: - MARK(body); - p = data + len - 1; - - break; - - case s_message_done: - UPDATE_STATE(NEW_MESSAGE()); - CALLBACK_NOTIFY(message_complete); - if (parser->upgrade) { - /* Exit, the rest of the message is in a different protocol. */ - RETURN((p - data) + 1); - } - break; - - case s_chunk_size_start: - { - assert(parser->nread == 1); - assert(parser->flags & F_CHUNKED); - - unhex_val = unhex[(unsigned char)ch]; - if (UNLIKELY(unhex_val == -1)) { - SET_ERRNO(HPE_INVALID_CHUNK_SIZE); - goto error; - } - - parser->content_length = unhex_val; - UPDATE_STATE(s_chunk_size); - break; - } - - case s_chunk_size: - { - uint64_t t; - - assert(parser->flags & F_CHUNKED); - - if (ch == CR) { - UPDATE_STATE(s_chunk_size_almost_done); - break; - } - - unhex_val = unhex[(unsigned char)ch]; - - if (unhex_val == -1) { - if (ch == ';' || ch == ' ') { - UPDATE_STATE(s_chunk_parameters); - break; - } - - SET_ERRNO(HPE_INVALID_CHUNK_SIZE); - goto error; - } - - t = parser->content_length; - t *= 16; - t += unhex_val; - - /* Overflow? Test against a conservative limit for simplicity. */ - if (UNLIKELY((ULLONG_MAX - 16) / 16 < parser->content_length)) { - SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); - goto error; - } - - parser->content_length = t; - break; - } - - case s_chunk_parameters: - { - assert(parser->flags & F_CHUNKED); - /* just ignore this shit. REFINE: check for overflow */ - if (ch == CR) { - UPDATE_STATE(s_chunk_size_almost_done); - break; - } - break; - } - - case s_chunk_size_almost_done: - { - assert(parser->flags & F_CHUNKED); - STRICT_CHECK(ch != LF); - - parser->nread = 0; - - if (parser->content_length == 0) { - parser->flags |= F_TRAILING; - UPDATE_STATE(s_header_field_start); - } else { - UPDATE_STATE(s_chunk_data); - } - CALLBACK_NOTIFY(chunk_header); - break; - } - - case s_chunk_data: - { - uint64_t to_read = MIN(parser->content_length, - (uint64_t) ((data + len) - p)); - - assert(parser->flags & F_CHUNKED); - assert(parser->content_length != 0 - && parser->content_length != ULLONG_MAX); - - /* See the explanation in s_body_identity for why the content - * length and data pointers are managed this way. - */ - MARK(body); - parser->content_length -= to_read; - p += to_read - 1; - - if (parser->content_length == 0) { - UPDATE_STATE(s_chunk_data_almost_done); - } - - break; - } - - case s_chunk_data_almost_done: - assert(parser->flags & F_CHUNKED); - assert(parser->content_length == 0); - STRICT_CHECK(ch != CR); - UPDATE_STATE(s_chunk_data_done); - CALLBACK_DATA(body); - break; - - case s_chunk_data_done: - assert(parser->flags & F_CHUNKED); - STRICT_CHECK(ch != LF); - parser->nread = 0; - UPDATE_STATE(s_chunk_size_start); - CALLBACK_NOTIFY(chunk_complete); - break; - - default: - assert(0 && "unhandled state"); - SET_ERRNO(HPE_INVALID_INTERNAL_STATE); - goto error; - } - } - - /* Run callbacks for any marks that we have leftover after we ran our of - * bytes. There should be at most one of these set, so it's OK to invoke - * them in series (unset marks will not result in callbacks). - * - * We use the NOADVANCE() variety of callbacks here because 'p' has already - * overflowed 'data' and this allows us to correct for the off-by-one that - * we'd otherwise have (since CALLBACK_DATA() is meant to be run with a 'p' - * value that's in-bounds). - */ - - assert(((header_field_mark ? 1 : 0) + - (header_value_mark ? 1 : 0) + - (url_mark ? 1 : 0) + - (body_mark ? 1 : 0) + - (status_mark ? 1 : 0)) <= 1); - - CALLBACK_DATA_NOADVANCE(header_field); - CALLBACK_DATA_NOADVANCE(header_value); - CALLBACK_DATA_NOADVANCE(url); - CALLBACK_DATA_NOADVANCE(body); - CALLBACK_DATA_NOADVANCE(status); - - RETURN(len); - -error: - if (HTTP_PARSER_ERRNO(parser) == HPE_OK) { - SET_ERRNO(HPE_UNKNOWN); - } - - RETURN(p - data); -} - - -/* Does the parser need to see an EOF to find the end of the message? */ -int -http_message_needs_eof (const http_parser *parser) -{ - if (parser->type == HTTP_REQUEST) { - return 0; - } - - /* See RFC 2616 section 4.4 */ - if (parser->status_code / 100 == 1 || /* 1xx e.g. Continue */ - parser->status_code == 204 || /* No Content */ - parser->status_code == 304 || /* Not Modified */ - parser->flags & F_SKIPBODY) { /* response to a HEAD request */ - return 0; - } - - if ((parser->flags & F_CHUNKED) || parser->content_length != ULLONG_MAX) { - return 0; - } - - return 1; -} - - -int -http_should_keep_alive (const http_parser *parser) -{ - if (parser->http_major > 0 && parser->http_minor > 0) { - /* HTTP/1.1 */ - if (parser->flags & F_CONNECTION_CLOSE) { - return 0; - } - } else { - /* HTTP/1.0 or earlier */ - if (!(parser->flags & F_CONNECTION_KEEP_ALIVE)) { - return 0; - } - } - - return !http_message_needs_eof(parser); -} - - -const char * -http_method_str (enum http_method m) -{ - return ELEM_AT(method_strings, m, ""); -} - - -void -http_parser_init (http_parser *parser, enum http_parser_type t) -{ - void *data = parser->data; /* preserve application data */ - memset(parser, 0, sizeof(*parser)); - parser->data = data; - parser->type = t; - parser->state = (t == HTTP_REQUEST ? s_start_req : (t == HTTP_RESPONSE ? s_start_res : s_start_req_or_res)); - parser->http_errno = HPE_OK; -} - -void -http_parser_settings_init(http_parser_settings *settings) -{ - memset(settings, 0, sizeof(*settings)); -} - -const char * -http_errno_name(enum http_errno err) { - assert(((size_t) err) < ARRAY_SIZE(http_strerror_tab)); - return http_strerror_tab[err].name; -} - -const char * -http_errno_description(enum http_errno err) { - assert(((size_t) err) < ARRAY_SIZE(http_strerror_tab)); - return http_strerror_tab[err].description; -} - -static enum http_host_state -http_parse_host_char(enum http_host_state s, const char ch) { - switch(s) { - case s_http_userinfo: - case s_http_userinfo_start: - if (ch == '@') { - return s_http_host_start; - } - - if (IS_USERINFO_CHAR(ch)) { - return s_http_userinfo; - } - break; - - case s_http_host_start: - if (ch == '[') { - return s_http_host_v6_start; - } - - if (IS_HOST_CHAR(ch)) { - return s_http_host; - } - - break; - - case s_http_host: - if (IS_HOST_CHAR(ch)) { - return s_http_host; - } - - /* FALLTHROUGH */ - case s_http_host_v6_end: - if (ch == ':') { - return s_http_host_port_start; - } - - break; - - case s_http_host_v6: - if (ch == ']') { - return s_http_host_v6_end; - } - - /* FALLTHROUGH */ - case s_http_host_v6_start: - if (IS_HEX(ch) || ch == ':' || ch == '.') { - return s_http_host_v6; - } - - if (s == s_http_host_v6 && ch == '%') { - return s_http_host_v6_zone_start; - } - break; - - case s_http_host_v6_zone: - if (ch == ']') { - return s_http_host_v6_end; - } - - /* FALLTHROUGH */ - case s_http_host_v6_zone_start: - /* RFC 6874 Zone ID consists of 1*( unreserved / pct-encoded) */ - if (IS_ALPHANUM(ch) || ch == '%' || ch == '.' || ch == '-' || ch == '_' || - ch == '~') { - return s_http_host_v6_zone; - } - break; - - case s_http_host_port: - case s_http_host_port_start: - if (IS_NUM(ch)) { - return s_http_host_port; - } - - break; - - default: - break; - } - return s_http_host_dead; -} - -static int -http_parse_host(const char * buf, struct http_parser_url *u, int found_at) { - assert(u->field_set & (1 << UF_HOST)); - enum http_host_state s; - - const char *p; - size_t buflen = u->field_data[UF_HOST].off + u->field_data[UF_HOST].len; - - u->field_data[UF_HOST].len = 0; - - s = found_at ? s_http_userinfo_start : s_http_host_start; - - for (p = buf + u->field_data[UF_HOST].off; p < buf + buflen; p++) { - enum http_host_state new_s = http_parse_host_char(s, *p); - - if (new_s == s_http_host_dead) { - return 1; - } - - switch(new_s) { - case s_http_host: - if (s != s_http_host) { - u->field_data[UF_HOST].off = p - buf; - } - u->field_data[UF_HOST].len++; - break; - - case s_http_host_v6: - if (s != s_http_host_v6) { - u->field_data[UF_HOST].off = p - buf; - } - u->field_data[UF_HOST].len++; - break; - - case s_http_host_v6_zone_start: - case s_http_host_v6_zone: - u->field_data[UF_HOST].len++; - break; - - case s_http_host_port: - if (s != s_http_host_port) { - u->field_data[UF_PORT].off = p - buf; - u->field_data[UF_PORT].len = 0; - u->field_set |= (1 << UF_PORT); - } - u->field_data[UF_PORT].len++; - break; - - case s_http_userinfo: - if (s != s_http_userinfo) { - u->field_data[UF_USERINFO].off = p - buf ; - u->field_data[UF_USERINFO].len = 0; - u->field_set |= (1 << UF_USERINFO); - } - u->field_data[UF_USERINFO].len++; - break; - - default: - break; - } - s = new_s; - } - - /* Make sure we don't end somewhere unexpected */ - switch (s) { - case s_http_host_start: - case s_http_host_v6_start: - case s_http_host_v6: - case s_http_host_v6_zone_start: - case s_http_host_v6_zone: - case s_http_host_port_start: - case s_http_userinfo: - case s_http_userinfo_start: - return 1; - default: - break; - } - - return 0; -} - -void -http_parser_url_init(struct http_parser_url *u) { - memset(u, 0, sizeof(*u)); -} - -int -http_parser_parse_url(const char *buf, size_t buflen, int is_connect, - struct http_parser_url *u) -{ - enum state s; - const char *p; - enum http_parser_url_fields uf, old_uf; - int found_at = 0; - - u->port = u->field_set = 0; - s = is_connect ? s_req_server_start : s_req_spaces_before_url; - old_uf = UF_MAX; - - for (p = buf; p < buf + buflen; p++) { - s = parse_url_char(s, *p); - - /* Figure out the next field that we're operating on */ - switch (s) { - case s_dead: - return 1; - - /* Skip delimeters */ - case s_req_schema_slash: - case s_req_schema_slash_slash: - case s_req_server_start: - case s_req_query_string_start: - case s_req_fragment_start: - continue; - - case s_req_schema: - uf = UF_SCHEMA; - break; - - case s_req_server_with_at: - found_at = 1; - - /* FALLTROUGH */ - case s_req_server: - uf = UF_HOST; - break; - - case s_req_path: - uf = UF_PATH; - break; - - case s_req_query_string: - uf = UF_QUERY; - break; - - case s_req_fragment: - uf = UF_FRAGMENT; - break; - - default: - assert(!"Unexpected state"); - return 1; - } - - /* Nothing's changed; soldier on */ - if (uf == old_uf) { - u->field_data[uf].len++; - continue; - } - - u->field_data[uf].off = p - buf; - u->field_data[uf].len = 1; - - u->field_set |= (1 << uf); - old_uf = uf; - } - - /* host must be present if there is a schema */ - /* parsing http:///toto will fail */ - if ((u->field_set & (1 << UF_SCHEMA)) && - (u->field_set & (1 << UF_HOST)) == 0) { - return 1; - } - - if (u->field_set & (1 << UF_HOST)) { - if (http_parse_host(buf, u, found_at) != 0) { - return 1; - } - } - - /* CONNECT requests can only contain "hostname:port" */ - if (is_connect && u->field_set != ((1 << UF_HOST)|(1 << UF_PORT))) { - return 1; - } - - if (u->field_set & (1 << UF_PORT)) { - /* Don't bother with endp; we've already validated the string */ - unsigned long v = strtoul(buf + u->field_data[UF_PORT].off, NULL, 10); - - /* Ports have a max value of 2^16 */ - if (v > 0xffff) { - return 1; - } - - u->port = (uint16_t) v; - } - - return 0; -} - -void -http_parser_pause(http_parser *parser, int paused) { - /* Users should only be pausing/unpausing a parser that is not in an error - * state. In non-debug builds, there's not much that we can do about this - * other than ignore it. - */ - if (HTTP_PARSER_ERRNO(parser) == HPE_OK || - HTTP_PARSER_ERRNO(parser) == HPE_PAUSED) { - SET_ERRNO((paused) ? HPE_PAUSED : HPE_OK); - } else { - assert(0 && "Attempting to pause parser in error state"); - } -} - -int -http_body_is_final(const struct http_parser *parser) { - return parser->state == s_message_done; -} - -unsigned long -http_parser_version(void) { - return HTTP_PARSER_VERSION_MAJOR * 0x10000 | - HTTP_PARSER_VERSION_MINOR * 0x00100 | - HTTP_PARSER_VERSION_PATCH * 0x00001; -} - -#endif // #if (SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8) && SE_ENABLE_INSPECTOR diff --git a/native/cocos/bindings/jswrapper/v8/debugger/http_parser.cpp b/native/cocos/bindings/jswrapper/v8/debugger/http_parser.cpp new file mode 100644 index 0000000000..422e4aae5e --- /dev/null +++ b/native/cocos/bindings/jswrapper/v8/debugger/http_parser.cpp @@ -0,0 +1,2409 @@ +/* Based on src/http/ngx_http_parse.c from NGINX copyright Igor Sysoev + * + * Additional changes are licensed under the same terms as NGINX and + * copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * 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 "http_parser.h" + +#if (SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8) && SE_ENABLE_INSPECTOR + + #include + #include + #include + #include + #include + #include + + #ifndef ULLONG_MAX + #define ULLONG_MAX ((uint64_t)-1) /* 2^64-1 */ + #endif + + #ifndef MIN + #define MIN(a, b) ((a) < (b) ? (a) : (b)) + #endif + + #ifndef ARRAY_SIZE + #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) + #endif + + #ifndef BIT_AT + #define BIT_AT(a, i) \ + (!!((unsigned int)(a)[(unsigned int)(i) >> 3] & \ + (1 << ((unsigned int)(i)&7)))) + #endif + + #ifndef ELEM_AT + #define ELEM_AT(a, i, v) ((unsigned int)(i) < ARRAY_SIZE(a) ? (a)[(i)] : (v)) + #endif + + #define SET_ERRNO(e) \ + do { \ + parser->http_errno = (e); \ + } while (0) + + #define CURRENT_STATE() p_state + #define UPDATE_STATE(V) p_state = (enum state)(V); + #define RETURN(V) \ + do { \ + parser->state = CURRENT_STATE(); \ + return (V); \ + } while (0); + #define REEXECUTE() \ + goto reexecute; + + #ifdef __GNUC__ + #define LIKELY(X) __builtin_expect(!!(X), 1) + #define UNLIKELY(X) __builtin_expect(!!(X), 0) + #else + #define LIKELY(X) (X) + #define UNLIKELY(X) (X) + #endif + + /* Run the notify callback FOR, returning ER if it fails */ + #define CALLBACK_NOTIFY_(FOR, ER) \ + do { \ + assert(HTTP_PARSER_ERRNO(parser) == HPE_OK); \ + \ + if (LIKELY(settings->on_##FOR)) { \ + parser->state = CURRENT_STATE(); \ + if (UNLIKELY(0 != settings->on_##FOR(parser))) { \ + SET_ERRNO(HPE_CB_##FOR); \ + } \ + UPDATE_STATE(parser->state); \ + \ + /* We either errored above or got paused; get out */ \ + if (UNLIKELY(HTTP_PARSER_ERRNO(parser) != HPE_OK)) { \ + return (ER); \ + } \ + } \ + } while (0) + + /* Run the notify callback FOR and consume the current byte */ + #define CALLBACK_NOTIFY(FOR) CALLBACK_NOTIFY_(FOR, p - data + 1) + + /* Run the notify callback FOR and don't consume the current byte */ + #define CALLBACK_NOTIFY_NOADVANCE(FOR) CALLBACK_NOTIFY_(FOR, p - data) + + /* Run data callback FOR with LEN bytes, returning ER if it fails */ + #define CALLBACK_DATA_(FOR, LEN, ER) \ + do { \ + assert(HTTP_PARSER_ERRNO(parser) == HPE_OK); \ + \ + if (FOR##_mark) { \ + if (LIKELY(settings->on_##FOR)) { \ + parser->state = CURRENT_STATE(); \ + if (UNLIKELY(0 != \ + settings->on_##FOR(parser, FOR##_mark, (LEN)))) { \ + SET_ERRNO(HPE_CB_##FOR); \ + } \ + UPDATE_STATE(parser->state); \ + \ + /* We either errored above or got paused; get out */ \ + if (UNLIKELY(HTTP_PARSER_ERRNO(parser) != HPE_OK)) { \ + return (ER); \ + } \ + } \ + FOR##_mark = NULL; \ + } \ + } while (0) + + /* Run the data callback FOR and consume the current byte */ + #define CALLBACK_DATA(FOR) \ + CALLBACK_DATA_(FOR, p - FOR##_mark, p - data + 1) + + /* Run the data callback FOR and don't consume the current byte */ + #define CALLBACK_DATA_NOADVANCE(FOR) \ + CALLBACK_DATA_(FOR, p - FOR##_mark, p - data) + + /* Set the mark FOR; non-destructive if mark is already set */ + #define MARK(FOR) \ + do { \ + if (!FOR##_mark) { \ + FOR##_mark = p; \ + } \ + } while (0) + + /* Don't allow the total size of the HTTP headers (including the status + * line) to exceed HTTP_MAX_HEADER_SIZE. This check is here to protect + * embedders against denial-of-service attacks where the attacker feeds + * us a never-ending header that the embedder keeps buffering. + * + * This check is arguably the responsibility of embedders but we're doing + * it on the embedder's behalf because most won't bother and this way we + * make the web a little safer. HTTP_MAX_HEADER_SIZE is still far bigger + * than any reasonable request or response so this should never affect + * day-to-day operation. + */ + #define COUNT_HEADER_SIZE(V) \ + do { \ + parser->nread += (V); \ + if (UNLIKELY(parser->nread > (HTTP_MAX_HEADER_SIZE))) { \ + SET_ERRNO(HPE_HEADER_OVERFLOW); \ + goto error; \ + } \ + } while (0) + + #define PROXY_CONNECTION "proxy-connection" + #define CONNECTION "connection" + #define CONTENT_LENGTH "content-length" + #define TRANSFER_ENCODING "transfer-encoding" + #define UPGRADE "upgrade" + #define CHUNKED "chunked" + #define KEEP_ALIVE "keep-alive" + #define CLOSE "close" + +static const char *method_strings[] = //NOLINT(readability-identifier-naming) + { + #define XX(num, name, string) #string, + HTTP_METHOD_MAP(XX) + #undef XX +}; + +/* Tokens as defined by rfc 2616. Also lowercases them. + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + */ +static const char tokens[256] = { + /* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */ + 0, 0, 0, 0, 0, 0, 0, 0, + /* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */ + 0, 0, 0, 0, 0, 0, 0, 0, + /* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */ + 0, 0, 0, 0, 0, 0, 0, 0, + /* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */ + 0, 0, 0, 0, 0, 0, 0, 0, + /* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */ + 0, '!', 0, '#', '$', '%', '&', '\'', + /* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */ + 0, 0, '*', '+', 0, '-', '.', 0, + /* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */ + '0', '1', '2', '3', '4', '5', '6', '7', + /* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */ + '8', '9', 0, 0, 0, 0, 0, 0, + /* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */ + 0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', + /* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */ + 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', + /* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */ + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', + /* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */ + 'x', 'y', 'z', 0, 0, 0, '^', '_', + /* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */ + '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', + /* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */ + 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', + /* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */ + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', + /* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */ + 'x', 'y', 'z', 0, '|', 0, '~', 0}; + +//NOLINTNEXTLINE(readability-identifier-naming) +static const int8_t unhex[256] = + {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; + + #if HTTP_PARSER_STRICT + #define T(v) 0 + #else + #define T(v) v + #endif + +//NOLINTNEXTLINE(readability-identifier-naming) +static const uint8_t normal_url_char[32] = { + /* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */ + 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0, + /* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */ + 0 | T(2) | 0 | 0 | T(16) | 0 | 0 | 0, + /* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */ + 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0, + /* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */ + 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0, + /* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */ + 0 | 2 | 4 | 0 | 16 | 32 | 64 | 128, + /* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, + /* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, + /* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 0, + /* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, + /* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, + /* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, + /* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, + /* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, + /* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, + /* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, + /* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 0, +}; + + #undef T +//NOLINTNEXTLINE(readability-identifier-naming) +enum state { s_dead = 1 /* important that this is > 0 */ + + , + s_start_req_or_res, //NOLINT + s_res_or_resp_H, //NOLINT + s_start_res, //NOLINT + s_res_H, //NOLINT + s_res_HT, //NOLINT + s_res_HTT, //NOLINT + s_res_HTTP, //NOLINT + s_res_first_http_major, //NOLINT + s_res_http_major, //NOLINT + s_res_first_http_minor, //NOLINT + s_res_http_minor, //NOLINT + s_res_first_status_code, //NOLINT + s_res_status_code, //NOLINT + s_res_status_start, //NOLINT + s_res_status, //NOLINT + s_res_line_almost_done, //NOLINT + s_start_req, //NOLINT + s_req_method, //NOLINT + s_req_spaces_before_url, //NOLINT + s_req_schema, //NOLINT + s_req_schema_slash, //NOLINT + s_req_schema_slash_slash, //NOLINT + s_req_server_start, //NOLINT + s_req_server, //NOLINT + s_req_server_with_at, //NOLINT + s_req_path, //NOLINT + s_req_query_string_start, //NOLINT + s_req_query_string, //NOLINT + s_req_fragment_start, //NOLINT + s_req_fragment, //NOLINT + s_req_http_start, //NOLINT + s_req_http_H, //NOLINT + s_req_http_HT, //NOLINT + s_req_http_HTT, //NOLINT + s_req_http_HTTP, //NOLINT + s_req_first_http_major, //NOLINT + s_req_http_major, //NOLINT + s_req_first_http_minor, //NOLINT + s_req_http_minor, //NOLINT + s_req_line_almost_done //NOLINT + + , + s_header_field_start, //NOLINT + s_header_field, //NOLINT + s_header_value_discard_ws, //NOLINT + s_header_value_discard_ws_almost_done, //NOLINT + s_header_value_discard_lws, //NOLINT + s_header_value_start, //NOLINT + s_header_value, //NOLINT + s_header_value_lws, //NOLINT + s_header_almost_done, //NOLINT + s_chunk_size_start, //NOLINT + s_chunk_size, //NOLINT + s_chunk_parameters, //NOLINT + s_chunk_size_almost_done, //NOLINT + s_headers_almost_done, //NOLINT + s_headers_done + + /* Important: 's_headers_done' must be the last 'header' state. All + * states beyond this must be 'body' states. It is used for overflow + * checking. See the PARSING_HEADER() macro. + */ + + , + s_chunk_data, //NOLINT + s_chunk_data_almost_done, //NOLINT + s_chunk_data_done //NOLINT + + , + s_body_identity, //NOLINT + s_body_identity_eof //NOLINT + , + s_message_done //NOLINT +}; + + #define PARSING_HEADER(state) (state <= s_headers_done) + +enum header_states { h_general = 0, //NOLINT + h_C, //NOLINT + h_CO, //NOLINT + h_CON //NOLINT + + , + h_matching_connection, //NOLINT + h_matching_proxy_connection, //NOLINT + h_matching_content_length, //NOLINT + h_matching_transfer_encoding, //NOLINT + h_matching_upgrade //NOLINT + , + h_connection, //NOLINT + h_content_length, //NOLINT + h_transfer_encoding, //NOLINT + h_upgrade //NOLINT + + , + h_matching_transfer_encoding_chunked, //NOLINT + h_matching_connection_token_start, //NOLINT + h_matching_connection_keep_alive, //NOLINT + h_matching_connection_close, //NOLINT + h_matching_connection_upgrade, //NOLINT + h_matching_connection_token //NOLINT + + , + h_transfer_encoding_chunked, //NOLINT + h_connection_keep_alive, //NOLINT + h_connection_close, //NOLINT + h_connection_upgrade //NOLINT +}; + +enum http_host_state { //NOLINT + s_http_host_dead = 1, //NOLINT + s_http_userinfo_start, //NOLINT + s_http_userinfo, //NOLINT + s_http_host_start, //NOLINT + s_http_host_v6_start, //NOLINT + s_http_host, //NOLINT + s_http_host_v6, //NOLINT + s_http_host_v6_end, //NOLINT + s_http_host_v6_zone_start, //NOLINT + s_http_host_v6_zone, //NOLINT + s_http_host_port_start, //NOLINT + s_http_host_port //NOLINT +}; + + /* Macros for character classes; depends on strict-mode */ + #define CR '\r' + #define LF '\n' + #define LOWER(c) (unsigned char)(c | 0x20) + #define IS_ALPHA(c) (LOWER(c) >= 'a' && LOWER(c) <= 'z') + #define IS_NUM(c) ((c) >= '0' && (c) <= '9') + #define IS_ALPHANUM(c) (IS_ALPHA(c) || IS_NUM(c)) + #define IS_HEX(c) (IS_NUM(c) || (LOWER(c) >= 'a' && LOWER(c) <= 'f')) + #define IS_MARK(c) ((c) == '-' || (c) == '_' || (c) == '.' || \ + (c) == '!' || (c) == '~' || (c) == '*' || (c) == '\'' || (c) == '(' || \ + (c) == ')') + #define IS_USERINFO_CHAR(c) (IS_ALPHANUM(c) || IS_MARK(c) || (c) == '%' || \ + (c) == ';' || (c) == ':' || (c) == '&' || (c) == '=' || (c) == '+' || \ + (c) == '$' || (c) == ',') + + #define STRICT_TOKEN(c) (tokens[(unsigned char)c]) + + #if HTTP_PARSER_STRICT + #define TOKEN(c) (tokens[(unsigned char)c]) + #define IS_URL_CHAR(c) (BIT_AT(normal_url_char, (unsigned char)c)) + #define IS_HOST_CHAR(c) (IS_ALPHANUM(c) || (c) == '.' || (c) == '-') + #else + #define TOKEN(c) ((c == ' ') ? ' ' : tokens[(unsigned char)c]) + #define IS_URL_CHAR(c) \ + (BIT_AT(normal_url_char, (unsigned char)c) || ((c)&0x80)) + #define IS_HOST_CHAR(c) \ + (IS_ALPHANUM(c) || (c) == '.' || (c) == '-' || (c) == '_') + #endif + + /** + * Verify that a char is a valid visible (printable) US-ASCII + * character or %x80-FF + **/ + #define IS_HEADER_CHAR(ch) \ + (ch == CR || ch == LF || ch == 9 || ((unsigned char)ch > 31 && ch != 127)) + + #define start_state (parser->type == HTTP_REQUEST ? s_start_req : s_start_res) + + #if HTTP_PARSER_STRICT + #define STRICT_CHECK(cond) \ + do { \ + if (cond) { \ + SET_ERRNO(HPE_STRICT); \ + goto error; \ + } \ + } while (0) + #define NEW_MESSAGE() (http_should_keep_alive(parser) ? start_state : s_dead) + #else + #define STRICT_CHECK(cond) + #define NEW_MESSAGE() start_state + #endif + + /* Map errno values to strings for human-readable output */ + #define HTTP_STRERROR_GEN(n, s) {"HPE_" #n, s}, +static struct { + const char *name; + const char *description; +} http_strerror_tab[] = { //NOLINT + HTTP_ERRNO_MAP(HTTP_STRERROR_GEN)}; + #undef HTTP_STRERROR_GEN + +int http_message_needs_eof(const http_parser *parser); //NOLINT + +/* Our URL parser. + * + * This is designed to be shared by http_parser_execute() for URL validation, + * hence it has a state transition + byte-for-byte interface. In addition, it + * is meant to be embedded in http_parser_parse_url(), which does the dirty + * work of turning state transitions URL components for its API. + * + * This function should only be invoked with non-space characters. It is + * assumed that the caller cares about (and can detect) the transition between + * URL and non-URL states by looking for these. + */ +static enum state +parse_url_char(enum state s, const char ch) { //NOLINT + if (ch == ' ' || ch == '\r' || ch == '\n') { + return s_dead; + } + + #if HTTP_PARSER_STRICT + if (ch == '\t' || ch == '\f') { + return s_dead; + } + #endif + + switch (s) { + case s_req_spaces_before_url: + /* Proxied requests are followed by scheme of an absolute URI (alpha). + * All methods except CONNECT are followed by '/' or '*'. + */ + + if (ch == '/' || ch == '*') { + return s_req_path; + } + + if (IS_ALPHA(ch)) { + return s_req_schema; + } + + break; + + case s_req_schema: + if (IS_ALPHA(ch)) { + return s; + } + + if (ch == ':') { + return s_req_schema_slash; + } + + break; + + case s_req_schema_slash: + if (ch == '/') { + return s_req_schema_slash_slash; + } + + break; + + case s_req_schema_slash_slash: + if (ch == '/') { + return s_req_server_start; + } + + break; + + case s_req_server_with_at: + if (ch == '@') { + return s_dead; + } + + /* FALLTHROUGH */ + case s_req_server_start: + case s_req_server: + if (ch == '/') { + return s_req_path; + } + + if (ch == '?') { + return s_req_query_string_start; + } + + if (ch == '@') { + return s_req_server_with_at; + } + + if (IS_USERINFO_CHAR(ch) || ch == '[' || ch == ']') { + return s_req_server; + } + + break; + + case s_req_path: + if (IS_URL_CHAR(ch)) { + return s; + } + + switch (ch) { + case '?': + return s_req_query_string_start; + + case '#': + return s_req_fragment_start; + } + + break; + + case s_req_query_string_start: + case s_req_query_string: + if (IS_URL_CHAR(ch)) { + return s_req_query_string; + } + + switch (ch) { + case '?': + /* allow extra '?' in query string */ + return s_req_query_string; + + case '#': + return s_req_fragment_start; + } + + break; + + case s_req_fragment_start: + if (IS_URL_CHAR(ch)) { + return s_req_fragment; + } + + switch (ch) { + case '?': + return s_req_fragment; + + case '#': + return s; + } + + break; + + case s_req_fragment: + if (IS_URL_CHAR(ch)) { + return s; + } + + switch (ch) { + case '?': + case '#': + return s; + } + + break; + + default: + break; + } + + /* We should never fall out of the switch above unless there's an error */ + return s_dead; +} +//NOLINTNEXTLINE +size_t http_parser_execute(http_parser * parser, + const http_parser_settings *settings, + const char * data, + size_t len) { + char c, ch; //NOLINT + int8_t unhex_val; //NOLINT + const char * p = data; + const char * header_field_mark = nullptr; + const char * header_value_mark = nullptr; + const char * url_mark = nullptr; + const char * body_mark = nullptr; + const char * status_mark = nullptr; + auto p_state = static_cast(parser->state); + const unsigned int lenient = parser->lenient_http_headers; + + /* We're in an error state. Don't bother doing anything. */ + if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { + return 0; + } + + if (len == 0) { + switch (CURRENT_STATE()) { + case s_body_identity_eof: + /* Use of CALLBACK_NOTIFY() here would erroneously return 1 byte read if + * we got paused. + */ + CALLBACK_NOTIFY_NOADVANCE(message_complete); + return 0; + + case s_dead: + case s_start_req_or_res: + case s_start_res: + case s_start_req: + return 0; + + default: + SET_ERRNO(HPE_INVALID_EOF_STATE); + return 1; + } + } + + if (CURRENT_STATE() == s_header_field) { + header_field_mark = data; + } + if (CURRENT_STATE() == s_header_value) { + header_value_mark = data; + } + switch (CURRENT_STATE()) { + case s_req_path: + case s_req_schema: + case s_req_schema_slash: + case s_req_schema_slash_slash: + case s_req_server_start: + case s_req_server: + case s_req_server_with_at: + case s_req_query_string_start: + case s_req_query_string: + case s_req_fragment_start: + case s_req_fragment: + url_mark = data; + break; + case s_res_status: + status_mark = data; + break; + default: + break; + } + + for (p = data; p != data + len; p++) { + ch = *p; + + if (PARSING_HEADER(CURRENT_STATE())) { + COUNT_HEADER_SIZE(1); + } + + reexecute: + switch (CURRENT_STATE()) { + case s_dead: + /* this state is used after a 'Connection: close' message + * the parser will error out if it reads another message + */ + if (LIKELY(ch == CR || ch == LF)) { + break; + } + + SET_ERRNO(HPE_CLOSED_CONNECTION); + goto error; + + case s_start_req_or_res: { + if (ch == CR || ch == LF) { + break; + } + parser->flags = 0; + parser->content_length = ULLONG_MAX; + + if (ch == 'H') { + UPDATE_STATE(s_res_or_resp_H); + + CALLBACK_NOTIFY(message_begin); + } else { + parser->type = HTTP_REQUEST; + UPDATE_STATE(s_start_req); + REEXECUTE(); + } + + break; + } + + case s_res_or_resp_H: + if (ch == 'T') { + parser->type = HTTP_RESPONSE; + UPDATE_STATE(s_res_HT); + } else { + if (UNLIKELY(ch != 'E')) { + SET_ERRNO(HPE_INVALID_CONSTANT); + goto error; + } + + parser->type = HTTP_REQUEST; + parser->method = HTTP_HEAD; + parser->index = 2; + UPDATE_STATE(s_req_method); + } + break; + + case s_start_res: { + parser->flags = 0; + parser->content_length = ULLONG_MAX; + + switch (ch) { + case 'H': + UPDATE_STATE(s_res_H); + break; + + case CR: + case LF: + break; + + default: + SET_ERRNO(HPE_INVALID_CONSTANT); + goto error; + } + + CALLBACK_NOTIFY(message_begin); + break; + } + + case s_res_H: + STRICT_CHECK(ch != 'T'); + UPDATE_STATE(s_res_HT); + break; + + case s_res_HT: + STRICT_CHECK(ch != 'T'); + UPDATE_STATE(s_res_HTT); + break; + + case s_res_HTT: + STRICT_CHECK(ch != 'P'); + UPDATE_STATE(s_res_HTTP); + break; + + case s_res_HTTP: + STRICT_CHECK(ch != '/'); + UPDATE_STATE(s_res_first_http_major); + break; + + case s_res_first_http_major: + if (UNLIKELY(ch < '0' || ch > '9')) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + parser->http_major = ch - '0'; + UPDATE_STATE(s_res_http_major); + break; + + /* major HTTP version or dot */ + case s_res_http_major: { + if (ch == '.') { + UPDATE_STATE(s_res_first_http_minor); + break; + } + + if (!IS_NUM(ch)) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + parser->http_major *= 10; + parser->http_major += ch - '0'; + + if (UNLIKELY(parser->http_major > 999)) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + break; + } + + /* first digit of minor HTTP version */ + case s_res_first_http_minor: + if (UNLIKELY(!IS_NUM(ch))) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + parser->http_minor = ch - '0'; + UPDATE_STATE(s_res_http_minor); + break; + + /* minor HTTP version or end of request line */ + case s_res_http_minor: { + if (ch == ' ') { + UPDATE_STATE(s_res_first_status_code); + break; + } + + if (UNLIKELY(!IS_NUM(ch))) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + parser->http_minor *= 10; + parser->http_minor += ch - '0'; + + if (UNLIKELY(parser->http_minor > 999)) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + break; + } + + case s_res_first_status_code: { + if (!IS_NUM(ch)) { + if (ch == ' ') { + break; + } + + SET_ERRNO(HPE_INVALID_STATUS); + goto error; + } + parser->status_code = ch - '0'; + UPDATE_STATE(s_res_status_code); + break; + } + + case s_res_status_code: { + if (!IS_NUM(ch)) { + switch (ch) { + case ' ': + UPDATE_STATE(s_res_status_start); + break; + case CR: + UPDATE_STATE(s_res_line_almost_done); + break; + case LF: + UPDATE_STATE(s_header_field_start); + break; + default: + SET_ERRNO(HPE_INVALID_STATUS); + goto error; + } + break; + } + + parser->status_code *= 10; + parser->status_code += ch - '0'; + + if (UNLIKELY(parser->status_code > 999)) { + SET_ERRNO(HPE_INVALID_STATUS); + goto error; + } + + break; + } + + case s_res_status_start: { + if (ch == CR) { + UPDATE_STATE(s_res_line_almost_done); + break; + } + + if (ch == LF) { + UPDATE_STATE(s_header_field_start); + break; + } + + MARK(status); + UPDATE_STATE(s_res_status); + parser->index = 0; + break; + } + + case s_res_status: + if (ch == CR) { + UPDATE_STATE(s_res_line_almost_done); + CALLBACK_DATA(status); + break; + } + + if (ch == LF) { + UPDATE_STATE(s_header_field_start); + CALLBACK_DATA(status); + break; + } + + break; + + case s_res_line_almost_done: + STRICT_CHECK(ch != LF); + UPDATE_STATE(s_header_field_start); + break; + + case s_start_req: { + if (ch == CR || ch == LF) { + break; + } + parser->flags = 0; + parser->content_length = ULLONG_MAX; + + if (UNLIKELY(!IS_ALPHA(ch))) { + SET_ERRNO(HPE_INVALID_METHOD); + goto error; + } + + parser->method = static_cast(0); + parser->index = 1; + switch (ch) { + case 'A': parser->method = HTTP_ACL; break; + case 'B': parser->method = HTTP_BIND; break; + case 'C': + parser->method = HTTP_CONNECT; /* or COPY, CHECKOUT */ + break; + case 'D': parser->method = HTTP_DELETE; break; + case 'G': parser->method = HTTP_GET; break; + case 'H': parser->method = HTTP_HEAD; break; + case 'L': + parser->method = HTTP_LOCK; /* or LINK */ + break; + case 'M': + parser->method = HTTP_MKCOL; /* or MOVE, MKACTIVITY, MERGE, M-SEARCH, MKCALENDAR */ + break; + case 'N': parser->method = HTTP_NOTIFY; break; + case 'O': parser->method = HTTP_OPTIONS; break; + case 'P': + parser->method = HTTP_POST; + /* or PROPFIND|PROPPATCH|PUT|PATCH|PURGE */ + break; + case 'R': + parser->method = HTTP_REPORT; /* or REBIND */ + break; + case 'S': + parser->method = HTTP_SUBSCRIBE; /* or SEARCH */ + break; + case 'T': parser->method = HTTP_TRACE; break; + case 'U': + parser->method = HTTP_UNLOCK; /* or UNSUBSCRIBE, UNBIND, UNLINK */ + break; + default: + SET_ERRNO(HPE_INVALID_METHOD); + goto error; + } + UPDATE_STATE(s_req_method); + + CALLBACK_NOTIFY(message_begin); + + break; + } + + case s_req_method: { + const char *matcher; + if (UNLIKELY(ch == '\0')) { + SET_ERRNO(HPE_INVALID_METHOD); + goto error; + } + + matcher = method_strings[parser->method]; + if (ch == ' ' && matcher[parser->index] == '\0') { + UPDATE_STATE(s_req_spaces_before_url); + } else if (ch == matcher[parser->index]) { + ; /* nada */ + } else if (IS_ALPHA(ch)) { + switch (parser->method << 16 | parser->index << 8 | ch) { //NOLINT + #define XX(meth, pos, ch, new_meth) \ + case (HTTP_##meth << 16 | pos << 8 | ch): \ + parser->method = HTTP_##new_meth; \ + break; + + XX(POST, 1, 'U', PUT) + XX(POST, 1, 'A', PATCH) + XX(CONNECT, 1, 'H', CHECKOUT) + XX(CONNECT, 2, 'P', COPY) + XX(MKCOL, 1, 'O', MOVE) + XX(MKCOL, 1, 'E', MERGE) + XX(MKCOL, 2, 'A', MKACTIVITY) + XX(MKCOL, 3, 'A', MKCALENDAR) + XX(SUBSCRIBE, 1, 'E', SEARCH) + XX(REPORT, 2, 'B', REBIND) + XX(POST, 1, 'R', PROPFIND) + XX(PROPFIND, 4, 'P', PROPPATCH) + XX(PUT, 2, 'R', PURGE) + XX(LOCK, 1, 'I', LINK) + XX(UNLOCK, 2, 'S', UNSUBSCRIBE) + XX(UNLOCK, 2, 'B', UNBIND) + XX(UNLOCK, 3, 'I', UNLINK) + #undef XX + + default: + SET_ERRNO(HPE_INVALID_METHOD); + goto error; + } + } else if (ch == '-' && + parser->index == 1 && //NOLINT + parser->method == HTTP_MKCOL) { //NOLINT + parser->method = HTTP_MSEARCH; + } else { + SET_ERRNO(HPE_INVALID_METHOD); + goto error; + } + + ++parser->index; + break; + } + + case s_req_spaces_before_url: { + if (ch == ' ') break; + + MARK(url); + if (parser->method == HTTP_CONNECT) { //NOLINT + UPDATE_STATE(s_req_server_start); + } + + UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch)); + if (UNLIKELY(CURRENT_STATE() == s_dead)) { + SET_ERRNO(HPE_INVALID_URL); + goto error; + } + + break; + } + + case s_req_schema: + case s_req_schema_slash: + case s_req_schema_slash_slash: + case s_req_server_start: { + switch (ch) { + /* No whitespace allowed here */ + case ' ': + case CR: + case LF: + SET_ERRNO(HPE_INVALID_URL); + goto error; + default: + UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch)); + if (UNLIKELY(CURRENT_STATE() == s_dead)) { + SET_ERRNO(HPE_INVALID_URL); + goto error; + } + } + + break; + } + + case s_req_server: + case s_req_server_with_at: + case s_req_path: + case s_req_query_string_start: + case s_req_query_string: + case s_req_fragment_start: + case s_req_fragment: { + switch (ch) { + case ' ': + UPDATE_STATE(s_req_http_start); + CALLBACK_DATA(url); + break; + case CR: + case LF: + parser->http_major = 0; + parser->http_minor = 9; + UPDATE_STATE((ch == CR) ? s_req_line_almost_done : s_header_field_start); + CALLBACK_DATA(url); + break; + default: + UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch)); + if (UNLIKELY(CURRENT_STATE() == s_dead)) { + SET_ERRNO(HPE_INVALID_URL); + goto error; + } + } + break; + } + + case s_req_http_start: + switch (ch) { + case 'H': + UPDATE_STATE(s_req_http_H); + break; + case ' ': + break; + default: + SET_ERRNO(HPE_INVALID_CONSTANT); + goto error; + } + break; + + case s_req_http_H: + STRICT_CHECK(ch != 'T'); + UPDATE_STATE(s_req_http_HT); + break; + + case s_req_http_HT: + STRICT_CHECK(ch != 'T'); + UPDATE_STATE(s_req_http_HTT); + break; + + case s_req_http_HTT: + STRICT_CHECK(ch != 'P'); + UPDATE_STATE(s_req_http_HTTP); + break; + + case s_req_http_HTTP: + STRICT_CHECK(ch != '/'); + UPDATE_STATE(s_req_first_http_major); + break; + + /* first digit of major HTTP version */ + case s_req_first_http_major: + if (UNLIKELY(ch < '1' || ch > '9')) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + parser->http_major = ch - '0'; + UPDATE_STATE(s_req_http_major); + break; + + /* major HTTP version or dot */ + case s_req_http_major: { + if (ch == '.') { + UPDATE_STATE(s_req_first_http_minor); + break; + } + + if (UNLIKELY(!IS_NUM(ch))) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + parser->http_major *= 10; + parser->http_major += ch - '0'; + + if (UNLIKELY(parser->http_major > 999)) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + break; + } + + /* first digit of minor HTTP version */ + case s_req_first_http_minor: + if (UNLIKELY(!IS_NUM(ch))) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + parser->http_minor = ch - '0'; + UPDATE_STATE(s_req_http_minor); + break; + + /* minor HTTP version or end of request line */ + case s_req_http_minor: { + if (ch == CR) { + UPDATE_STATE(s_req_line_almost_done); + break; + } + + if (ch == LF) { + UPDATE_STATE(s_header_field_start); + break; + } + + /* XXX allow spaces after digit? */ + + if (UNLIKELY(!IS_NUM(ch))) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + parser->http_minor *= 10; + parser->http_minor += ch - '0'; + + if (UNLIKELY(parser->http_minor > 999)) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + break; + } + + /* end of request line */ + case s_req_line_almost_done: { + if (UNLIKELY(ch != LF)) { + SET_ERRNO(HPE_LF_EXPECTED); + goto error; + } + + UPDATE_STATE(s_header_field_start); + break; + } + + case s_header_field_start: { + if (ch == CR) { + UPDATE_STATE(s_headers_almost_done); + break; + } + + if (ch == LF) { + /* they might be just sending \n instead of \r\n so this would be + * the second \n to denote the end of headers*/ + UPDATE_STATE(s_headers_almost_done); + REEXECUTE(); + } + + c = TOKEN(ch); + + if (UNLIKELY(!c)) { + SET_ERRNO(HPE_INVALID_HEADER_TOKEN); + goto error; + } + + MARK(header_field); + + parser->index = 0; + UPDATE_STATE(s_header_field); + + switch (c) { + case 'c': + parser->header_state = h_C; + break; + + case 'p': + parser->header_state = h_matching_proxy_connection; + break; + + case 't': + parser->header_state = h_matching_transfer_encoding; + break; + + case 'u': + parser->header_state = h_matching_upgrade; + break; + + default: + parser->header_state = h_general; + break; + } + break; + } + + case s_header_field: { + const char *start = p; + for (; p != data + len; p++) { + ch = *p; + c = TOKEN(ch); + + if (!c) { + break; + } + + switch (parser->header_state) { //NOLINT + case h_general: + break; + + case h_C: + parser->index++; + parser->header_state = (c == 'o' ? h_CO : h_general); + break; + + case h_CO: + parser->index++; + parser->header_state = (c == 'n' ? h_CON : h_general); + break; + + case h_CON: + parser->index++; + switch (c) { + case 'n': + parser->header_state = h_matching_connection; + break; + case 't': + parser->header_state = h_matching_content_length; + break; + default: + parser->header_state = h_general; + break; + } + break; + + /* connection */ + + case h_matching_connection: + parser->index++; + if (parser->index > sizeof(CONNECTION) - 1 || c != CONNECTION[parser->index]) { + parser->header_state = h_general; + } else if (parser->index == sizeof(CONNECTION) - 2) { + parser->header_state = h_connection; + } + break; + + /* proxy-connection */ + + case h_matching_proxy_connection: + parser->index++; + if (parser->index > sizeof(PROXY_CONNECTION) - 1 || c != PROXY_CONNECTION[parser->index]) { + parser->header_state = h_general; + } else if (parser->index == sizeof(PROXY_CONNECTION) - 2) { + parser->header_state = h_connection; + } + break; + + /* content-length */ + + case h_matching_content_length: + parser->index++; + if (parser->index > sizeof(CONTENT_LENGTH) - 1 || c != CONTENT_LENGTH[parser->index]) { + parser->header_state = h_general; + } else if (parser->index == sizeof(CONTENT_LENGTH) - 2) { + if (parser->flags & F_CONTENTLENGTH) { //NOLINT + SET_ERRNO(HPE_UNEXPECTED_CONTENT_LENGTH); + goto error; + } + parser->header_state = h_content_length; + parser->flags |= F_CONTENTLENGTH; + } + break; + + /* transfer-encoding */ + + case h_matching_transfer_encoding: + parser->index++; + if (parser->index > sizeof(TRANSFER_ENCODING) - 1 || c != TRANSFER_ENCODING[parser->index]) { + parser->header_state = h_general; + } else if (parser->index == sizeof(TRANSFER_ENCODING) - 2) { + parser->header_state = h_transfer_encoding; + } + break; + + /* upgrade */ + + case h_matching_upgrade: + parser->index++; + if (parser->index > sizeof(UPGRADE) - 1 || c != UPGRADE[parser->index]) { + parser->header_state = h_general; + } else if (parser->index == sizeof(UPGRADE) - 2) { + parser->header_state = h_upgrade; + } + break; + + case h_connection: + case h_content_length: + case h_transfer_encoding: + case h_upgrade: + if (ch != ' ') parser->header_state = h_general; + break; + + default: + assert(0 && "Unknown header_state"); + break; + } + } + + COUNT_HEADER_SIZE(p - start); + + if (p == data + len) { + --p; + break; + } + + if (ch == ':') { + UPDATE_STATE(s_header_value_discard_ws); + CALLBACK_DATA(header_field); + break; + } + + SET_ERRNO(HPE_INVALID_HEADER_TOKEN); + goto error; + } + + case s_header_value_discard_ws: + if (ch == ' ' || ch == '\t') break; + + if (ch == CR) { + UPDATE_STATE(s_header_value_discard_ws_almost_done); + break; + } + + if (ch == LF) { + UPDATE_STATE(s_header_value_discard_lws); + break; + } + + /* FALLTHROUGH */ + + case s_header_value_start: { + MARK(header_value); + + UPDATE_STATE(s_header_value); + parser->index = 0; + + c = LOWER(ch); + + switch (parser->header_state) { //NOLINT + case h_upgrade: + parser->flags |= F_UPGRADE; + parser->header_state = h_general; + break; + + case h_transfer_encoding: + /* looking for 'Transfer-Encoding: chunked' */ + if ('c' == c) { + parser->header_state = h_matching_transfer_encoding_chunked; + } else { + parser->header_state = h_general; + } + break; + + case h_content_length: + if (UNLIKELY(!IS_NUM(ch))) { + SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); + goto error; + } + + parser->content_length = ch - '0'; + break; + + case h_connection: + /* looking for 'Connection: keep-alive' */ + if (c == 'k') { + parser->header_state = h_matching_connection_keep_alive; + /* looking for 'Connection: close' */ + } else if (c == 'c') { + parser->header_state = h_matching_connection_close; + } else if (c == 'u') { + parser->header_state = h_matching_connection_upgrade; + } else { + parser->header_state = h_matching_connection_token; + } + break; + + /* Multi-value `Connection` header */ + case h_matching_connection_token_start: + break; + + default: + parser->header_state = h_general; + break; + } + break; + } + + case s_header_value: { + const char *start = p; + auto hState = static_cast(parser->header_state); + for (; p != data + len; p++) { + ch = *p; + if (ch == CR) { + UPDATE_STATE(s_header_almost_done); + parser->header_state = hState; + CALLBACK_DATA(header_value); + break; + } + + if (ch == LF) { + UPDATE_STATE(s_header_almost_done); + COUNT_HEADER_SIZE(p - start); + parser->header_state = hState; + CALLBACK_DATA_NOADVANCE(header_value); + REEXECUTE(); + } + + if (!lenient && !IS_HEADER_CHAR(ch)) { + SET_ERRNO(HPE_INVALID_HEADER_TOKEN); + goto error; + } + + c = LOWER(ch); + + switch (hState) { + case h_general: { + const char *pCr; + const char *pLf; + size_t limit = data + len - p; + + limit = MIN(limit, HTTP_MAX_HEADER_SIZE); + + pCr = static_cast(memchr(p, CR, limit)); + pLf = static_cast(memchr(p, LF, limit)); + if (pCr != nullptr) { + if (pLf != nullptr && pCr >= pLf) { + p = pLf; + } else { + p = pCr; + } + } else if (UNLIKELY(pLf != nullptr)) { + p = pLf; + } else { + p = data + len; + } + --p; + + break; + } + + case h_connection: + case h_transfer_encoding: + assert(0 && "Shouldn't get here."); + break; + + case h_content_length: { + uint64_t t; + + if (ch == ' ') break; + + if (UNLIKELY(!IS_NUM(ch))) { + SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); + parser->header_state = hState; + goto error; + } + + t = parser->content_length; + t *= 10; + t += ch - '0'; + + /* Overflow? Test against a conservative limit for simplicity. */ + if (UNLIKELY((ULLONG_MAX - 10) / 10 < parser->content_length)) { + SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); + parser->header_state = hState; + goto error; + } + + parser->content_length = t; + break; + } + + /* Transfer-Encoding: chunked */ + case h_matching_transfer_encoding_chunked: + parser->index++; + if (parser->index > sizeof(CHUNKED) - 1 || c != CHUNKED[parser->index]) { + hState = h_general; + } else if (parser->index == sizeof(CHUNKED) - 2) { + hState = h_transfer_encoding_chunked; + } + break; + + case h_matching_connection_token_start: + /* looking for 'Connection: keep-alive' */ + if (c == 'k') { + hState = h_matching_connection_keep_alive; + /* looking for 'Connection: close' */ + } else if (c == 'c') { + hState = h_matching_connection_close; + } else if (c == 'u') { + hState = h_matching_connection_upgrade; + } else if (STRICT_TOKEN(c)) { + hState = h_matching_connection_token; + } else if (c == ' ' || c == '\t') { + /* Skip lws */ + } else { + hState = h_general; + } + break; + + /* looking for 'Connection: keep-alive' */ + case h_matching_connection_keep_alive: + parser->index++; + if (parser->index > sizeof(KEEP_ALIVE) - 1 || c != KEEP_ALIVE[parser->index]) { + hState = h_matching_connection_token; + } else if (parser->index == sizeof(KEEP_ALIVE) - 2) { + hState = h_connection_keep_alive; + } + break; + + /* looking for 'Connection: close' */ + case h_matching_connection_close: + parser->index++; + if (parser->index > sizeof(CLOSE) - 1 || c != CLOSE[parser->index]) { + hState = h_matching_connection_token; + } else if (parser->index == sizeof(CLOSE) - 2) { + hState = h_connection_close; + } + break; + + /* looking for 'Connection: upgrade' */ + case h_matching_connection_upgrade: + parser->index++; + if (parser->index > sizeof(UPGRADE) - 1 || + c != UPGRADE[parser->index]) { + hState = h_matching_connection_token; + } else if (parser->index == sizeof(UPGRADE) - 2) { + hState = h_connection_upgrade; + } + break; + + case h_matching_connection_token: + if (ch == ',') { + hState = h_matching_connection_token_start; + parser->index = 0; + } + break; + + case h_transfer_encoding_chunked: + if (ch != ' ') hState = h_general; + break; + + case h_connection_keep_alive: + case h_connection_close: + case h_connection_upgrade: + if (ch == ',') { + if (hState == h_connection_keep_alive) { + parser->flags |= F_CONNECTION_KEEP_ALIVE; + } else if (hState == h_connection_close) { + parser->flags |= F_CONNECTION_CLOSE; + } else if (hState == h_connection_upgrade) { + parser->flags |= F_CONNECTION_UPGRADE; + } + hState = h_matching_connection_token_start; + parser->index = 0; + } else if (ch != ' ') { + hState = h_matching_connection_token; + } + break; + + default: + UPDATE_STATE(s_header_value); + hState = h_general; + break; + } + } + parser->header_state = hState; + + COUNT_HEADER_SIZE(p - start); + + if (p == data + len) { + --p; + } + break; + } + + case s_header_almost_done: { + if (UNLIKELY(ch != LF)) { + SET_ERRNO(HPE_LF_EXPECTED); + goto error; + } + + UPDATE_STATE(s_header_value_lws); + break; + } + + case s_header_value_lws: { + if (ch == ' ' || ch == '\t') { + UPDATE_STATE(s_header_value_start); + REEXECUTE(); + } + + /* finished the header */ + switch (parser->header_state) { //NOLINT + case h_connection_keep_alive: + parser->flags |= F_CONNECTION_KEEP_ALIVE; + break; + case h_connection_close: + parser->flags |= F_CONNECTION_CLOSE; + break; + case h_transfer_encoding_chunked: + parser->flags |= F_CHUNKED; + break; + case h_connection_upgrade: + parser->flags |= F_CONNECTION_UPGRADE; + break; + default: + break; + } + + UPDATE_STATE(s_header_field_start); + REEXECUTE(); + } + + case s_header_value_discard_ws_almost_done: { + STRICT_CHECK(ch != LF); + UPDATE_STATE(s_header_value_discard_lws); + break; + } + + case s_header_value_discard_lws: { + if (ch == ' ' || ch == '\t') { + UPDATE_STATE(s_header_value_discard_ws); + break; + } + switch (parser->header_state) { //NOLINT + case h_connection_keep_alive: + parser->flags |= F_CONNECTION_KEEP_ALIVE; + break; + case h_connection_close: + parser->flags |= F_CONNECTION_CLOSE; + break; + case h_connection_upgrade: + parser->flags |= F_CONNECTION_UPGRADE; + break; + case h_transfer_encoding_chunked: + parser->flags |= F_CHUNKED; + break; + default: + break; + } + + /* header value was empty */ + MARK(header_value); + UPDATE_STATE(s_header_field_start); + CALLBACK_DATA_NOADVANCE(header_value); + REEXECUTE(); + } + + case s_headers_almost_done: { + STRICT_CHECK(ch != LF); + + if (parser->flags & F_TRAILING) { //NOLINT + /* End of a chunked request */ + UPDATE_STATE(s_message_done); + CALLBACK_NOTIFY_NOADVANCE(chunk_complete); + REEXECUTE(); + } + + /* Cannot use chunked encoding and a content-length header together + per the HTTP specification. */ + if ((parser->flags & F_CHUNKED) && //NOLINT + (parser->flags & F_CONTENTLENGTH)) { //NOLINT + SET_ERRNO(HPE_UNEXPECTED_CONTENT_LENGTH); + goto error; + } + + UPDATE_STATE(s_headers_done); + + /* Set this here so that on_headers_complete() callbacks can see it */ + parser->upgrade = + ((parser->flags & (F_UPGRADE | F_CONNECTION_UPGRADE)) == //NOLINT + (F_UPGRADE | F_CONNECTION_UPGRADE) || + parser->method == HTTP_CONNECT); //NOLINT + + /* Here we call the headers_complete callback. This is somewhat + * different than other callbacks because if the user returns 1, we + * will interpret that as saying that this message has no body. This + * is needed for the annoying case of recieving a response to a HEAD + * request. + * + * We'd like to use CALLBACK_NOTIFY_NOADVANCE() here but we cannot, so + * we have to simulate it by handling a change in errno below. + */ + if (settings->on_headers_complete) { + switch (settings->on_headers_complete(parser)) { + case 0: + break; + + case 2: + parser->upgrade = 1; + + case 1: + parser->flags |= F_SKIPBODY; + break; + + default: + SET_ERRNO(HPE_CB_headers_complete); + RETURN(p - data); /* Error */ + } + } + + if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { + RETURN(p - data); + } + + REEXECUTE(); + } + + case s_headers_done: { + int hasBody; + STRICT_CHECK(ch != LF); + + parser->nread = 0; + + hasBody = parser->flags & F_CHUNKED || //NOLINT + (parser->content_length > 0 && parser->content_length != ULLONG_MAX); + if (parser->upgrade && (parser->method == HTTP_CONNECT || //NOLINT + (parser->flags & F_SKIPBODY) || !hasBody)) { //NOLINT + /* Exit, the rest of the message is in a different protocol. */ + UPDATE_STATE(NEW_MESSAGE()); + CALLBACK_NOTIFY(message_complete); + RETURN((p - data) + 1); + } + + if (parser->flags & F_SKIPBODY) { //NOLINT + UPDATE_STATE(NEW_MESSAGE()); + CALLBACK_NOTIFY(message_complete); + } else if (parser->flags & F_CHUNKED) { //NOLINT + /* chunked encoding - ignore Content-Length header */ + UPDATE_STATE(s_chunk_size_start); + } else { + if (parser->content_length == 0) { + /* Content-Length header given but zero: Content-Length: 0\r\n */ + UPDATE_STATE(NEW_MESSAGE()); + CALLBACK_NOTIFY(message_complete); + } else if (parser->content_length != ULLONG_MAX) { + /* Content-Length header given and non-zero */ + UPDATE_STATE(s_body_identity); + } else { + if (!http_message_needs_eof(parser)) { + /* Assume content-length 0 - read the next */ + UPDATE_STATE(NEW_MESSAGE()); + CALLBACK_NOTIFY(message_complete); + } else { + /* Read body until EOF */ + UPDATE_STATE(s_body_identity_eof); + } + } + } + + break; + } + + case s_body_identity: { + uint64_t toRead = MIN(parser->content_length, + (uint64_t)((data + len) - p)); + + assert(parser->content_length != 0 && parser->content_length != ULLONG_MAX); + + /* The difference between advancing content_length and p is because + * the latter will automaticaly advance on the next loop iteration. + * Further, if content_length ends up at 0, we want to see the last + * byte again for our message complete callback. + */ + MARK(body); + parser->content_length -= toRead; + p += toRead - 1; + + if (parser->content_length == 0) { + UPDATE_STATE(s_message_done); + + /* Mimic CALLBACK_DATA_NOADVANCE() but with one extra byte. + * + * The alternative to doing this is to wait for the next byte to + * trigger the data callback, just as in every other case. The + * problem with this is that this makes it difficult for the test + * harness to distinguish between complete-on-EOF and + * complete-on-length. It's not clear that this distinction is + * important for applications, but let's keep it for now. + */ + CALLBACK_DATA_(body, p - body_mark + 1, p - data); + REEXECUTE(); + } + + break; + } + + /* read until EOF */ + case s_body_identity_eof: + MARK(body); + p = data + len - 1; + + break; + + case s_message_done: + UPDATE_STATE(NEW_MESSAGE()); + CALLBACK_NOTIFY(message_complete); + if (parser->upgrade) { + /* Exit, the rest of the message is in a different protocol. */ + RETURN((p - data) + 1); + } + break; + + case s_chunk_size_start: { + assert(parser->nread == 1); + assert(parser->flags & F_CHUNKED); + + unhex_val = unhex[static_cast(ch)]; + if (UNLIKELY(unhex_val == -1)) { + SET_ERRNO(HPE_INVALID_CHUNK_SIZE); + goto error; + } + + parser->content_length = unhex_val; + UPDATE_STATE(s_chunk_size); + break; + } + + case s_chunk_size: { + uint64_t t; + + assert(parser->flags & F_CHUNKED); + + if (ch == CR) { + UPDATE_STATE(s_chunk_size_almost_done); + break; + } + + unhex_val = unhex[static_cast(ch)]; + + if (unhex_val == -1) { + if (ch == ';' || ch == ' ') { + UPDATE_STATE(s_chunk_parameters); + break; + } + + SET_ERRNO(HPE_INVALID_CHUNK_SIZE); + goto error; + } + + t = parser->content_length; + t *= 16; + t += unhex_val; + + /* Overflow? Test against a conservative limit for simplicity. */ + if (UNLIKELY((ULLONG_MAX - 16) / 16 < parser->content_length)) { + SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); + goto error; + } + + parser->content_length = t; + break; + } + + case s_chunk_parameters: { + assert(parser->flags & F_CHUNKED); + /* just ignore this shit. REFINE: check for overflow */ + if (ch == CR) { + UPDATE_STATE(s_chunk_size_almost_done); + break; + } + break; + } + + case s_chunk_size_almost_done: { + assert(parser->flags & F_CHUNKED); + STRICT_CHECK(ch != LF); + + parser->nread = 0; + + if (parser->content_length == 0) { + parser->flags |= F_TRAILING; + UPDATE_STATE(s_header_field_start); + } else { + UPDATE_STATE(s_chunk_data); + } + CALLBACK_NOTIFY(chunk_header); + break; + } + + case s_chunk_data: { + uint64_t toRead = MIN(parser->content_length, + (uint64_t)((data + len) - p)); + + assert(parser->flags & F_CHUNKED); + assert(parser->content_length != 0 && parser->content_length != ULLONG_MAX); + + /* See the explanation in s_body_identity for why the content + * length and data pointers are managed this way. + */ + MARK(body); + parser->content_length -= toRead; + p += toRead - 1; + + if (parser->content_length == 0) { + UPDATE_STATE(s_chunk_data_almost_done); + } + + break; + } + + case s_chunk_data_almost_done: + assert(parser->flags & F_CHUNKED); + assert(parser->content_length == 0); + STRICT_CHECK(ch != CR); + UPDATE_STATE(s_chunk_data_done); + CALLBACK_DATA(body); + break; + + case s_chunk_data_done: + assert(parser->flags & F_CHUNKED); + STRICT_CHECK(ch != LF); + parser->nread = 0; + UPDATE_STATE(s_chunk_size_start); + CALLBACK_NOTIFY(chunk_complete); + break; + + default: + assert(0 && "unhandled state"); + SET_ERRNO(HPE_INVALID_INTERNAL_STATE); + goto error; + } + } + + /* Run callbacks for any marks that we have leftover after we ran our of + * bytes. There should be at most one of these set, so it's OK to invoke + * them in series (unset marks will not result in callbacks). + * + * We use the NOADVANCE() variety of callbacks here because 'p' has already + * overflowed 'data' and this allows us to correct for the off-by-one that + * we'd otherwise have (since CALLBACK_DATA() is meant to be run with a 'p' + * value that's in-bounds). + */ + + assert(((header_field_mark ? 1 : 0) + + (header_value_mark ? 1 : 0) + + (url_mark ? 1 : 0) + + (body_mark ? 1 : 0) + + (status_mark ? 1 : 0)) <= 1); + + CALLBACK_DATA_NOADVANCE(header_field); + CALLBACK_DATA_NOADVANCE(header_value); + CALLBACK_DATA_NOADVANCE(url); + CALLBACK_DATA_NOADVANCE(body); + CALLBACK_DATA_NOADVANCE(status); + + RETURN(len); + +error: + if (HTTP_PARSER_ERRNO(parser) == HPE_OK) { + SET_ERRNO(HPE_UNKNOWN); + } + + RETURN(p - data); +} + +/* Does the parser need to see an EOF to find the end of the message? */ +int http_message_needs_eof(const http_parser *parser) { //NOLINT + if (parser->type == HTTP_REQUEST) { //NOLINT + return 0; + } + + /* See RFC 2616 section 4.4 */ + if (parser->status_code / 100 == 1 || /* 1xx e.g. Continue NOLINT */ + parser->status_code == 204 || /* No Content NOLINT*/ + parser->status_code == 304 || /* Not Modified/ NOLINT*/ + parser->flags & F_SKIPBODY) { /* response to a HEAD request NOLINT */ + return 0; + } + + if ((parser->flags & F_CHUNKED) || parser->content_length != ULLONG_MAX) { //NOLINT + return 0; + } + + return 1; +} + +int http_should_keep_alive(const http_parser *parser) { //NOLINT + if (parser->http_major > 0 && parser->http_minor > 0) { + /* HTTP/1.1 */ + if (parser->flags & F_CONNECTION_CLOSE) { //NOLINT + return 0; + } + } else { + /* HTTP/1.0 or earlier */ + if (!(parser->flags & F_CONNECTION_KEEP_ALIVE)) { //NOLINT + return 0; + } + } + + return !http_message_needs_eof(parser); +} + +const char * +http_method_str(enum http_method m) { //NOLINT + return ELEM_AT(method_strings, m, ""); +} + +void http_parser_init(http_parser *parser, enum http_parser_type t) { //NOLINT + void *data = parser->data; /* preserve application data */ + memset(parser, 0, sizeof(*parser)); + parser->data = data; + parser->type = t; + parser->state = (t == HTTP_REQUEST ? s_start_req : (t == HTTP_RESPONSE ? s_start_res : s_start_req_or_res)); + parser->http_errno = HPE_OK; +} + +void http_parser_settings_init(http_parser_settings *settings) { //NOLINT + memset(settings, 0, sizeof(*settings)); +} + +const char * +http_errno_name(enum http_errno err) { //NOLINT + assert(((size_t)err) < ARRAY_SIZE(http_strerror_tab)); + return http_strerror_tab[err].name; +} + +const char * +http_errno_description(enum http_errno err) { //NOLINT + assert(((size_t)err) < ARRAY_SIZE(http_strerror_tab)); + return http_strerror_tab[err].description; +} + +static enum http_host_state +http_parse_host_char(enum http_host_state s, const char ch) { //NOLINT + switch (s) { + case s_http_userinfo: + case s_http_userinfo_start: + if (ch == '@') { + return s_http_host_start; + } + + if (IS_USERINFO_CHAR(ch)) { + return s_http_userinfo; + } + break; + + case s_http_host_start: + if (ch == '[') { + return s_http_host_v6_start; + } + + if (IS_HOST_CHAR(ch)) { + return s_http_host; + } + + break; + + case s_http_host: + if (IS_HOST_CHAR(ch)) { + return s_http_host; + } + + /* FALLTHROUGH */ + case s_http_host_v6_end: + if (ch == ':') { + return s_http_host_port_start; + } + + break; + + case s_http_host_v6: + if (ch == ']') { + return s_http_host_v6_end; + } + + /* FALLTHROUGH */ + case s_http_host_v6_start: + if (IS_HEX(ch) || ch == ':' || ch == '.') { + return s_http_host_v6; + } + + if (s == s_http_host_v6 && ch == '%') { + return s_http_host_v6_zone_start; + } + break; + + case s_http_host_v6_zone: + if (ch == ']') { + return s_http_host_v6_end; + } + + /* FALLTHROUGH */ + case s_http_host_v6_zone_start: + /* RFC 6874 Zone ID consists of 1*( unreserved / pct-encoded) */ + if (IS_ALPHANUM(ch) || ch == '%' || ch == '.' || ch == '-' || ch == '_' || + ch == '~') { + return s_http_host_v6_zone; + } + break; + + case s_http_host_port: + case s_http_host_port_start: + if (IS_NUM(ch)) { + return s_http_host_port; + } + + break; + + default: + break; + } + return s_http_host_dead; +} + +static int +http_parse_host(const char *buf, struct http_parser_url *u, int found_at) { //NOLINT + assert(u->field_set & (1 << UF_HOST)); + enum http_host_state s; + + const char *p; + size_t buflen = u->field_data[UF_HOST].off + u->field_data[UF_HOST].len; + + u->field_data[UF_HOST].len = 0; + + s = found_at ? s_http_userinfo_start : s_http_host_start; + + for (p = buf + u->field_data[UF_HOST].off; p < buf + buflen; p++) { + enum http_host_state newS = http_parse_host_char(s, *p); + + if (newS == s_http_host_dead) { + return 1; + } + + switch (newS) { + case s_http_host: + if (s != s_http_host) { + u->field_data[UF_HOST].off = p - buf; + } + u->field_data[UF_HOST].len++; + break; + + case s_http_host_v6: + if (s != s_http_host_v6) { + u->field_data[UF_HOST].off = p - buf; + } + u->field_data[UF_HOST].len++; + break; + + case s_http_host_v6_zone_start: + case s_http_host_v6_zone: + u->field_data[UF_HOST].len++; + break; + + case s_http_host_port: + if (s != s_http_host_port) { + u->field_data[UF_PORT].off = p - buf; + u->field_data[UF_PORT].len = 0; + u->field_set |= (1 << UF_PORT); + } + u->field_data[UF_PORT].len++; + break; + + case s_http_userinfo: + if (s != s_http_userinfo) { + u->field_data[UF_USERINFO].off = p - buf; + u->field_data[UF_USERINFO].len = 0; + u->field_set |= (1 << UF_USERINFO); + } + u->field_data[UF_USERINFO].len++; + break; + + default: + break; + } + s = newS; + } + + /* Make sure we don't end somewhere unexpected */ + switch (s) { + case s_http_host_start: + case s_http_host_v6_start: + case s_http_host_v6: + case s_http_host_v6_zone_start: + case s_http_host_v6_zone: + case s_http_host_port_start: + case s_http_userinfo: + case s_http_userinfo_start: + return 1; + default: + break; + } + + return 0; +} + +void http_parser_url_init(struct http_parser_url *u) { //NOLINT + memset(u, 0, sizeof(*u)); +} + +int http_parser_parse_url(const char *buf, size_t buflen, int is_connect, //NOLINT + struct http_parser_url *u) { + enum state s; + const char * p; + enum http_parser_url_fields uf, old_uf; //NOLINT + int found_at = 0; //NOLINT + + u->port = u->field_set = 0; + s = is_connect ? s_req_server_start : s_req_spaces_before_url; + old_uf = UF_MAX; + + for (p = buf; p < buf + buflen; p++) { + s = parse_url_char(s, *p); + + /* Figure out the next field that we're operating on */ + switch (s) { + case s_dead: + return 1; + + /* Skip delimeters */ + case s_req_schema_slash: + case s_req_schema_slash_slash: + case s_req_server_start: + case s_req_query_string_start: + case s_req_fragment_start: + continue; + + case s_req_schema: + uf = UF_SCHEMA; + break; + + case s_req_server_with_at: + found_at = 1; + + /* FALLTROUGH */ + case s_req_server: + uf = UF_HOST; + break; + + case s_req_path: + uf = UF_PATH; + break; + + case s_req_query_string: + uf = UF_QUERY; + break; + + case s_req_fragment: + uf = UF_FRAGMENT; + break; + + default: + assert(!"Unexpected state"); + return 1; + } + + /* Nothing's changed; soldier on */ + if (uf == old_uf) { + u->field_data[uf].len++; + continue; + } + + u->field_data[uf].off = p - buf; + u->field_data[uf].len = 1; + + u->field_set |= (1 << uf); + old_uf = uf; + } + + /* host must be present if there is a schema */ + /* parsing http:///toto will fail */ + if ((u->field_set & (1 << UF_SCHEMA)) && + (u->field_set & (1 << UF_HOST)) == 0) { + return 1; + } + + if (u->field_set & (1 << UF_HOST)) { + if (http_parse_host(buf, u, found_at) != 0) { + return 1; + } + } + + /* CONNECT requests can only contain "hostname:port" */ + if (is_connect && u->field_set != ((1 << UF_HOST) | (1 << UF_PORT))) { + return 1; + } + + if (u->field_set & (1 << UF_PORT)) { + /* Don't bother with endp; we've already validated the string */ + auto v = strtoul(buf + u->field_data[UF_PORT].off, nullptr, 10); + + /* Ports have a max value of 2^16 */ + if (v > 0xffff) { + return 1; + } + + u->port = (uint16_t)v; //NOLINT + } + + return 0; +} + +void http_parser_pause(http_parser *parser, int paused) { //NOLINT + /* Users should only be pausing/unpausing a parser that is not in an error + * state. In non-debug builds, there's not much that we can do about this + * other than ignore it. + */ + if (HTTP_PARSER_ERRNO(parser) == HPE_OK || + HTTP_PARSER_ERRNO(parser) == HPE_PAUSED) { + SET_ERRNO((paused) ? HPE_PAUSED : HPE_OK); + } else { + assert(0 && "Attempting to pause parser in error state"); + } +} + +int http_body_is_final(const struct http_parser *parser) { //NOLINT + return parser->state == s_message_done; //NOLINT +} + +unsigned long //NOLINT +http_parser_version(void) { //NOLINT + return HTTP_PARSER_VERSION_MAJOR * 0x10000 | + HTTP_PARSER_VERSION_MINOR * 0x00100 | + HTTP_PARSER_VERSION_PATCH * 0x00001; +} + +#endif // #if (SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8) && SE_ENABLE_INSPECTOR diff --git a/native/cocos/bindings/jswrapper/v8/debugger/http_parser.h b/native/cocos/bindings/jswrapper/v8/debugger/http_parser.h index c1fa3678cd..14b908e84e 100644 --- a/native/cocos/bindings/jswrapper/v8/debugger/http_parser.h +++ b/native/cocos/bindings/jswrapper/v8/debugger/http_parser.h @@ -38,16 +38,16 @@ extern "C" { (!defined(_MSC_VER) || _MSC_VER < 1600) && !defined(__WINE__) #include #include -typedef __int8 int8_t; -typedef unsigned __int8 uint8_t; -typedef __int16 int16_t; +typedef __int8 int8_t; +typedef unsigned __int8 uint8_t; +typedef __int16 int16_t; typedef unsigned __int16 uint16_t; -typedef __int32 int32_t; +typedef __int32 int32_t; typedef unsigned __int32 uint32_t; -typedef __int64 int64_t; +typedef __int64 int64_t; typedef unsigned __int64 uint64_t; #else - #include + #include #endif /* Compile with -DHTTP_PARSER_STRICT=0 to make less checks, but run @@ -68,8 +68,8 @@ typedef unsigned __int64 uint64_t; #define HTTP_MAX_HEADER_SIZE (80 * 1024) #endif -typedef struct http_parser http_parser; -typedef struct http_parser_settings http_parser_settings; +using http_parser = struct http_parser; +using http_parser_settings = struct http_parser_settings; /* Callbacks should return non-zero to indicate an error. The parser will * then halt execution. @@ -89,8 +89,8 @@ typedef struct http_parser_settings http_parser_settings; * many times for each string. E.G. you might get 10 callbacks for "on_url" * each providing just a few characters more data. */ -typedef int (*http_data_cb)(http_parser *, const char *at, size_t length); -typedef int (*http_cb)(http_parser *); +using http_data_cb = int (*)(http_parser *, const char *, size_t); +using http_cb = int (*)(http_parser *); /* Request Methods */ #define HTTP_METHOD_MAP(XX) \ @@ -135,25 +135,25 @@ typedef int (*http_cb)(http_parser *); XX(31, LINK, LINK) \ XX(32, UNLINK, UNLINK) -enum http_method { +enum http_method { //NOLINT(readability-identifier-naming) #define XX(num, name, string) HTTP_##name = num, HTTP_METHOD_MAP(XX) #undef XX }; -enum http_parser_type { HTTP_REQUEST, +enum http_parser_type { HTTP_REQUEST, //NOLINT(readability-identifier-naming) HTTP_RESPONSE, HTTP_BOTH }; /* Flag values for http_parser.flags field */ -enum flags { F_CHUNKED = 1 << 0, +enum flags { F_CHUNKED = 1 << 0, //NOLINT(readability-identifier-naming) F_CONNECTION_KEEP_ALIVE = 1 << 1, - F_CONNECTION_CLOSE = 1 << 2, - F_CONNECTION_UPGRADE = 1 << 3, - F_TRAILING = 1 << 4, - F_UPGRADE = 1 << 5, - F_SKIPBODY = 1 << 6, - F_CONTENTLENGTH = 1 << 7 + F_CONNECTION_CLOSE = 1 << 2, + F_CONNECTION_UPGRADE = 1 << 3, + F_TRAILING = 1 << 4, + F_UPGRADE = 1 << 5, + F_SKIPBODY = 1 << 6, + F_CONTENTLENGTH = 1 << 7 }; /* Map for errno-related constants @@ -207,7 +207,7 @@ enum flags { F_CHUNKED = 1 << 0, /* Define HPE_* values for each errno value above */ #define HTTP_ERRNO_GEN(n, s) HPE_##n, -enum http_errno { +enum http_errno { //NOLINT(readability-identifier-naming) HTTP_ERRNO_MAP(HTTP_ERRNO_GEN) }; #undef HTTP_ERRNO_GEN @@ -228,11 +228,11 @@ struct http_parser { uint64_t content_length; /* # bytes in body (0 if no Content-Length header) */ /** READ-ONLY **/ - unsigned short http_major; - unsigned short http_minor; - unsigned int status_code : 16; /* responses only */ - unsigned int method : 8; /* requests only */ - unsigned int http_errno : 7; + unsigned short http_major; //NOLINT(google-runtime-int) + unsigned short http_minor; //NOLINT(google-runtime-int) + unsigned int status_code : 16; /* responses only */ + unsigned int method : 8; /* requests only */ + unsigned int http_errno : 7; /* 1 = Upgrade header was present and the parser has exited because of that. * 0 = No upgrade header present. @@ -246,14 +246,14 @@ struct http_parser { }; struct http_parser_settings { - http_cb on_message_begin; + http_cb on_message_begin; http_data_cb on_url; http_data_cb on_status; http_data_cb on_header_field; http_data_cb on_header_value; - http_cb on_headers_complete; + http_cb on_headers_complete; http_data_cb on_body; - http_cb on_message_complete; + http_cb on_message_complete; /* When on_chunk_header is called, the current chunk length is stored * in parser->content_length. */ @@ -261,14 +261,14 @@ struct http_parser_settings { http_cb on_chunk_complete; }; -enum http_parser_url_fields { UF_SCHEMA = 0, - UF_HOST = 1, - UF_PORT = 2, - UF_PATH = 3, - UF_QUERY = 4, +enum http_parser_url_fields { UF_SCHEMA = 0, //NOLINT(readability-identifier-naming) + UF_HOST = 1, + UF_PORT = 2, + UF_PATH = 3, + UF_QUERY = 4, UF_FRAGMENT = 5, UF_USERINFO = 6, - UF_MAX = 7 + UF_MAX = 7 }; /* Result structure for http_parser_parse_url(). @@ -278,9 +278,9 @@ enum http_parser_url_fields { UF_SCHEMA = 0, * because we probably have padding left over), we convert any port to * a uint16_t. */ -struct http_parser_url { - uint16_t field_set; /* Bitmask of (1 << UF_*) values */ - uint16_t port; /* Converted UF_PORT string */ +struct http_parser_url { //NOLINT(readability-identifier-naming) + uint16_t field_set; /* Bitmask of (1 << UF_*) values */ + uint16_t port; /* Converted UF_PORT string */ struct { uint16_t off; /* Offset into buffer in which field starts */ @@ -298,20 +298,20 @@ struct http_parser_url { * unsigned patch = version & 255; * printf("http_parser v%u.%u.%u\n", major, minor, patch); */ -unsigned long http_parser_version(void); +unsigned long http_parser_version(void); //NOLINT(readability-identifier-naming,google-runtime-int) -void http_parser_init(http_parser *parser, enum http_parser_type type); +void http_parser_init(http_parser *parser, enum http_parser_type type); //NOLINT(readability-identifier-naming) /* Initialize http_parser_settings members to 0 */ -void http_parser_settings_init(http_parser_settings *settings); +void http_parser_settings_init(http_parser_settings *settings); //NOLINT(readability-identifier-naming) /* Executes the parser. Returns number of parsed bytes. Sets * `parser->http_errno` on error. */ -size_t http_parser_execute(http_parser *parser, +size_t http_parser_execute(http_parser * parser, //NOLINT(readability-identifier-naming) const http_parser_settings *settings, - const char *data, - size_t len); + const char * data, + size_t len); /* If http_should_keep_alive() in the on_headers_complete or * on_message_complete callback returns 0, then this should be @@ -319,30 +319,30 @@ size_t http_parser_execute(http_parser *parser, * If you are the server, respond with the "Connection: close" header. * If you are the client, close the connection. */ -int http_should_keep_alive(const http_parser *parser); +int http_should_keep_alive(const http_parser *parser); //NOLINT(readability-identifier-naming) /* Returns a string version of the HTTP method. */ -const char *http_method_str(enum http_method m); +const char *http_method_str(enum http_method m); //NOLINT(readability-identifier-naming) /* Return a string name of the given error */ -const char *http_errno_name(enum http_errno err); +const char *http_errno_name(enum http_errno err); //NOLINT(readability-identifier-naming) /* Return a string description of the given error */ -const char *http_errno_description(enum http_errno err); +const char *http_errno_description(enum http_errno err); //NOLINT(readability-identifier-naming) /* Initialize all http_parser_url members to 0 */ -void http_parser_url_init(struct http_parser_url *u); +void http_parser_url_init(struct http_parser_url *u); //NOLINT(readability-identifier-naming) /* Parse a URL; return nonzero on failure */ -int http_parser_parse_url(const char *buf, size_t buflen, - int is_connect, +int http_parser_parse_url(const char *buf, size_t buflen, //NOLINT(readability-identifier-naming) + int is_connect, //NOLINT(readability-identifier-naming) struct http_parser_url *u); /* Pause or un-pause the parser; a nonzero value pauses */ -void http_parser_pause(http_parser *parser, int paused); +void http_parser_pause(http_parser *parser, int paused); //NOLINT(readability-identifier-naming) /* Checks if this is the final chunk of the body. */ -int http_body_is_final(const http_parser *parser); +int http_body_is_final(const http_parser *parser); //NOLINT(readability-identifier-naming) #ifdef __cplusplus } diff --git a/native/cocos/bindings/manual/JavaScriptJavaBridge.cpp b/native/cocos/bindings/manual/JavaScriptJavaBridge.cpp index c78a338a0f..a0e44075f9 100644 --- a/native/cocos/bindings/manual/JavaScriptJavaBridge.cpp +++ b/native/cocos/bindings/manual/JavaScriptJavaBridge.cpp @@ -25,14 +25,18 @@ ****************************************************************************/ #include "cocos/bindings/manual/JavaScriptJavaBridge.h" -#include "platform/android/jni/JniHelper.h" +#include "cocos/base/UTF8.h" #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_conversions.h" -#include "cocos/base/UTF8.h" +#include "platform/java/jni/JniHelper.h" -#include -#include +#if CC_PLATFORM == CC_PLATFORM_ANDROID + #include +#elif CC_PLATFORM == CC_PLATFORM_OHOS + #include +#endif #include +#include #ifdef LOG_TAG #undef LOG_TAG @@ -47,15 +51,15 @@ extern "C" { -JNIEXPORT jint JNICALL JNI_JSJAVABRIDGE(evalString)(JNIEnv *env, jclass cls, jstring value) { +JNIEXPORT jint JNICALL JNI_JSJAVABRIDGE(evalString)(JNIEnv *env, jclass /*cls*/, jstring value) { if (!se::ScriptEngine::getInstance()->isValid()) { CC_LOG_DEBUG("ScriptEngine has not been initialized"); return 0; } se::AutoHandleScope hs; - bool strFlag = false; - std::string strValue = cc::StringUtils::getStringUTFCharsJNI(env, value, &strFlag); + bool strFlag = false; + std::string strValue = cc::StringUtils::getStringUTFCharsJNI(env, value, &strFlag); if (!strFlag) { CC_LOG_DEBUG("JavaScriptJavaBridge_evalString error, invalid string code"); return 0; @@ -89,86 +93,86 @@ public: FUNCTION }; - typedef std::vector ValueTypes; + using ValueTypes = std::vector; - typedef union { - int intValue; - long longValue; - float floatValue; - int boolValue; + using ReturnValue = union { + int intValue; + int64_t longValue; + float floatValue; + int boolValue; std::string *stringValue; - } ReturnValue; + }; class CallInfo { public: CallInfo(const char *className, const char *methodName, const char *methodSig) - : m_valid(false), - m_error(JSJ_ERR_OK), - m_className(className), - m_methodName(methodName), - m_methodSig(methodSig), - m_returnType(ValueType::VOID), - m_argumentsCount(0), - m_retjstring(NULL), - m_env(NULL), - m_classID(NULL), - m_methodID(NULL) { - memset(&m_ret, 0, sizeof(m_ret)); - m_valid = validateMethodSig() && getMethodInfo(); + : _mValid(false), + _mError(JSJ_ERR_OK), + _mClassName(className), + _mMethodName(methodName), + _mMethodSig(methodSig), + _mReturnType(ValueType::VOID), + _mArgumentsCount(0), + _mRetjstring(nullptr), + _mEnv(nullptr), + _mClassID(nullptr), + _mMethodID(nullptr) { + memset(&_mRet, 0, sizeof(_mRet)); + _mValid = validateMethodSig() && getMethodInfo(); } ~CallInfo(); bool isValid() { - return m_valid; + return _mValid; } int getErrorCode() { - return m_error; + return _mError; } JNIEnv *getEnv() { - return m_env; + return _mEnv; } ValueType argumentTypeAtIndex(size_t index) { - return m_argumentsType.at(index); + return _mArgumentsType.at(index); } int getArgumentsCount() { - return m_argumentsCount; + return _mArgumentsCount; } ValueType getReturnValueType() { - return m_returnType; + return _mReturnType; } ReturnValue getReturnValue() { - return m_ret; + return _mRet; } bool execute(); bool executeWithArgs(jvalue *args); private: - bool m_valid; - int m_error; + bool _mValid; + int _mError; - std::string m_className; - std::string m_methodName; - std::string m_methodSig; - int m_argumentsCount; - ValueTypes m_argumentsType; - ValueType m_returnType; + std::string _mClassName; + std::string _mMethodName; + std::string _mMethodSig; + int _mArgumentsCount; + ValueTypes _mArgumentsType; + ValueType _mReturnType; - ReturnValue m_ret; - jstring m_retjstring; + ReturnValue _mRet; + jstring _mRetjstring; - JNIEnv *m_env; - jclass m_classID; - jmethodID m_methodID; + JNIEnv * _mEnv; + jclass _mClassID; + jmethodID _mMethodID; - bool validateMethodSig(); - bool getMethodInfo(); + bool validateMethodSig(); + bool getMethodInfo(); ValueType checkType(const std::string &sig, size_t *pos); }; @@ -176,54 +180,55 @@ public: }; JavaScriptJavaBridge::CallInfo::~CallInfo() { - if (m_returnType == ValueType::STRING && m_ret.stringValue) { - delete m_ret.stringValue; + if (_mReturnType == ValueType::STRING && _mRet.stringValue) { + delete _mRet.stringValue; } } bool JavaScriptJavaBridge::CallInfo::execute() { - switch (m_returnType) { + switch (_mReturnType) { case JavaScriptJavaBridge::ValueType::VOID: - m_env->CallStaticVoidMethod(m_classID, m_methodID); + _mEnv->CallStaticVoidMethod(_mClassID, _mMethodID); break; case JavaScriptJavaBridge::ValueType::INTEGER: - m_ret.intValue = m_env->CallStaticIntMethod(m_classID, m_methodID); + _mRet.intValue = _mEnv->CallStaticIntMethod(_mClassID, _mMethodID); break; case JavaScriptJavaBridge::ValueType::LONG: - m_ret.longValue = m_env->CallStaticLongMethod(m_classID, m_methodID); + _mRet.longValue = _mEnv->CallStaticLongMethod(_mClassID, _mMethodID); break; case JavaScriptJavaBridge::ValueType::FLOAT: - m_ret.floatValue = m_env->CallStaticFloatMethod(m_classID, m_methodID); + _mRet.floatValue = _mEnv->CallStaticFloatMethod(_mClassID, _mMethodID); break; case JavaScriptJavaBridge::ValueType::BOOLEAN: - m_ret.boolValue = m_env->CallStaticBooleanMethod(m_classID, m_methodID); + _mRet.boolValue = _mEnv->CallStaticBooleanMethod(_mClassID, _mMethodID); break; case JavaScriptJavaBridge::ValueType::STRING: { - m_retjstring = (jstring)m_env->CallStaticObjectMethod(m_classID, m_methodID); - if (m_retjstring) { - std::string strValue = cc::StringUtils::getStringUTFCharsJNI(m_env, m_retjstring); - m_ret.stringValue = new std::string(strValue); - } else - m_ret.stringValue = nullptr; + _mRetjstring = static_cast(_mEnv->CallStaticObjectMethod(_mClassID, _mMethodID)); + if (_mRetjstring) { + std::string strValue = cc::StringUtils::getStringUTFCharsJNI(_mEnv, _mRetjstring); + _mRet.stringValue = new std::string(strValue); + } else { + _mRet.stringValue = nullptr; + } break; } default: - m_error = JSJ_ERR_TYPE_NOT_SUPPORT; - SE_LOGD("Return type '%d' is not supported", static_cast(m_returnType)); + _mError = JSJ_ERR_TYPE_NOT_SUPPORT; + SE_LOGD("Return type '%d' is not supported", static_cast(_mReturnType)); return false; } - if (m_env->ExceptionCheck() == JNI_TRUE) { - m_env->ExceptionDescribe(); - m_env->ExceptionClear(); - m_error = JSJ_ERR_EXCEPTION_OCCURRED; + if (_mEnv->ExceptionCheck() == JNI_TRUE) { + _mEnv->ExceptionDescribe(); + _mEnv->ExceptionClear(); + _mError = JSJ_ERR_EXCEPTION_OCCURRED; return false; } @@ -231,44 +236,44 @@ bool JavaScriptJavaBridge::CallInfo::execute() { } bool JavaScriptJavaBridge::CallInfo::executeWithArgs(jvalue *args) { - switch (m_returnType) { + switch (_mReturnType) { case JavaScriptJavaBridge::ValueType::VOID: - m_env->CallStaticVoidMethodA(m_classID, m_methodID, args); + _mEnv->CallStaticVoidMethodA(_mClassID, _mMethodID, args); break; case JavaScriptJavaBridge::ValueType::INTEGER: - m_ret.intValue = m_env->CallStaticIntMethodA(m_classID, m_methodID, args); + _mRet.intValue = _mEnv->CallStaticIntMethodA(_mClassID, _mMethodID, args); break; case JavaScriptJavaBridge::ValueType::LONG: - m_ret.longValue = m_env->CallStaticIntMethodA(m_classID, m_methodID, args); + _mRet.longValue = _mEnv->CallStaticIntMethodA(_mClassID, _mMethodID, args); break; case JavaScriptJavaBridge::ValueType::FLOAT: - m_ret.floatValue = m_env->CallStaticFloatMethodA(m_classID, m_methodID, args); + _mRet.floatValue = _mEnv->CallStaticFloatMethodA(_mClassID, _mMethodID, args); break; case JavaScriptJavaBridge::ValueType::BOOLEAN: - m_ret.boolValue = m_env->CallStaticBooleanMethodA(m_classID, m_methodID, args); + _mRet.boolValue = _mEnv->CallStaticBooleanMethodA(_mClassID, _mMethodID, args); break; case JavaScriptJavaBridge::ValueType::STRING: { - m_retjstring = (jstring)m_env->CallStaticObjectMethodA(m_classID, m_methodID, args); - std::string strValue = cc::StringUtils::getStringUTFCharsJNI(m_env, m_retjstring); - m_ret.stringValue = new std::string(strValue); + _mRetjstring = static_cast(_mEnv->CallStaticObjectMethodA(_mClassID, _mMethodID, args)); + std::string strValue = cc::StringUtils::getStringUTFCharsJNI(_mEnv, _mRetjstring); + _mRet.stringValue = new std::string(strValue); break; } default: - m_error = JSJ_ERR_TYPE_NOT_SUPPORT; - SE_LOGD("Return type '%d' is not supported", static_cast(m_returnType)); + _mError = JSJ_ERR_TYPE_NOT_SUPPORT; + SE_LOGD("Return type '%d' is not supported", static_cast(_mReturnType)); return false; } - if (m_env->ExceptionCheck() == JNI_TRUE) { - m_env->ExceptionDescribe(); - m_env->ExceptionClear(); - m_error = JSJ_ERR_EXCEPTION_OCCURRED; + if (_mEnv->ExceptionCheck() == JNI_TRUE) { + _mEnv->ExceptionDescribe(); + _mEnv->ExceptionClear(); + _mError = JSJ_ERR_EXCEPTION_OCCURRED; return false; } @@ -276,30 +281,30 @@ bool JavaScriptJavaBridge::CallInfo::executeWithArgs(jvalue *args) { } bool JavaScriptJavaBridge::CallInfo::validateMethodSig() { - size_t len = m_methodSig.length(); - if (len < 3 || m_methodSig[0] != '(') // min sig is "()V" + size_t len = _mMethodSig.length(); + if (len < 3 || _mMethodSig[0] != '(') // min sig is "()V" { - m_error = JSJ_ERR_INVALID_SIGNATURES; + _mError = JSJ_ERR_INVALID_SIGNATURES; return false; } size_t pos = 1; - while (pos < len && m_methodSig[pos] != ')') { - JavaScriptJavaBridge::ValueType type = checkType(m_methodSig, &pos); + while (pos < len && _mMethodSig[pos] != ')') { + JavaScriptJavaBridge::ValueType type = checkType(_mMethodSig, &pos); if (type == ValueType::INVALID) return false; - m_argumentsCount++; - m_argumentsType.push_back(type); + _mArgumentsCount++; + _mArgumentsType.push_back(type); pos++; } - if (pos >= len || m_methodSig[pos] != ')') { - m_error = JSJ_ERR_INVALID_SIGNATURES; + if (pos >= len || _mMethodSig[pos] != ')') { + _mError = JSJ_ERR_INVALID_SIGNATURES; return false; } pos++; - m_returnType = checkType(m_methodSig, &pos); + _mReturnType = checkType(_mMethodSig, &pos); return true; } @@ -318,41 +323,47 @@ JavaScriptJavaBridge::ValueType JavaScriptJavaBridge::CallInfo::checkType(const case 'L': size_t pos2 = sig.find_first_of(';', *pos + 1); if (pos2 == std::string::npos) { - m_error = JSJ_ERR_INVALID_SIGNATURES; + _mError = JSJ_ERR_INVALID_SIGNATURES; return ValueType::INVALID; } const std::string t = sig.substr(*pos, pos2 - *pos + 1); - if (t.compare("Ljava/lang/String;") == 0) { + if (t == "Ljava/lang/String;") { *pos = pos2; return ValueType::STRING; - } else if (t.compare("Ljava/util/Vector;") == 0) { + } + + if (t == "Ljava/util/Vector;") { *pos = pos2; return ValueType::VECTOR; - } else { - m_error = JSJ_ERR_TYPE_NOT_SUPPORT; - return ValueType::INVALID; } + + _mError = JSJ_ERR_TYPE_NOT_SUPPORT; + return ValueType::INVALID; } - m_error = JSJ_ERR_TYPE_NOT_SUPPORT; + _mError = JSJ_ERR_TYPE_NOT_SUPPORT; return ValueType::INVALID; } bool JavaScriptJavaBridge::CallInfo::getMethodInfo() { - m_methodID = 0; - m_env = 0; + _mMethodID = nullptr; + _mEnv = nullptr; JavaVM *jvm = cc::JniHelper::getJavaVM(); - jint ret = jvm->GetEnv((void **)&m_env, JNI_VERSION_1_4); + jint ret = jvm->GetEnv(reinterpret_cast(&_mEnv), JNI_VERSION_1_4); switch (ret) { case JNI_OK: break; case JNI_EDETACHED: - if (jvm->AttachCurrentThread(&m_env, NULL) < 0) { +#if CC_PLATFORM == CC_PLATFORM_ANDROID + if (jvm->AttachCurrentThread(&_mEnv, nullptr) < 0) { +#else + if (jvm->AttachCurrentThread(reinterpret_cast(&_mEnv), nullptr) < 0) { +#endif SE_LOGD("%s", "Failed to get the environment using AttachCurrentThread()"); - m_error = JSJ_ERR_VM_THREAD_DETACHED; + _mError = JSJ_ERR_VM_THREAD_DETACHED; return false; } break; @@ -360,31 +371,31 @@ bool JavaScriptJavaBridge::CallInfo::getMethodInfo() { case JNI_EVERSION: default: SE_LOGD("%s", "Failed to get the environment using GetEnv()"); - m_error = JSJ_ERR_VM_FAILURE; + _mError = JSJ_ERR_VM_FAILURE; return false; } - jstring _jstrClassName = m_env->NewStringUTF(m_className.c_str()); - m_classID = (jclass)m_env->CallObjectMethod(cc::JniHelper::classloader, - cc::JniHelper::loadclassMethod_methodID, - _jstrClassName); + jstring jstrClassName = _mEnv->NewStringUTF(_mClassName.c_str()); + _mClassID = static_cast(_mEnv->CallObjectMethod(cc::JniHelper::classloader, + cc::JniHelper::loadclassMethodMethodId, + jstrClassName)); - if (NULL == m_classID) { - SE_LOGD("Classloader failed to find class of %s", m_className.c_str()); - m_env->DeleteLocalRef(_jstrClassName); - m_env->ExceptionClear(); - m_error = JSJ_ERR_CLASS_NOT_FOUND; + if (nullptr == _mClassID) { + SE_LOGD("Classloader failed to find class of %s", _mClassName.c_str()); + ccDeleteLocalRef(_mEnv, jstrClassName); + _mEnv->ExceptionClear(); + _mError = JSJ_ERR_CLASS_NOT_FOUND; return false; } - m_env->DeleteLocalRef(_jstrClassName); - m_methodID = m_env->GetStaticMethodID(m_classID, m_methodName.c_str(), m_methodSig.c_str()); - if (!m_methodID) { - m_env->ExceptionClear(); + ccDeleteLocalRef(_mEnv, jstrClassName); + _mMethodID = _mEnv->GetStaticMethodID(_mClassID, _mMethodName.c_str(), _mMethodSig.c_str()); + if (!_mMethodID) { + _mEnv->ExceptionClear(); SE_LOGD("Failed to find method id of %s.%s %s", - m_className.c_str(), - m_methodName.c_str(), - m_methodSig.c_str()); - m_error = JSJ_ERR_METHOD_NOT_FOUND; + _mClassName.c_str(), + _mMethodName.c_str(), + _mMethodSig.c_str()); + _mError = JSJ_ERR_METHOD_NOT_FOUND; return false; } @@ -407,10 +418,11 @@ bool JavaScriptJavaBridge::convertReturnValue(ReturnValue retValue, ValueType ty ret->setBoolean(retValue.boolValue); break; case JavaScriptJavaBridge::ValueType::STRING: - if (retValue.stringValue) + if (retValue.stringValue) { ret->setString(*retValue.stringValue); - else + } else { ret->setNull(); + } break; default: ret->setUndefined(); @@ -420,29 +432,31 @@ bool JavaScriptJavaBridge::convertReturnValue(ReturnValue retValue, ValueType ty return true; } -se::Class *__jsb_JavaScriptJavaBridge_class = nullptr; +se::Class *__jsb_JavaScriptJavaBridge_class = nullptr; // NOLINT -static bool JavaScriptJavaBridge_finalize(se::State &s) { - JavaScriptJavaBridge *cobj = (JavaScriptJavaBridge *)s.nativeThisObject(); +static bool JavaScriptJavaBridge_finalize(se::State &s) { //NOLINT(readability-identifier-naming,google-runtime-references) + auto *cobj = static_cast(s.nativeThisObject()); delete cobj; return true; } SE_BIND_FINALIZE_FUNC(JavaScriptJavaBridge_finalize) -static bool JavaScriptJavaBridge_constructor(se::State &s) { - JavaScriptJavaBridge *cobj = new (std::nothrow) JavaScriptJavaBridge(); +static bool JavaScriptJavaBridge_constructor(se::State &s) { //NOLINT(readability-identifier-naming,google-runtime-references) + auto *cobj = new (std::nothrow) JavaScriptJavaBridge(); s.thisObject()->setPrivateData(cobj); return true; } SE_BIND_CTOR(JavaScriptJavaBridge_constructor, __jsb_JavaScriptJavaBridge_class, JavaScriptJavaBridge_finalize) -static bool JavaScriptJavaBridge_callStaticMethod(se::State &s) { +static bool JavaScriptJavaBridge_callStaticMethod(se::State &s) { //NOLINT(readability-identifier-naming,google-runtime-references) const auto &args = s.args(); - int argc = (int)args.size(); + auto argc = static_cast(args.size()); if (argc == 3) { - bool ok = false; - std::string clsName, methodName, methodSig; + bool ok = false; + std::string clsName; + std::string methodName; + std::string methodSig; ok = seval_to_std_string(args[0], &clsName); SE_PRECONDITION2(ok, false, "Converting class name failed!"); @@ -454,7 +468,7 @@ static bool JavaScriptJavaBridge_callStaticMethod(se::State &s) { JavaScriptJavaBridge::CallInfo call(clsName.c_str(), methodName.c_str(), methodSig.c_str()); if (call.isValid()) { - ok = call.execute(); + ok = call.execute(); int errorCode = call.getErrorCode(); if (!ok || errorCode < 0) { SE_REPORT_ERROR("call result code: %d", call.getErrorCode()); @@ -465,9 +479,13 @@ static bool JavaScriptJavaBridge_callStaticMethod(se::State &s) { } SE_REPORT_ERROR("JavaScriptJavaBridge::CallInfo isn't valid!"); return false; - } else if (argc > 3) { - bool ok = false; - std::string clsName, methodName, methodSig; + } + + if (argc > 3) { + bool ok = false; + std::string clsName; + std::string methodName; + std::string methodSig; ok = seval_to_std_string(args[0], &clsName); SE_PRECONDITION2(ok, false, "Converting class name failed!"); @@ -479,8 +497,8 @@ static bool JavaScriptJavaBridge_callStaticMethod(se::State &s) { JavaScriptJavaBridge::CallInfo call(clsName.c_str(), methodName.c_str(), methodSig.c_str()); if (call.isValid() && call.getArgumentsCount() == (argc - 3)) { - int count = argc - 3; - jvalue *jargs = new jvalue[count]; + int count = argc - 3; + auto * jargs = new jvalue[count]; std::vector toReleaseObjects; for (int i = 0; i < count; ++i) { int index = i + 3; @@ -492,13 +510,13 @@ static bool JavaScriptJavaBridge_callStaticMethod(se::State &s) { break; } case JavaScriptJavaBridge::ValueType::LONG: { - long longVal = 0L; - seval_to_long(args[index], &longVal); + int64_t longVal = 0L; + sevalue_to_native(args[index], &longVal, nullptr); jargs[i].j = longVal; break; } case JavaScriptJavaBridge::ValueType::FLOAT: { - float floatNumber = 0.0f; + float floatNumber = 0.0F; seval_to_float(args[index], &floatNumber); jargs[i].f = floatNumber; break; @@ -509,9 +527,9 @@ static bool JavaScriptJavaBridge_callStaticMethod(se::State &s) { } case JavaScriptJavaBridge::ValueType::STRING: { const auto &arg = args[index]; - if (arg.isNull() || arg.isUndefined()) + if (arg.isNull() || arg.isUndefined()) { jargs[i].l = nullptr; - else { + } else { std::string str; seval_to_std_string(args[index], &str); jargs[i].l = call.getEnv()->NewStringUTF(str.c_str()); @@ -527,10 +545,9 @@ static bool JavaScriptJavaBridge_callStaticMethod(se::State &s) { } ok = call.executeWithArgs(jargs); for (const auto &obj : toReleaseObjects) { - call.getEnv()->DeleteLocalRef(obj); + ccDeleteLocalRef(call.getEnv(), obj); } - if (jargs) - delete[] jargs; + delete[] jargs; int errorCode = call.getErrorCode(); if (!ok || errorCode < 0) { SE_REPORT_ERROR("js_JSJavaBridge : call result code: %d", errorCode); @@ -548,7 +565,7 @@ static bool JavaScriptJavaBridge_callStaticMethod(se::State &s) { } SE_BIND_FUNC(JavaScriptJavaBridge_callStaticMethod) -bool register_javascript_java_bridge(se::Object *obj) { +bool register_javascript_java_bridge(se::Object *obj) { //NOLINT(readability-identifier-naming) se::Class *cls = se::Class::create("JavascriptJavaBridge", obj, nullptr, _SE(JavaScriptJavaBridge_constructor)); cls->defineFinalizeFunction(_SE(JavaScriptJavaBridge_finalize)); diff --git a/native/cocos/bindings/manual/jsb_conversions.h b/native/cocos/bindings/manual/jsb_conversions.h index 0c02569909..ea93bc9b1f 100644 --- a/native/cocos/bindings/manual/jsb_conversions.h +++ b/native/cocos/bindings/manual/jsb_conversions.h @@ -25,17 +25,18 @@ #pragma once +#include +#include #include "bindings/jswrapper/SeApi.h" #include "bindings/manual/jsb_classtype.h" -#include "cocos/base/Vector.h" #include "cocos/base/Map.h" +#include "cocos/base/Vector.h" +#include "cocos/math/Geometry.h" #include "cocos/math/Vec2.h" #include "cocos/math/Vec3.h" -#include "cocos/math/Geometry.h" #include "extensions/cocos-ext.h" #include "network/Downloader.h" -#include -#include + #if USE_SPINE #include "cocos/editor-support/spine-creator-support/spine-cocos2dx.h" #endif @@ -156,45 +157,45 @@ struct InputAssemblerInfo; #endif // se value -> native value -bool seval_to_int32(const se::Value &v, int32_t *ret); -bool seval_to_uint32(const se::Value &v, uint32_t *ret); -bool seval_to_uint(const se::Value &v, unsigned int *ret); -bool seval_to_int8(const se::Value &v, int8_t *ret); -bool seval_to_uint8(const se::Value &v, uint8_t *ret); -bool seval_to_int16(const se::Value &v, int16_t *ret); -bool seval_to_uint16(const se::Value &v, uint16_t *ret); -bool seval_to_boolean(const se::Value &v, bool *ret); -bool seval_to_float(const se::Value &v, float *ret); -bool seval_to_double(const se::Value &v, double *ret); -bool seval_to_long(const se::Value &v, long *ret); -bool seval_to_ulong(const se::Value &v, unsigned long *ret); -bool seval_to_longlong(const se::Value &v, long long *ret); -bool seval_to_size(const se::Value &v, size_t *ret); -bool seval_to_std_string(const se::Value &v, std::string *ret); -bool seval_to_Vec2(const se::Value &v, cc::Vec2 *pt); -bool seval_to_Vec3(const se::Value &v, cc::Vec3 *pt); -bool seval_to_Vec4(const se::Value &v, cc::Vec4 *pt); -bool seval_to_Mat4(const se::Value &v, cc::Mat4 *mat); -bool seval_to_Size(const se::Value &v, cc::Size *size); -bool seval_to_ccvalue(const se::Value &v, cc::Value *ret); -bool seval_to_ccvaluemap(const se::Value &v, cc::ValueMap *ret); -bool seval_to_ccvaluemapintkey(const se::Value &v, cc::ValueMapIntKey *ret); -bool seval_to_ccvaluevector(const se::Value &v, cc::ValueVector *ret); -bool sevals_variadic_to_ccvaluevector(const se::ValueArray &args, cc::ValueVector *ret); -bool seval_to_std_vector_string(const se::Value &v, std::vector *ret); -bool seval_to_std_vector_int(const se::Value &v, std::vector *ret); -bool seval_to_std_vector_uint16(const se::Value &v, std::vector *ret); -bool seval_to_std_vector_float(const se::Value &v, std::vector *ret); -bool seval_to_std_vector_Vec2(const se::Value &v, std::vector *ret); -bool seval_to_Uint8Array(const se::Value &v, uint8_t *ret); -bool seval_to_uintptr_t(const se::Value &v, uintptr_t *ret); +bool seval_to_int32(const se::Value &v, int32_t *ret); //NOLINT +bool seval_to_uint32(const se::Value &v, uint32_t *ret); //NOLINT +bool seval_to_uint(const se::Value &v, unsigned int *ret); //NOLINT +bool seval_to_int8(const se::Value &v, int8_t *ret); //NOLINT +bool seval_to_uint8(const se::Value &v, uint8_t *ret); //NOLINT +bool seval_to_int16(const se::Value &v, int16_t *ret); //NOLINT +bool seval_to_uint16(const se::Value &v, uint16_t *ret); //NOLINT +bool seval_to_boolean(const se::Value &v, bool *ret); //NOLINT +bool seval_to_float(const se::Value &v, float *ret); //NOLINT +bool seval_to_double(const se::Value &v, double *ret); //NOLINT +bool seval_to_long(const se::Value &v, long *ret); //NOLINT +bool seval_to_ulong(const se::Value &v, unsigned long *ret); //NOLINT +bool seval_to_longlong(const se::Value &v, long long *ret); //NOLINT +bool seval_to_size(const se::Value &v, size_t *ret); //NOLINT +bool seval_to_std_string(const se::Value &v, std::string *ret); //NOLINT +bool seval_to_Vec2(const se::Value &v, cc::Vec2 *pt); //NOLINT +bool seval_to_Vec3(const se::Value &v, cc::Vec3 *pt); //NOLINT +bool seval_to_Vec4(const se::Value &v, cc::Vec4 *pt); //NOLINT +bool seval_to_Mat4(const se::Value &v, cc::Mat4 *mat); //NOLINT +bool seval_to_Size(const se::Value &v, cc::Size *size); //NOLINT +bool seval_to_ccvalue(const se::Value &v, cc::Value *ret); //NOLINT +bool seval_to_ccvaluemap(const se::Value &v, cc::ValueMap *ret); //NOLINT +bool seval_to_ccvaluemapintkey(const se::Value &v, cc::ValueMapIntKey *ret); //NOLINT +bool seval_to_ccvaluevector(const se::Value &v, cc::ValueVector *ret); //NOLINT +bool sevals_variadic_to_ccvaluevector(const se::ValueArray &args, cc::ValueVector *ret); //NOLINT +bool seval_to_std_vector_string(const se::Value &v, std::vector *ret); //NOLINT +bool seval_to_std_vector_int(const se::Value &v, std::vector *ret); //NOLINT +bool seval_to_std_vector_uint16(const se::Value &v, std::vector *ret); //NOLINT +bool seval_to_std_vector_float(const se::Value &v, std::vector *ret); //NOLINT +bool seval_to_std_vector_Vec2(const se::Value &v, std::vector *ret); //NOLINT +bool seval_to_Uint8Array(const se::Value &v, uint8_t *ret); //NOLINT +bool seval_to_uintptr_t(const se::Value &v, uintptr_t *ret); //NOLINT -bool seval_to_std_map_string_string(const se::Value &v, std::map *ret); -bool seval_to_Data(const se::Value &v, cc::Data *ret); -bool seval_to_DownloaderHints(const se::Value &v, cc::network::DownloaderHints *ret); +bool seval_to_std_map_string_string(const se::Value &v, std::map *ret); //NOLINT +bool seval_to_Data(const se::Value &v, cc::Data *ret); //NOLINT +bool seval_to_DownloaderHints(const se::Value &v, cc::network::DownloaderHints *ret); //NOLINT template -bool seval_to_native_ptr(const se::Value &v, T *ret) { +bool seval_to_native_ptr(const se::Value &v, T *ret) { //NOLINT assert(ret != nullptr); if (v.isObject()) { @@ -228,7 +229,7 @@ seval_to_type(const se::Value &v, bool &ok) { return T(); } T *nativeObj = (T *)v.toObject()->getPrivateData(); - ok = true; + ok = true; return *nativeObj; } template @@ -283,9 +284,9 @@ seval_to_std_vector(const se::Value &v, std::vector *ret) { se::Object *obj = v.toObject(); assert(obj->isArray()); - bool ok = true; + bool ok = true; uint32_t len = 0; - ok = obj->getArrayLength(&len); + ok = obj->getArrayLength(&len); if (!ok) { ret->clear(); return false; @@ -303,7 +304,7 @@ seval_to_std_vector(const se::Value &v, std::vector *ret) { if (tmp.isObject()) { T nativeObj = (T)tmp.toObject()->getPrivateData(); - (*ret)[i] = nativeObj; + (*ret)[i] = nativeObj; } else if (tmp.isNullOrUndefined()) { (*ret)[i] = nullptr; } else { @@ -323,9 +324,9 @@ seval_to_std_vector(const se::Value &v, std::vector *ret) { se::Object *obj = v.toObject(); assert(obj->isArray()); - bool ok = true; + bool ok = true; uint32_t len = 0; - ok = obj->getArrayLength(&len); + ok = obj->getArrayLength(&len); if (!ok) { ret->clear(); return false; @@ -356,7 +357,7 @@ bool seval_to_Map_string_key(const se::Value &v, cc::Map *ret) { se::Object *obj = v.toObject(); std::vector allKeys; - bool ok = obj->getAllKeys(&allKeys); + bool ok = obj->getAllKeys(&allKeys); if (!ok) { ret->clear(); return false; @@ -378,43 +379,42 @@ bool seval_to_Map_string_key(const se::Value &v, cc::Map *ret) { } // native value -> se value -bool int8_to_seval(int8_t v, se::Value *ret); -bool uint8_to_seval(uint8_t v, se::Value *ret); -bool int32_to_seval(int32_t v, se::Value *ret); -bool uint32_to_seval(uint32_t v, se::Value *ret); -bool int16_to_seval(uint16_t v, se::Value *ret); -bool uint16_to_seval(uint16_t v, se::Value *ret); -bool boolean_to_seval(bool v, se::Value *ret); -bool float_to_seval(float v, se::Value *ret); -bool double_to_seval(double v, se::Value *ret); -bool long_to_seval(long v, se::Value *ret); -bool ulong_to_seval(unsigned long v, se::Value *ret); -bool longlong_to_seval(long long v, se::Value *ret); -bool uintptr_t_to_seval(uintptr_t v, se::Value *ret); -bool size_to_seval(size_t v, se::Value *ret); -bool std_string_to_seval(const std::string &v, se::Value *ret); +bool int8_to_seval(int8_t v, se::Value *ret); //NOLINT +bool uint8_to_seval(uint8_t v, se::Value *ret); //NOLINT +bool int32_to_seval(int32_t v, se::Value *ret); //NOLINT +bool uint32_to_seval(uint32_t v, se::Value *ret); //NOLINT +bool int16_to_seval(uint16_t v, se::Value *ret); //NOLINT +bool uint16_to_seval(uint16_t v, se::Value *ret); //NOLINT +bool boolean_to_seval(bool v, se::Value *ret); //NOLINT +bool float_to_seval(float v, se::Value *ret); //NOLINT +bool double_to_seval(double v, se::Value *ret); //NOLINT +bool long_to_seval(long v, se::Value *ret); //NOLINT +bool ulong_to_seval(unsigned long v, se::Value *ret); //NOLINT +bool longlong_to_seval(long long v, se::Value *ret); //NOLINT +bool uintptr_t_to_seval(uintptr_t v, se::Value *ret); //NOLINT +bool size_to_seval(size_t v, se::Value *ret); //NOLINT +bool std_string_to_seval(const std::string &v, se::Value *ret); //NOLINT -bool Vec2_to_seval(const cc::Vec2 &v, se::Value *ret); -bool Vec3_to_seval(const cc::Vec3 &v, se::Value *ret); -bool Vec4_to_seval(const cc::Vec4 &v, se::Value *ret); -bool Mat4_to_seval(const cc::Mat4 &v, se::Value *ret); -bool Size_to_seval(const cc::Size &v, se::Value *ret); -bool Rect_to_seval(const cc::Rect &v, se::Value *ret); -bool ccvalue_to_seval(const cc::Value &v, se::Value *ret); -bool ccvaluemap_to_seval(const cc::ValueMap &v, se::Value *ret); -bool ccvaluemapintkey_to_seval(const cc::ValueMapIntKey &v, se::Value *ret); -bool ccvaluevector_to_seval(const cc::ValueVector &v, se::Value *ret); -bool std_vector_string_to_seval(const std::vector &v, se::Value *ret); -bool std_vector_int_to_seval(const std::vector &v, se::Value *ret); -bool std_vector_uint16_to_seval(const std::vector &v, se::Value *ret); -bool std_vector_float_to_seval(const std::vector &v, se::Value *ret); -bool std_map_string_string_to_seval(const std::map &v, se::Value *ret); +bool Vec2_to_seval(const cc::Vec2 &v, se::Value *ret); //NOLINT +bool Vec3_to_seval(const cc::Vec3 &v, se::Value *ret); //NOLINT +bool Vec4_to_seval(const cc::Vec4 &v, se::Value *ret); //NOLINT +bool Mat4_to_seval(const cc::Mat4 &v, se::Value *ret); //NOLINT +bool Size_to_seval(const cc::Size &v, se::Value *ret); //NOLINT +bool Rect_to_seval(const cc::Rect &v, se::Value *ret); //NOLINT +bool ccvalue_to_seval(const cc::Value &v, se::Value *ret); //NOLINT +bool ccvaluemap_to_seval(const cc::ValueMap &v, se::Value *ret); //NOLINT +bool ccvaluemapintkey_to_seval(const cc::ValueMapIntKey &v, se::Value *ret); //NOLINT +bool ccvaluevector_to_seval(const cc::ValueVector &v, se::Value *ret); //NOLINT +bool std_vector_string_to_seval(const std::vector &v, se::Value *ret); //NOLINT +bool std_vector_int_to_seval(const std::vector &v, se::Value *ret); //NOLINT +bool std_vector_uint16_to_seval(const std::vector &v, se::Value *ret); //NOLINT +bool std_vector_float_to_seval(const std::vector &v, se::Value *ret); //NOLINT +bool std_map_string_string_to_seval(const std::map &v, se::Value *ret); //NOLINT +bool ManifestAsset_to_seval(const cc::extension::ManifestAsset &v, se::Value *ret); //NOLINT +bool Data_to_seval(const cc::Data &v, se::Value *ret); //NOLINT +bool DownloadTask_to_seval(const cc::network::DownloadTask &v, se::Value *ret); //NOLINT -bool ManifestAsset_to_seval(const cc::extension::ManifestAsset &v, se::Value *ret); -bool Data_to_seval(const cc::Data &v, se::Value *ret); -bool DownloadTask_to_seval(const cc::network::DownloadTask &v, se::Value *ret); - -//TODO: should add these functions if only bind gfx. +// TODO: should add these functions if only bind gfx. // gfx_color_attachment_to_seval // gfx_depth_stecil_attachment_to_seval // sub_pass_info_to_seval @@ -426,15 +426,15 @@ template typename std::enable_if::value, bool>::type native_ptr_to_seval(T *v_c, se::Value *ret, bool *isReturnCachedValue = nullptr) { typedef typename std::decay::type>::type DecayT; - DecayT *v = const_cast(v_c); + DecayT * v = const_cast(v_c); assert(ret != nullptr); if (v == nullptr) { ret->setNull(); return true; } - se::Object *obj = nullptr; - auto iter = se::NativePtrToObjectMap::find(v); + se::Object *obj = nullptr; + auto iter = se::NativePtrToObjectMap::find(v); if (iter == se::NativePtrToObjectMap::end()) { // If we couldn't find native object in map, then the native object is created from native code. e.g. TMXLayer::getTileAt // CC_LOG_DEBUGWARN("WARNING: non-Ref type: (%s) isn't catched!", typeid(*v).name()); se::Class *cls = JSBClassType::findClass(v); @@ -461,7 +461,7 @@ template typename std::enable_if::value && !std::is_pointer::value, bool>::type native_ptr_to_seval(T &v_ref, se::Value *ret, bool *isReturnCachedValue = nullptr) { typedef typename std::decay::type>::type DecayT; - DecayT *v = const_cast(&v_ref); + DecayT * v = const_cast(&v_ref); assert(ret != nullptr); if (v == nullptr) { @@ -469,8 +469,8 @@ native_ptr_to_seval(T &v_ref, se::Value *ret, bool *isReturnCachedValue = nullpt return true; } - se::Object *obj = nullptr; - auto iter = se::NativePtrToObjectMap::find(v); + se::Object *obj = nullptr; + auto iter = se::NativePtrToObjectMap::find(v); if (iter == se::NativePtrToObjectMap::end()) { // If we couldn't find native object in map, then the native object is created from native code. e.g. TMXLayer::getTileAt // CC_LOG_DEBUGWARN("WARNING: non-Ref type: (%s) isn't catched!", typeid(*v).name()); se::Class *cls = JSBClassType::findClass(v); @@ -500,8 +500,8 @@ bool native_ptr_to_rooted_seval(const typename std::enable_if(v); assert(cls != nullptr); @@ -530,15 +530,15 @@ template typename std::enable_if::value, bool>::type native_ptr_to_seval(T *vp, se::Class *cls, se::Value *ret, bool *isReturnCachedValue = nullptr) { typedef typename std::decay::type>::type DecayT; - DecayT *v = const_cast(vp); + DecayT * v = const_cast(vp); assert(ret != nullptr); if (v == nullptr) { ret->setNull(); return true; } - se::Object *obj = nullptr; - auto iter = se::NativePtrToObjectMap::find(v); + se::Object *obj = nullptr; + auto iter = se::NativePtrToObjectMap::find(v); if (iter == se::NativePtrToObjectMap::end()) { // If we couldn't find native object in map, then the native object is created from native code. e.g. TMXLayer::getTileAt // CC_LOG_DEBUGWARN("WARNING: Ref type: (%s) isn't catched!", typeid(*v).name()); assert(cls != nullptr); @@ -565,7 +565,7 @@ template typename std::enable_if::value, bool>::type native_ptr_to_seval(T &v_ref, se::Class *cls, se::Value *ret, bool *isReturnCachedValue = nullptr) { typedef typename std::decay::type>::type DecayT; - DecayT *v = const_cast(&v_ref); + DecayT * v = const_cast(&v_ref); assert(ret != nullptr); if (v == nullptr) { @@ -573,8 +573,8 @@ native_ptr_to_seval(T &v_ref, se::Class *cls, se::Value *ret, bool *isReturnCach return true; } - se::Object *obj = nullptr; - auto iter = se::NativePtrToObjectMap::find(v); + se::Object *obj = nullptr; + auto iter = se::NativePtrToObjectMap::find(v); if (iter == se::NativePtrToObjectMap::end()) { // If we couldn't find native object in map, then the native object is created from native code. e.g. TMXLayer::getTileAt // CC_LOG_DEBUGWARN("WARNING: Ref type: (%s) isn't catched!", typeid(*v).name()); assert(cls != nullptr); @@ -604,8 +604,8 @@ bool native_ptr_to_rooted_seval(typename std::enable_if typename std::enable_if::value, bool>::type native_ptr_to_seval(T *vp, se::Value *ret, bool *isReturnCachedValue = nullptr) { typedef typename std::decay::type>::type DecayT; - DecayT *v = const_cast(vp); + DecayT * v = const_cast(vp); assert(ret != nullptr); if (v == nullptr) { ret->setNull(); return true; } - se::Object *obj = nullptr; - auto iter = se::NativePtrToObjectMap::find(v); + se::Object *obj = nullptr; + auto iter = se::NativePtrToObjectMap::find(v); if (iter == se::NativePtrToObjectMap::end()) { // If we couldn't find native object in map, then the native object is created from native code. e.g. TMXLayer::getTileAt // CC_LOG_DEBUGWARN("WARNING: Ref type: (%s) isn't catched!", typeid(*v).name()); se::Class *cls = JSBClassType::findClass(v); @@ -669,15 +669,15 @@ template typename std::enable_if::value, bool>::type native_ptr_to_seval(T *vp, se::Class *cls, se::Value *ret, bool *isReturnCachedValue = nullptr) { typedef typename std::decay::type>::type DecayT; - DecayT *v = const_cast(vp); + DecayT * v = const_cast(vp); assert(ret != nullptr); if (v == nullptr) { ret->setNull(); return true; } - se::Object *obj = nullptr; - auto iter = se::NativePtrToObjectMap::find(v); + se::Object *obj = nullptr; + auto iter = se::NativePtrToObjectMap::find(v); if (iter == se::NativePtrToObjectMap::end()) { // If we couldn't find native object in map, then the native object is created from native code. e.g. TMXLayer::getTileAt // CC_LOG_DEBUGWARN("WARNING: Ref type: (%s) isn't catched!", typeid(*v).name()); assert(cls != nullptr); @@ -702,10 +702,10 @@ native_ptr_to_seval(T *vp, se::Class *cls, se::Value *ret, bool *isReturnCachedV template bool std_vector_to_seval(const std::vector &v, se::Value *ret) { assert(ret != nullptr); - bool ok = true; + bool ok = true; se::HandleObject obj(se::Object::createArrayObject(v.size())); - uint32_t i = 0; + uint32_t i = 0; se::Value tmp; for (const auto &e : v) { native_ptr_to_seval(e, &tmp); @@ -760,10 +760,10 @@ holder_convert_to(In &input) { template struct HolderType { - using type = typename std::remove_const::type; + using type = typename std::remove_const::type; using local_type = typename std::conditional_t, std::add_pointer_t, type>; - local_type data; - type *ptr = nullptr; + local_type data; + type * ptr = nullptr; constexpr inline type &value() { if (ptr) return *ptr; return holder_convert_to(data); @@ -775,20 +775,20 @@ struct HolderType { template <> struct HolderType { - using type = const char *; + using type = const char *; using local_type = std::string; - local_type data; + local_type data; std::remove_const_t *ptr = nullptr; - inline type value() { return data.c_str(); } + inline type value() { return data.c_str(); } }; template struct HolderType, true> { - using type = std::function; + using type = std::function; using local_type = std::function; - local_type data; + local_type data; std::remove_const_t *ptr = nullptr; - inline type value() { return data; } + inline type value() { return data; } }; ///////////////////////////////////convertion////////////////////////////////////////////////////////// @@ -805,7 +805,7 @@ template inline typename std::enable_if_t::value, bool> sevalue_to_native(const se::Value &from, T *to, se::Object *ctx) { typename std::underlying_type_t tmp; - bool ret = sevalue_to_native(from, &tmp, ctx); + bool ret = sevalue_to_native(from, &tmp, ctx); if (ret) *to = static_cast(tmp); return ret; } @@ -835,14 +835,14 @@ bool sevalue_to_native(const se::Value &from, std::array *to, se:: assert(array->isArray() || array->isArrayBuffer() || array->isTypedArray()); if (array->isTypedArray()) { uint8_t *data = nullptr; - size_t size = 0; + size_t size = 0; array->getTypedArrayData(&data, &size); for (size_t i = 0; i < std::min(size, CNT); i++) { (*to)[i] = data[i]; } } else if (array->isArrayBuffer()) { uint8_t *data = nullptr; - size_t size = 0; + size_t size = 0; array->getArrayBufferData(&data, &size); for (size_t i = 0; i < std::min(size, CNT); i++) { (*to)[i] = data[i]; @@ -1044,15 +1044,15 @@ inline bool sevalue_to_native(const se::Value &from, std::vector assert(from.isObject()); se::Object *in = from.toObject(); if (in->isTypedArray()) { - uint8_t *data = nullptr; - size_t dataLen = 0; + uint8_t *data = nullptr; + size_t dataLen = 0; in->getTypedArrayData(&data, &dataLen); to->resize(dataLen); to->assign(data, data + dataLen); return true; } else if (in->isArrayBuffer()) { - uint8_t *data = nullptr; - size_t dataLen = 0; + uint8_t *data = nullptr; + size_t dataLen = 0; in->getArrayBufferData(&data, &dataLen); to->resize(dataLen); to->assign(data, data + dataLen); @@ -1079,13 +1079,13 @@ inline bool sevalue_to_native(const se::Value &from, std::function * self->attachObject(callback); *func = [callback, self](Args... inargs) { se::AutoHandleScope hs; - bool ok = true; - se::ValueArray args; - int idx = 0; + bool ok = true; + se::ValueArray args; + int idx = 0; args.resize(sizeof...(Args)); nativevalue_to_se_args_v(args, inargs...); se::Value rval; - bool succeed = callback->call(args, self, &rval); + bool succeed = callback->call(args, self, &rval); if (!succeed) { se::ScriptEngine::getInstance()->clearException(); } @@ -1129,7 +1129,6 @@ inline bool sevalue_to_native(const se::Value &from, HolderType #else template inline typename std::enable_if, bool>::type sevalue_to_native(const se::Value &from, HolderType *holder, se::Object *ctx) { - void *ptr = from.toObject()->getPrivateData(); if (ptr) { holder->data = static_cast(ptr); @@ -1254,7 +1253,7 @@ nativevalue_to_se(const T &from, se::Value &to, se::Object *ctx) { template inline bool nativevalue_to_se(const std::vector &from, se::Value &to, se::Object *ctx) { se::Object *array = se::Object::createArrayObject(from.size()); - se::Value tmp; + se::Value tmp; for (size_t i = 0; i < from.size(); i++) { nativevalue_to_se(from[i], tmp, ctx); array->setArrayElement((uint32_t)i, tmp); @@ -1283,7 +1282,7 @@ inline bool nativevalue_to_se(const std::vector &from, se::Value &to, s template inline bool nativevalue_to_se(const std::array &from, se::Value &to, se::Object *ctx) { se::Object *array = se::Object::createArrayObject(N); - se::Value tmp; + se::Value tmp; for (size_t i = 0; i < N; i++) { nativevalue_to_se(from[i], tmp, ctx); array->setArrayElement((uint32_t)i, tmp); @@ -1478,7 +1477,7 @@ inline bool nativevalue_to_se(const cc::network::DownloadTask &v, se::Value &ret template bool nativevalue_to_se(const spine::Vector &v, se::Value &ret, se::Object *) { se::HandleObject obj(se::Object::createArrayObject(v.size())); - bool ok = true; + bool ok = true; spine::Vector tmpv = v; for (uint32_t i = 0, count = (uint32_t)tmpv.size(); i < count; i++) { @@ -1500,7 +1499,7 @@ bool nativevalue_to_se(const spine::Vector &v, se::Value &ret, se::Object *) template bool nativevalue_to_se(const spine::Vector &v, se::Value &ret, se::Object *) { se::HandleObject obj(se::Object::createArrayObject(v.size())); - bool ok = true; + bool ok = true; spine::Vector tmpv = v; for (uint32_t i = 0, count = (uint32_t)tmpv.size(); i < count; i++) { @@ -1524,9 +1523,9 @@ bool sevalue_to_native(const se::Value &v, spine::Vector *ret, se::Object * se::Object *obj = v.toObject(); assert(obj->isArray()); - bool ok = true; + bool ok = true; uint32_t len = 0; - ok = obj->getArrayLength(&len); + ok = obj->getArrayLength(&len); if (!ok) { ret->clear(); return false; diff --git a/native/cocos/bindings/manual/jsb_gfx_manual.cpp b/native/cocos/bindings/manual/jsb_gfx_manual.cpp index 4bd06120ef..f0225c7b60 100644 --- a/native/cocos/bindings/manual/jsb_gfx_manual.cpp +++ b/native/cocos/bindings/manual/jsb_gfx_manual.cpp @@ -36,12 +36,12 @@ bool js_gfx_Device_copyBuffersToTexture(se::State &s) { cc::gfx::Device *cobj = (cc::gfx::Device *)s.nativeThisObject(); SE_PRECONDITION2(cobj, false, "js_gfx_Device_copyBuffersToTexture : Invalid Native Object"); - const auto &args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto & args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 3) { - cc::gfx::BufferDataList arg0; - cc::gfx::Texture *arg1 = nullptr; + cc::gfx::BufferDataList arg0; + cc::gfx::Texture * arg1 = nullptr; cc::gfx::BufferTextureCopyList arg2; if (args[0].isObject()) { se::Object *dataObj = args[0].toObject(); @@ -53,7 +53,7 @@ bool js_gfx_Device_copyBuffersToTexture(se::State &s) { se::Value value; for (uint32_t i = 0; i < length; ++i) { if (dataObj->getArrayElement(i, &value)) { - uint8_t *ptr = nullptr; + uint8_t * ptr = nullptr; CC_UNUSED size_t dataLength = 0; if (value.isObject()) { se::Object *obj = value.toObject(); @@ -92,12 +92,12 @@ bool js_gfx_Device_copyTexImagesToTexture(se::State &s) { cc::gfx::Device *cobj = (cc::gfx::Device *)s.nativeThisObject(); SE_PRECONDITION2(cobj, false, "js_gfx_Device_copyBuffersToTexture : Invalid Native Object"); - const auto &args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto & args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 3) { - cc::gfx::BufferDataList arg0; - cc::gfx::Texture *arg1 = nullptr; + cc::gfx::BufferDataList arg0; + cc::gfx::Texture * arg1 = nullptr; cc::gfx::BufferTextureCopyList arg2; if (args[0].isObject()) { se::Object *dataObj = args[0].toObject(); @@ -111,7 +111,7 @@ bool js_gfx_Device_copyTexImagesToTexture(se::State &s) { if (dataObj->getArrayElement(i, &value)) { if (value.isObject()) { CC_UNUSED size_t dataLength = 0; - uint8_t *address = nullptr; + uint8_t * address = nullptr; value.toObject()->getTypedArrayData(&address, &dataLength); arg0[i] = address; } else { @@ -139,7 +139,7 @@ static bool js_gfx_Device_createBuffer(se::State &s) { cc::gfx::Device *cobj = (cc::gfx::Device *)s.nativeThisObject(); SE_PRECONDITION2(cobj, false, "js_gfx_Device_createBuffer : Invalid Native Object"); const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 2) { cc::gfx::Buffer *buffer = nullptr; @@ -172,15 +172,15 @@ static bool js_gfx_Device_createTexture(se::State &s) { cc::gfx::Device *cobj = (cc::gfx::Device *)s.nativeThisObject(); SE_PRECONDITION2(cobj, false, "js_gfx_Device_createTexture : Invalid Native Object"); const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 2) { - cc::gfx::Texture *texture = nullptr; - bool createTextureView = false; + cc::gfx::Texture *texture = nullptr; + bool createTextureView = false; seval_to_boolean(args[1], &createTextureView); if (createTextureView) { auto textureViewInfo = (cc::gfx::TextureViewInfo *)(args[0].toObject()->getPrivateData()); - texture = cobj->createTexture(*textureViewInfo); + texture = cobj->createTexture(*textureViewInfo); } else { cc::gfx::TextureInfo textureInfo; sevalue_to_native(args[0], &textureInfo, s.thisObject()); @@ -199,11 +199,11 @@ static bool js_gfx_Device_createTexture(se::State &s) { SE_BIND_FUNC(js_gfx_Device_createTexture) static bool js_gfx_Buffer_initialize(se::State &s) { - CC_UNUSED bool ok = true; + CC_UNUSED bool ok = true; cc::gfx::Buffer *cobj = (cc::gfx::Buffer *)s.nativeThisObject(); SE_PRECONDITION2(cobj, false, "js_gfx_Buffer_initialize : Invalid Native Object"); const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 2) { bool initWithBufferViewInfo = false; @@ -228,11 +228,11 @@ static bool js_gfx_Buffer_initialize(se::State &s) { SE_BIND_FUNC(js_gfx_Buffer_initialize) static bool js_gfx_Texture_initialize(se::State &s) { - CC_UNUSED bool ok = true; + CC_UNUSED bool ok = true; cc::gfx::Texture *cobj = (cc::gfx::Texture *)s.nativeThisObject(); SE_PRECONDITION2(cobj, false, "js_gfx_Texture_initialize : Invalid Native Object"); const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 2) { bool initWithTextureViewInfo = false; @@ -259,13 +259,13 @@ SE_BIND_FUNC(js_gfx_Texture_initialize) static bool js_gfx_GFXBuffer_update(se::State &s) { cc::gfx::Buffer *cobj = (cc::gfx::Buffer *)s.nativeThisObject(); SE_PRECONDITION2(cobj, false, "js_gfx_GFXBuffer_update : Invalid Native Object"); - const auto &args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto & args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; - uint8_t *arg0 = nullptr; + uint8_t * arg0 = nullptr; CC_UNUSED size_t dataLength = 0; - se::Object *obj = args[0].toObject(); + se::Object * obj = args[0].toObject(); if (obj->isArrayBuffer()) { ok = obj->getArrayBufferData(&arg0, &dataLength); SE_PRECONDITION2(ok, false, "getArrayBufferData failed!"); @@ -296,12 +296,12 @@ SE_BIND_FUNC(js_gfx_GFXBuffer_update) static bool js_gfx_CommandBuffer_execute(se::State &s) { cc::gfx::CommandBuffer *cobj = (cc::gfx::CommandBuffer *)s.nativeThisObject(); SE_PRECONDITION2(cobj, false, "js_gfx_CommandBuffer_execute : Invalid Native Object"); - const auto &args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto & args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 2) { cc::gfx::CommandBufferList cmdBufs; - unsigned int count = 0; + unsigned int count = 0; ok &= seval_to_uint32(args[1], (uint32_t *)&count); se::Object *jsarr = args[0].toObject(); @@ -323,7 +323,7 @@ static bool js_gfx_CommandBuffer_execute(se::State &s) { } cc::gfx::CommandBuffer *cmdBuf = (cc::gfx::CommandBuffer *)tmp.toObject()->getPrivateData(); - cmdBufs[i] = cmdBuf; + cmdBufs[i] = cmdBuf; } } @@ -340,17 +340,17 @@ static bool js_gfx_CommandBuffer_updateBuffer(se::State &s) { cc::gfx::CommandBuffer *cobj = (cc::gfx::CommandBuffer *)s.nativeThisObject(); SE_PRECONDITION2(cobj, false, "js_gfx_CommandBuffer_updateBuffer : Invalid Native Object"); - const auto &args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto & args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; cc::gfx::Buffer *arg0 = nullptr; SE_PRECONDITION2(args[0].isObject(), false, "js_gfx_CommandBuffer_updateBuffer : Invalid Native Object"); arg0 = (cc::gfx::Buffer *)args[0].toObject()->getPrivateData(); - uint8_t *arg1 = nullptr; + uint8_t * arg1 = nullptr; CC_UNUSED size_t dataLength = 0; - se::Object *obj = args[1].toObject(); + se::Object * obj = args[1].toObject(); if (obj->isArrayBuffer()) { ok = obj->getArrayBufferData(&arg1, &dataLength); SE_PRECONDITION2(ok, false, "getArrayBufferData failed!"); @@ -376,12 +376,12 @@ static bool js_gfx_CommandBuffer_copyBuffersToTexture(se::State &s) { cc::gfx::CommandBuffer *cobj = (cc::gfx::CommandBuffer *)s.nativeThisObject(); SE_PRECONDITION2(cobj, false, "js_gfx_CommandBuffer_copyBuffersToTexture : Invalid Native Object"); - const auto &args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto & args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 3) { - cc::gfx::BufferDataList arg0; - cc::gfx::Texture *arg1 = nullptr; + cc::gfx::BufferDataList arg0; + cc::gfx::Texture * arg1 = nullptr; cc::gfx::BufferTextureCopyList arg2; if (args[0].isObject()) { se::Object *dataObj = args[0].toObject(); @@ -393,9 +393,9 @@ static bool js_gfx_CommandBuffer_copyBuffersToTexture(se::State &s) { se::Value value; for (uint32_t i = 0; i < length; ++i) { if (dataObj->getArrayElement(i, &value)) { - uint8_t *ptr = nullptr; + uint8_t * ptr = nullptr; CC_UNUSED size_t dataLength = 0; - se::Object *obj = value.toObject(); + se::Object * obj = value.toObject(); if (obj->isArrayBuffer()) { ok = obj->getArrayBufferData(&ptr, &dataLength); SE_PRECONDITION2(ok, false, "getArrayBufferData failed!"); @@ -424,13 +424,13 @@ static bool js_gfx_InputAssembler_extractDrawInfo(se::State &s) { cc::gfx::InputAssembler *cobj = (cc::gfx::InputAssembler *)s.nativeThisObject(); SE_PRECONDITION2(cobj, false, "js_gfx_InputAssembler_extractDrawInfo : Invalid Native Object"); const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 1) { cc::gfx::DrawInfo nativeDrawInfo; cobj->extractDrawInfo(nativeDrawInfo); se::Object *drawInfo = args[0].toObject(); - se::Value attrValue(nativeDrawInfo.vertexCount); + se::Value attrValue(nativeDrawInfo.vertexCount); drawInfo->setProperty("vertexCount", attrValue); attrValue.setUint32(nativeDrawInfo.firstVertex); @@ -458,6 +458,12 @@ static bool js_gfx_InputAssembler_extractDrawInfo(se::State &s) { } SE_BIND_FUNC(js_gfx_InputAssembler_extractDrawInfo) +bool js_gfx_get_deviceInstance(se::State &s) { + nativevalue_to_se(cc::gfx::Device::getInstance(), s.rval(), nullptr); + return true; +} +SE_BIND_PROP_GET(js_gfx_get_deviceInstance) + bool register_all_gfx_manual(se::Object *obj) { __jsb_cc_gfx_Device_proto->defineFunction("copyBuffersToTexture", _SE(js_gfx_Device_copyBuffersToTexture)); __jsb_cc_gfx_Device_proto->defineFunction("copyTexImagesToTexture", _SE(js_gfx_Device_copyTexImagesToTexture)); @@ -489,6 +495,7 @@ bool register_all_gfx_manual(se::Object *obj) { se::Value jsret; nativevalue_to_se(cc::gfx::Device::getInstance(), jsret, nullptr); ns->setProperty("deviceInstance", jsret); + // ns->defineProperty("deviceInstance", _SE(js_gfx_get_deviceInstance), nullptr); } return true; diff --git a/native/cocos/bindings/manual/jsb_global.cpp b/native/cocos/bindings/manual/jsb_global.cpp index 5902dd9ae6..c8eb4adbfa 100644 --- a/native/cocos/bindings/manual/jsb_global.cpp +++ b/native/cocos/bindings/manual/jsb_global.cpp @@ -38,64 +38,64 @@ #include "xxtea/xxtea.h" #if CC_PLATFORM == CC_PLATFORM_ANDROID - #include "platform/android/jni/JniImp.h" + #include "platform/java/jni/JniImp.h" #endif #include #include #include -using namespace cc; +using namespace cc; //NOLINT -static LegacyThreadPool *__threadPool = nullptr; +static LegacyThreadPool *gThreadPool = nullptr; -static std::shared_ptr _localDownloader = nullptr; -static std::map> _localDownloaderHandlers; -static uint64_t _localDownloaderTaskId = 1000000; +static std::shared_ptr gLocalDownloader = nullptr; +static std::map> gLocalDownloaderHandlers; +static uint64_t gLocalDownloaderTaskId = 1000000; static cc::network::Downloader *localDownloader() { - if (!_localDownloader) { - _localDownloader = std::make_shared(); - _localDownloader->onDataTaskSuccess = [=](const cc::network::DownloadTask & task, + if (!gLocalDownloader) { + gLocalDownloader = std::make_shared(); + gLocalDownloader->onDataTaskSuccess = [=](const cc::network::DownloadTask & task, const std::vector &data) { if (data.empty()) { SE_REPORT_ERROR("Getting image from (%s) failed!", task.requestURL.c_str()); return; } - auto callback = _localDownloaderHandlers.find(task.identifier); - if (callback == _localDownloaderHandlers.end()) { + auto callback = gLocalDownloaderHandlers.find(task.identifier); + if (callback == gLocalDownloaderHandlers.end()) { SE_REPORT_ERROR("Getting image from (%s), callback not found!!", task.requestURL.c_str()); return; } - size_t imageBytes = data.size(); - unsigned char *imageData = (unsigned char *)malloc(imageBytes); + size_t imageBytes = data.size(); + auto * imageData = static_cast(malloc(imageBytes)); memcpy(imageData, data.data(), imageBytes); (callback->second)("", imageData, static_cast(imageBytes)); //initImageFunc("", imageData, imageBytes); - _localDownloaderHandlers.erase(callback); + gLocalDownloaderHandlers.erase(callback); }; - _localDownloader->onTaskError = [=](const cc::network::DownloadTask &task, - int errorCode, - int errorCodeInternal, - const std::string & errorStr) { + gLocalDownloader->onTaskError = [=](const cc::network::DownloadTask &task, + int errorCode, //NOLINT + int errorCodeInternal, //NOLINT + const std::string & errorStr) { //NOLINT SE_REPORT_ERROR("Getting image from (%s) failed!", task.requestURL.c_str()); - _localDownloaderHandlers.erase(task.identifier); + gLocalDownloaderHandlers.erase(task.identifier); }; } - return _localDownloader.get(); + return gLocalDownloader.get(); } -static void localDownloaderCreateTask(const std::string &url, std::function callback) { +static void localDownloaderCreateTask(const std::string &url, const std::function &callback) { std::stringstream ss; - ss << "jsb_loadimage_" << (_localDownloaderTaskId++); + ss << "jsb_loadimage_" << (gLocalDownloaderTaskId++); std::string key = ss.str(); auto task = localDownloader()->createDownloadDataTask(url, key); - _localDownloaderHandlers.emplace(std::make_pair(task->identifier, callback)); + gLocalDownloaderHandlers.emplace(std::make_pair(task->identifier, callback)); } -bool jsb_set_extend_property(const char *ns, const char *clsName) { +bool jsb_set_extend_property(const char *ns, const char *clsName) { //NOLINT se::Object *globalObj = se::ScriptEngine::getInstance()->getGlobalObject(); se::Value nsVal; if (globalObj->getProperty(ns, &nsVal) && nsVal.isObject()) { @@ -118,11 +118,11 @@ bool jsb_set_extend_property(const char *ns, const char *clsName) { namespace { -std::unordered_map __moduleCache; +std::unordered_map gModuleCache; -static bool require(se::State &s) { +static bool require(se::State &s) { //NOLINT const auto &args = s.args(); - int argc = (int)args.size(); + int argc = static_cast(args.size()); assert(argc >= 1); assert(args[0].isString()); @@ -130,7 +130,7 @@ static bool require(se::State &s) { } SE_BIND_FUNC(require) -static bool doModuleRequire(const std::string &path, se::Value *ret, const std::string &prevScriptFileDir) { +static bool doModuleRequire(const std::string &path, se::Value *ret, const std::string &prevScriptFileDir) { //NOLINT se::AutoHandleScope hs; assert(!path.empty()); @@ -140,24 +140,28 @@ static bool doModuleRequire(const std::string &path, se::Value *ret, const std:: std::string fullPath; std::string pathWithSuffix = path; - if (pathWithSuffix.rfind(".js") != (pathWithSuffix.length() - 3)) + if (pathWithSuffix.rfind(".js") != (pathWithSuffix.length() - 3)) { pathWithSuffix += ".js"; + } std::string scriptBuffer = fileOperationDelegate.onGetStringFromFile(pathWithSuffix); if (scriptBuffer.empty() && !prevScriptFileDir.empty()) { std::string secondPath = prevScriptFileDir; - if (secondPath[secondPath.length() - 1] != '/') + if (secondPath[secondPath.length() - 1] != '/') { secondPath += "/"; + } secondPath += path; if (FileUtils::getInstance()->isDirectoryExist(secondPath)) { - if (secondPath[secondPath.length() - 1] != '/') + if (secondPath[secondPath.length() - 1] != '/') { secondPath += "/"; + } secondPath += "index.js"; } else { - if (path.rfind(".js") != (path.length() - 3)) + if (path.rfind(".js") != (path.length() - 3)) { secondPath += ".js"; + } } fullPath = fileOperationDelegate.onGetFullPath(secondPath); @@ -167,8 +171,8 @@ static bool doModuleRequire(const std::string &path, se::Value *ret, const std:: } if (!scriptBuffer.empty()) { - const auto &iter = __moduleCache.find(fullPath); - if (iter != __moduleCache.end()) { + const auto &iter = gModuleCache.find(fullPath); + if (iter != gModuleCache.end()) { *ret = iter->second; // printf("Found cache: %s, value: %d\n", fullPath.c_str(), (int)ret->getType()); return true; @@ -187,8 +191,8 @@ static bool doModuleRequire(const std::string &path, se::Value *ret, const std:: // fwrite(scriptBuffer.c_str(), scriptBuffer.length(), 1, fp); // fclose(fp); - std::string reletivePath = fullPath; #if CC_PLATFORM == CC_PLATFORM_MAC_OSX || CC_PLATFORM == CC_PLATFORM_MAC_IOS + std::string reletivePath = fullPath; #if CC_PLATFORM == CC_PLATFORM_MAC_OSX const std::string reletivePathKey = "/Contents/Resources"; #else @@ -199,27 +203,27 @@ static bool doModuleRequire(const std::string &path, se::Value *ret, const std:: if (pos != std::string::npos) { reletivePath = reletivePath.substr(pos + reletivePathKey.length() + 1); } +#else + const std::string &reletivePath = fullPath; #endif - // RENDERER_LOGD("Evaluate: %s", fullPath.c_str()); - auto se = se::ScriptEngine::getInstance(); bool succeed = se->evalString(scriptBuffer.c_str(), scriptBuffer.length(), nullptr, reletivePath.c_str()); se::Value moduleVal; if (succeed && se->getGlobalObject()->getProperty("module", &moduleVal) && moduleVal.isObject()) { se::Value exportsVal; if (moduleVal.toObject()->getProperty("exports", &exportsVal)) { - if (ret != nullptr) + if (ret != nullptr) { *ret = exportsVal; - - __moduleCache[fullPath] = std::move(exportsVal); + } + gModuleCache[fullPath] = std::move(exportsVal); } else { - __moduleCache[fullPath] = se::Value::Undefined; + gModuleCache[fullPath] = se::Value::Undefined; } // clear module.exports moduleVal.toObject()->setProperty("exports", se::Value::Undefined); } else { - __moduleCache[fullPath] = se::Value::Undefined; + gModuleCache[fullPath] = se::Value::Undefined; } assert(succeed); return succeed; @@ -230,9 +234,9 @@ static bool doModuleRequire(const std::string &path, se::Value *ret, const std:: return false; } -static bool moduleRequire(se::State &s) { +static bool moduleRequire(se::State &s) { //NOLINT const auto &args = s.args(); - int argc = (int)args.size(); + int argc = static_cast(args.size()); assert(argc >= 2); assert(args[0].isString()); assert(args[1].isString()); @@ -242,22 +246,22 @@ static bool moduleRequire(se::State &s) { SE_BIND_FUNC(moduleRequire) } // namespace -bool jsb_run_script(const std::string &filePath, se::Value *rval /* = nullptr */) { +bool jsb_run_script(const std::string &filePath, se::Value *rval /* = nullptr */) { //NOLINT se::AutoHandleScope hs; return se::ScriptEngine::getInstance()->runScript(filePath, rval); } -bool jsb_run_script_module(const std::string &filePath, se::Value *rval /* = nullptr */) { +bool jsb_run_script_module(const std::string &filePath, se::Value *rval /* = nullptr */) { //NOLINT return doModuleRequire(filePath, rval, ""); } -static bool jsc_garbageCollect(se::State &s) { +static bool jsc_garbageCollect(se::State &s) { //NOLINT se::ScriptEngine::getInstance()->garbageCollect(); return true; } SE_BIND_FUNC(jsc_garbageCollect) -static bool jsc_dumpNativePtrToSeObjectMap(se::State &s) { +static bool jsc_dumpNativePtrToSeObjectMap(se::State &s) { //NOLINT CC_LOG_DEBUG(">>> total: %d, Dump (native -> jsobj) map begin", (int)se::NativePtrToObjectMap::size()); struct NamePtrStruct { @@ -279,14 +283,15 @@ static bool jsc_dumpNativePtrToSeObjectMap(se::State &s) { std::sort(namePtrArray.begin(), namePtrArray.end(), [](const NamePtrStruct &a, const NamePtrStruct &b) -> bool { std::string left = a.name; std::string right = b.name; - for (std::string::const_iterator lit = left.begin(), rit = right.begin(); lit != left.end() && rit != right.end(); ++lit, ++rit) - if (::tolower(*lit) < ::tolower(*rit)) + for (std::string::const_iterator lit = left.begin(), rit = right.begin(); lit != left.end() && rit != right.end(); ++lit, ++rit) { + if (::tolower(*lit) < ::tolower(*rit)) { return true; - else if (::tolower(*lit) > ::tolower(*rit)) + } + if (::tolower(*lit) > ::tolower(*rit)) { return false; - if (left.size() < right.size()) - return true; - return false; + } + } + return left.size() < right.size(); }); for (const auto &e : namePtrArray) { @@ -297,20 +302,20 @@ static bool jsc_dumpNativePtrToSeObjectMap(se::State &s) { } SE_BIND_FUNC(jsc_dumpNativePtrToSeObjectMap) -static bool jsc_dumpRoot(se::State &s) { +static bool jsc_dumpRoot(se::State &s) { //NOLINT assert(false); return true; } SE_BIND_FUNC(jsc_dumpRoot) -static bool JSBCore_platform(se::State &s) { +static bool JSBCore_platform(se::State &s) { //NOLINT Application::Platform platform = Application::getInstance()->getPlatform(); - s.rval().setInt32((int32_t)platform); + s.rval().setInt32(static_cast(platform)); return true; } SE_BIND_FUNC(JSBCore_platform) -static bool JSBCore_os(se::State &s) { +static bool JSBCore_os(se::State &s) { //NOLINT se::Value os; // osx, ios, android, windows, linux, etc.. @@ -324,6 +329,8 @@ static bool JSBCore_os(se::State &s) { os.setString("Linux"); #elif (CC_PLATFORM == CC_PLATFORM_MAC_OSX) os.setString("OS X"); +#elif (CC_PLATFORM == CC_PLATFORM_OHOS) + os.setString("OHOS"); #endif s.rval() = os; @@ -331,7 +338,7 @@ static bool JSBCore_os(se::State &s) { } SE_BIND_FUNC(JSBCore_os) -static bool JSBCore_getCurrentLanguage(se::State &s) { +static bool JSBCore_getCurrentLanguage(se::State &s) { //NOLINT std::string languageStr; Application::LanguageType language = Application::getInstance()->getCurrentLanguage(); switch (language) { @@ -401,30 +408,30 @@ static bool JSBCore_getCurrentLanguage(se::State &s) { } SE_BIND_FUNC(JSBCore_getCurrentLanguage) -static bool JSBCore_getCurrentLanguageCode(se::State &s) { +static bool JSBCore_getCurrentLanguageCode(se::State &s) { //NOLINT std::string language = Application::getInstance()->getCurrentLanguageCode(); s.rval().setString(language); return true; } SE_BIND_FUNC(JSBCore_getCurrentLanguageCode) -static bool JSB_getOSVersion(se::State &s) { +static bool JSB_getOSVersion(se::State &s) { //NOLINT std::string systemVersion = Application::getInstance()->getSystemVersion(); s.rval().setString(systemVersion); return true; } SE_BIND_FUNC(JSB_getOSVersion) -static bool JSB_core_restartVM(se::State &s) { +static bool JSB_core_restartVM(se::State &s) { //NOLINT //REFINE: release AudioEngine, waiting HttpClient & WebSocket threads to exit. Application::getInstance()->restart(); return true; } SE_BIND_FUNC(JSB_core_restartVM) -static bool JSB_isObjectValid(se::State &s) { +static bool JSB_isObjectValid(se::State &s) { //NOLINT const auto &args = s.args(); - int argc = (int)args.size(); + int argc = static_cast(args.size()); if (argc == 1) { void *nativePtr = nullptr; seval_to_native_ptr(args[0], &nativePtr); @@ -437,11 +444,12 @@ static bool JSB_isObjectValid(se::State &s) { } SE_BIND_FUNC(JSB_isObjectValid) -static bool JSB_setCursorEnabled(se::State &s) { +static bool JSB_setCursorEnabled(se::State &s) { //NOLINT const auto &args = s.args(); - int argc = (int)args.size(); + int argc = static_cast(args.size()); SE_PRECONDITION2(argc == 1, false, "Invalid number of arguments"); - bool ok = true, value = true; + bool ok = true; + bool value = true; ok &= seval_to_boolean(args[0], &value); SE_PRECONDITION2(ok, false, "Error processing arguments"); @@ -450,9 +458,9 @@ static bool JSB_setCursorEnabled(se::State &s) { } SE_BIND_FUNC(JSB_setCursorEnabled) -static bool JSB_saveByteCode(se::State &s) { +static bool JSB_saveByteCode(se::State &s) { //NOLINT const auto &args = s.args(); - int argc = (int)args.size(); + int argc = static_cast(args.size()); SE_PRECONDITION2(argc == 2, false, "Invalid number of arguments"); bool ok = true; std::string srcfile; @@ -466,7 +474,7 @@ static bool JSB_saveByteCode(se::State &s) { } SE_BIND_FUNC(JSB_saveByteCode) -static bool getOrCreatePlainObject_r(const char *name, se::Object *parent, se::Object **outObj) { +static bool getOrCreatePlainObject_r(const char *name, se::Object *parent, se::Object **outObj) { //NOLINT assert(parent != nullptr); assert(outObj != nullptr); se::Value tmp; @@ -482,10 +490,10 @@ static bool getOrCreatePlainObject_r(const char *name, se::Object *parent, se::O return true; } -static bool js_performance_now(se::State &s) { +static bool js_performance_now(se::State &s) { //NOLINT auto now = std::chrono::steady_clock::now(); auto micro = std::chrono::duration_cast(now - se::ScriptEngine::getInstance()->getStartTime()).count(); - s.rval().setNumber((double)micro * 0.001); + s.rval().setNumber(static_cast(micro) * 0.001); return true; } SE_BIND_FUNC(js_performance_now) @@ -502,7 +510,7 @@ struct ImageInfo { }; uint8_t *convertRGB2RGBA(uint32_t length, uint8_t *src) { - uint8_t *dst = reinterpret_cast(malloc(length)); + auto *dst = reinterpret_cast(malloc(length)); for (uint32_t i = 0; i < length; i += 4) { dst[i] = *src++; dst[i + 1] = *src++; @@ -513,7 +521,7 @@ uint8_t *convertRGB2RGBA(uint32_t length, uint8_t *src) { } uint8_t *convertIA2RGBA(uint32_t length, uint8_t *src) { - uint8_t *dst = reinterpret_cast(malloc(length)); + auto *dst = reinterpret_cast(malloc(length)); for (uint32_t i = 0; i < length; i += 4) { dst[i] = *src; dst[i + 1] = *src; @@ -524,7 +532,7 @@ uint8_t *convertIA2RGBA(uint32_t length, uint8_t *src) { } uint8_t *convertI2RGBA(uint32_t length, uint8_t *src) { - uint8_t *dst = reinterpret_cast(malloc(length)); + auto *dst = reinterpret_cast(malloc(length)); for (uint32_t i = 0; i < length; i += 4) { dst[i] = *src; dst[i + 1] = *src; @@ -535,10 +543,10 @@ uint8_t *convertI2RGBA(uint32_t length, uint8_t *src) { } struct ImageInfo *createImageInfo(Image *img) { - struct ImageInfo *imgInfo = new struct ImageInfo(); - imgInfo->length = (uint32_t)img->getDataLen(); - imgInfo->width = img->getWidth(); - imgInfo->height = img->getHeight(); + auto *imgInfo = new struct ImageInfo(); + imgInfo->length = static_cast(img->getDataLen()); + imgInfo->width = img->getWidth(); + imgInfo->height = img->getHeight(); img->takeData(&imgInfo->data); imgInfo->format = img->getRenderFormat(); imgInfo->compressed = img->isCompressed(); @@ -580,7 +588,7 @@ struct ImageInfo *createImageInfo(Image *img) { } } // namespace -bool jsb_global_load_image(const std::string &path, const se::Value &callbackVal) { +bool jsb_global_load_image(const std::string &path, const se::Value &callbackVal) { //NOLINT(readability-identifier-naming) if (path.empty()) { se::ValueArray seArgs; callbackVal.toObject()->call(seArgs, nullptr); @@ -590,9 +598,9 @@ bool jsb_global_load_image(const std::string &path, const se::Value &callbackVal std::shared_ptr callbackPtr = std::make_shared(callbackVal); auto initImageFunc = [path, callbackPtr](const std::string &fullPath, unsigned char *imageData, int imageBytes) { - Image *img = new (std::nothrow) Image(); + auto *img = new (std::nothrow) Image(); - __threadPool->pushTask([=](int tid) { + gThreadPool->pushTask([=](int /*tid*/) { // NOTE: FileUtils::getInstance()->fullPathForFilename isn't a threadsafe method, // Image::initWithImageFile will call fullPathForFilename internally which may // cause thread race issues. Therefore, we get the full path of file before @@ -618,7 +626,7 @@ bool jsb_global_load_image(const std::string &path, const se::Value &callbackVal if (loadSucceed) { se::HandleObject retObj(se::Object::createPlainObject()); - ulong_to_seval((unsigned long)imgInfo->data, &dataVal); + ulong_to_seval(reinterpret_cast(imgInfo->data), &dataVal); //NOLINT Why use addr? See #3033. retObj->setProperty("data", dataVal); retObj->setProperty("width", se::Value(imgInfo->width)); retObj->setProperty("height", se::Value(imgInfo->height)); @@ -644,7 +652,7 @@ bool jsb_global_load_image(const std::string &path, const se::Value &callbackVal size_t dataStartPos = pos + strlen("base64,"); const char * base64Data = path.data() + dataStartPos; size_t dataLen = path.length() - dataStartPos; - imageBytes = base64Decode((const unsigned char *)base64Data, (unsigned int)dataLen, &imageData); + imageBytes = base64Decode(reinterpret_cast(base64Data), static_cast(dataLen), &imageData); if (imageBytes <= 0 || imageData == nullptr) { SE_REPORT_ERROR("Decode base64 image data failed!"); return false; @@ -652,8 +660,9 @@ bool jsb_global_load_image(const std::string &path, const se::Value &callbackVal initImageFunc("", imageData, imageBytes); } else { std::string fullPath(FileUtils::getInstance()->fullPathForFilename(path)); - if (0 == path.find("file://")) + if (0 == path.find("file://")) { fullPath = FileUtils::getInstance()->fullPathForFilename(path.substr(strlen("file://"))); + } if (fullPath.empty()) { SE_REPORT_ERROR("File (%s) doesn't exist!", path.c_str()); @@ -664,7 +673,7 @@ bool jsb_global_load_image(const std::string &path, const se::Value &callbackVal return true; } -static bool js_loadImage(se::State &s) { +static bool js_loadImage(se::State &s) { //NOLINT const auto & args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; @@ -684,16 +693,15 @@ static bool js_loadImage(se::State &s) { } SE_BIND_FUNC(js_loadImage) -static bool js_destroyImage(se::State &s) { +static bool js_destroyImage(se::State &s) { //NOLINT const auto & args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; if (argc == 1) { - unsigned long data = 0; + unsigned long data = 0; //NOLINT ok &= seval_to_ulong(args[0], &data); SE_PRECONDITION2(ok, false, "js_destroyImage : Error processing arguments"); free(reinterpret_cast(data)); - return true; } SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); @@ -701,7 +709,7 @@ static bool js_destroyImage(se::State &s) { } SE_BIND_FUNC(js_destroyImage) -static bool JSB_openURL(se::State &s) { +static bool JSB_openURL(se::State &s) { //NOLINT const auto & args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; @@ -718,7 +726,7 @@ static bool JSB_openURL(se::State &s) { } SE_BIND_FUNC(JSB_openURL) -static bool JSB_copyTextToClipboard(se::State &s) { +static bool JSB_copyTextToClipboard(se::State &s) { //NOLINT const auto & args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; @@ -735,7 +743,7 @@ static bool JSB_copyTextToClipboard(se::State &s) { } SE_BIND_FUNC(JSB_copyTextToClipboard) -static bool JSB_setPreferredFramesPerSecond(se::State &s) { +static bool JSB_setPreferredFramesPerSecond(se::State &s) { //NOLINT const auto & args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; @@ -754,7 +762,7 @@ static bool JSB_setPreferredFramesPerSecond(se::State &s) { SE_BIND_FUNC(JSB_setPreferredFramesPerSecond) #if CC_USE_EDITBOX -static bool JSB_showInputBox(se::State &s) { +static bool JSB_showInputBox(se::State &s) { //NOLINT const auto &args = s.args(); size_t argc = args.size(); if (argc == 1) { @@ -778,44 +786,51 @@ static bool JSB_showInputBox(se::State &s) { if (obj->getProperty("confirmHold", &tmp)) { SE_PRECONDITION2(tmp.isBoolean(), false, "confirmHold is invalid!"); - if (!tmp.isUndefined()) + if (!tmp.isUndefined()) { showInfo.confirmHold = tmp.toBoolean(); + } } if (obj->getProperty("confirmType", &tmp)) { SE_PRECONDITION2(tmp.isString(), false, "confirmType is invalid!"); - if (!tmp.isUndefined()) + if (!tmp.isUndefined()) { showInfo.confirmType = tmp.toString(); + } } if (obj->getProperty("inputType", &tmp)) { SE_PRECONDITION2(tmp.isString(), false, "inputType is invalid!"); - if (!tmp.isUndefined()) + if (!tmp.isUndefined()) { showInfo.inputType = tmp.toString(); + } } if (obj->getProperty("originX", &tmp)) { SE_PRECONDITION2(tmp.isNumber(), false, "originX is invalid!"); - if (!tmp.isUndefined()) + if (!tmp.isUndefined()) { showInfo.x = tmp.toInt32(); + } } if (obj->getProperty("originY", &tmp)) { SE_PRECONDITION2(tmp.isNumber(), false, "originY is invalid!"); - if (!tmp.isUndefined()) + if (!tmp.isUndefined()) { showInfo.y = tmp.toInt32(); + } } if (obj->getProperty("width", &tmp)) { SE_PRECONDITION2(tmp.isNumber(), false, "width is invalid!"); - if (!tmp.isUndefined()) + if (!tmp.isUndefined()) { showInfo.width = tmp.toInt32(); + } } if (obj->getProperty("height", &tmp)) { SE_PRECONDITION2(tmp.isNumber(), false, "height is invalid!"); - if (!tmp.isUndefined()) + if (!tmp.isUndefined()) { showInfo.height = tmp.toInt32(); + } } EditBox::show(showInfo); @@ -828,7 +843,7 @@ static bool JSB_showInputBox(se::State &s) { } SE_BIND_FUNC(JSB_showInputBox); -static bool JSB_hideInputBox(se::State &s) { +static bool JSB_hideInputBox(se::State &s) { //NOLINT EditBox::hide(); return true; } @@ -836,8 +851,8 @@ SE_BIND_FUNC(JSB_hideInputBox) #endif -bool jsb_register_global_variables(se::Object *global) { - __threadPool = LegacyThreadPool::newFixedThreadPool(3); +bool jsb_register_global_variables(se::Object *global) { //NOLINT + gThreadPool = LegacyThreadPool::newFixedThreadPool(3); global->defineFunction("require", _SE(require)); global->defineFunction("requireModule", _SE(moduleRequire)); @@ -876,8 +891,8 @@ bool jsb_register_global_variables(se::Object *global) { se::ScriptEngine::getInstance()->clearException(); se::ScriptEngine::getInstance()->addBeforeCleanupHook([]() { - delete __threadPool; - __threadPool = nullptr; + delete gThreadPool; + gThreadPool = nullptr; PoolManager::getInstance()->getCurrentPool()->clear(); }); @@ -885,7 +900,7 @@ bool jsb_register_global_variables(se::Object *global) { se::ScriptEngine::getInstance()->addAfterCleanupHook([]() { PoolManager::getInstance()->getCurrentPool()->clear(); - __moduleCache.clear(); + gModuleCache.clear(); SAFE_DEC_REF(__jsbObj); SAFE_DEC_REF(__glObj); diff --git a/native/cocos/bindings/manual/jsb_global.h b/native/cocos/bindings/manual/jsb_global.h index 9de4c006e3..da6702f9f4 100644 --- a/native/cocos/bindings/manual/jsb_global.h +++ b/native/cocos/bindings/manual/jsb_global.h @@ -29,28 +29,28 @@ template inline typename std::enable_if::value, T>::type * -jsb_override_new(Args &&...args) { +jsb_override_new(Args &&...args) { //NOLINT(readability-identifier-naming) //create object in gfx way return CC_NEW(T(std::forward(args)...)); } template inline typename std::enable_if::value, void>::type -jsb_override_delete(T *arg) { +jsb_override_delete(T *arg) { //NOLINT(readability-identifier-naming) //create object in gfx way CC_DELETE(arg); } template inline typename std::enable_if::value, T>::type * -jsb_override_new(Args &&...args) { +jsb_override_new(Args &&...args) { //NOLINT(readability-identifier-naming) //create object in the default way return new T(std::forward(args)...); } template inline typename std::enable_if::value, void>::type -jsb_override_delete(T *arg) { +jsb_override_delete(T *arg) { //NOLINT(readability-identifier-naming) //create object in gfx way delete (arg); } @@ -63,10 +63,10 @@ class Class; class Value; } // namespace se -bool jsb_register_global_variables(se::Object *global); +bool jsb_register_global_variables(se::Object *global); //NOLINT(readability-identifier-naming) -bool jsb_set_extend_property(const char *ns, const char *clsName); -bool jsb_run_script(const std::string &filePath, se::Value *rval = nullptr); -bool jsb_run_script_module(const std::string &filePath, se::Value *rval = nullptr); +bool jsb_set_extend_property(const char *ns, const char *clsName); //NOLINT(readability-identifier-naming) +bool jsb_run_script(const std::string &filePath, se::Value *rval = nullptr); //NOLINT(readability-identifier-naming) +bool jsb_run_script_module(const std::string &filePath, se::Value *rval = nullptr); //NOLINT(readability-identifier-naming) -bool jsb_global_load_image(const std::string &path, const se::Value &callbackVal); +bool jsb_global_load_image(const std::string &path, const se::Value &callbackVal); //NOLINT(readability-identifier-naming) diff --git a/native/cocos/bindings/manual/jsb_global_init.cpp b/native/cocos/bindings/manual/jsb_global_init.cpp index 7b06342d9b..3e585d1551 100644 --- a/native/cocos/bindings/manual/jsb_global_init.cpp +++ b/native/cocos/bindings/manual/jsb_global_init.cpp @@ -23,29 +23,29 @@ THE SOFTWARE. ****************************************************************************/ -#include "jsb_global_init.h" #include "base/CoreStd.h" #include "base/Scheduler.h" #include "base/ZipUtils.h" #include "base/base64.h" #include "jsb_conversions.h" +#include "jsb_global_init.h" #include "xxtea/xxtea.h" #include #include #include -using namespace cc; +using namespace cc; //NOLINT -se::Object *__jsbObj = nullptr; -se::Object *__glObj = nullptr; +se::Object *__jsbObj = nullptr; //NOLINT +se::Object *__glObj = nullptr; //NOLINT -static std::string xxteaKey = ""; -void jsb_set_xxtea_key(const std::string &key) { +static std::string xxteaKey; +void jsb_set_xxtea_key(const std::string &key) { //NOLINT xxteaKey = key; } -static const char *BYTE_CODE_FILE_EXT = ".jsc"; +static const char *BYTE_CODE_FILE_EXT = ".jsc"; //NOLINT static std::string removeFileExt(const std::string &filePath) { size_t pos = filePath.rfind('.'); @@ -55,7 +55,8 @@ static std::string removeFileExt(const std::string &filePath) { return filePath; } -void jsb_init_file_operation_delegate() { +void jsb_init_file_operation_delegate() { //NOLINT + static se::ScriptEngine::FileOperationDelegate delegate; if (!delegate.isValid()) { delegate.onGetDataFromFile = [](const std::string &path, const std::function &readCallback) -> void { @@ -68,7 +69,9 @@ void jsb_init_file_operation_delegate() { fileData = FileUtils::getInstance()->getDataFromFile(byteCodePath); size_t dataLen = 0; - uint8_t *data = xxtea_decrypt((unsigned char *)fileData.getBytes(), (uint32_t)fileData.getSize(), (unsigned char *)xxteaKey.c_str(), (uint32_t)xxteaKey.size(), (uint32_t *)&dataLen); + uint8_t *data = xxtea_decrypt(fileData.getBytes(), static_cast(fileData.getSize()), + reinterpret_cast(xxteaKey.data()), + static_cast(xxteaKey.size()), reinterpret_cast(&dataLen)); if (data == nullptr) { SE_REPORT_ERROR("Can't decrypt code for %s", byteCodePath.c_str()); @@ -107,7 +110,9 @@ void jsb_init_file_operation_delegate() { Data fileData = FileUtils::getInstance()->getDataFromFile(byteCodePath); uint32_t dataLen; - uint8_t *data = xxtea_decrypt((uint8_t *)fileData.getBytes(), (uint32_t)fileData.getSize(), (uint8_t *)xxteaKey.c_str(), (uint32_t)xxteaKey.size(), &dataLen); + uint8_t *data = xxtea_decrypt(static_cast(fileData.getBytes()), static_cast(fileData.getSize()), + reinterpret_cast(xxteaKey.data()), + static_cast(xxteaKey.size()), &dataLen); if (data == nullptr) { SE_REPORT_ERROR("Can't decrypt code for %s", byteCodePath.c_str()); @@ -126,19 +131,17 @@ void jsb_init_file_operation_delegate() { free(unpackedData); free(data); - return ret; - } else { - std::string ret(reinterpret_cast(data), dataLen); - free(data); return ret; } + std::string ret(reinterpret_cast(data), dataLen); + free(data); + return ret; } if (FileUtils::getInstance()->isFileExist(path)) { return FileUtils::getInstance()->getStringFromFile(path); - } else { - SE_LOGE("ScriptEngine::onGetStringFromFile %s not found, possible missing file.\n", path.c_str()); } + SE_LOGE("ScriptEngine::onGetStringFromFile %s not found, possible missing file.\n", path.c_str()); return ""; }; @@ -162,17 +165,18 @@ void jsb_init_file_operation_delegate() { } } -bool jsb_enable_debugger(const std::string &debuggerServerAddr, uint32_t port, bool isWaitForConnect) { - if (debuggerServerAddr.empty() || port == 0) +bool jsb_enable_debugger(const std::string &debuggerServerAddr, uint32_t port, bool isWaitForConnect) { //NOLINT + if (debuggerServerAddr.empty() || port == 0) { return false; + } auto se = se::ScriptEngine::getInstance(); - se->enableDebugger(debuggerServerAddr.c_str(), port, isWaitForConnect); + se->enableDebugger(debuggerServerAddr, port, isWaitForConnect); // For debugger main loop class SimpleRunLoop { public: - void update(float dt) { + void update(float dt) { //NOLINT se::ScriptEngine::getInstance()->mainLoopUpdate(); } }; diff --git a/native/cocos/bindings/manual/jsb_global_init.h b/native/cocos/bindings/manual/jsb_global_init.h index b6ad1f0682..2df2454a35 100644 --- a/native/cocos/bindings/manual/jsb_global_init.h +++ b/native/cocos/bindings/manual/jsb_global_init.h @@ -25,19 +25,19 @@ #pragma once -#include "base/CoreStd.h" -#include "base/memory/Memory.h" #include #include #include +#include "base/CoreStd.h" +#include "base/memory/Memory.h" namespace se { class Object; } // namespace se -extern se::Object *__jsbObj; -extern se::Object *__glObj; +extern se::Object *__jsbObj; //NOLINT +extern se::Object *__glObj; //NOLINT -void jsb_init_file_operation_delegate(); -void jsb_set_xxtea_key(const std::string &key); -bool jsb_enable_debugger(const std::string &debuggerServerAddr, uint32_t port, bool isWaitForConnect = false); +void jsb_init_file_operation_delegate(); //NOLINT +void jsb_set_xxtea_key(const std::string &key); //NOLINT +bool jsb_enable_debugger(const std::string &debuggerServerAddr, uint32_t port, bool isWaitForConnect = false); //NOLINT \ No newline at end of file diff --git a/native/cocos/bindings/manual/jsb_module_register.cpp b/native/cocos/bindings/manual/jsb_module_register.cpp index ca5082d21a..4678c4034b 100644 --- a/native/cocos/bindings/manual/jsb_module_register.cpp +++ b/native/cocos/bindings/manual/jsb_module_register.cpp @@ -23,21 +23,21 @@ THE SOFTWARE. ****************************************************************************/ -#include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_module_register.h" -#include "cocos/bindings/auto/jsb_cocos_auto.h" #include "cocos/base/AutoreleasePool.h" -#include "cocos/bindings/dop/jsb_dop.h" +#include "cocos/bindings/auto/jsb_cocos_auto.h" #include "cocos/bindings/auto/jsb_extension_auto.h" -#include "cocos/bindings/auto/jsb_network_auto.h" #include "cocos/bindings/auto/jsb_gfx_auto.h" +#include "cocos/bindings/auto/jsb_network_auto.h" #include "cocos/bindings/auto/jsb_pipeline_auto.h" -#include "cocos/bindings/manual/jsb_pipeline_manual.h" +#include "cocos/bindings/dop/jsb_dop.h" +#include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_cocos_manual.h" -#include "cocos/bindings/manual/jsb_network_manual.h" #include "cocos/bindings/manual/jsb_conversions.h" #include "cocos/bindings/manual/jsb_gfx_manual.h" #include "cocos/bindings/manual/jsb_global.h" +#include "cocos/bindings/manual/jsb_network_manual.h" +#include "cocos/bindings/manual/jsb_pipeline_manual.h" #include "cocos/bindings/manual/jsb_platform.h" #include "cocos/bindings/manual/jsb_xmlhttprequest.h" @@ -57,11 +57,11 @@ #include "cocos/bindings/manual/JavaScriptObjCBridge.h" #endif -#if (CC_PLATFORM == CC_PLATFORM_ANDROID) +#if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) #include "cocos/bindings/manual/JavaScriptJavaBridge.h" #endif -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS || CC_PLATFORM == CC_PLATFORM_ANDROID) +#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS || CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) #if USE_VIDEO #include "cocos/bindings/auto/jsb_video_auto.h" @@ -132,7 +132,7 @@ bool jsb_register_all_modules() { se->addRegisterCallback(register_javascript_objc_bridge); #endif -#if (CC_PLATFORM == CC_PLATFORM_ANDROID) +#if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) se->addRegisterCallback(register_javascript_java_bridge); #endif @@ -164,7 +164,7 @@ bool jsb_register_all_modules() { se->addRegisterCallback(register_all_physics); #endif -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS || CC_PLATFORM == CC_PLATFORM_ANDROID) +#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS || CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) #if USE_VIDEO se->addRegisterCallback(register_all_video); diff --git a/native/cocos/bindings/manual/jsb_platform_android.cpp b/native/cocos/bindings/manual/jsb_platform_android.cpp index d45ec1d29f..e1e642d81c 100644 --- a/native/cocos/bindings/manual/jsb_platform_android.cpp +++ b/native/cocos/bindings/manual/jsb_platform_android.cpp @@ -29,7 +29,7 @@ #include "cocos/bindings/manual/jsb_conversions.h" #include "cocos/bindings/manual/jsb_global.h" #include "cocos/platform/FileUtils.h" -#include "cocos/platform/android/jni/JniHelper.h" +#include "cocos/platform/java/jni/JniHelper.h" #include diff --git a/native/cocos/bindings/manual/jsb_platform_ohos.cpp b/native/cocos/bindings/manual/jsb_platform_ohos.cpp new file mode 100644 index 0000000000..3872131ade --- /dev/null +++ b/native/cocos/bindings/manual/jsb_platform_ohos.cpp @@ -0,0 +1,90 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +#include "jsb_platform.h" + +#include "cocos/bindings/jswrapper/SeApi.h" +#include "cocos/bindings/manual/jsb_conversions.h" +#include "cocos/bindings/manual/jsb_global.h" +#include "cocos/platform/FileUtils.h" +#include "cocos/platform/java/jni/JniHelper.h" + +#include + +#ifndef JCLS_CANVASIMPL + #define JCLS_CANVASIMPL "com/cocos/lib/CanvasRenderingContext2DImpl" +#endif + +using namespace cc; //NOLINT + +static std::unordered_map gFontFamilyNameMap; + +const std::unordered_map &getFontFamilyNameMap() { + return gFontFamilyNameMap; +} + +static bool JSB_loadFont(se::State &s) { //NOLINT + const auto & args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; + if (argc >= 1) { + s.rval().setNull(); + + std::string originalFamilyName; + ok &= seval_to_std_string(args[0], &originalFamilyName); + SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: originalFamilyName"); + + std::string source; + ok &= seval_to_std_string(args[1], &source); + SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: source"); + + std::string fontFilePath; + std::regex re(R"(url\(\s*'\s*(.*?)\s*'\s*\))"); + std::match_results results; + if (std::regex_search(source.cbegin(), source.cend(), results, re)) { + fontFilePath = results[1].str(); + } + + fontFilePath = FileUtils::getInstance()->fullPathForFilename(fontFilePath); + if (fontFilePath.empty()) { + SE_LOGE("Font (%s) doesn't exist!", fontFilePath.c_str()); + return true; + } + + JniHelper::callStaticVoidMethod(JCLS_CANVASIMPL, "loadTypeface", originalFamilyName, fontFilePath); + + s.rval().setString(originalFamilyName); + + return true; + } + + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + return false; +} +SE_BIND_FUNC(JSB_loadFont) + +bool register_platform_bindings(se::Object *obj) { //NOLINT + __jsbObj->defineFunction("loadFont", _SE(JSB_loadFont)); + return true; +} \ No newline at end of file diff --git a/native/cocos/bindings/manual/jsb_websocket_server.cpp b/native/cocos/bindings/manual/jsb_websocket_server.cpp index 8a32126be5..29467034e7 100644 --- a/native/cocos/bindings/manual/jsb_websocket_server.cpp +++ b/native/cocos/bindings/manual/jsb_websocket_server.cpp @@ -26,7 +26,11 @@ #if (USE_SOCKET > 0) && (USE_WEBSOCKET_SERVER > 0) #include "cocos/bindings/manual/jsb_websocket_server.h" - #include "uv/uv.h" + #if CC_PLATFORM == CC_PLATFORM_OHOS + #include "uv.h" + #else + #include "uv/uv.h" + #endif #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_conversions.h" #include "cocos/bindings/manual/jsb_global.h" diff --git a/native/cocos/editor-support/dragonbones/parser/JSONDataParser.cpp b/native/cocos/editor-support/dragonbones/parser/JSONDataParser.cpp index 4dd8b4e6dc..007122a83f 100644 --- a/native/cocos/editor-support/dragonbones/parser/JSONDataParser.cpp +++ b/native/cocos/editor-support/dragonbones/parser/JSONDataParser.cpp @@ -5,55 +5,48 @@ DRAGONBONES_NAMESPACE_BEGIN void JSONDataParser::_getCurvePoint( float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, - float t, - Point& result -) -{ - const auto l_t = 1.0f - t; + float t, + Point &result) { + const auto l_t = 1.0f - t; const auto powA = l_t * l_t; const auto powB = t * t; - const auto kA = l_t * powA; - const auto kB = 3.0f * t * powA; - const auto kC = 3.0f * l_t * powB; - const auto kD = t * powB; + const auto kA = l_t * powA; + const auto kB = 3.0f * t * powA; + const auto kC = 3.0f * l_t * powB; + const auto kD = t * powB; result.x = kA * x1 + kB * x2 + kC * x3 + kD * x4; result.y = kA * y1 + kB * y2 + kC * y3 + kD * y4; } -void JSONDataParser::_samplingEasingCurve(const rapidjson::Value& curve, std::vector& samples) -{ +void JSONDataParser::_samplingEasingCurve(const rapidjson::Value &curve, std::vector &samples) { int curveCount = curve.Size(); - int stepIndex = -2; - for (std::size_t i = 0, l = samples.size(); i < l; ++i) - { - float t = (float)(i + 1) / (l + 1); // float + int stepIndex = -2; + for (std::size_t i = 0, l = samples.size(); i < l; ++i) { + float t = (float)(i + 1) / (l + 1); // float while ((stepIndex + 6 < curveCount ? curve[stepIndex + 6].GetDouble() : 1) < t) // stepIndex + 3 * 2 { stepIndex += 6; } const auto isInCurve = stepIndex >= 0 && stepIndex + 6 < curveCount; - const auto x1 = isInCurve ? curve[stepIndex].GetDouble() : 0.0f; - const auto y1 = isInCurve ? curve[stepIndex + 1].GetDouble() : 0.0f; - const auto x2 = curve[stepIndex + 2].GetDouble(); - const auto y2 = curve[stepIndex + 3].GetDouble(); - const auto x3 = curve[stepIndex + 4].GetDouble(); - const auto y3 = curve[stepIndex + 5].GetDouble(); - const auto x4 = isInCurve ? curve[stepIndex + 6].GetDouble() : 1.0f; - const auto y4 = isInCurve ? curve[stepIndex + 7].GetDouble() : 1.0f; + const auto x1 = isInCurve ? curve[stepIndex].GetDouble() : 0.0f; + const auto y1 = isInCurve ? curve[stepIndex + 1].GetDouble() : 0.0f; + const auto x2 = curve[stepIndex + 2].GetDouble(); + const auto y2 = curve[stepIndex + 3].GetDouble(); + const auto x3 = curve[stepIndex + 4].GetDouble(); + const auto y3 = curve[stepIndex + 5].GetDouble(); + const auto x4 = isInCurve ? curve[stepIndex + 6].GetDouble() : 1.0f; + const auto y4 = isInCurve ? curve[stepIndex + 7].GetDouble() : 1.0f; - float lower = 0.0f; + float lower = 0.0f; float higher = 1.0f; - while (higher - lower > 0.0001f) - { + while (higher - lower > 0.0001f) { const auto percentage = (higher + lower) * 0.5f; _getCurvePoint(x1, y1, x2, y2, x3, y3, x4, y4, percentage, _helpPoint); - if (t - _helpPoint.x > 0.0f) - { + if (t - _helpPoint.x > 0.0f) { lower = percentage; - } - else { + } else { higher = percentage; } } @@ -62,42 +55,34 @@ void JSONDataParser::_samplingEasingCurve(const rapidjson::Value& curve, std::ve } } -void JSONDataParser::_parseActionDataInFrame(const rapidjson::Value& rawData, unsigned frameStart, BoneData* bone, SlotData* slot) -{ - if (rawData.HasMember(EVENT)) - { +void JSONDataParser::_parseActionDataInFrame(const rapidjson::Value &rawData, unsigned frameStart, BoneData *bone, SlotData *slot) { + if (rawData.HasMember(EVENT)) { _mergeActionFrame(rawData[EVENT], frameStart, ActionType::Frame, bone, slot); } - if (rawData.HasMember(SOUND)) - { + if (rawData.HasMember(SOUND)) { _mergeActionFrame(rawData[SOUND], frameStart, ActionType::Sound, bone, slot); } - if (rawData.HasMember(ACTION)) - { + if (rawData.HasMember(ACTION)) { _mergeActionFrame(rawData[ACTION], frameStart, ActionType::Play, bone, slot); } - - if (rawData.HasMember(EVENTS)) - { + + if (rawData.HasMember(EVENTS)) { _mergeActionFrame(rawData[EVENTS], frameStart, ActionType::Frame, bone, slot); } - if (rawData.HasMember(ACTIONS)) - { + if (rawData.HasMember(ACTIONS)) { _mergeActionFrame(rawData[ACTIONS], frameStart, ActionType::Play, bone, slot); } } -void JSONDataParser::_mergeActionFrame(const rapidjson::Value& rawData, unsigned frameStart, ActionType type, BoneData* bone, SlotData* slot) -{ - const auto actionOffset = _armature->actions.size(); - const auto& actions = _parseActionData(rawData, type, bone, slot); - ActionFrame* frame = nullptr; +void JSONDataParser::_mergeActionFrame(const rapidjson::Value &rawData, unsigned frameStart, ActionType type, BoneData *bone, SlotData *slot) { + const auto actionOffset = _armature->actions.size(); + const auto & actions = _parseActionData(rawData, type, bone, slot); + ActionFrame *frame = nullptr; - for (const auto action : actions) - { + for (const auto action : actions) { _armature->addAction(action, false); } @@ -107,10 +92,9 @@ void JSONDataParser::_mergeActionFrame(const rapidjson::Value& rawData, unsigned _actionFrames[0].frameStart = 0; } - for (auto& eachFrame : _actionFrames) // Get same frame. + for (auto &eachFrame : _actionFrames) // Get same frame. { - if (eachFrame.frameStart == frameStart) - { + if (eachFrame.frameStart == frameStart) { frame = &eachFrame; break; } @@ -120,7 +104,7 @@ void JSONDataParser::_mergeActionFrame(const rapidjson::Value& rawData, unsigned { const auto frameCount = _actionFrames.size(); _actionFrames.resize(frameCount + 1); - frame = &_actionFrames[frameCount]; + frame = &_actionFrames[frameCount]; frame->frameStart = frameStart; } @@ -130,12 +114,11 @@ void JSONDataParser::_mergeActionFrame(const rapidjson::Value& rawData, unsigned } } -unsigned JSONDataParser::_parseCacheActionFrame(ActionFrame& frame) -{ +unsigned JSONDataParser::_parseCacheActionFrame(ActionFrame &frame) { const auto frameOffset = _frameArray.size(); const auto actionCount = frame.actions.size(); _frameArray.resize(_frameArray.size() + 1 + 1 + actionCount); - _frameArray[frameOffset + (unsigned)BinaryOffset::FramePosition] = frame.frameStart; + _frameArray[frameOffset + (unsigned)BinaryOffset::FramePosition] = frame.frameStart; _frameArray[frameOffset + (unsigned)BinaryOffset::FramePosition + 1] = actionCount; // Action count. for (std::size_t i = 0; i < actionCount; ++i) // Action offsets. @@ -146,19 +129,15 @@ unsigned JSONDataParser::_parseCacheActionFrame(ActionFrame& frame) return frameOffset; } -ArmatureData* JSONDataParser::_parseArmature(const rapidjson::Value& rawData, float scale) -{ +ArmatureData *JSONDataParser::_parseArmature(const rapidjson::Value &rawData, float scale) { const auto armature = BaseObject::borrowObject(); - armature->name = _getString(rawData, NAME, ""); + armature->name = _getString(rawData, NAME, ""); armature->frameRate = _getNumber(rawData, FRAME_RATE, _data->frameRate); - armature->scale = scale; + armature->scale = scale; - if (rawData.HasMember(TYPE) && rawData[TYPE].IsString()) - { + if (rawData.HasMember(TYPE) && rawData[TYPE].IsString()) { armature->type = _getArmatureType(rawData[TYPE].GetString()); - } - else - { + } else { armature->type = (ArmatureType)_getNumber(rawData, TYPE, (int)ArmatureType::Armature); } @@ -169,57 +148,49 @@ ArmatureData* JSONDataParser::_parseArmature(const rapidjson::Value& rawData, fl _armature = armature; - if (rawData.HasMember(CANVAS)) - { - const auto& rawCanvas = rawData[CANVAS]; - const auto canvas = BaseObject::borrowObject(); + if (rawData.HasMember(CANVAS)) { + const auto &rawCanvas = rawData[CANVAS]; + const auto canvas = BaseObject::borrowObject(); canvas->hasBackground = rawCanvas.HasMember(COLOR); - canvas->color = _getNumber(rawCanvas, COLOR, 0); - canvas->aabb.x = _getNumber(rawCanvas, X, 0.0f) * armature->scale; - canvas->aabb.y = _getNumber(rawCanvas, Y, 0.0f) * armature->scale; - canvas->aabb.width = _getNumber(rawCanvas, WIDTH, 0.0f) * armature->scale; - canvas->aabb.height = _getNumber(rawCanvas, HEIGHT, 0.0f) * armature->scale; + canvas->color = _getNumber(rawCanvas, COLOR, 0); + canvas->aabb.x = _getNumber(rawCanvas, X, 0.0f) * armature->scale; + canvas->aabb.y = _getNumber(rawCanvas, Y, 0.0f) * armature->scale; + canvas->aabb.width = _getNumber(rawCanvas, WIDTH, 0.0f) * armature->scale; + canvas->aabb.height = _getNumber(rawCanvas, HEIGHT, 0.0f) * armature->scale; // armature->canvas = canvas; } - if (rawData.HasMember(AABB)) - { - const auto& rawAABB = rawData[AABB]; - armature->aabb.x = _getNumber(rawAABB, X, 0.0f) * armature->scale; - armature->aabb.y = _getNumber(rawAABB, Y, 0.0f) * armature->scale; - armature->aabb.width = _getNumber(rawAABB, WIDTH, 0.0f) * armature->scale; + if (rawData.HasMember(AABB)) { + const auto &rawAABB = rawData[AABB]; + armature->aabb.x = _getNumber(rawAABB, X, 0.0f) * armature->scale; + armature->aabb.y = _getNumber(rawAABB, Y, 0.0f) * armature->scale; + armature->aabb.width = _getNumber(rawAABB, WIDTH, 0.0f) * armature->scale; armature->aabb.height = _getNumber(rawAABB, HEIGHT, 0.0f) * armature->scale; } - if (rawData.HasMember(BONE)) - { - const auto& rawBones = rawData[BONE]; - for (std::size_t i = 0, l = rawBones.Size(); i < l; ++i) - { - const auto& rawBone = rawBones[i]; - const auto& parentName = _getString(rawBone, PARENT, ""); - const auto bone = _parseBone(rawBone); + if (rawData.HasMember(BONE)) { + const auto &rawBones = rawData[BONE]; + for (std::size_t i = 0, l = rawBones.Size(); i < l; ++i) { + const auto &rawBone = rawBones[i]; + const auto &parentName = _getString(rawBone, PARENT, ""); + const auto bone = _parseBone(rawBone); if (!parentName.empty()) // Get bone parent. { const auto parent = armature->getBone(parentName); - if (parent != nullptr) - { + if (parent != nullptr) { bone->parent = parent; - } - else // Cache. + } else // Cache. { - auto& cacheBones = _cacheBones[parentName]; + auto &cacheBones = _cacheBones[parentName]; cacheBones.push_back(bone); } } - + auto iterator = _cacheBones.find(bone->name); - if (iterator != _cacheBones.end()) - { - for (const auto child : _cacheBones[bone->name]) - { + if (iterator != _cacheBones.end()) { + for (const auto child : _cacheBones[bone->name]) { child->parent = bone; } @@ -231,14 +202,11 @@ ArmatureData* JSONDataParser::_parseArmature(const rapidjson::Value& rawData, fl } } - if (rawData.HasMember(IK)) - { - const auto& rawIKS = rawData[IK]; - for (std::size_t i = 0, l = rawIKS.Size(); i < l; ++i) - { + if (rawData.HasMember(IK)) { + const auto &rawIKS = rawData[IK]; + for (std::size_t i = 0, l = rawIKS.Size(); i < l; ++i) { const auto constraint = _parseIKConstraint(rawIKS[i]); - if (constraint) - { + if (constraint) { armature->addConstraint(constraint); } } @@ -246,29 +214,25 @@ ArmatureData* JSONDataParser::_parseArmature(const rapidjson::Value& rawData, fl armature->sortBones(); - if (rawData.HasMember(SLOT)) - { - int zOrder = 0; - const auto& rawSlots = rawData[SLOT]; - for (std::size_t i = 0, l = rawSlots.Size(); i < l; ++i) - { + if (rawData.HasMember(SLOT)) { + int zOrder = 0; + const auto &rawSlots = rawData[SLOT]; + for (std::size_t i = 0, l = rawSlots.Size(); i < l; ++i) { armature->addSlot(_parseSlot(rawSlots[i], zOrder++)); } } - if (rawData.HasMember(SKIN)) - { - const auto& rawSkins = rawData[SKIN]; - for (std::size_t i = 0, l = rawSkins.Size(); i < l; ++i) - { + if (rawData.HasMember(SKIN)) { + const auto &rawSkins = rawData[SKIN]; + for (std::size_t i = 0, l = rawSkins.Size(); i < l; ++i) { armature->addSkin(_parseSkin(rawSkins[i])); } } for (std::size_t i = 0, l = _cacheRawMeshes.size(); i < l; ++i) // Link mesh. - { - const auto rawMeshData = _cacheRawMeshes[i]; - const auto& shareName = _getString(*rawMeshData, SHARE, ""); + { + const auto rawMeshData = _cacheRawMeshes[i]; + const auto &shareName = _getString(*rawMeshData, SHARE, ""); if (shareName.empty()) { continue; } @@ -288,39 +252,32 @@ ArmatureData* JSONDataParser::_parseArmature(const rapidjson::Value& rawData, fl mesh->vertices.shareFrom(shareMesh->vertices); } - if (rawData.HasMember(ANIMATION)) - { - const auto& rawAnimations = rawData[ANIMATION]; - for (std::size_t i = 0, l = rawAnimations.Size(); i < l; ++i) - { + if (rawData.HasMember(ANIMATION)) { + const auto &rawAnimations = rawData[ANIMATION]; + for (std::size_t i = 0, l = rawAnimations.Size(); i < l; ++i) { armature->addAnimation(_parseAnimation(rawAnimations[i])); } } - if (rawData.HasMember(DEFAULT_ACTIONS)) - { - const auto& actions = _parseActionData(rawData[DEFAULT_ACTIONS], ActionType::Play, nullptr, nullptr); - for (const auto action : actions) - { + if (rawData.HasMember(DEFAULT_ACTIONS)) { + const auto &actions = _parseActionData(rawData[DEFAULT_ACTIONS], ActionType::Play, nullptr, nullptr); + for (const auto action : actions) { armature->addAction(action, true); if (action->type == ActionType::Play) // Set default animation from default action. - { + { const auto animation = armature->getAnimation(action->name); - if (animation != nullptr) - { + if (animation != nullptr) { armature->defaultAnimation = animation; } } } } - if (rawData.HasMember(ACTIONS)) - { - const auto& actions = _parseActionData(rawData[ACTIONS], ActionType::Play, nullptr, nullptr); + if (rawData.HasMember(ACTIONS)) { + const auto &actions = _parseActionData(rawData[ACTIONS], ActionType::Play, nullptr, nullptr); - for (const auto action : actions) - { + for (const auto action : actions) { armature->addAction(action, false); } } @@ -339,54 +296,46 @@ ArmatureData* JSONDataParser::_parseArmature(const rapidjson::Value& rawData, fl return armature; } -BoneData* JSONDataParser::_parseBone(const rapidjson::Value& rawData) -{ - const auto bone = BaseObject::borrowObject(); +BoneData *JSONDataParser::_parseBone(const rapidjson::Value &rawData) { + const auto bone = BaseObject::borrowObject(); bone->inheritTranslation = _getBoolean(rawData, INHERIT_TRANSLATION, true); - bone->inheritRotation = _getBoolean(rawData, INHERIT_ROTATION, true); - bone->inheritScale = _getBoolean(rawData, INHERIT_SCALE, true); - bone->inheritReflection = _getBoolean(rawData, INHERIT_REFLECTION, true); - bone->length = _getNumber(rawData, LENGTH, 0.0f) * _armature->scale; - bone->name = _getString(rawData, NAME, ""); + bone->inheritRotation = _getBoolean(rawData, INHERIT_ROTATION, true); + bone->inheritScale = _getBoolean(rawData, INHERIT_SCALE, true); + bone->inheritReflection = _getBoolean(rawData, INHERIT_REFLECTION, true); + bone->length = _getNumber(rawData, LENGTH, 0.0f) * _armature->scale; + bone->name = _getString(rawData, NAME, ""); - if (rawData.HasMember(TRANSFORM)) - { + if (rawData.HasMember(TRANSFORM)) { _parseTransform(rawData[TRANSFORM], bone->transform, _armature->scale); } return bone; } -ConstraintData* JSONDataParser::_parseIKConstraint(const rapidjson::Value& rawData) -{ +ConstraintData *JSONDataParser::_parseIKConstraint(const rapidjson::Value &rawData) { const auto bone = _armature->getBone(_getString(rawData, BONE, "")); - if (bone == nullptr) - { + if (bone == nullptr) { return nullptr; } const auto target = _armature->getBone(_getString(rawData, TARGET, "")); - if (target == nullptr) - { + if (target == nullptr) { return nullptr; } - const auto constraint = BaseObject::borrowObject(); + const auto constraint = BaseObject::borrowObject(); constraint->scaleEnabled = _getBoolean(rawData, SCALE, false); constraint->bendPositive = _getBoolean(rawData, BEND_POSITIVE, true); - constraint->weight = _getNumber(rawData, WEIGHT, 1.0f); - constraint->name = _getString(rawData, NAME, ""); - constraint->bone = bone; - constraint->target = target; + constraint->weight = _getNumber(rawData, WEIGHT, 1.0f); + constraint->name = _getString(rawData, NAME, ""); + constraint->bone = bone; + constraint->target = target; const auto chain = _getNumber(rawData, CHAIN, (unsigned)0); - if (chain > 0 && bone->parent != nullptr) - { + if (chain > 0 && bone->parent != nullptr) { constraint->root = bone->parent; constraint->bone = bone; - } - else - { + } else { constraint->root = bone; constraint->bone = nullptr; } @@ -394,76 +343,58 @@ ConstraintData* JSONDataParser::_parseIKConstraint(const rapidjson::Value& rawDa return constraint; } -SlotData* JSONDataParser::_parseSlot(const rapidjson::Value& rawData, int zOrder) -{ - const auto slot = BaseObject::borrowObject(); +SlotData *JSONDataParser::_parseSlot(const rapidjson::Value &rawData, int zOrder) { + const auto slot = BaseObject::borrowObject(); slot->displayIndex = _getNumber(rawData, DISPLAY_INDEX, (int)0); - slot->zOrder = zOrder; - slot->name = _getString(rawData, NAME, ""); - slot->parent = _armature->getBone(_getString(rawData, PARENT, "")); + slot->zOrder = zOrder; + slot->name = _getString(rawData, NAME, ""); + slot->parent = _armature->getBone(_getString(rawData, PARENT, "")); - if (rawData.HasMember(BLEND_MODE) && rawData[BLEND_MODE].IsString()) - { + if (rawData.HasMember(BLEND_MODE) && rawData[BLEND_MODE].IsString()) { slot->blendMode = _getBlendMode(rawData[BLEND_MODE].GetString()); - } - else - { + } else { slot->blendMode = (BlendMode)_getNumber(rawData, BLEND_MODE, (int)BlendMode::Normal); } - if (rawData.HasMember(COLOR)) - { + if (rawData.HasMember(COLOR)) { slot->color = SlotData::createColor(); _parseColorTransform(rawData[COLOR], *slot->color); - } - else - { + } else { slot->color = &SlotData::DEFAULT_COLOR; } - if (rawData.HasMember(ACTIONS)) - { + if (rawData.HasMember(ACTIONS)) { _slotChildActions[slot->name] = _parseActionData(rawData[ACTIONS], ActionType::Play, nullptr, nullptr); } return slot; } -SkinData * JSONDataParser::_parseSkin(const rapidjson::Value& rawData) -{ +SkinData *JSONDataParser::_parseSkin(const rapidjson::Value &rawData) { const auto skin = BaseObject::borrowObject(); - skin->name = _getString(rawData, NAME, DEFAULT_NAME); - if (skin->name.empty()) - { + skin->name = _getString(rawData, NAME, DEFAULT_NAME); + if (skin->name.empty()) { skin->name = DEFAULT_NAME; } - if (rawData.HasMember(SLOT)) - { - const auto& rawSlots = rawData[SLOT]; - _skin = skin; + if (rawData.HasMember(SLOT)) { + const auto &rawSlots = rawData[SLOT]; + _skin = skin; - for (std::size_t i = 0, l = rawSlots.Size(); i < l; ++i) - { - const auto& rawSlot = rawSlots[i]; - const auto& slotName = _getString(rawSlot, NAME, ""); - const auto slot = _armature->getSlot(slotName); - if (slot != nullptr) - { + for (std::size_t i = 0, l = rawSlots.Size(); i < l; ++i) { + const auto &rawSlot = rawSlots[i]; + const auto &slotName = _getString(rawSlot, NAME, ""); + const auto slot = _armature->getSlot(slotName); + if (slot != nullptr) { _slot = slot; - if (rawSlot.HasMember(DISPLAY)) - { - const auto& rawDisplays = rawSlot[DISPLAY]; - for (std::size_t j = 0, lJ = rawDisplays.Size(); j < lJ; ++j) - { - const auto& rawDisplay = rawDisplays[j]; - if (!rawDisplay.IsNull()) - { + if (rawSlot.HasMember(DISPLAY)) { + const auto &rawDisplays = rawSlot[DISPLAY]; + for (std::size_t j = 0, lJ = rawDisplays.Size(); j < lJ; ++j) { + const auto &rawDisplay = rawDisplays[j]; + if (!rawDisplay.IsNull()) { skin->addDisplay(slotName, _parseDisplay(rawDisplay)); - } - else - { + } else { skin->addDisplay(slotName, nullptr); } } @@ -479,58 +410,45 @@ SkinData * JSONDataParser::_parseSkin(const rapidjson::Value& rawData) return skin; } -DisplayData* JSONDataParser::_parseDisplay(const rapidjson::Value& rawData) -{ - const auto& name = _getString(rawData, NAME, ""); - const auto& path = _getString(rawData, PATH, ""); - auto type = DisplayType::Image; - DisplayData* display = nullptr; +DisplayData *JSONDataParser::_parseDisplay(const rapidjson::Value &rawData) { + const auto & name = _getString(rawData, NAME, ""); + const auto & path = _getString(rawData, PATH, ""); + auto type = DisplayType::Image; + DisplayData *display = nullptr; - if (rawData.HasMember(TYPE) && rawData[TYPE].IsString()) - { + if (rawData.HasMember(TYPE) && rawData[TYPE].IsString()) { type = _getDisplayType(rawData[TYPE].GetString()); - } - else - { + } else { type = (DisplayType)_getNumber(rawData, TYPE, (int)DisplayType::Image); } - switch (type) - { - case dragonBones::DisplayType::Image: - { + switch (type) { + case dragonBones::DisplayType::Image: { const auto imageDisplay = BaseObject::borrowObject(); - imageDisplay->name = name; - imageDisplay->path = !path.empty() ? path : name; + imageDisplay->name = name; + imageDisplay->path = !path.empty() ? path : name; _parsePivot(rawData, *imageDisplay); display = imageDisplay; break; } - case dragonBones::DisplayType::Armature: - { - const auto armatureDisplay = BaseObject::borrowObject(); - armatureDisplay->name = name; - armatureDisplay->path = !path.empty() ? path : name; + case dragonBones::DisplayType::Armature: { + const auto armatureDisplay = BaseObject::borrowObject(); + armatureDisplay->name = name; + armatureDisplay->path = !path.empty() ? path : name; armatureDisplay->inheritAnimation = true; - if (rawData.HasMember(ACTIONS)) - { - const auto& actions = _parseActionData(rawData[ACTIONS], ActionType::Play, nullptr, nullptr); + if (rawData.HasMember(ACTIONS)) { + const auto &actions = _parseActionData(rawData[ACTIONS], ActionType::Play, nullptr, nullptr); - for (const auto action : actions) - { + for (const auto action : actions) { armatureDisplay->addAction(action); } - } - else if (_slotChildActions.find(_slot->name) != _slotChildActions.cend()) - { + } else if (_slotChildActions.find(_slot->name) != _slotChildActions.cend()) { const auto displays = _skin->getDisplays(_slot->name); - if (displays == nullptr ? _slot->displayIndex == 0 : (std::size_t)_slot->displayIndex == displays->size()) - { - for (const auto action : _slotChildActions[_slot->name]) - { + if (displays == nullptr ? _slot->displayIndex == 0 : (std::size_t)_slot->displayIndex == displays->size()) { + for (const auto action : _slotChildActions[_slot->name]) { armatureDisplay->addAction(action); } @@ -542,21 +460,17 @@ DisplayData* JSONDataParser::_parseDisplay(const rapidjson::Value& rawData) break; } - case dragonBones::DisplayType::Mesh: - { - const auto meshDisplay = BaseObject::borrowObject(); + case dragonBones::DisplayType::Mesh: { + const auto meshDisplay = BaseObject::borrowObject(); meshDisplay->vertices.inheritDeform = _getBoolean(rawData, INHERIT_DEFORM, true); - meshDisplay->name = name; - meshDisplay->path = !path.empty() ? path : name; - meshDisplay->vertices.data = _data; + meshDisplay->name = name; + meshDisplay->path = !path.empty() ? path : name; + meshDisplay->vertices.data = _data; - if (rawData.HasMember(SHARE)) - { + if (rawData.HasMember(SHARE)) { _cacheRawMeshes.push_back(&rawData); _cacheMeshes.push_back(meshDisplay); - } - else - { + } else { _parseMesh(rawData, *meshDisplay); } @@ -564,120 +478,111 @@ DisplayData* JSONDataParser::_parseDisplay(const rapidjson::Value& rawData) break; } - case dragonBones::DisplayType::BoundingBox: - { + case dragonBones::DisplayType::BoundingBox: { const auto boundingBox = _parseBoundingBox(rawData); - if (boundingBox != nullptr) - { - const auto boundingBoxDisplay = BaseObject::borrowObject(); - boundingBoxDisplay->name = name; - boundingBoxDisplay->path = !path.empty() ? path : name; + if (boundingBox != nullptr) { + const auto boundingBoxDisplay = BaseObject::borrowObject(); + boundingBoxDisplay->name = name; + boundingBoxDisplay->path = !path.empty() ? path : name; boundingBoxDisplay->boundingBox = boundingBox; display = boundingBoxDisplay; } break; } + case dragonBones::DisplayType::Path: + default: + // suppress warning + //TODO: + break; } - if (display != nullptr && rawData.HasMember(TRANSFORM)) - { + if (display != nullptr && rawData.HasMember(TRANSFORM)) { _parseTransform(rawData[TRANSFORM], display->transform, _armature->scale); } return display; } -void JSONDataParser::_parsePivot(const rapidjson::Value& rawData, ImageDisplayData& display) -{ - if (rawData.HasMember(PIVOT)) - { - const auto& rawPivot = rawData[PIVOT]; - display.pivot.x = _getNumber(rawPivot, X, 0.0f); - display.pivot.y = _getNumber(rawPivot, Y, 0.0f); - } - else - { +void JSONDataParser::_parsePivot(const rapidjson::Value &rawData, ImageDisplayData &display) { + if (rawData.HasMember(PIVOT)) { + const auto &rawPivot = rawData[PIVOT]; + display.pivot.x = _getNumber(rawPivot, X, 0.0f); + display.pivot.y = _getNumber(rawPivot, Y, 0.0f); + } else { display.pivot.x = 0.5f; display.pivot.y = 0.5f; } } -void JSONDataParser::_parseMesh(const rapidjson::Value& rawData, MeshDisplayData& mesh) -{ - const auto& rawVertices = rawData[VERTICES]; - const auto& rawUVs = rawData[UVS]; - const auto& rawTriangles = rawData[TRIANGLES]; - const auto vertexCount = rawVertices.Size() / 2; - const auto triangleCount = rawTriangles.Size() / 3; - const auto vertexOffset = _floatArray.size(); - const auto uvOffset = vertexOffset + vertexCount * 2; - const auto meshOffset = _intArray.size(); - const auto meshName = _skin->name + "_" + _slot->name + "_" + mesh.name; // Cache pose data. +void JSONDataParser::_parseMesh(const rapidjson::Value &rawData, MeshDisplayData &mesh) { + const auto &rawVertices = rawData[VERTICES]; + const auto &rawUVs = rawData[UVS]; + const auto &rawTriangles = rawData[TRIANGLES]; + const auto vertexCount = rawVertices.Size() / 2; + const auto triangleCount = rawTriangles.Size() / 3; + const auto vertexOffset = _floatArray.size(); + const auto uvOffset = vertexOffset + vertexCount * 2; + const auto meshOffset = _intArray.size(); + const auto meshName = _skin->name + "_" + _slot->name + "_" + mesh.name; // Cache pose data. mesh.vertices.offset = meshOffset; _intArray.resize(_intArray.size() + 1 + 1 + 1 + 1 + triangleCount * 3); - _intArray[meshOffset + (unsigned)BinaryOffset::MeshVertexCount] = vertexCount; + _intArray[meshOffset + (unsigned)BinaryOffset::MeshVertexCount] = vertexCount; _intArray[meshOffset + (unsigned)BinaryOffset::MeshTriangleCount] = triangleCount; - _intArray[meshOffset + (unsigned)BinaryOffset::MeshFloatOffset] = vertexOffset; - for (std::size_t i = 0, l = triangleCount * 3; i < l; ++i) - { + _intArray[meshOffset + (unsigned)BinaryOffset::MeshFloatOffset] = vertexOffset; + for (std::size_t i = 0, l = triangleCount * 3; i < l; ++i) { _intArray[meshOffset + (unsigned)BinaryOffset::MeshVertexIndices + i] = rawTriangles[i].GetUint(); } _floatArray.resize(_floatArray.size() + vertexCount * 2 + vertexCount * 2); - for (std::size_t i = 0, l = vertexCount * 2; i < l; ++i) - { + for (std::size_t i = 0, l = vertexCount * 2; i < l; ++i) { _floatArray[vertexOffset + i] = rawVertices[i].GetDouble(); - _floatArray[uvOffset + i] = rawUVs[i].GetDouble(); + _floatArray[uvOffset + i] = rawUVs[i].GetDouble(); } - if (rawData.HasMember(WEIGHTS)) - { - const auto& rawWeights = rawData[WEIGHTS]; - const auto& rawSlotPose = rawData[SLOT_POSE]; - const auto& rawBonePoses = rawData[BONE_POSE]; - const auto& sortedBones = _armature->sortedBones; + if (rawData.HasMember(WEIGHTS)) { + const auto & rawWeights = rawData[WEIGHTS]; + const auto & rawSlotPose = rawData[SLOT_POSE]; + const auto & rawBonePoses = rawData[BONE_POSE]; + const auto & sortedBones = _armature->sortedBones; std::vector weightBoneIndices; - const unsigned weightBoneCount = rawBonePoses.Size() / 7; - const auto floatOffset = _floatArray.size(); - const auto weightCount = (rawWeights.Size() - vertexCount) / 2; // uint - const auto weightOffset = _intArray.size(); - const auto weight = BaseObject::borrowObject(); + const unsigned weightBoneCount = rawBonePoses.Size() / 7; + const auto floatOffset = _floatArray.size(); + const auto weightCount = (rawWeights.Size() - vertexCount) / 2; // uint + const auto weightOffset = _intArray.size(); + const auto weight = BaseObject::borrowObject(); - weight->count = weightCount; + weight->count = weightCount; weight->offset = weightOffset; weightBoneIndices.resize(weightBoneCount); _intArray.resize(_intArray.size() + 1 + 1 + weightBoneCount + vertexCount + weightCount); _intArray[weightOffset + (unsigned)BinaryOffset::WeigthFloatOffset] = floatOffset; - for (std::size_t i = 0; i < weightBoneCount; ++i) - { + for (std::size_t i = 0; i < weightBoneCount; ++i) { const auto rawBoneIndex = rawBonePoses[i * 7].GetUint(); - const auto bone = _rawBones[rawBoneIndex]; + const auto bone = _rawBones[rawBoneIndex]; weight->addBone(bone); - weightBoneIndices[i] = rawBoneIndex; + weightBoneIndices[i] = rawBoneIndex; _intArray[weightOffset + (unsigned)BinaryOffset::WeigthBoneIndices + i] = indexOf(sortedBones, bone); } _floatArray.resize(_floatArray.size() + weightCount * 3); - _helpMatrixA.a = rawSlotPose[0].GetDouble(); - _helpMatrixA.b = rawSlotPose[1].GetDouble(); - _helpMatrixA.c = rawSlotPose[2].GetDouble(); - _helpMatrixA.d = rawSlotPose[3].GetDouble(); + _helpMatrixA.a = rawSlotPose[0].GetDouble(); + _helpMatrixA.b = rawSlotPose[1].GetDouble(); + _helpMatrixA.c = rawSlotPose[2].GetDouble(); + _helpMatrixA.d = rawSlotPose[3].GetDouble(); _helpMatrixA.tx = rawSlotPose[4].GetDouble(); _helpMatrixA.ty = rawSlotPose[5].GetDouble(); for ( std::size_t i = 0, iW = 0, iB = weightOffset + (unsigned)BinaryOffset::WeigthBoneIndices + weightBoneCount, iV = floatOffset; i < vertexCount; - ++i - ) - { - const auto iD = i * 2; + ++i) { + const auto iD = i * 2; const auto vertexBoneCount = rawWeights[iW++].GetUint(); - _intArray[iB++] = vertexBoneCount; + _intArray[iB++] = vertexBoneCount; auto x = _floatArray[vertexOffset + iD]; auto y = _floatArray[vertexOffset + iD + 1]; @@ -686,49 +591,43 @@ void JSONDataParser::_parseMesh(const rapidjson::Value& rawData, MeshDisplayData x = _helpPoint.x; y = _helpPoint.y; - for (std::size_t j = 0; j < vertexBoneCount; ++j) - { + for (std::size_t j = 0; j < vertexBoneCount; ++j) { const auto rawBoneIndex = rawWeights[iW++].GetUint(); - const auto boneIndex = indexOf(weightBoneIndices, rawBoneIndex); + const auto boneIndex = indexOf(weightBoneIndices, rawBoneIndex); const auto matrixOffset = boneIndex * 7 + 1; - _helpMatrixB.a = rawBonePoses[matrixOffset + 0].GetDouble(); - _helpMatrixB.b = rawBonePoses[matrixOffset + 1].GetDouble(); - _helpMatrixB.c = rawBonePoses[matrixOffset + 2].GetDouble(); - _helpMatrixB.d = rawBonePoses[matrixOffset + 3].GetDouble(); + _helpMatrixB.a = rawBonePoses[matrixOffset + 0].GetDouble(); + _helpMatrixB.b = rawBonePoses[matrixOffset + 1].GetDouble(); + _helpMatrixB.c = rawBonePoses[matrixOffset + 2].GetDouble(); + _helpMatrixB.d = rawBonePoses[matrixOffset + 3].GetDouble(); _helpMatrixB.tx = rawBonePoses[matrixOffset + 4].GetDouble(); _helpMatrixB.ty = rawBonePoses[matrixOffset + 5].GetDouble(); _helpMatrixB.invert(); _helpMatrixB.transformPoint(x, y, _helpPoint); - _intArray[iB++] = boneIndex; + _intArray[iB++] = boneIndex; _floatArray[iV++] = rawWeights[iW++].GetDouble(); _floatArray[iV++] = _helpPoint.x; _floatArray[iV++] = _helpPoint.y; } } - mesh.vertices.weight = weight; - _weightSlotPose[meshName] = &rawSlotPose; + mesh.vertices.weight = weight; + _weightSlotPose[meshName] = &rawSlotPose; _weightBonePoses[meshName] = &rawBonePoses; } } -BoundingBoxData* JSONDataParser::_parseBoundingBox(const rapidjson::Value& rawData) -{ - BoundingBoxData* boundingBox = nullptr; - BoundingBoxType type = BoundingBoxType::Rectangle; - if (rawData.HasMember(SUB_TYPE) && rawData[SUB_TYPE].IsString()) - { +BoundingBoxData *JSONDataParser::_parseBoundingBox(const rapidjson::Value &rawData) { + BoundingBoxData *boundingBox = nullptr; + BoundingBoxType type = BoundingBoxType::Rectangle; + if (rawData.HasMember(SUB_TYPE) && rawData[SUB_TYPE].IsString()) { type = _getBoundingBoxType(rawData[SUB_TYPE].GetString()); - } - else - { + } else { type = (BoundingBoxType)_getNumber(rawData, SUB_TYPE, (int)type); } - switch (type) - { + switch (type) { case BoundingBoxType::Rectangle: boundingBox = BaseObject::borrowObject(); break; @@ -742,12 +641,10 @@ BoundingBoxData* JSONDataParser::_parseBoundingBox(const rapidjson::Value& rawDa break; } - if (boundingBox != nullptr) - { + if (boundingBox != nullptr) { boundingBox->color = _getNumber(rawData, COLOR, 0x000000); - if (boundingBox->type == BoundingBoxType::Rectangle || boundingBox->type == BoundingBoxType::Ellipse) - { - boundingBox->width = _getNumber(rawData, WIDTH, 0.0f); + if (boundingBox->type == BoundingBoxType::Rectangle || boundingBox->type == BoundingBoxType::Ellipse) { + boundingBox->width = _getNumber(rawData, WIDTH, 0.0f); boundingBox->height = _getNumber(rawData, HEIGHT, 0.0f); } } @@ -755,49 +652,37 @@ BoundingBoxData* JSONDataParser::_parseBoundingBox(const rapidjson::Value& rawDa return boundingBox; } -PolygonBoundingBoxData* JSONDataParser::_parsePolygonBoundingBox(const rapidjson::Value& rawData) -{ +PolygonBoundingBoxData *JSONDataParser::_parsePolygonBoundingBox(const rapidjson::Value &rawData) { const auto polygonBoundingBox = BaseObject::borrowObject(); - if (rawData.HasMember(VERTICES)) - { - const auto& rawVertices = rawData[VERTICES]; - auto& vertices = polygonBoundingBox->vertices; + if (rawData.HasMember(VERTICES)) { + const auto &rawVertices = rawData[VERTICES]; + auto & vertices = polygonBoundingBox->vertices; polygonBoundingBox->vertices.resize(rawVertices.Size()); - for (std::size_t i = 0, l = rawVertices.Size(); i < l; i += 2) - { - const auto x = rawVertices[i].GetDouble(); - const auto y = rawVertices[i + 1].GetDouble(); - vertices[i] = x; + for (std::size_t i = 0, l = rawVertices.Size(); i < l; i += 2) { + const auto x = rawVertices[i].GetDouble(); + const auto y = rawVertices[i + 1].GetDouble(); + vertices[i] = x; vertices[i + 1] = y; // AABB. - if (i == 0) - { - polygonBoundingBox->x = x; - polygonBoundingBox->y = y; - polygonBoundingBox->width = x; + if (i == 0) { + polygonBoundingBox->x = x; + polygonBoundingBox->y = y; + polygonBoundingBox->width = x; polygonBoundingBox->height = y; - } - else - { - if (x < polygonBoundingBox->x) - { + } else { + if (x < polygonBoundingBox->x) { polygonBoundingBox->x = x; - } - else if (x > polygonBoundingBox->width) - { + } else if (x > polygonBoundingBox->width) { polygonBoundingBox->width = x; } - if (y < polygonBoundingBox->y) - { + if (y < polygonBoundingBox->y) { polygonBoundingBox->y = y; - } - else if (y > polygonBoundingBox->height) - { + } else if (y > polygonBoundingBox->height) { polygonBoundingBox->height = y; } } @@ -805,87 +690,72 @@ PolygonBoundingBoxData* JSONDataParser::_parsePolygonBoundingBox(const rapidjson polygonBoundingBox->width -= polygonBoundingBox->x; polygonBoundingBox->height -= polygonBoundingBox->y; - } - else - { + } else { DRAGONBONES_ASSERT(false, "Data error.\n Please reexport DragonBones Data to fixed the bug."); } return polygonBoundingBox; } -AnimationData* JSONDataParser::_parseAnimation(const rapidjson::Value& rawData) -{ - const auto animation = BaseObject::borrowObject(); +AnimationData *JSONDataParser::_parseAnimation(const rapidjson::Value &rawData) { + const auto animation = BaseObject::borrowObject(); animation->frameCount = std::max(_getNumber(rawData, DURATION, (unsigned)1), (unsigned)1); - animation->playTimes = _getNumber(rawData, PLAY_TIMES, (unsigned)1); - animation->duration = (float)animation->frameCount / _armature->frameRate; // float + animation->playTimes = _getNumber(rawData, PLAY_TIMES, (unsigned)1); + animation->duration = (float)animation->frameCount / _armature->frameRate; // float animation->fadeInTime = _getNumber(rawData, FADE_IN_TIME, 0.0f); - animation->scale = _getNumber(rawData, SCALE, 1.0f); - animation->name = _getString(rawData, NAME, DEFAULT_NAME); + animation->scale = _getNumber(rawData, SCALE, 1.0f); + animation->name = _getString(rawData, NAME, DEFAULT_NAME); - if (animation->name.empty()) - { + if (animation->name.empty()) { animation->name = DEFAULT_NAME; } - animation->frameIntOffset = _frameIntArray.size(); + animation->frameIntOffset = _frameIntArray.size(); animation->frameFloatOffset = _frameFloatArray.size(); - animation->frameOffset = _frameArray.size(); + animation->frameOffset = _frameArray.size(); _animation = animation; - if (rawData.HasMember(FRAME)) - { - const auto& rawFrames = rawData[FRAME]; - const auto keyFrameCount = rawFrames.Size(); - if (keyFrameCount > 0) - { - for (std::size_t i = 0, frameStart = 0; i < keyFrameCount; ++i) - { - const auto& rawFrame = rawFrames[i]; + if (rawData.HasMember(FRAME)) { + const auto &rawFrames = rawData[FRAME]; + const auto keyFrameCount = rawFrames.Size(); + if (keyFrameCount > 0) { + for (std::size_t i = 0, frameStart = 0; i < keyFrameCount; ++i) { + const auto &rawFrame = rawFrames[i]; _parseActionDataInFrame(rawFrame, frameStart, nullptr, nullptr); frameStart += _getNumber(rawFrame, DURATION, (unsigned)1); } } } - if (rawData.HasMember(Z_ORDER)) - { + if (rawData.HasMember(Z_ORDER)) { _animation->zOrderTimeline = _parseTimeline( rawData[Z_ORDER], FRAME, TimelineType::ZOrder, false, false, 0, - std::bind(&JSONDataParser::_parseZOrderFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3) - ); + std::bind(&JSONDataParser::_parseZOrderFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); } - if (rawData.HasMember(BONE)) - { - const auto& rawTimelines = rawData[BONE]; - for (std::size_t i = 0, l = rawTimelines.Size(); i < l; ++i) - { + if (rawData.HasMember(BONE)) { + const auto &rawTimelines = rawData[BONE]; + for (std::size_t i = 0, l = rawTimelines.Size(); i < l; ++i) { _parseBoneTimeline(rawTimelines[i]); } } - if (rawData.HasMember(SLOT)) - { - const auto& rawTimelines = rawData[SLOT]; - for (std::size_t i = 0, l = rawTimelines.Size(); i < l; ++i) - { + if (rawData.HasMember(SLOT)) { + const auto &rawTimelines = rawData[SLOT]; + for (std::size_t i = 0, l = rawTimelines.Size(); i < l; ++i) { _parseSlotTimeline(rawTimelines[i]); } } - if (rawData.HasMember(FFD)) - { - const auto& rawTimelines = rawData[FFD]; - for (std::size_t i = 0, l = rawTimelines.Size(); i < l; ++i) - { - const auto& rawTimeline = rawTimelines[i]; - auto skinName = _getString(rawTimeline, SKIN, DEFAULT_NAME); - const auto& slotName = _getString(rawTimeline, SLOT, ""); - const auto& displayName = _getString(rawTimeline, NAME, ""); + if (rawData.HasMember(FFD)) { + const auto &rawTimelines = rawData[FFD]; + for (std::size_t i = 0, l = rawTimelines.Size(); i < l; ++i) { + const auto &rawTimeline = rawTimelines[i]; + auto skinName = _getString(rawTimeline, SKIN, DEFAULT_NAME); + const auto &slotName = _getString(rawTimeline, SLOT, ""); + const auto &displayName = _getString(rawTimeline, NAME, ""); if (skinName.empty()) // { @@ -894,18 +764,15 @@ AnimationData* JSONDataParser::_parseAnimation(const rapidjson::Value& rawData) _slot = _armature->getSlot(slotName); _mesh = _armature->getMesh(skinName, slotName, displayName); - if (_slot == nullptr || _mesh == nullptr) - { + if (_slot == nullptr || _mesh == nullptr) { continue; } const auto timeline = _parseTimeline( - rawTimeline, FRAME, TimelineType::SlotDeform, - false, true, 0, - std::bind(&JSONDataParser::_parseSlotFFDFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3) - ); - if (timeline != nullptr) - { + rawTimeline, FRAME, TimelineType::SlotDeform, + false, true, 0, + std::bind(&JSONDataParser::_parseSlotFFDFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); + if (timeline != nullptr) { _animation->addSlotTimeline(_slot, timeline); } @@ -914,75 +781,62 @@ AnimationData* JSONDataParser::_parseAnimation(const rapidjson::Value& rawData) } } - if (rawData.HasMember(IK)) - { - const auto& rawTimelines = rawData[IK]; - for (std::size_t i = 0, l = rawTimelines.Size(); i < l; ++i) - { - const auto& rawTimeline = rawTimelines[i]; - const auto& constraintName = _getString(rawTimeline, NAME, ""); - const auto constraint = _armature->getConstraint(constraintName); - if (constraint == nullptr) - { + if (rawData.HasMember(IK)) { + const auto &rawTimelines = rawData[IK]; + for (std::size_t i = 0, l = rawTimelines.Size(); i < l; ++i) { + const auto &rawTimeline = rawTimelines[i]; + const auto &constraintName = _getString(rawTimeline, NAME, ""); + const auto constraint = _armature->getConstraint(constraintName); + if (constraint == nullptr) { continue; } const auto timeline = _parseTimeline( - rawTimeline, FRAME, TimelineType::IKConstraint, + rawTimeline, FRAME, TimelineType::IKConstraint, true, false, 2, - std::bind(&JSONDataParser::_parseIKConstraintFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3) - ); + std::bind(&JSONDataParser::_parseIKConstraintFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); - if (timeline != nullptr) - { + if (timeline != nullptr) { _animation->addConstraintTimeline(constraint, timeline); } } } - if (_actionFrames.size() > 0) - { + if (_actionFrames.size() > 0) { std::sort(_actionFrames.begin(), _actionFrames.end()); const auto timeline = _animation->actionTimeline = BaseObject::borrowObject(); - const auto keyFrameCount = _actionFrames.size(); - timeline->type = TimelineType::Action; - timeline->offset = _timelineArray.size(); + const auto keyFrameCount = _actionFrames.size(); + timeline->type = TimelineType::Action; + timeline->offset = _timelineArray.size(); _timelineArray.resize(_timelineArray.size() + 1 + 1 + 1 + 1 + 1 + keyFrameCount); - _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineScale] = 100; - _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineOffset] = 0; - _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineKeyFrameCount] = keyFrameCount; - _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueCount] = 0; + _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineScale] = 100; + _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineOffset] = 0; + _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineKeyFrameCount] = keyFrameCount; + _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueCount] = 0; _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueOffset] = 0; _timeline = timeline; - if (keyFrameCount == 1) - { - timeline->frameIndicesOffset = -1; + if (keyFrameCount == 1) { + timeline->frameIndicesOffset = -1; _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameOffset + 0] = _parseCacheActionFrame(_actionFrames[0]) - _animation->frameOffset; - } - else { - const auto totalFrameCount = _animation->frameCount + 1; // One more frame than animation. - auto& frameIndices = _data->frameIndices; + } else { + const auto totalFrameCount = _animation->frameCount + 1; // One more frame than animation. + auto & frameIndices = _data->frameIndices; timeline->frameIndicesOffset = frameIndices.size(); frameIndices.resize(frameIndices.size() + totalFrameCount); for ( std::size_t i = 0, iK = 0, frameStart = 0, frameCount = 0; i < totalFrameCount; - ++i - ) - { - if (frameStart + frameCount <= i && iK < keyFrameCount) - { - auto& frame = _actionFrames[iK]; - frameStart = frame.frameStart; - if (iK == keyFrameCount - 1) - { + ++i) { + if (frameStart + frameCount <= i && iK < keyFrameCount) { + auto &frame = _actionFrames[iK]; + frameStart = frame.frameStart; + if (iK == keyFrameCount - 1) { frameCount = _animation->frameCount - frameStart; - } - else { + } else { frameCount = _actionFrames[iK + 1].frameStart - frameStart; } @@ -1003,42 +857,33 @@ AnimationData* JSONDataParser::_parseAnimation(const rapidjson::Value& rawData) return animation; } -TimelineData* JSONDataParser::_parseTimeline( - const rapidjson::Value& rawData, const char* framesKey, TimelineType type, +TimelineData *JSONDataParser::_parseTimeline( + const rapidjson::Value &rawData, const char *framesKey, TimelineType type, bool addIntOffset, bool addFloatOffset, unsigned frameValueCount, - const std::function& frameParser -) -{ - if (!rawData.HasMember(framesKey)) - { + const std::function &frameParser) { + if (!rawData.HasMember(framesKey)) { return nullptr; } - const auto& rawFrames = rawData[framesKey]; - const auto keyFrameCount = rawFrames.Size(); - if (keyFrameCount == 0) - { + const auto &rawFrames = rawData[framesKey]; + const auto keyFrameCount = rawFrames.Size(); + if (keyFrameCount == 0) { return nullptr; } const auto timeline = BaseObject::borrowObject(); - timeline->type = type; - timeline->offset = _timelineArray.size(); + timeline->type = type; + timeline->offset = _timelineArray.size(); _timelineArray.resize(_timelineArray.size() + 1 + 1 + 1 + 1 + 1 + keyFrameCount); - _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineScale] = _getNumber(rawData, SCALE, 1.0f) * 100.f; - _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineOffset] = _getNumber(rawData, OFFSET, 0.0f) * 100.f; - _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineKeyFrameCount] = keyFrameCount; + _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineScale] = _getNumber(rawData, SCALE, 1.0f) * 100.f; + _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineOffset] = _getNumber(rawData, OFFSET, 0.0f) * 100.f; + _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineKeyFrameCount] = keyFrameCount; _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueCount] = frameValueCount; - if (addIntOffset) - { + if (addIntOffset) { _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueOffset] = _frameIntArray.size() - _animation->frameIntOffset; - } - else if (addFloatOffset) - { + } else if (addFloatOffset) { _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueOffset] = _frameFloatArray.size() - _animation->frameFloatOffset; - } - else - { + } else { _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueOffset] = 0; } @@ -1046,30 +891,25 @@ TimelineData* JSONDataParser::_parseTimeline( if (keyFrameCount == 1) // Only one frame. { - timeline->frameIndicesOffset = -1; + timeline->frameIndicesOffset = -1; _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameOffset + 0] = frameParser(rawFrames[0], 0, 0) - _animation->frameOffset; - } - else { - unsigned frameIndicesOffset = 0; - auto& frameIndices = _data->frameIndices; - const auto totalFrameCount = _animation->frameCount + 1; // One more frame than animation. - frameIndicesOffset = frameIndices.size(); + } else { + unsigned frameIndicesOffset = 0; + auto & frameIndices = _data->frameIndices; + const auto totalFrameCount = _animation->frameCount + 1; // One more frame than animation. + frameIndicesOffset = frameIndices.size(); frameIndices.resize(frameIndicesOffset + totalFrameCount); timeline->frameIndicesOffset = frameIndicesOffset; for ( std::size_t i = 0, iK = 0, frameStart = 0, frameCount = 0; i < totalFrameCount; - ++i - ) - { - if (frameStart + frameCount <= i && iK < keyFrameCount) - { - const auto& rawFrame = rawFrames[iK]; - frameStart = i; - frameCount = _getNumber(rawFrame, DURATION, (unsigned)1); - if (iK == keyFrameCount - 1) - { + ++i) { + if (frameStart + frameCount <= i && iK < keyFrameCount) { + const auto &rawFrame = rawFrames[iK]; + frameStart = i; + frameCount = _getNumber(rawFrame, DURATION, (unsigned)1); + if (iK == keyFrameCount - 1) { frameCount = _animation->frameCount - frameStart; } @@ -1086,65 +926,51 @@ TimelineData* JSONDataParser::_parseTimeline( return timeline; } -void JSONDataParser::_parseBoneTimeline(const rapidjson::Value& rawData) -{ +void JSONDataParser::_parseBoneTimeline(const rapidjson::Value &rawData) { const auto bone = _armature->getBone(_getString(rawData, NAME, "")); - if (bone == nullptr) - { + if (bone == nullptr) { return; } _bone = bone; _slot = _armature->getSlot(_bone->name); - if (rawData.HasMember(TRANSLATE_FRAME)) - { + if (rawData.HasMember(TRANSLATE_FRAME)) { const auto timeline = _parseTimeline( rawData, TRANSLATE_FRAME, TimelineType::BoneTranslate, false, true, 2, - std::bind(&JSONDataParser::_parseBoneTranslateFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3) - ); - if (timeline != nullptr) - { + std::bind(&JSONDataParser::_parseBoneTranslateFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); + if (timeline != nullptr) { _animation->addBoneTimeline(bone, timeline); } } - if (rawData.HasMember(ROTATE_FRAME)) - { + if (rawData.HasMember(ROTATE_FRAME)) { const auto timeline = _parseTimeline( rawData, ROTATE_FRAME, TimelineType::BoneRotate, false, true, 2, - std::bind(&JSONDataParser::_parseBoneRotateFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3) - ); - if (timeline != nullptr) - { + std::bind(&JSONDataParser::_parseBoneRotateFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); + if (timeline != nullptr) { _animation->addBoneTimeline(bone, timeline); } } - if (rawData.HasMember(SCALE_FRAME)) - { + if (rawData.HasMember(SCALE_FRAME)) { const auto timeline = _parseTimeline( rawData, SCALE_FRAME, TimelineType::BoneScale, false, true, 2, - std::bind(&JSONDataParser::_parseBoneScaleFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3) - ); - if (timeline != nullptr) - { + std::bind(&JSONDataParser::_parseBoneScaleFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); + if (timeline != nullptr) { _animation->addBoneTimeline(bone, timeline); } } - if (rawData.HasMember(FRAME)) - { + if (rawData.HasMember(FRAME)) { const auto timeline = _parseTimeline( rawData, FRAME, TimelineType::BoneAll, false, true, 6, - std::bind(&JSONDataParser::_parseBoneAllFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3) - ); - if (timeline != nullptr) - { + std::bind(&JSONDataParser::_parseBoneAllFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); + if (timeline != nullptr) { _animation->addBoneTimeline(bone, timeline); } } @@ -1153,67 +979,52 @@ void JSONDataParser::_parseBoneTimeline(const rapidjson::Value& rawData) _slot = nullptr; } -void JSONDataParser::_parseSlotTimeline(const rapidjson::Value& rawData) -{ +void JSONDataParser::_parseSlotTimeline(const rapidjson::Value &rawData) { const auto slot = _armature->getSlot(_getString(rawData, NAME, "")); - if (slot == nullptr) - { + if (slot == nullptr) { return; } - TimelineData* displayTimeline = nullptr; - TimelineData* colorTimeline = nullptr; - _slot = slot; + TimelineData *displayTimeline = nullptr; + TimelineData *colorTimeline = nullptr; + _slot = slot; - if (rawData.HasMember(DISPLAY_FRAME)) - { + if (rawData.HasMember(DISPLAY_FRAME)) { displayTimeline = _parseTimeline( rawData, DISPLAY_FRAME, TimelineType::SlotDisplay, false, false, 0, - std::bind(&JSONDataParser::_parseSlotDisplayFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3) - ); - } - else - { + std::bind(&JSONDataParser::_parseSlotDisplayFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); + } else { displayTimeline = _parseTimeline( rawData, FRAME, TimelineType::SlotDisplay, false, false, 0, - std::bind(&JSONDataParser::_parseSlotDisplayFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3) - ); + std::bind(&JSONDataParser::_parseSlotDisplayFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); } - if (rawData.HasMember(COLOR_FRAME)) - { + if (rawData.HasMember(COLOR_FRAME)) { colorTimeline = _parseTimeline( rawData, COLOR_FRAME, TimelineType::SlotColor, true, false, 1, - std::bind(&JSONDataParser::_parseSlotColorFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3) - ); - } - else - { + std::bind(&JSONDataParser::_parseSlotColorFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); + } else { colorTimeline = _parseTimeline( rawData, FRAME, TimelineType::SlotColor, true, false, 1, - std::bind(&JSONDataParser::_parseSlotColorFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3) - ); + std::bind(&JSONDataParser::_parseSlotColorFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); } - if (displayTimeline != nullptr) - { + if (displayTimeline != nullptr) { _animation->addSlotTimeline(slot, displayTimeline); } - if (colorTimeline != nullptr) - { + if (colorTimeline != nullptr) { _animation->addSlotTimeline(slot, colorTimeline); } _slot = nullptr; } -unsigned JSONDataParser::_parseFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount) -{ +unsigned JSONDataParser::_parseFrame(const rapidjson::Value &rawData, unsigned frameStart, unsigned frameCount) { const auto frameOffset = _frameArray.size(); _frameArray.resize(_frameArray.size() + 1); _frameArray[frameOffset + (unsigned)BinaryOffset::FramePosition] = frameStart; @@ -1221,66 +1032,48 @@ unsigned JSONDataParser::_parseFrame(const rapidjson::Value& rawData, unsigned f return frameOffset; } -unsigned JSONDataParser::_parseTweenFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount) -{ +unsigned JSONDataParser::_parseTweenFrame(const rapidjson::Value &rawData, unsigned frameStart, unsigned frameCount) { const auto frameOffset = _parseFrame(rawData, frameStart, frameCount); - if (frameCount > 0) - { - if (rawData.HasMember(CURVE)) - { + if (frameCount > 0) { + if (rawData.HasMember(CURVE)) { const auto sampleCount = frameCount + 1; _helpArray.resize(sampleCount); _samplingEasingCurve(rawData[CURVE], _helpArray); _frameArray.resize(_frameArray.size() + 1 + 1 + _helpArray.size()); - _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int)TweenType::Curve; + _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int)TweenType::Curve; _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenEasingOrCurveSampleCount] = sampleCount; - for (std::size_t i = 0; i < sampleCount; ++i) - { + for (std::size_t i = 0; i < sampleCount; ++i) { _frameArray[frameOffset + (unsigned)BinaryOffset::FrameCurveSamples + i] = _helpArray[i] * 10000.0f; } - } - else - { - const auto noTween = -2.0f; - auto tweenEasing = noTween; - if (rawData.HasMember(TWEEN_EASING)) - { + } else { + const auto noTween = -2.0f; + auto tweenEasing = noTween; + if (rawData.HasMember(TWEEN_EASING)) { tweenEasing = _getNumber(rawData, TWEEN_EASING, noTween); } - if (tweenEasing == noTween) - { + if (tweenEasing == noTween) { _frameArray.resize(_frameArray.size() + 1); _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::None; - } - else if (tweenEasing == 0.0f) - { + } else if (tweenEasing == 0.0f) { _frameArray.resize(_frameArray.size() + 1); _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::Line; - } - else if (tweenEasing < 0.0f) - { + } else if (tweenEasing < 0.0f) { _frameArray.resize(_frameArray.size() + 1 + 1); - _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::QuadIn; + _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::QuadIn; _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenEasingOrCurveSampleCount] = -tweenEasing * 100.0f; - } - else if (tweenEasing <= 1.0f) - { + } else if (tweenEasing <= 1.0f) { _frameArray.resize(_frameArray.size() + 1 + 1); - _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::QuadOut; + _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::QuadOut; _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenEasingOrCurveSampleCount] = tweenEasing * 100.0f; - } - else - { + } else { _frameArray.resize(_frameArray.size() + 1 + 1); - _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::QuadInOut; + _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::QuadInOut; _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenEasingOrCurveSampleCount] = tweenEasing * 100.0f - 100.0f; } } - } - else - { + } else { _frameArray.resize(_frameArray.size() + 1); _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::None; } @@ -1288,12 +1081,11 @@ unsigned JSONDataParser::_parseTweenFrame(const rapidjson::Value& rawData, unsig return frameOffset; } -unsigned JSONDataParser::_parseActionFrame(const ActionFrame& frame, unsigned frameStart, unsigned frameCount) -{ +unsigned JSONDataParser::_parseActionFrame(const ActionFrame &frame, unsigned frameStart, unsigned frameCount) { const auto frameOffset = _frameArray.size(); const auto actionCount = frame.actions.size(); _frameArray.resize(_frameArray.size() + 1 + 1 + actionCount); - _frameArray[frameOffset + (unsigned)BinaryOffset::FramePosition] = frameStart; + _frameArray[frameOffset + (unsigned)BinaryOffset::FramePosition] = frameStart; _frameArray[frameOffset + (unsigned)BinaryOffset::FramePosition + 1] = actionCount; // Action count. for (std::size_t i = 0; i < actionCount; ++i) // Action offsets. @@ -1304,55 +1096,46 @@ unsigned JSONDataParser::_parseActionFrame(const ActionFrame& frame, unsigned fr return frameOffset; } -unsigned JSONDataParser::_parseZOrderFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount) -{ +unsigned JSONDataParser::_parseZOrderFrame(const rapidjson::Value &rawData, unsigned frameStart, unsigned frameCount) { const auto frameOffset = _parseFrame(rawData, frameStart, frameCount); - if (rawData.HasMember(Z_ORDER)) - { - const auto& rawZOrder = rawData[Z_ORDER]; - if (!rawZOrder.Empty()) - { - const auto slotCount = _armature->sortedSlots.size(); + if (rawData.HasMember(Z_ORDER)) { + const auto &rawZOrder = rawData[Z_ORDER]; + if (!rawZOrder.Empty()) { + const auto slotCount = _armature->sortedSlots.size(); std::vector unchanged; std::vector zOrders; unchanged.resize(slotCount - rawZOrder.Size() / 2); zOrders.resize(slotCount); - for (std::size_t i = 0; i < unchanged.size(); ++i) - { + for (std::size_t i = 0; i < unchanged.size(); ++i) { unchanged[i] = 0; } - for (std::size_t i = 0; i < slotCount; ++i) - { + for (std::size_t i = 0; i < slotCount; ++i) { zOrders[i] = -1; } - unsigned originalIndex = 0; + unsigned originalIndex = 0; unsigned unchangedIndex = 0; - for (std::size_t i = 0, l = rawZOrder.Size(); i < l; i += 2) - { - const auto slotIndex = rawZOrder[i].GetInt(); + for (std::size_t i = 0, l = rawZOrder.Size(); i < l; i += 2) { + const auto slotIndex = rawZOrder[i].GetInt(); const auto zOrderOffset = rawZOrder[i + 1].GetInt(); - while (originalIndex != (unsigned)slotIndex) - { + while (originalIndex != (unsigned)slotIndex) { unchanged[unchangedIndex++] = originalIndex++; } - + unsigned index = originalIndex + zOrderOffset; // CCASSERT(index >= 0 && index < zOrders.size(), "DragonBones::JSONDataParser index is invalid"); - - if (!(index >= 0 && index < zOrders.size())) - { + + if (!(index >= 0 && index < zOrders.size())) { originalIndex++; continue; } zOrders[index] = originalIndex++; } - while (originalIndex < slotCount) - { + while (originalIndex < slotCount) { unchanged[unchangedIndex++] = originalIndex++; } @@ -1360,20 +1143,16 @@ unsigned JSONDataParser::_parseZOrderFrame(const rapidjson::Value& rawData, unsi _frameArray[frameOffset + 1] = slotCount; int i = slotCount; - while (i--) - { - if (zOrders[i] == -1) - { + while (i--) { + if (zOrders[i] == -1) { // _frameArray[frameOffset + 2 + i] = unchanged[--unchangedIndex]; - - if(unchangedIndex > 0) { + + if (unchangedIndex > 0) { _frameArray[frameOffset + 2 + i] = unchanged[--unchangedIndex]; - } - else { + } else { _frameArray[frameOffset + 2 + i] = 0; } - } - else { + } else { _frameArray[frameOffset + 2 + i] = zOrders[i]; } } @@ -1388,26 +1167,19 @@ unsigned JSONDataParser::_parseZOrderFrame(const rapidjson::Value& rawData, unsi return frameOffset; } -unsigned JSONDataParser::_parseBoneAllFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount) -{ +unsigned JSONDataParser::_parseBoneAllFrame(const rapidjson::Value &rawData, unsigned frameStart, unsigned frameCount) { _helpTransform.identity(); - if (rawData.HasMember(TRANSFORM)) - { + if (rawData.HasMember(TRANSFORM)) { _parseTransform(rawData[TRANSFORM], _helpTransform, 1.0f); } // Modify rotation. auto rotation = _helpTransform.rotation; - if (frameStart != 0) - { - if (_prevClockwise == 0) - { + if (frameStart != 0) { + if (_prevClockwise == 0) { rotation = _prevRotation + Transform::normalizeRadian(rotation - _prevRotation); - } - else - { - if (_prevClockwise > 0 ? rotation >= _prevRotation : rotation <= _prevRotation) - { + } else { + if (_prevClockwise > 0 ? rotation >= _prevRotation : rotation <= _prevRotation) { _prevClockwise = _prevClockwise > 0 ? _prevClockwise - 1 : _prevClockwise + 1; } @@ -1416,10 +1188,10 @@ unsigned JSONDataParser::_parseBoneAllFrame(const rapidjson::Value& rawData, uns } _prevClockwise = _getNumber(rawData, TWEEN_ROTATE, 0.0f); - _prevRotation = rotation; + _prevRotation = rotation; // - const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount); - auto frameFloatOffset = _frameFloatArray.size(); + const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount); + auto frameFloatOffset = _frameFloatArray.size(); _frameFloatArray.resize(_frameFloatArray.size() + 6); _frameFloatArray[frameFloatOffset++] = _helpTransform.x; _frameFloatArray[frameFloatOffset++] = _helpTransform.y; @@ -1432,10 +1204,9 @@ unsigned JSONDataParser::_parseBoneAllFrame(const rapidjson::Value& rawData, uns return frameOffset; } -unsigned JSONDataParser::_parseBoneTranslateFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount) -{ - const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount); - auto frameFloatOffset = _frameFloatArray.size(); +unsigned JSONDataParser::_parseBoneTranslateFrame(const rapidjson::Value &rawData, unsigned frameStart, unsigned frameCount) { + const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount); + auto frameFloatOffset = _frameFloatArray.size(); _frameFloatArray.resize(_frameFloatArray.size() + 2); _frameFloatArray[frameFloatOffset++] = _getNumber(rawData, X, 0.0f); _frameFloatArray[frameFloatOffset++] = _getNumber(rawData, Y, 0.0f); @@ -1443,20 +1214,14 @@ unsigned JSONDataParser::_parseBoneTranslateFrame(const rapidjson::Value& rawDat return frameOffset; } -unsigned JSONDataParser::_parseBoneRotateFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount) -{ +unsigned JSONDataParser::_parseBoneRotateFrame(const rapidjson::Value &rawData, unsigned frameStart, unsigned frameCount) { // Modify rotation. auto rotation = _getNumber(rawData, ROTATE, 0.0f) * Transform::DEG_RAD; - if (frameStart != 0) - { - if (_prevClockwise == 0) - { + if (frameStart != 0) { + if (_prevClockwise == 0) { rotation = _prevRotation + Transform::normalizeRadian(rotation - _prevRotation); - } - else - { - if (_prevClockwise > 0 ? rotation >= _prevRotation : rotation <= _prevRotation) - { + } else { + if (_prevClockwise > 0 ? rotation >= _prevRotation : rotation <= _prevRotation) { _prevClockwise = _prevClockwise > 0 ? _prevClockwise - 1 : _prevClockwise + 1; } @@ -1465,10 +1230,10 @@ unsigned JSONDataParser::_parseBoneRotateFrame(const rapidjson::Value& rawData, } _prevClockwise = _getNumber(rawData, CLOCK_WISE, 0.0f); - _prevRotation = rotation; + _prevRotation = rotation; // - const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount); - auto frameFloatOffset = _frameFloatArray.size(); + const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount); + auto frameFloatOffset = _frameFloatArray.size(); _frameFloatArray.resize(_frameFloatArray.size() + 2); _frameFloatArray[frameFloatOffset++] = rotation; _frameFloatArray[frameFloatOffset++] = _getNumber(rawData, SKEW, 0.0f) * Transform::DEG_RAD; @@ -1476,8 +1241,7 @@ unsigned JSONDataParser::_parseBoneRotateFrame(const rapidjson::Value& rawData, return frameOffset; } -unsigned JSONDataParser::_parseBoneScaleFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount) -{ +unsigned JSONDataParser::_parseBoneScaleFrame(const rapidjson::Value &rawData, unsigned frameStart, unsigned frameCount) { const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount); auto frameFloatOffset = _frameFloatArray.size(); @@ -1488,18 +1252,14 @@ unsigned JSONDataParser::_parseBoneScaleFrame(const rapidjson::Value& rawData, u return frameOffset; } -unsigned JSONDataParser::_parseSlotDisplayFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount) -{ +unsigned JSONDataParser::_parseSlotDisplayFrame(const rapidjson::Value &rawData, unsigned frameStart, unsigned frameCount) { const auto frameOffset = _parseFrame(rawData, frameStart, frameCount); _frameArray.resize(_frameArray.size() + 1); - if (rawData.HasMember(VALUE)) - { + if (rawData.HasMember(VALUE)) { _frameArray[frameOffset + 1] = _getNumber(rawData, VALUE, 0); - } - else - { + } else { _frameArray[frameOffset + 1] = _getNumber(rawData, DISPLAY_INDEX, 0); } @@ -1508,14 +1268,12 @@ unsigned JSONDataParser::_parseSlotDisplayFrame(const rapidjson::Value& rawData, return frameOffset; } -unsigned JSONDataParser::_parseSlotColorFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount) -{ +unsigned JSONDataParser::_parseSlotColorFrame(const rapidjson::Value &rawData, unsigned frameStart, unsigned frameCount) { const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount); - auto colorOffset = -1; + auto colorOffset = -1; - if (rawData.HasMember(VALUE) || rawData.HasMember(COLOR)) - { - const auto& rawColor = rawData.HasMember(VALUE) ? rawData[VALUE] : rawData[COLOR]; + if (rawData.HasMember(VALUE) || rawData.HasMember(COLOR)) { + const auto &rawColor = rawData.HasMember(VALUE) ? rawData[VALUE] : rawData[COLOR]; if ( rawColor.HasMember(ALPHA_MULTIPLIER) || rawColor.HasMember(RED_MULTIPLIER) || @@ -1524,9 +1282,7 @@ unsigned JSONDataParser::_parseSlotColorFrame(const rapidjson::Value& rawData, u rawColor.HasMember(ALPHA_OFFSET) || rawColor.HasMember(RED_OFFSET) || rawColor.HasMember(GREEN_OFFSET) || - rawColor.HasMember(BLUE_OFFSET) - ) - { + rawColor.HasMember(BLUE_OFFSET)) { _parseColorTransform(rawColor, _helpColorTransform); colorOffset = _intArray.size(); _intArray.resize(_intArray.size() + 8); @@ -1542,10 +1298,8 @@ unsigned JSONDataParser::_parseSlotColorFrame(const rapidjson::Value& rawData, u } } - if (colorOffset < 0) - { - if (_defaultColorOffset < 0) - { + if (colorOffset < 0) { + if (_defaultColorOffset < 0) { _defaultColorOffset = colorOffset = _intArray.size(); _intArray.resize(_intArray.size() + 8); _intArray[colorOffset++] = 100; @@ -1568,86 +1322,73 @@ unsigned JSONDataParser::_parseSlotColorFrame(const rapidjson::Value& rawData, u return frameOffset; } -unsigned JSONDataParser::_parseSlotFFDFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount) -{ +unsigned JSONDataParser::_parseSlotFFDFrame(const rapidjson::Value &rawData, unsigned frameStart, unsigned frameCount) { const auto frameFloatOffset = _frameFloatArray.size(); - const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount); - const auto offset = _getNumber(rawData, OFFSET, (unsigned)0); - const auto vertexCount = (unsigned)_intArray[_mesh->vertices.offset + (unsigned)BinaryOffset::MeshVertexCount]; - const auto meshName = _mesh->parent->name + "_" + _slot->name + "_" + _mesh->name; - const auto weight = _mesh->vertices.weight; + const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount); + const auto offset = _getNumber(rawData, OFFSET, (unsigned)0); + const auto vertexCount = (unsigned)_intArray[_mesh->vertices.offset + (unsigned)BinaryOffset::MeshVertexCount]; + const auto meshName = _mesh->parent->name + "_" + _slot->name + "_" + _mesh->name; + const auto weight = _mesh->vertices.weight; - auto x = 0.0f; - auto y = 0.0f; + auto x = 0.0f; + auto y = 0.0f; unsigned iB = 0; unsigned iV = 0; - if (weight != nullptr) - { - const auto& rawSlotPose = *(_weightSlotPose[meshName]); + if (weight != nullptr) { + const auto &rawSlotPose = *(_weightSlotPose[meshName]); - _helpMatrixA.a = rawSlotPose[0].GetDouble(); - _helpMatrixA.b = rawSlotPose[1].GetDouble(); - _helpMatrixA.c = rawSlotPose[2].GetDouble(); - _helpMatrixA.d = rawSlotPose[3].GetDouble(); + _helpMatrixA.a = rawSlotPose[0].GetDouble(); + _helpMatrixA.b = rawSlotPose[1].GetDouble(); + _helpMatrixA.c = rawSlotPose[2].GetDouble(); + _helpMatrixA.d = rawSlotPose[3].GetDouble(); _helpMatrixA.tx = rawSlotPose[4].GetDouble(); _helpMatrixA.ty = rawSlotPose[5].GetDouble(); _frameFloatArray.resize(_frameFloatArray.size() + weight->count * 2); iB = weight->offset + (unsigned)BinaryOffset::WeigthBoneIndices + weight->bones.size(); - } - else - { + } else { _frameFloatArray.resize(_frameFloatArray.size() + vertexCount * 2); } for ( std::size_t i = 0; i < vertexCount * 2; - i += 2 - ) - { + i += 2) { if (!rawData.HasMember(VERTICES)) // Fill 0. { x = 0.0f; y = 0.0f; - } - else - { + } else { if (i < offset || i - offset >= rawData[VERTICES].Size()) { x = 0.0f; - } - else - { + } else { x = rawData[VERTICES][i - offset].GetDouble(); } if (i + 1 < offset || i + 1 - offset >= rawData[VERTICES].Size()) { y = 0.0f; - } - else - { + } else { y = rawData[VERTICES][i + 1 - offset].GetDouble(); } } if (weight != nullptr) // If mesh is skinned, transform point by bone bind pose. { - const auto& rawBonePoses = *(_weightBonePoses[meshName]); + const auto & rawBonePoses = *(_weightBonePoses[meshName]); const unsigned vertexBoneCount = _intArray[iB++]; _helpMatrixA.transformPoint(x, y, _helpPoint, true); x = _helpPoint.x; y = _helpPoint.y; - for (std::size_t j = 0; j < vertexBoneCount; ++j) - { - const auto boneIndex = _intArray[iB++]; + for (std::size_t j = 0; j < vertexBoneCount; ++j) { + const auto boneIndex = _intArray[iB++]; const auto matrixOffset = boneIndex * 7 + 1; - _helpMatrixB.a = rawBonePoses[matrixOffset + 0].GetDouble(); - _helpMatrixB.b = rawBonePoses[matrixOffset + 1].GetDouble(); - _helpMatrixB.c = rawBonePoses[matrixOffset + 2].GetDouble(); - _helpMatrixB.d = rawBonePoses[matrixOffset + 3].GetDouble(); + _helpMatrixB.a = rawBonePoses[matrixOffset + 0].GetDouble(); + _helpMatrixB.b = rawBonePoses[matrixOffset + 1].GetDouble(); + _helpMatrixB.c = rawBonePoses[matrixOffset + 2].GetDouble(); + _helpMatrixB.d = rawBonePoses[matrixOffset + 3].GetDouble(); _helpMatrixB.tx = rawBonePoses[matrixOffset + 4].GetDouble(); _helpMatrixB.ty = rawBonePoses[matrixOffset + 5].GetDouble(); _helpMatrixB.invert(); @@ -1656,31 +1397,27 @@ unsigned JSONDataParser::_parseSlotFFDFrame(const rapidjson::Value& rawData, uns _frameFloatArray[frameFloatOffset + iV++] = _helpPoint.x; _frameFloatArray[frameFloatOffset + iV++] = _helpPoint.y; } - } - else - { - _frameFloatArray[frameFloatOffset + i] = x; + } else { + _frameFloatArray[frameFloatOffset + i] = x; _frameFloatArray[frameFloatOffset + i + 1] = y; } } - if (frameStart == 0) - { + if (frameStart == 0) { const auto frameIntOffset = _frameIntArray.size(); _frameIntArray.resize(_frameIntArray.size() + 1 + 1 + 1 + 1 + 1); - _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformVertexOffset] = _mesh->vertices.offset; - _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformCount] = _frameFloatArray.size() - frameFloatOffset; - _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformValueCount] = _frameFloatArray.size() - frameFloatOffset; - _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformValueOffset] = 0; - _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformFloatOffset] = frameFloatOffset; + _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformVertexOffset] = _mesh->vertices.offset; + _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformCount] = _frameFloatArray.size() - frameFloatOffset; + _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformValueCount] = _frameFloatArray.size() - frameFloatOffset; + _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformValueOffset] = 0; + _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformFloatOffset] = frameFloatOffset; _timelineArray[_timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueCount] = frameIntOffset - _animation->frameIntOffset; } return frameOffset; } -unsigned JSONDataParser::_parseIKConstraintFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount) -{ +unsigned JSONDataParser::_parseIKConstraintFrame(const rapidjson::Value &rawData, unsigned frameStart, unsigned frameCount) { const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount); auto frameIntOffset = _frameIntArray.size(); @@ -1691,103 +1428,78 @@ unsigned JSONDataParser::_parseIKConstraintFrame(const rapidjson::Value& rawData return frameOffset; } -const std::vector& JSONDataParser::_parseActionData(const rapidjson::Value& rawData, ActionType type, BoneData* bone, SlotData* slot) -{ - static std::vector actions; +const std::vector &JSONDataParser::_parseActionData(const rapidjson::Value &rawData, ActionType type, BoneData *bone, SlotData *slot) { + static std::vector actions; actions.clear(); - if (rawData.IsString()) - { + if (rawData.IsString()) { const auto action = BaseObject::borrowObject(); - action->type = type; - action->name = rawData.GetString(); - action->bone = bone; - action->slot = slot; + action->type = type; + action->name = rawData.GetString(); + action->bone = bone; + action->slot = slot; actions.push_back(action); - } - else if (rawData.IsArray()) - { - for (std::size_t iA = 0, lA = rawData.Size(); iA < lA; ++iA) - { - const auto& rawAction = rawData[iA]; - const auto action = BaseObject::borrowObject(); + } else if (rawData.IsArray()) { + for (std::size_t iA = 0, lA = rawData.Size(); iA < lA; ++iA) { + const auto &rawAction = rawData[iA]; + const auto action = BaseObject::borrowObject(); - if (rawAction.HasMember(GOTO_AND_PLAY)) - { + if (rawAction.HasMember(GOTO_AND_PLAY)) { action->type = ActionType::Play; action->name = _getString(rawAction, GOTO_AND_PLAY, ""); - } - else - { - if (rawAction.HasMember(TYPE) && rawAction[TYPE].IsString()) - { + } else { + if (rawAction.HasMember(TYPE) && rawAction[TYPE].IsString()) { action->type = _getActionType(rawAction[TYPE].GetString()); - } - else - { + } else { action->type = (ActionType)_getNumber(rawAction, TYPE, (int)type); } action->name = _getString(rawAction, NAME, ""); } - if (rawAction.HasMember(BONE)) - { - const auto& boneName = _getString(rawAction, BONE, ""); - action->bone = _armature->getBone(boneName); - } - else { + if (rawAction.HasMember(BONE)) { + const auto &boneName = _getString(rawAction, BONE, ""); + action->bone = _armature->getBone(boneName); + } else { action->bone = bone; } - if (rawAction.HasMember(SLOT)) - { - const auto& slotName = _getString(rawAction, SLOT, ""); - action->slot = _armature->getSlot(slotName); - } - else - { + if (rawAction.HasMember(SLOT)) { + const auto &slotName = _getString(rawAction, SLOT, ""); + action->slot = _armature->getSlot(slotName); + } else { action->slot = slot; } - if (rawAction.HasMember(INTS)) - { - if (action->data == nullptr) - { + if (rawAction.HasMember(INTS)) { + if (action->data == nullptr) { action->data = BaseObject::borrowObject(); } - const auto& rawInts = rawAction[INTS]; - for (std::size_t i = 0, l = rawInts.Size(); i < l; ++i) - { + const auto &rawInts = rawAction[INTS]; + for (std::size_t i = 0, l = rawInts.Size(); i < l; ++i) { action->data->addInt(rawInts[i].GetInt()); } } - if (rawAction.HasMember(FLOATS)) - { - if (action->data == nullptr) - { + if (rawAction.HasMember(FLOATS)) { + if (action->data == nullptr) { action->data = BaseObject::borrowObject(); } - const auto& rawFloats = rawAction[FLOATS]; - for (std::size_t i = 0, l = rawFloats.Size(); i < l; ++i) - { + const auto &rawFloats = rawAction[FLOATS]; + for (std::size_t i = 0, l = rawFloats.Size(); i < l; ++i) { action->data->addFloat(rawFloats[i].GetDouble()); } } - if (rawAction.HasMember(STRINGS)) - { - if (action->data == nullptr) - { + if (rawAction.HasMember(STRINGS)) { + if (action->data == nullptr) { action->data = BaseObject::borrowObject(); } - const auto& rawStrings = rawAction[STRINGS]; - for (std::size_t i = 0, l = rawStrings.Size(); i < l; ++i) - { + const auto &rawStrings = rawAction[STRINGS]; + for (std::size_t i = 0, l = rawStrings.Size(); i < l; ++i) { action->data->addString(rawStrings[i].GetString()); } } @@ -1799,40 +1511,34 @@ const std::vector& JSONDataParser::_parseActionData(const rapidjson return actions; } -void JSONDataParser::_parseTransform(const rapidjson::Value& rawData, Transform& transform, float scale) -{ +void JSONDataParser::_parseTransform(const rapidjson::Value &rawData, Transform &transform, float scale) { transform.x = _getNumber(rawData, X, 0.0f) * scale; transform.y = _getNumber(rawData, Y, 0.0f) * scale; - if (rawData.HasMember(ROTATE) || rawData.HasMember(SKEW)) - { + if (rawData.HasMember(ROTATE) || rawData.HasMember(SKEW)) { transform.rotation = Transform::normalizeRadian(_getNumber(rawData, ROTATE, 0.0f) * Transform::DEG_RAD); - transform.skew = Transform::normalizeRadian(_getNumber(rawData, SKEW, 0.0f) * Transform::DEG_RAD); - } - else if (rawData.HasMember(SKEW_X) || rawData.HasMember(SKEW_Y)) - { + transform.skew = Transform::normalizeRadian(_getNumber(rawData, SKEW, 0.0f) * Transform::DEG_RAD); + } else if (rawData.HasMember(SKEW_X) || rawData.HasMember(SKEW_Y)) { transform.rotation = Transform::normalizeRadian(_getNumber(rawData, SKEW_Y, 0.0f) * Transform::DEG_RAD); - transform.skew = Transform::normalizeRadian(_getNumber(rawData, SKEW_X, 0.0f) * Transform::DEG_RAD) - transform.rotation; + transform.skew = Transform::normalizeRadian(_getNumber(rawData, SKEW_X, 0.0f) * Transform::DEG_RAD) - transform.rotation; } transform.scaleX = _getNumber(rawData, SCALE_X, 1.0f); transform.scaleY = _getNumber(rawData, SCALE_Y, 1.0f); } -void JSONDataParser::_parseColorTransform(const rapidjson::Value& rawData, ColorTransform& color) -{ +void JSONDataParser::_parseColorTransform(const rapidjson::Value &rawData, ColorTransform &color) { color.alphaMultiplier = _getNumber(rawData, ALPHA_MULTIPLIER, (int)100) * 0.01f; - color.redMultiplier = _getNumber(rawData, RED_MULTIPLIER, (int)100) * 0.01f; + color.redMultiplier = _getNumber(rawData, RED_MULTIPLIER, (int)100) * 0.01f; color.greenMultiplier = _getNumber(rawData, GREEN_MULTIPLIER, (int)100) * 0.01f; - color.blueMultiplier = _getNumber(rawData, BLUE_MULTIPLIER, (int)100) * 0.01f; - color.alphaOffset = _getNumber(rawData, ALPHA_OFFSET, (int)0); - color.redOffset = _getNumber(rawData, RED_OFFSET, (int)0); - color.greenOffset = _getNumber(rawData, GREEN_OFFSET, (int)0); - color.blueOffset = _getNumber(rawData, BLUE_OFFSET, (int)0); + color.blueMultiplier = _getNumber(rawData, BLUE_MULTIPLIER, (int)100) * 0.01f; + color.alphaOffset = _getNumber(rawData, ALPHA_OFFSET, (int)0); + color.redOffset = _getNumber(rawData, RED_OFFSET, (int)0); + color.greenOffset = _getNumber(rawData, GREEN_OFFSET, (int)0); + color.blueOffset = _getNumber(rawData, BLUE_OFFSET, (int)0); } -void JSONDataParser::_parseArray(const rapidjson::Value& rawData) -{ +void JSONDataParser::_parseArray(const rapidjson::Value &rawData) { _intArray.clear(); _floatArray.clear(); _frameIntArray.clear(); @@ -1841,19 +1547,16 @@ void JSONDataParser::_parseArray(const rapidjson::Value& rawData) _timelineArray.clear(); } -DragonBonesData* JSONDataParser::_parseDragonBonesData(const rapidjson::Value& rawData, float scale) -{ - const auto& version = _getString(rawData, VERSION, ""); - const auto& compatibleVersion = _getString(rawData, COMPATIBLE_VERSION, ""); +DragonBonesData *JSONDataParser::_parseDragonBonesData(const rapidjson::Value &rawData, float scale) { + const auto &version = _getString(rawData, VERSION, ""); + const auto &compatibleVersion = _getString(rawData, COMPATIBLE_VERSION, ""); if ( indexOf(DATA_VERSIONS, version) >= 0 || - indexOf(DATA_VERSIONS, compatibleVersion) >= 0 - ) - { + indexOf(DATA_VERSIONS, compatibleVersion) >= 0) { const auto data = BaseObject::borrowObject(); - data->version = version; - data->name = _getString(rawData, NAME, ""); + data->version = version; + data->name = _getString(rawData, NAME, ""); data->frameRate = _getNumber(rawData, FRAME_RATE, 24); if (data->frameRate == 0) // Data error. @@ -1861,37 +1564,30 @@ DragonBonesData* JSONDataParser::_parseDragonBonesData(const rapidjson::Value& r data->frameRate = 24; } - if (rawData.HasMember(ARMATURE)) - { + if (rawData.HasMember(ARMATURE)) { _data = data; _parseArray(rawData); - const auto& rawArmatures = rawData[ARMATURE]; - for (std::size_t i = 0, l = rawArmatures.Size(); i < l; ++i) - { + const auto &rawArmatures = rawData[ARMATURE]; + for (std::size_t i = 0, l = rawArmatures.Size(); i < l; ++i) { data->addArmature(_parseArmature(rawArmatures[i], scale)); } - if (data->binary == nullptr) - { + if (data->binary == nullptr) { // Align. - if (fmod(_intArray.size(), 2) != 0) - { + if (fmod(_intArray.size(), 2) != 0) { _intArray.push_back(0); } - if (fmod(_frameIntArray.size(), 2) != 0) - { + if (fmod(_frameIntArray.size(), 2) != 0) { _frameIntArray.push_back(0); } - if (fmod(_frameArray.size(), 2) != 0) - { + if (fmod(_frameArray.size(), 2) != 0) { _frameArray.push_back(0); } - if (fmod(_timelineArray.size(), 2) != 0) - { + if (fmod(_timelineArray.size(), 2) != 0) { _timelineArray.push_back(0); } @@ -1901,109 +1597,95 @@ DragonBonesData* JSONDataParser::_parseDragonBonesData(const rapidjson::Value& r const auto l4 = _frameFloatArray.size() * 4; const auto l5 = _frameArray.size() * 2; const auto l6 = _timelineArray.size() * 2; - - auto binary = new char[l1 + l2 + l3 + l4 + l5 + l6]; - auto intArray = (int16_t*)binary; - auto floatArray = (float*)(binary + l1); - auto frameIntArray = (int16_t*)(binary + l1 + l2); - auto frameFloatArray = (float*)(binary + l1 + l2 + l3); - auto frameArray = (int16_t*)(binary + l1 + l2 + l3 + l4); - auto timelineArray = (uint16_t*)(binary + l1 + l2 + l3 + l4 + l5); - for (std::size_t i = 0, l = _intArray.size(); i < l; ++i) - { + auto binary = new char[l1 + l2 + l3 + l4 + l5 + l6]; + auto intArray = (int16_t *)binary; + auto floatArray = (float *)(binary + l1); + auto frameIntArray = (int16_t *)(binary + l1 + l2); + auto frameFloatArray = (float *)(binary + l1 + l2 + l3); + auto frameArray = (int16_t *)(binary + l1 + l2 + l3 + l4); + auto timelineArray = (uint16_t *)(binary + l1 + l2 + l3 + l4 + l5); + + for (std::size_t i = 0, l = _intArray.size(); i < l; ++i) { intArray[i] = _intArray[i]; } - for (std::size_t i = 0, l = _floatArray.size(); i < l; ++i) - { + for (std::size_t i = 0, l = _floatArray.size(); i < l; ++i) { floatArray[i] = _floatArray[i]; } - for (std::size_t i = 0, l = _frameIntArray.size(); i < l; ++i) - { + for (std::size_t i = 0, l = _frameIntArray.size(); i < l; ++i) { frameIntArray[i] = _frameIntArray[i]; } - for (std::size_t i = 0, l = _frameFloatArray.size(); i < l; ++i) - { + for (std::size_t i = 0, l = _frameFloatArray.size(); i < l; ++i) { frameFloatArray[i] = _frameFloatArray[i]; } - for (std::size_t i = 0, l = _frameArray.size(); i < l; ++i) - { + for (std::size_t i = 0, l = _frameArray.size(); i < l; ++i) { frameArray[i] = _frameArray[i]; } - for (std::size_t i = 0, l = _timelineArray.size(); i < l; ++i) - { + for (std::size_t i = 0, l = _timelineArray.size(); i < l; ++i) { timelineArray[i] = _timelineArray[i]; } - data->binary = binary; - data->intArray = intArray; - data->floatArray = floatArray; - data->frameIntArray = frameIntArray; + data->binary = binary; + data->intArray = intArray; + data->floatArray = floatArray; + data->frameIntArray = frameIntArray; data->frameFloatArray = frameFloatArray; - data->frameArray = frameArray; - data->timelineArray = timelineArray; + data->frameArray = frameArray; + data->timelineArray = timelineArray; } _defaultColorOffset = -1; - _data = nullptr; + _data = nullptr; } - if (rawData.HasMember(TEXTURE_ATLAS)) - { - _rawTextureAtlases = (rapidjson::Value*)&(rawData[TEXTURE_ATLAS]); + if (rawData.HasMember(TEXTURE_ATLAS)) { + _rawTextureAtlases = (rapidjson::Value *)&(rawData[TEXTURE_ATLAS]); } return data; - } - else - { + } else { DRAGONBONES_ASSERT( false, "Nonsupport data version: " + version + "\n" + - "Please convert DragonBones data to support version.\n" + - "Read more: https://github.com/DragonBones/Tools/" - ); + "Please convert DragonBones data to support version.\n" + + "Read more: https://github.com/DragonBones/Tools/"); } return nullptr; } -void JSONDataParser::_parseTextureAtlasData(const rapidjson::Value& rawData, TextureAtlasData& textureAtlasData, float scale) -{ - textureAtlasData.format = _getTextureFormat(_getString(rawData, FORMAT, "")); - textureAtlasData.width = _getNumber(rawData, WIDTH, (unsigned)0); - textureAtlasData.height = _getNumber(rawData, HEIGHT, (unsigned)0); - textureAtlasData.scale = scale == 1.0f ? 1.0f / _getNumber(rawData, SCALE, 1.0f) : scale; - textureAtlasData.name = _getString(rawData, NAME, ""); +void JSONDataParser::_parseTextureAtlasData(const rapidjson::Value &rawData, TextureAtlasData &textureAtlasData, float scale) { + textureAtlasData.format = _getTextureFormat(_getString(rawData, FORMAT, "")); + textureAtlasData.width = _getNumber(rawData, WIDTH, (unsigned)0); + textureAtlasData.height = _getNumber(rawData, HEIGHT, (unsigned)0); + textureAtlasData.scale = scale == 1.0f ? 1.0f / _getNumber(rawData, SCALE, 1.0f) : scale; + textureAtlasData.name = _getString(rawData, NAME, ""); textureAtlasData.imagePath = _getString(rawData, IMAGE_PATH, ""); - if (rawData.HasMember(SUB_TEXTURE)) - { - const auto& rawTextures = rawData[SUB_TEXTURE]; - for (std::size_t i = 0, l = rawTextures.Size(); i < l; ++i) - { - const auto& rawTexture = rawTextures[i]; - const auto textureData = textureAtlasData.createTexture(); - textureData->rotated = _getBoolean(rawTexture, ROTATED, false); - textureData->name = _getString(rawTexture, NAME, ""); - textureData->region.x = _getNumber(rawTexture, X, 0.0f); - textureData->region.y = _getNumber(rawTexture, Y, 0.0f); - textureData->region.width = _getNumber(rawTexture, WIDTH, 0.0f); + if (rawData.HasMember(SUB_TEXTURE)) { + const auto &rawTextures = rawData[SUB_TEXTURE]; + for (std::size_t i = 0, l = rawTextures.Size(); i < l; ++i) { + const auto &rawTexture = rawTextures[i]; + const auto textureData = textureAtlasData.createTexture(); + textureData->rotated = _getBoolean(rawTexture, ROTATED, false); + textureData->name = _getString(rawTexture, NAME, ""); + textureData->region.x = _getNumber(rawTexture, X, 0.0f); + textureData->region.y = _getNumber(rawTexture, Y, 0.0f); + textureData->region.width = _getNumber(rawTexture, WIDTH, 0.0f); textureData->region.height = _getNumber(rawTexture, HEIGHT, 0.0f); - const auto frameWidth = _getNumber(rawTexture, FRAME_WIDTH, -1.0f); + const auto frameWidth = _getNumber(rawTexture, FRAME_WIDTH, -1.0f); const auto frameHeight = _getNumber(rawTexture, FRAME_HEIGHT, -1.0f); - if (frameWidth > 0.0f && frameHeight > 0.0f) - { - textureData->frame = TextureData::createRectangle(); - textureData->frame->x = _getNumber(rawTexture, FRAME_X, 0.0f); - textureData->frame->y = _getNumber(rawTexture, FRAME_Y, 0.0f); - textureData->frame->width = frameWidth; + if (frameWidth > 0.0f && frameHeight > 0.0f) { + textureData->frame = TextureData::createRectangle(); + textureData->frame->x = _getNumber(rawTexture, FRAME_X, 0.0f); + textureData->frame->y = _getNumber(rawTexture, FRAME_Y, 0.0f); + textureData->frame->width = frameWidth; textureData->frame->height = frameHeight; } @@ -2012,8 +1694,7 @@ void JSONDataParser::_parseTextureAtlasData(const rapidjson::Value& rawData, Tex } } -DragonBonesData* JSONDataParser::parseDragonBonesData(const char* rawData, float scale) -{ +DragonBonesData *JSONDataParser::parseDragonBonesData(const char *rawData, float scale) { DRAGONBONES_ASSERT(rawData != nullptr, ""); rapidjson::Document document; @@ -2022,21 +1703,17 @@ DragonBonesData* JSONDataParser::parseDragonBonesData(const char* rawData, float return _parseDragonBonesData(document, scale); } -bool JSONDataParser::parseTextureAtlasData(const char* rawData, TextureAtlasData& textureAtlasData, float scale) -{ - if (rawData == nullptr) - { - if (_rawTextureAtlases == nullptr || _rawTextureAtlases->Empty()) - { +bool JSONDataParser::parseTextureAtlasData(const char *rawData, TextureAtlasData &textureAtlasData, float scale) { + if (rawData == nullptr) { + if (_rawTextureAtlases == nullptr || _rawTextureAtlases->Empty()) { return false; } - const auto& rawTextureAtlas = (*_rawTextureAtlases)[_rawTextureAtlasIndex++]; + const auto &rawTextureAtlas = (*_rawTextureAtlases)[_rawTextureAtlasIndex++]; _parseTextureAtlasData(rawTextureAtlas, textureAtlasData, scale); - if (_rawTextureAtlasIndex >= _rawTextureAtlases->Size()) - { + if (_rawTextureAtlasIndex >= _rawTextureAtlases->Size()) { _rawTextureAtlasIndex = 0; - _rawTextureAtlases = nullptr; + _rawTextureAtlases = nullptr; } return true; diff --git a/native/cocos/network/Downloader-android.cpp b/native/cocos/network/Downloader-java.cpp similarity index 68% rename from native/cocos/network/Downloader-android.cpp rename to native/cocos/network/Downloader-java.cpp index 19ec8b1d3d..5e5b39e7b1 100644 --- a/native/cocos/network/Downloader-android.cpp +++ b/native/cocos/network/Downloader-java.cpp @@ -24,14 +24,14 @@ THE SOFTWARE. ****************************************************************************/ -#include "network/Downloader-android.h" +#include "network/Downloader-java.h" #include "network/Downloader.h" -#include "platform/android/jni/JniHelper.h" -#include "platform/android/jni/JniImp.h" +#include "platform/java/jni/JniHelper.h" +#include "platform/java/jni/JniImp.h" -#include #include +#include #ifndef JCLS_DOWNLOADER #define JCLS_DOWNLOADER "com/cocos/lib/CocosDownloader" @@ -44,15 +44,15 @@ #endif #define JNI_DOWNLOADER(FUNC) JNI_METHOD1(ORG_DOWNLOADER_CLASS_NAME, FUNC) -std::unordered_map sDownloaderMap; -std::mutex sDownloaderMutex; +std::unordered_map sDownloaderMap; +std::mutex sDownloaderMutex; -static void _insertDownloaderAndroid(int id, cc::network::DownloaderAndroid *downloaderPtr) { +static void insertDownloaderJava(int id, cc::network::DownloaderJava *downloaderPtr) { std::lock_guard guard(sDownloaderMutex); sDownloaderMap.insert(std::make_pair(id, downloaderPtr)); } -static void _eraseDownloaderAndroid(int id) { +static void eraseDownloaderJava(int id) { std::lock_guard guard(sDownloaderMutex); sDownloaderMap.erase(id); } @@ -60,20 +60,19 @@ static void _eraseDownloaderAndroid(int id) { /** * If not found, return nullptr, otherwise return the Downloader */ -static cc::network::DownloaderAndroid *_findDownloaderAndroid(int id) { +static cc::network::DownloaderJava *findDownloaderJava(int id) { std::lock_guard guard(sDownloaderMutex); - auto iter = sDownloaderMap.find(id); + auto iter = sDownloaderMap.find(id); if (sDownloaderMap.end() == iter) { return nullptr; - } else { - return iter->second; } + return iter->second; } namespace cc { namespace network { -static int sTaskCounter = 0; +static int sTaskCounter = 0; static int sDownloaderCounter = 0; struct DownloadTaskAndroid : public IDownloadTask { @@ -81,18 +80,18 @@ struct DownloadTaskAndroid : public IDownloadTask { : id(++sTaskCounter) { DLLOG("Construct DownloadTaskAndroid: %p", this); } - virtual ~DownloadTaskAndroid() { + ~DownloadTaskAndroid() override { DLLOG("Destruct DownloadTaskAndroid: %p", this); } - int id; + int id; std::shared_ptr task; // reference to DownloadTask, when task finish, release }; -DownloaderAndroid::DownloaderAndroid(const DownloaderHints &hints) +DownloaderJava::DownloaderJava(const DownloaderHints &hints) : _id(++sDownloaderCounter), _impl(nullptr) { - DLLOG("Construct DownloaderAndroid: %p", this); + DLLOG("Construct DownloaderJava: %p", this); JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_DOWNLOADER, @@ -110,14 +109,14 @@ DownloaderAndroid::DownloaderAndroid(const DownloaderHints &hints) DLLOG("android downloader: jObj: %p, _impl: %p", jObj, _impl); //It's not thread-safe here, use thread-safe method instead //sDownloaderMap.insert(make_pair(_id, this)); - _insertDownloaderAndroid(_id, this); - methodInfo.env->DeleteLocalRef(jStr); - methodInfo.env->DeleteLocalRef(jObj); - methodInfo.env->DeleteLocalRef(methodInfo.classID); + insertDownloaderJava(_id, this); + ccDeleteLocalRef(methodInfo.env, jStr); + ccDeleteLocalRef(methodInfo.env, jObj); + ccDeleteLocalRef(methodInfo.env, methodInfo.classID); } } -DownloaderAndroid::~DownloaderAndroid() { +DownloaderJava::~DownloaderJava() { if (_impl != nullptr) { JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, @@ -128,18 +127,18 @@ DownloaderAndroid::~DownloaderAndroid() { methodInfo.classID, methodInfo.methodID, _impl); - methodInfo.env->DeleteLocalRef(methodInfo.classID); + ccDeleteLocalRef(methodInfo.env, methodInfo.classID); } //It's not thread-safe here, use thread-safe method instead //sDownloaderMap.erase(_id); - _eraseDownloaderAndroid(_id); + eraseDownloaderJava(_id); JniHelper::getEnv()->DeleteGlobalRef(_impl); } - DLLOG("Destruct DownloaderAndroid: %p", this); + DLLOG("Destruct DownloaderJava: %p", this); } -IDownloadTask *DownloaderAndroid::createCoTask(std::shared_ptr &task) { - DownloadTaskAndroid *coTask = new DownloadTaskAndroid; +IDownloadTask *DownloaderJava::createCoTask(std::shared_ptr &task) { + auto *coTask = new DownloadTaskAndroid; coTask->task = task; JniMethodInfo methodInfo; @@ -147,33 +146,33 @@ IDownloadTask *DownloaderAndroid::createCoTask(std::shared_ptrFindClass("java/lang/String"); - jstring jstrURL = methodInfo.env->NewStringUTF(task->requestURL.c_str()); - jstring jstrPath = methodInfo.env->NewStringUTF(task->storagePath.c_str()); - jobjectArray jarrayHeader = methodInfo.env->NewObjectArray(task->header.size() * 2, jclassString, NULL); - const std::map &headMap = task->header; - int index = 0; - for (auto it = headMap.cbegin(); it != headMap.cend(); ++it) { - methodInfo.env->SetObjectArrayElement(jarrayHeader, index++, methodInfo.env->NewStringUTF(it->first.c_str())); - methodInfo.env->SetObjectArrayElement(jarrayHeader, index++, methodInfo.env->NewStringUTF(it->second.c_str())); + jclass jclassString = methodInfo.env->FindClass("java/lang/String"); + jstring jstrURL = methodInfo.env->NewStringUTF(task->requestURL.c_str()); + jstring jstrPath = methodInfo.env->NewStringUTF(task->storagePath.c_str()); + jobjectArray jarrayHeader = methodInfo.env->NewObjectArray(task->header.size() * 2, jclassString, nullptr); + const std::map &headMap = task->header; + int index = 0; + for (const auto &it : headMap) { + methodInfo.env->SetObjectArrayElement(jarrayHeader, index++, methodInfo.env->NewStringUTF(it.first.c_str())); + methodInfo.env->SetObjectArrayElement(jarrayHeader, index++, methodInfo.env->NewStringUTF(it.second.c_str())); } methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, _impl, coTask->id, jstrURL, jstrPath, jarrayHeader); for (int i = 0; i < index; ++i) { - methodInfo.env->DeleteLocalRef(methodInfo.env->GetObjectArrayElement(jarrayHeader, i)); + ccDeleteLocalRef(methodInfo.env, methodInfo.env->GetObjectArrayElement(jarrayHeader, i)); } - methodInfo.env->DeleteLocalRef(jclassString); - methodInfo.env->DeleteLocalRef(jstrURL); - methodInfo.env->DeleteLocalRef(jstrPath); - methodInfo.env->DeleteLocalRef(jarrayHeader); - methodInfo.env->DeleteLocalRef(methodInfo.classID); + ccDeleteLocalRef(methodInfo.env, jclassString); + ccDeleteLocalRef(methodInfo.env, jstrURL); + ccDeleteLocalRef(methodInfo.env, jstrPath); + ccDeleteLocalRef(methodInfo.env, jarrayHeader); + ccDeleteLocalRef(methodInfo.env, methodInfo.classID); } - DLLOG("DownloaderAndroid::createCoTask id: %d", coTask->id); + DLLOG("DownloaderJava::createCoTask id: %d", coTask->id); _taskMap.insert(std::make_pair(coTask->id, coTask)); return coTask; } -void DownloaderAndroid::abort(const std::unique_ptr &task) { +void DownloaderJava::abort(const std::unique_ptr &task) { auto iter = _taskMap.begin(); for (; iter != _taskMap.end(); iter++) { if (task.get() == iter->second) { @@ -192,7 +191,7 @@ void DownloaderAndroid::abort(const std::unique_ptr &task) { methodInfo.methodID, _impl, iter->first); - methodInfo.env->DeleteLocalRef(methodInfo.classID); + ccDeleteLocalRef(methodInfo.env, methodInfo.classID); DownloadTaskAndroid *coTask = iter->second; _taskMap.erase(iter); @@ -205,30 +204,30 @@ void DownloaderAndroid::abort(const std::unique_ptr &task) { coTask->task.reset(); } } - DLLOG("DownloaderAndroid:abort"); + DLLOG("DownloaderJava:abort"); } -void DownloaderAndroid::_onProcess(int taskId, int64_t dl, int64_t dlNow, int64_t dlTotal) { - DLLOG("DownloaderAndroid::onProgress(taskId: %d, dl: %lld, dlnow: %lld, dltotal: %lld)", taskId, dl, dlNow, dlTotal); +void DownloaderJava::onProcessImpl(int taskId, int64_t dl, int64_t dlNow, int64_t dlTotal) { + DLLOG("DownloaderJava::onProgress(taskId: %d, dl: %lld, dlnow: %lld, dltotal: %lld)", taskId, dl, dlNow, dlTotal); auto iter = _taskMap.find(taskId); if (_taskMap.end() == iter) { - DLLOG("DownloaderAndroid::onProgress can't find task with id: %d", taskId); + DLLOG("DownloaderJava::onProgress can't find task with id: %d", taskId); return; } - DownloadTaskAndroid *coTask = iter->second; + DownloadTaskAndroid * coTask = iter->second; std::function transferDataToBuffer; onTaskProgress(*coTask->task, dl, dlNow, dlTotal, transferDataToBuffer); } -void DownloaderAndroid::_onFinish(int taskId, int errCode, const char *errStr, const std::vector &data) { - DLLOG("DownloaderAndroid::_onFinish(taskId: %d, errCode: %d, errStr: %s)", taskId, errCode, (errStr) ? errStr : "null"); +void DownloaderJava::onFinishImpl(int taskId, int errCode, const char *errStr, const std::vector &data) { + DLLOG("DownloaderJava::onFinishImpl(taskId: %d, errCode: %d, errStr: %s)", taskId, errCode, (errStr) ? errStr : "null"); auto iter = _taskMap.find(taskId); if (_taskMap.end() == iter) { - DLLOG("DownloaderAndroid::_onFinish can't find task with id: %d", taskId); + DLLOG("DownloaderJava::onFinishImpl can't find task with id: %d", taskId); return; } DownloadTaskAndroid *coTask = iter->second; - std::string str = (errStr ? errStr : ""); + std::string str = (errStr ? errStr : ""); _taskMap.erase(iter); onTaskFinish(*coTask->task, errStr ? DownloadTask::ERROR_IMPL_INTERNAL : DownloadTask::ERROR_NO_ERROR, @@ -242,26 +241,26 @@ void DownloaderAndroid::_onFinish(int taskId, int errCode, const char *errStr, c extern "C" { -JNIEXPORT void JNICALL JNI_DOWNLOADER(nativeOnProgress)(JNIEnv *env, jclass clazz, jint id, jint taskId, jlong dl, jlong dlnow, jlong dltotal) { +JNIEXPORT void JNICALL JNI_DOWNLOADER(nativeOnProgress)(JNIEnv * /*env*/, jclass /*clazz*/, jint id, jint taskId, jlong dl, jlong dlnow, jlong dltotal) { auto func = [=]() -> void { DLLOG("_nativeOnProgress(id: %d, taskId: %d, dl: %lld, dlnow: %lld, dltotal: %lld)", id, taskId, dl, dlnow, dltotal); //It's not thread-safe here, use thread-safe method instead - cc::network::DownloaderAndroid *downloader = _findDownloaderAndroid(id); + cc::network::DownloaderJava *downloader = findDownloaderJava(id); if (nullptr == downloader) { DLLOG("_nativeOnProgress can't find downloader by key: %p for task: %d", clazz, id); return; } - downloader->_onProcess((int)taskId, (int64_t)dl, (int64_t)dlnow, (int64_t)dltotal); + downloader->onProcessImpl((int)taskId, (int64_t)dl, (int64_t)dlnow, (int64_t)dltotal); }; cc::Application::getInstance()->getScheduler()->performFunctionInCocosThread(func); } -JNIEXPORT void JNICALL JNI_DOWNLOADER(nativeOnFinish)(JNIEnv *env, jclass clazz, jint id, jint taskId, jint errCode, jstring errStr, jbyteArray data) { - std::string errStrTmp; +JNIEXPORT void JNICALL JNI_DOWNLOADER(nativeOnFinish)(JNIEnv *env, jclass /*clazz*/, jint id, jint taskId, jint errCode, jstring errStr, jbyteArray data) { + std::string errStrTmp; std::vector dataTmp; if (errStr) { const char *nativeErrStr = env->GetStringUTFChars(errStr, JNI_FALSE); - errStrTmp = nativeErrStr; + errStrTmp = nativeErrStr; env->ReleaseStringUTFChars(errStr, nativeErrStr); } if (data && env->GetArrayLength(data) > 0) { @@ -272,7 +271,7 @@ JNIEXPORT void JNICALL JNI_DOWNLOADER(nativeOnFinish)(JNIEnv *env, jclass clazz, auto func = [errStrTmp = std::move(errStrTmp), dataTmp = std::move(dataTmp), id, taskId, errCode]() -> void { DLLOG("_nativeOnFinish(id: %d, taskId: %d)", id, taskId); //It's not thread-safe here, use thread-safe method instead - cc::network::DownloaderAndroid *downloader = _findDownloaderAndroid(id); + cc::network::DownloaderJava *downloader = findDownloaderJava(id); if (nullptr == downloader) { DLLOG("_nativeOnFinish can't find downloader id: %d for task: %d", id, taskId); return; @@ -280,12 +279,12 @@ JNIEXPORT void JNICALL JNI_DOWNLOADER(nativeOnFinish)(JNIEnv *env, jclass clazz, std::vector buf; if (!errStrTmp.empty()) { // failure - downloader->_onFinish((int)taskId, (int)errCode, errStrTmp.c_str(), buf); + downloader->onFinishImpl((int)taskId, (int)errCode, errStrTmp.c_str(), buf); return; } // success - downloader->_onFinish((int)taskId, (int)errCode, nullptr, dataTmp); + downloader->onFinishImpl((int)taskId, (int)errCode, nullptr, dataTmp); }; cc::Application::getInstance()->getScheduler()->performFunctionInCocosThread(func); } diff --git a/native/cocos/network/Downloader-android.h b/native/cocos/network/Downloader-java.h similarity index 74% rename from native/cocos/network/Downloader-android.h rename to native/cocos/network/Downloader-java.h index a93e9c7525..250d4337b3 100644 --- a/native/cocos/network/Downloader-android.h +++ b/native/cocos/network/Downloader-java.h @@ -35,22 +35,22 @@ namespace network { class DownloadTaskAndroid; struct DownloaderHints; -class DownloaderAndroid : public IDownloaderImpl { +class DownloaderJava : public IDownloaderImpl { public: - DownloaderAndroid(const DownloaderHints &hints); - virtual ~DownloaderAndroid(); + explicit DownloaderJava(const DownloaderHints &hints); + ~DownloaderJava() override; - virtual IDownloadTask *createCoTask(std::shared_ptr &task) override; + IDownloadTask *createCoTask(std::shared_ptr &task) override; - virtual void abort(const std::unique_ptr &task) override; + void abort(const std::unique_ptr &task) override; // designed called by internal - void _onProcess(int taskId, int64_t dl, int64_t dlNow, int64_t dlTotal); - void _onFinish(int taskId, int errCode, const char *errStr, const std::vector &data); + void onProcessImpl(int taskId, int64_t dl, int64_t dlNow, int64_t dlTotal); + void onFinishImpl(int taskId, int errCode, const char *errStr, const std::vector &data); protected: - int _id; - _jobject *_impl; + int _id; + _jobject * _impl; std::unordered_map _taskMap; }; } // namespace network diff --git a/native/cocos/network/Downloader.cpp b/native/cocos/network/Downloader.cpp index 433a05e2ee..05a94c986e 100644 --- a/native/cocos/network/Downloader.cpp +++ b/native/cocos/network/Downloader.cpp @@ -25,23 +25,25 @@ THE SOFTWARE. ****************************************************************************/ +#include + #include "network/Downloader.h" // include platform specific implement class #if (CC_PLATFORM == CC_PLATFORM_MAC_OSX || CC_PLATFORM == CC_PLATFORM_MAC_IOS) #include "network/DownloaderImpl-apple.h" - #define DownloaderImpl DownloaderApple + #define DownloaderImpl DownloaderApple //NOLINT(readability-identifier-naming) -#elif (CC_PLATFORM == CC_PLATFORM_ANDROID) +#elif (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) - #include "network/Downloader-android.h" - #define DownloaderImpl DownloaderAndroid + #include "network/Downloader-java.h" + #define DownloaderImpl DownloaderJava //NOLINT(readability-identifier-naming) #else #include "network/Downloader-curl.h" - #define DownloaderImpl DownloaderCURL + #define DownloaderImpl DownloaderCURL //NOLINT(readability-identifier-naming) #endif @@ -69,21 +71,21 @@ Downloader::Downloader() { Downloader::Downloader(const DownloaderHints &hints) { DLLOG("Construct Downloader %p", this); - _impl.reset(new DownloaderImpl(hints)); + _impl = std::make_unique(hints); _impl->onTaskProgress = [this](const DownloadTask &task, - int64_t bytesReceived, - int64_t totalBytesReceived, - int64_t totalBytesExpected, + int64_t bytesReceived, + int64_t totalBytesReceived, + int64_t totalBytesExpected, std::function & /*transferDataToBuffer*/) { if (onTaskProgress) { onTaskProgress(task, bytesReceived, totalBytesReceived, totalBytesExpected); } }; - _impl->onTaskFinish = [this](const DownloadTask &task, - int errorCode, - int errorCodeInternal, - const std::string &errorStr, + _impl->onTaskFinish = [this](const DownloadTask & task, + int errorCode, + int errorCodeInternal, + const std::string & errorStr, const std::vector &data) { if (DownloadTask::ERROR_NO_ERROR != errorCode) { if (onTaskError) { @@ -111,11 +113,11 @@ Downloader::~Downloader() { } std::shared_ptr Downloader::createDownloadDataTask(const std::string &srcUrl, const std::string &identifier /* = ""*/) { - DownloadTask *task_ = new (std::nothrow) DownloadTask(); - std::shared_ptr task(task_); + auto * iTask = new (std::nothrow) DownloadTask(); + std::shared_ptr task(iTask); do { - task_->requestURL = srcUrl; - task_->identifier = identifier; + iTask->requestURL = srcUrl; + iTask->identifier = identifier; if (0 == srcUrl.length()) { if (onTaskError) { onTaskError(*task, DownloadTask::ERROR_INVALID_PARAMS, 0, "URL or is empty."); @@ -123,23 +125,23 @@ std::shared_ptr Downloader::createDownloadDataTask(const std task.reset(); break; } - task_->_coTask.reset(_impl->createCoTask(task)); - } while (0); + iTask->_coTask.reset(_impl->createCoTask(task)); + } while (false); return task; } -std::shared_ptr Downloader::createDownloadFileTask(const std::string &srcUrl, - const std::string &storagePath, +std::shared_ptr Downloader::createDownloadFileTask(const std::string & srcUrl, + const std::string & storagePath, const std::map &header, - const std::string &identifier /* = ""*/) { - DownloadTask *task_ = new (std::nothrow) DownloadTask(); - std::shared_ptr task(task_); + const std::string & identifier /* = ""*/) { + auto * iTask = new (std::nothrow) DownloadTask(); + std::shared_ptr task(iTask); do { - task_->requestURL = srcUrl; - task_->storagePath = storagePath; - task_->identifier = identifier; - task_->header = header; + iTask->requestURL = srcUrl; + iTask->storagePath = storagePath; + iTask->identifier = identifier; + iTask->header = header; if (0 == srcUrl.length() || 0 == storagePath.length()) { if (onTaskError) { onTaskError(*task, DownloadTask::ERROR_INVALID_PARAMS, 0, "URL or storage path is empty."); @@ -147,8 +149,8 @@ std::shared_ptr Downloader::createDownloadFileTask(const std task.reset(); break; } - task_->_coTask.reset(_impl->createCoTask(task)); - } while (0); + iTask->_coTask.reset(_impl->createCoTask(task)); + } while (false); return task; } diff --git a/native/cocos/network/HttpClient-android.cpp b/native/cocos/network/HttpClient-java.cpp similarity index 79% rename from native/cocos/network/HttpClient-android.cpp rename to native/cocos/network/HttpClient-java.cpp index a5db27c179..57c549c517 100644 --- a/native/cocos/network/HttpClient-android.cpp +++ b/native/cocos/network/HttpClient-java.cpp @@ -26,42 +26,40 @@ THE SOFTWARE. ****************************************************************************/ -#if (CC_PLATFORM == CC_PLATFORM_ANDROID) +#include "network/HttpClient.h" - #include "network/HttpClient.h" +#include +#include +#include +#include - #include - #include - #include - #include +#include "platform/Application.h" +#include "platform/FileUtils.h" +#include "platform/java/jni/JniHelper.h" - #include "platform/Application.h" - #include "platform/FileUtils.h" - #include "platform/android/jni/JniHelper.h" +#include "base/Log.h" +#include "base/UTF8.h" - #include "base/UTF8.h" - #include "base/Log.h" - - #ifndef JCLS_HTTPCLIENT - #define JCLS_HTTPCLIENT "com/cocos/lib/CocosHttpURLConnection" - #endif +#ifndef JCLS_HTTPCLIENT + #define JCLS_HTTPCLIENT "com/cocos/lib/CocosHttpURLConnection" +#endif namespace cc { namespace network { -typedef std::vector HttpRequestHeaders; -typedef HttpRequestHeaders::iterator HttpRequestHeadersIter; -typedef std::vector HttpCookies; -typedef HttpCookies::iterator HttpCookiesIter; +using HttpRequestHeaders = std::vector; +using HttpRequestHeadersIter = HttpRequestHeaders::iterator; +using HttpCookies = std::vector; +using HttpCookiesIter = HttpCookies::iterator; -static HttpClient *_httpClient = nullptr; // pointer to singleton +static HttpClient *gHttpClient = nullptr; // pointer to singleton struct CookiesInfo { std::string domain; - bool tailmatch; + bool tailmatch; std::string path; - bool secure; + bool secure; std::string key; std::string value; std::string expires; @@ -69,23 +67,23 @@ struct CookiesInfo { //static size_t writeData(void *ptr, size_t size, size_t nmemb, void *stream) static size_t writeData(void *buffer, size_t sizes, HttpResponse *response) { - std::vector *recvBuffer = (std::vector *)response->getResponseData(); + auto *recvBuffer = static_cast *>(response->getResponseData()); recvBuffer->clear(); - recvBuffer->insert(recvBuffer->end(), (char *)buffer, ((char *)buffer) + sizes); + recvBuffer->insert(recvBuffer->end(), static_cast(buffer), (static_cast(buffer)) + sizes); return sizes; } //static size_t writeHeaderData(void *ptr, size_t size, size_t nmemb, void *stream) size_t writeHeaderData(void *buffer, size_t sizes, HttpResponse *response) { - std::vector *recvBuffer = (std::vector *)response->getResponseHeader(); + auto *recvBuffer = static_cast *>(response->getResponseHeader()); recvBuffer->clear(); - recvBuffer->insert(recvBuffer->end(), (char *)buffer, (char *)buffer + sizes); + recvBuffer->insert(recvBuffer->end(), static_cast(buffer), static_cast(buffer) + sizes); return sizes; } class HttpURLConnection { public: - HttpURLConnection(HttpClient *httpClient) + explicit HttpURLConnection(HttpClient *httpClient) : _client(httpClient), _httpURLConnection(nullptr), _requestmethod(""), @@ -111,8 +109,8 @@ public: jstring jstr = methodInfo.env->NewStringUTF(_requestmethod.c_str()); methodInfo.env->CallStaticVoidMethod( methodInfo.classID, methodInfo.methodID, _httpURLConnection, jstr); - methodInfo.env->DeleteLocalRef(jstr); - methodInfo.env->DeleteLocalRef(methodInfo.classID); + ccDeleteLocalRef(methodInfo.env, jstr); + ccDeleteLocalRef(methodInfo.env, methodInfo.classID); } else { CC_LOG_ERROR("HttpClient::%s failed!", __FUNCTION__); } @@ -145,7 +143,7 @@ public: } int connect() { - int suc = 0; + int suc = 0; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_HTTPCLIENT, @@ -153,7 +151,7 @@ public: "(Ljava/net/HttpURLConnection;)I")) { suc = methodInfo.env->CallStaticIntMethod( methodInfo.classID, methodInfo.methodID, _httpURLConnection); - methodInfo.env->DeleteLocalRef(methodInfo.classID); + ccDeleteLocalRef(methodInfo.env, methodInfo.classID); } else { CC_LOG_ERROR("HttpClient::%s failed!", __FUNCTION__); } @@ -169,14 +167,14 @@ public: "(Ljava/net/HttpURLConnection;)V")) { methodInfo.env->CallStaticVoidMethod( methodInfo.classID, methodInfo.methodID, _httpURLConnection); - methodInfo.env->DeleteLocalRef(methodInfo.classID); + ccDeleteLocalRef(methodInfo.env, methodInfo.classID); } else { CC_LOG_ERROR("HttpClient::%s failed!", __FUNCTION__); } } int getResponseCode() { - int responseCode = 0; + int responseCode = 0; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_HTTPCLIENT, @@ -184,7 +182,7 @@ public: "(Ljava/net/HttpURLConnection;)I")) { responseCode = methodInfo.env->CallStaticIntMethod( methodInfo.classID, methodInfo.methodID, _httpURLConnection); - methodInfo.env->DeleteLocalRef(methodInfo.classID); + ccDeleteLocalRef(methodInfo.env, methodInfo.classID); } else { CC_LOG_ERROR("HttpClient::%s failed!", __FUNCTION__); } @@ -193,7 +191,7 @@ public: } char *getResponseMessage() { - char *message = nullptr; + char * message = nullptr; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_HTTPCLIENT, @@ -201,11 +199,11 @@ public: "(Ljava/net/HttpURLConnection;)Ljava/lang/String;")) { jobject jObj = methodInfo.env->CallStaticObjectMethod( methodInfo.classID, methodInfo.methodID, _httpURLConnection); - message = getBufferFromJString((jstring)jObj, methodInfo.env); + message = getBufferFromJString(static_cast(jObj), methodInfo.env); if (nullptr != jObj) { - methodInfo.env->DeleteLocalRef(jObj); + ccDeleteLocalRef(methodInfo.env, jObj); } - methodInfo.env->DeleteLocalRef(methodInfo.classID); + ccDeleteLocalRef(methodInfo.env, methodInfo.classID); } else { CC_LOG_ERROR("HttpClient::%s failed!", __FUNCTION__); } @@ -219,15 +217,14 @@ public: JCLS_HTTPCLIENT, "sendRequest", "(Ljava/net/HttpURLConnection;[B)V")) { - jbyteArray bytearray; - ssize_t dataSize = request->getRequestDataSize(); - bytearray = methodInfo.env->NewByteArray(dataSize); - methodInfo.env->SetByteArrayRegion(bytearray, 0, dataSize, (const jbyte *)request->getRequestData()); + ssize_t dataSize = request->getRequestDataSize(); + bytearray = methodInfo.env->NewByteArray(dataSize); + methodInfo.env->SetByteArrayRegion(bytearray, 0, dataSize, reinterpret_cast(request->getRequestData())); methodInfo.env->CallStaticVoidMethod( methodInfo.classID, methodInfo.methodID, _httpURLConnection, bytearray); - methodInfo.env->DeleteLocalRef(bytearray); - methodInfo.env->DeleteLocalRef(methodInfo.classID); + ccDeleteLocalRef(methodInfo.env, bytearray); + ccDeleteLocalRef(methodInfo.env, methodInfo.classID); } else { CC_LOG_ERROR("HttpClient::%s failed!", __FUNCTION__); } @@ -256,7 +253,7 @@ public: } char *getResponseHeaders() { - char *headers = nullptr; + char * headers = nullptr; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_HTTPCLIENT, @@ -264,11 +261,11 @@ public: "(Ljava/net/HttpURLConnection;)Ljava/lang/String;")) { jobject jObj = methodInfo.env->CallStaticObjectMethod( methodInfo.classID, methodInfo.methodID, _httpURLConnection); - headers = getBufferFromJString((jstring)jObj, methodInfo.env); + headers = getBufferFromJString(static_cast(jObj), methodInfo.env); if (nullptr != jObj) { - methodInfo.env->DeleteLocalRef(jObj); + ccDeleteLocalRef(methodInfo.env, jObj); } - methodInfo.env->DeleteLocalRef(methodInfo.classID); + ccDeleteLocalRef(methodInfo.env, methodInfo.classID); } else { CC_LOG_ERROR("HttpClient::%s failed!", __FUNCTION__); } @@ -281,7 +278,7 @@ public: return nullptr; } - char *content = nullptr; + char * content = nullptr; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_HTTPCLIENT, @@ -290,11 +287,11 @@ public: jobject jObj = methodInfo.env->CallStaticObjectMethod( methodInfo.classID, methodInfo.methodID, _httpURLConnection); - _contentLength = getCStrFromJByteArray((jbyteArray)jObj, methodInfo.env, &content); + _contentLength = getCStrFromJByteArray(static_cast(jObj), methodInfo.env, &content); if (nullptr != jObj) { - methodInfo.env->DeleteLocalRef(jObj); + ccDeleteLocalRef(methodInfo.env, jObj); } - methodInfo.env->DeleteLocalRef(methodInfo.classID); + ccDeleteLocalRef(methodInfo.env, methodInfo.classID); } else { CC_LOG_ERROR("HttpClient::%s failed!", __FUNCTION__); } @@ -303,21 +300,21 @@ public: } char *getResponseHeaderByKey(const char *key) { - char *value = nullptr; + char * value = nullptr; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_HTTPCLIENT, "getResponseHeaderByKey", "(Ljava/net/HttpURLConnection;Ljava/lang/String;)Ljava/lang/String;")) { jstring jstrKey = methodInfo.env->NewStringUTF(key); - jobject jObj = methodInfo.env->CallStaticObjectMethod( + jobject jObj = methodInfo.env->CallStaticObjectMethod( methodInfo.classID, methodInfo.methodID, _httpURLConnection, jstrKey); - value = getBufferFromJString((jstring)jObj, methodInfo.env); - methodInfo.env->DeleteLocalRef(jstrKey); + value = getBufferFromJString(static_cast(jObj), methodInfo.env); + ccDeleteLocalRef(methodInfo.env, jstrKey); if (nullptr != jObj) { - methodInfo.env->DeleteLocalRef(jObj); + ccDeleteLocalRef(methodInfo.env, jObj); } - methodInfo.env->DeleteLocalRef(methodInfo.classID); + ccDeleteLocalRef(methodInfo.env, methodInfo.classID); } else { CC_LOG_ERROR("HttpClient::%s failed!", __FUNCTION__); } @@ -326,17 +323,17 @@ public: } int getResponseHeaderByKeyInt(const char *key) { - int contentLength = 0; + int contentLength = 0; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_HTTPCLIENT, "getResponseHeaderByKeyInt", "(Ljava/net/HttpURLConnection;Ljava/lang/String;)I")) { jstring jstrKey = methodInfo.env->NewStringUTF(key); - contentLength = methodInfo.env->CallStaticIntMethod( + contentLength = methodInfo.env->CallStaticIntMethod( methodInfo.classID, methodInfo.methodID, _httpURLConnection, jstrKey); - methodInfo.env->DeleteLocalRef(jstrKey); - methodInfo.env->DeleteLocalRef(methodInfo.classID); + ccDeleteLocalRef(methodInfo.env, jstrKey); + ccDeleteLocalRef(methodInfo.env, methodInfo.classID); } else { CC_LOG_ERROR("HttpClient::%s failed!", __FUNCTION__); } @@ -345,7 +342,7 @@ public: } char *getResponseHeaderByIdx(int idx) { - char *header = nullptr; + char * header = nullptr; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_HTTPCLIENT, @@ -353,11 +350,11 @@ public: "(Ljava/net/HttpURLConnection;I)Ljava/lang/String;")) { jobject jObj = methodInfo.env->CallStaticObjectMethod( methodInfo.classID, methodInfo.methodID, _httpURLConnection, idx); - header = getBufferFromJString((jstring)jObj, methodInfo.env); + header = getBufferFromJString(static_cast(jObj), methodInfo.env); if (nullptr != jObj) { - methodInfo.env->DeleteLocalRef(jObj); + ccDeleteLocalRef(methodInfo.env, jObj); } - methodInfo.env->DeleteLocalRef(methodInfo.classID); + ccDeleteLocalRef(methodInfo.env, methodInfo.classID); } else { CC_LOG_ERROR("HttpClient::%s failed!", __FUNCTION__); } @@ -369,7 +366,7 @@ public: return _cookieFileName; } - void setCookieFileName(std::string &filename) { + void setCookieFileName(std::string &filename) { //NOLINT _cookieFileName = filename; } @@ -384,13 +381,13 @@ private: JCLS_HTTPCLIENT, "createHttpURLConnection", "(Ljava/lang/String;)Ljava/net/HttpURLConnection;")) { - _url = url; - jstring jurl = methodInfo.env->NewStringUTF(url.c_str()); - jobject jObj = methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID, jurl); + _url = url; + jstring jurl = methodInfo.env->NewStringUTF(url.c_str()); + jobject jObj = methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID, jurl); _httpURLConnection = methodInfo.env->NewGlobalRef(jObj); - methodInfo.env->DeleteLocalRef(jurl); - methodInfo.env->DeleteLocalRef(jObj); - methodInfo.env->DeleteLocalRef(methodInfo.classID); + ccDeleteLocalRef(methodInfo.env, jurl); + ccDeleteLocalRef(methodInfo.env, jObj); + ccDeleteLocalRef(methodInfo.env, methodInfo.classID); } else { CC_LOG_ERROR("HttpClient::%s failed!", __FUNCTION__); } @@ -406,9 +403,9 @@ private: jstring jstrVal = methodInfo.env->NewStringUTF(value); methodInfo.env->CallStaticVoidMethod( methodInfo.classID, methodInfo.methodID, _httpURLConnection, jstrKey, jstrVal); - methodInfo.env->DeleteLocalRef(jstrKey); - methodInfo.env->DeleteLocalRef(jstrVal); - methodInfo.env->DeleteLocalRef(methodInfo.classID); + ccDeleteLocalRef(methodInfo.env, jstrKey); + ccDeleteLocalRef(methodInfo.env, jstrVal); + ccDeleteLocalRef(methodInfo.env, methodInfo.classID); } else { CC_LOG_ERROR("HttpClient::%s failed!", __FUNCTION__); } @@ -423,20 +420,22 @@ private: std::string cookiesInfo = FileUtils::getInstance()->getStringFromFile(_cookieFileName); - if (cookiesInfo.empty()) + if (cookiesInfo.empty()) { return; + } HttpCookies cookiesVec; cookiesVec.clear(); std::stringstream stream(cookiesInfo); - std::string item; + std::string item; while (std::getline(stream, item, '\n')) { cookiesVec.push_back(item); } - if (cookiesVec.empty()) + if (cookiesVec.empty()) { return; + } std::vector cookiesInfoVec; cookiesInfoVec.clear(); @@ -446,12 +445,13 @@ private: cookies = cookies.substr(10); } - if (cookies.at(0) == '#') + if (cookies.at(0) == '#') { continue; + } - CookiesInfo co; - std::stringstream streamInfo(cookies); - std::string item; + CookiesInfo co; + std::stringstream streamInfo(cookies); + std::string item; std::vector elems; while (std::getline(streamInfo, item, '\t')) { @@ -462,24 +462,25 @@ private: if (co.domain.at(0) == '.') { co.domain = co.domain.substr(1); } - co.tailmatch = strcmp("TRUE", elems.at(1).c_str()) ? true : false; - co.path = elems.at(2); - co.secure = strcmp("TRUE", elems.at(3).c_str()) ? true : false; - co.expires = elems.at(4); - co.key = elems.at(5); - co.value = elems.at(6); + co.tailmatch = strcmp("TRUE", elems.at(1).c_str()) != 0; + co.path = elems.at(2); + co.secure = strcmp("TRUE", elems.at(3).c_str()) != 0; + co.expires = elems.at(4); + co.key = elems.at(5); + co.value = elems.at(6); cookiesInfoVec.push_back(co); } - std::string sendCookiesInfo = ""; - int cookiesCount = 0; + std::string sendCookiesInfo; + int cookiesCount = 0; for (auto &cookieInfo : cookiesInfoVec) { if (_url.find(cookieInfo.domain) != std::string::npos) { std::string keyValue = cookieInfo.key; keyValue.append("="); keyValue.append(cookieInfo.value); - if (cookiesCount != 0) + if (cookiesCount != 0) { sendCookiesInfo.append(";"); + } sendCookiesInfo.append(keyValue); } @@ -498,15 +499,16 @@ private: "(Ljava/net/HttpURLConnection;II)V")) { methodInfo.env->CallStaticVoidMethod( methodInfo.classID, methodInfo.methodID, _httpURLConnection, readMiliseconds, connectMiliseconds); - methodInfo.env->DeleteLocalRef(methodInfo.classID); + ccDeleteLocalRef(methodInfo.env, methodInfo.classID); } else { CC_LOG_ERROR("HttpClient::%s failed!", __FUNCTION__); } } void setVerifySSL() { - if (_client->getSSLVerification().empty()) + if (_client->getSSLVerification().empty()) { return; + } std::string fullpath = FileUtils::getInstance()->fullPathForFilename(_client->getSSLVerification()); @@ -518,8 +520,8 @@ private: jstring jstrfullpath = methodInfo.env->NewStringUTF(fullpath.c_str()); methodInfo.env->CallStaticVoidMethod( methodInfo.classID, methodInfo.methodID, _httpURLConnection, jstrfullpath); - methodInfo.env->DeleteLocalRef(jstrfullpath); - methodInfo.env->DeleteLocalRef(methodInfo.classID); + ccDeleteLocalRef(methodInfo.env, jstrfullpath); + ccDeleteLocalRef(methodInfo.env, methodInfo.classID); } else { CC_LOG_ERROR("HttpClient::%s failed!", __FUNCTION__); } @@ -534,14 +536,15 @@ private: return false; } - setReadAndConnectTimeout(request->getTimeout() * 1000, request->getTimeout() * 1000); + setReadAndConnectTimeout(static_cast(request->getTimeout() * 1000), + static_cast(request->getTimeout() * 1000)); setVerifySSL(); return true; } - char *getBufferFromJString(jstring jstr, JNIEnv *env) { + char *getBufferFromJString(jstring jstr, JNIEnv *env) { //NOLINT(readability-convert-member-functions-to-static) if (nullptr == jstr) { return nullptr; } @@ -549,17 +552,17 @@ private: return strdup(strValue.c_str()); } - int getCStrFromJByteArray(jbyteArray jba, JNIEnv *env, char **ppData) { + int getCStrFromJByteArray(jbyteArray jba, JNIEnv *env, char **ppData) { //NOLINT(readability-convert-member-functions-to-static) if (nullptr == jba) { *ppData = nullptr; return 0; } - int len = env->GetArrayLength(jba); - char *str = (char *)malloc(sizeof(char) * len); - env->GetByteArrayRegion(jba, 0, len, (jbyte *)str); + int len = env->GetArrayLength(jba); + auto *str = static_cast(malloc(sizeof(jbyte) * len)); + env->GetByteArrayRegion(jba, 0, len, str); - *ppData = str; + *ppData = reinterpret_cast(str); return len; } @@ -569,17 +572,17 @@ private: private: HttpClient *_client; - jobject _httpURLConnection; + jobject _httpURLConnection; std::string _requestmethod; std::string _responseCookies; std::string _cookieFileName; std::string _url; - int _contentLength; + int _contentLength; }; // Process Response void HttpClient::processResponse(HttpResponse *response, char *responseMessage) { - auto request = response->getHttpRequest(); + auto request = response->getHttpRequest(); HttpRequest::Type requestType = request->getRequestType(); if (HttpRequest::Type::GET != requestType && @@ -591,8 +594,8 @@ void HttpClient::processResponse(HttpResponse *response, char *responseMessage) return; } - long responseCode = -1; - int retValue = 0; + int64_t responseCode = -1; + int retValue = 0; HttpURLConnection urlConnection(this); if (!urlConnection.init(request)) { @@ -661,12 +664,12 @@ void HttpClient::processResponse(HttpResponse *response, char *responseMessage) free(cookiesInfo); //content len - int contentLength = urlConnection.getResponseHeaderByKeyInt("Content-Length"); - char *contentInfo = urlConnection.getResponseContent(response); + int contentLength = urlConnection.getResponseHeaderByKeyInt("Content-Length"); + char *contentInfo = urlConnection.getResponseContent(response); if (nullptr != contentInfo) { - std::vector *recvBuffer = (std::vector *)response->getResponseData(); + auto *recvBuffer = static_cast *>(response->getResponseData()); recvBuffer->clear(); - recvBuffer->insert(recvBuffer->begin(), (char *)contentInfo, ((char *)contentInfo) + urlConnection.getContentLength()); + recvBuffer->insert(recvBuffer->begin(), contentInfo, contentInfo + urlConnection.getContentLength()); } free(contentInfo); @@ -715,7 +718,7 @@ void HttpClient::networkThread() { } // Create a HttpResponse object, the default setting is http access failed - HttpResponse *response = new (std::nothrow) HttpResponse(request); + auto *response = new (std::nothrow) HttpResponse(request); processResponse(response, _responseMessage); // add response packet into queue @@ -769,23 +772,23 @@ void HttpClient::networkThreadAlone(HttpRequest *request, HttpResponse *response // HttpClient implementation HttpClient *HttpClient::getInstance() { - if (_httpClient == nullptr) { - _httpClient = new (std::nothrow) HttpClient(); + if (gHttpClient == nullptr) { + gHttpClient = new (std::nothrow) HttpClient(); } - return _httpClient; + return gHttpClient; } void HttpClient::destroyInstance() { - if (_httpClient == nullptr) { + if (gHttpClient == nullptr) { CC_LOG_DEBUG("HttpClient singleton is nullptr"); return; } CC_LOG_DEBUG("HttpClient::destroyInstance ..."); - auto thiz = _httpClient; - _httpClient = nullptr; + auto thiz = gHttpClient; + gHttpClient = nullptr; if (auto sche = thiz->_scheduler.lock()) { sche->unscheduleAllForTarget(thiz); @@ -839,12 +842,12 @@ HttpClient::~HttpClient() { bool HttpClient::lazyInitThreadSemaphore() { if (_isInited) { return true; - } else { - auto t = std::thread(CC_CALLBACK_0(HttpClient::networkThread, this)); - t.detach(); - _isInited = true; } + auto t = std::thread(CC_CALLBACK_0(HttpClient::networkThread, this)); + t.detach(); + _isInited = true; + return true; } @@ -875,7 +878,7 @@ void HttpClient::sendImmediate(HttpRequest *request) { request->retain(); // Create a HttpResponse object, the default setting is http access failed - HttpResponse *response = new (std::nothrow) HttpResponse(request); + auto *response = new (std::nothrow) HttpResponse(request); auto t = std::thread(&HttpClient::networkThreadAlone, this, request, response); t.detach(); @@ -897,7 +900,7 @@ void HttpClient::dispatchResponseCallbacks() { _responseQueueMutex.unlock(); if (response) { - HttpRequest *request = response->getHttpRequest(); + HttpRequest * request = response->getHttpRequest(); const ccHttpRequestCallback &callback = request->getResponseCallback(); if (callback != nullptr) { @@ -963,5 +966,3 @@ const std::string &HttpClient::getSSLVerification() { } // namespace network } // namespace cc - -#endif // #if (CC_PLATFORM == CC_PLATFORM_ANDROID) diff --git a/native/cocos/network/WebSocket-libwebsockets.cpp b/native/cocos/network/WebSocket-libwebsockets.cpp index 5b28c0d4c7..6fdf06e6ae 100644 --- a/native/cocos/network/WebSocket-libwebsockets.cpp +++ b/native/cocos/network/WebSocket-libwebsockets.cpp @@ -25,7 +25,15 @@ THE SOFTWARE. ****************************************************************************/ -#include "websockets/libwebsockets.h" +/*************************************************************************** +* "[WebSocket module] is based in part on the work of the libwebsockets project +* (http://libwebsockets.org)" +*****************************************************************************/ +#if __OHOS__ + #include "libwebsockets.h" +#else + #include "websockets/libwebsockets.h" +#endif #include #include @@ -56,6 +64,9 @@ #define WS_RX_BUFFER_SIZE (65536) #define WS_RESERVE_RECEIVE_BUFFER_SIZE (4096) +#ifdef LOG_TAG + #undef LOG_TAG +#endif #define LOG_TAG "WebSocket.cpp" struct lws; @@ -121,7 +132,7 @@ static void wsLog(const char *format, ...) { #endif #define DO_QUOTEME(x) #x -#define QUOTEME(x) DO_QUOTEME(x) +#define QUOTEME(x) DO_QUOTEME(x) // Since CC_LOG_DEBUG isn't thread safe, we uses LOGD for multi-thread logging. #ifdef ANDROID @@ -132,6 +143,10 @@ static void wsLog(const char *format, ...) { #endif #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) +#elif defined(__OHOS__) + #include "cocos/base/Log.h" + #define LOGD(...) CC_LOG_DEBUG(__VA_ARGS__) + #define LOGE(...) CC_LOG_ERROR(__VA_ARGS__) #else #if CC_DEBUG > 0 #define LOGD(fmt, ...) wsLog("D/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__) @@ -144,7 +159,7 @@ static void wsLog(const char *format, ...) { static void printWebSocketLog(int level, const char *line) { #if CC_DEBUG > 0 - static const char *const log_level_names[] = { + static const char *const LOG_LEVEL_NAMES[] = { "ERR", "WARN", "NOTICE", @@ -161,9 +176,10 @@ static void printWebSocketLog(int level, const char *line) { int n; for (n = 0; n < LLL_COUNT; n++) { - if (level != (1 << n)) + if (level != (1 << n)) { continue; - sprintf(buf, "%s: ", log_level_names[n]); + } + sprintf(buf, "%s: ", LOG_LEVEL_NAMES[n]); break; } @@ -255,7 +271,7 @@ static std::recursive_mutex instanceMutex; static struct lws_context * wsContext = nullptr; static WsThreadHelper * wsHelper = nullptr; -#if (CC_PLATFORM == CC_PLATFORM_ANDROID) +#if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) static std::string getFileNameForPath(const std::string &filePath) { std::string fileName = filePath; const size_t lastSlashIdx = fileName.find_last_of("\\/"); @@ -804,7 +820,7 @@ cc::network::WebSocket::Delegate *WebSocketImpl::getDelegate() const { struct lws_vhost *WebSocketImpl::createVhost(struct lws_protocols *protocols, int *sslConnectionOut) { auto *fileUtils = cc::FileUtils::getInstance(); - bool isCAFileExist = fileUtils->isFileExist(_caFilePath); + bool isCAFileExist = fileUtils->isFileExist(_caFilePath); if (isCAFileExist) { _caFilePath = fileUtils->fullPathForFilename(_caFilePath); } @@ -814,7 +830,7 @@ struct lws_vhost *WebSocketImpl::createVhost(struct lws_protocols *protocols, in int sslConnection = *sslConnectionOut; if (sslConnection != 0) { if (isCAFileExist) { -#if (CC_PLATFORM == CC_PLATFORM_ANDROID) +#if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) // if ca file is in the apk, try to extract it to writable path std::string writablePath = fileUtils->getWritablePath(); std::string caFileName = getFileNameForPath(_caFilePath); diff --git a/native/cocos/network/WebSocketServer.h b/native/cocos/network/WebSocketServer.h index 976f184860..816730c2fe 100644 --- a/native/cocos/network/WebSocketServer.h +++ b/native/cocos/network/WebSocketServer.h @@ -41,8 +41,13 @@ #include #include + #if CC_PLATFORM == CC_PLATFORM_OHOS + #include "libwebsockets.h" + #else + #include "websockets/libwebsockets.h" + #endif + #include "cocos/base/Macros.h" - #include "websockets/libwebsockets.h" namespace cc { namespace network { diff --git a/native/cocos/platform/Application.cpp b/native/cocos/platform/Application.cpp index 058ae7312b..905b1a02ed 100644 --- a/native/cocos/platform/Application.cpp +++ b/native/cocos/platform/Application.cpp @@ -37,8 +37,9 @@ #include "cocos/network/HttpClient.h" namespace cc { -void Application::restartVM() { +using std::chrono::duration_cast; +void Application::restartVM() { cc::EventDispatcher::dispatchRestartVM(); auto *scriptEngine = se::ScriptEngine::getInstance(); @@ -65,7 +66,6 @@ void Application::restartVM() { } void Application::tick() { - if (_needRestart) { restartVM(); _needRestart = false; @@ -73,16 +73,16 @@ void Application::tick() { static std::chrono::steady_clock::time_point prevTime; static std::chrono::steady_clock::time_point now; - static float dt = 0.f; - static double dtNS = NANOSECONDS_60FPS; + static float dt = 0.0F; + static double dtNS = NANOSECONDS_60FPS; ++_totalFrames; // iOS/macOS use its own fps limitation algorithm. -#if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_WINDOWS) +#if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_WINDOWS || CC_PLATFORM == CC_PLATFORM_OHOS) if (dtNS < _prefererredNanosecondsPerFrame) { std::this_thread::sleep_for( - std::chrono::nanoseconds(_prefererredNanosecondsPerFrame - static_cast(dtNS))); + std::chrono::nanoseconds(_prefererredNanosecondsPerFrame - static_cast(dtNS))); //NOLINT dtNS = _prefererredNanosecondsPerFrame; } #endif @@ -97,9 +97,9 @@ void Application::tick() { currentPool->clear(); } - now = std::chrono::steady_clock::now(); - dtNS = dtNS * 0.1 + 0.9 * std::chrono::duration_cast(now - prevTime).count(); - dt = (float)dtNS / NANOSECONDS_PER_SECOND; + now = std::chrono::steady_clock::now(); + dtNS = dtNS * 0.1 + 0.9 * static_cast(duration_cast(now - prevTime).count()); + dt = static_cast(dtNS) / NANOSECONDS_PER_SECOND; } } // namespace cc diff --git a/native/cocos/platform/Application.h b/native/cocos/platform/Application.h index 7e26ea7321..004985fc81 100644 --- a/native/cocos/platform/Application.h +++ b/native/cocos/platform/Application.h @@ -26,15 +26,15 @@ #pragma once -#include #include +#include #include // // std::this_thread::sleep_for #include "base/Macros.h" -#include "bindings/event/EventDispatcher.h" -#include "base/Scheduler.h" #include "base/AutoreleasePool.h" +#include "base/Scheduler.h" #include "base/TypeDef.h" +#include "bindings/event/EventDispatcher.h" #include "math/Vec2.h" #define NANOSECONDS_PER_SECOND 1000000000 @@ -58,6 +58,7 @@ public: ANDROIDOS, /**< Android, because ANDROID is a macro, so use ANDROIDOS instead */ IPHONE, /**< iPhone */ IPAD, /**< iPad */ + OHOS, /**< Open Harmony OS> */ }; enum class LanguageType { @@ -98,7 +99,7 @@ public: void restartVM(); - inline std::shared_ptr getScheduler() const { return _scheduler; } + inline std::shared_ptr getScheduler() const { return _scheduler; } //NOLINT(readability-convert-member-functions-to-static) /** * @brief Sets the preferred frame rate for main loop callback. @@ -161,13 +162,13 @@ public: inline const cc::Vec2 &getViewLogicalSize() const { return _viewLogicalSize; } private: - static Application *_instance; - static std::shared_ptr _scheduler; - int _fps = 60; - long _prefererredNanosecondsPerFrame = NANOSECONDS_60FPS; - uint _totalFrames = 0; - cc::Vec2 _viewLogicalSize; - bool _needRestart = false; + static Application * _instance; //NOLINT(readability-identifier-naming) + static std::shared_ptr _scheduler; //NOLINT(readability-identifier-naming) + int _fps = 60; + long _prefererredNanosecondsPerFrame = NANOSECONDS_60FPS; //NOLINT + uint _totalFrames = 0; + cc::Vec2 _viewLogicalSize; + bool _needRestart = false; }; // end of platform group diff --git a/native/cocos/platform/Device.h b/native/cocos/platform/Device.h index c7c48dbbb3..354099c55b 100644 --- a/native/cocos/platform/Device.h +++ b/native/cocos/platform/Device.h @@ -28,10 +28,11 @@ #ifndef __CCDEVICE_H__ #define __CCDEVICE_H__ -#include "base/Macros.h" #include "base/Data.h" +#include "base/Macros.h" #include "math/Vec4.h" + namespace cc { struct FontDefinition; @@ -49,24 +50,24 @@ class CC_DLL Device { public: // https://developer.mozilla.org/en-US/docs/Web/API/Window/orientation enum class Orientation { - PORTRAIT = 0, - LANDSCAPE_LEFT = -90, + PORTRAIT = 0, + LANDSCAPE_LEFT = -90, PORTRAIT_UPSIDE_DOWN = 180, - LANDSCAPE_RIGHT = 90 + LANDSCAPE_RIGHT = 90 }; struct MotionValue { - float accelerationX = 0.0f; - float accelerationY = 0.0f; - float accelerationZ = 0.0f; + float accelerationX = 0.0F; + float accelerationY = 0.0F; + float accelerationZ = 0.0F; - float accelerationIncludingGravityX = 0.0f; - float accelerationIncludingGravityY = 0.0f; - float accelerationIncludingGravityZ = 0.0f; + float accelerationIncludingGravityX = 0.0F; + float accelerationIncludingGravityY = 0.0F; + float accelerationIncludingGravityZ = 0.0F; - float rotationRateAlpha = 0.0f; - float rotationRateBeta = 0.0f; - float rotationRateGamma = 0.0f; + float rotationRateAlpha = 0.0F; + float rotationRateBeta = 0.0F; + float rotationRateGamma = 0.0F; }; /** diff --git a/native/cocos/platform/FileUtils.cpp b/native/cocos/platform/FileUtils.cpp index 27c8324e0e..4631688d43 100644 --- a/native/cocos/platform/FileUtils.cpp +++ b/native/cocos/platform/FileUtils.cpp @@ -27,14 +27,18 @@ #include "platform/FileUtils.h" +#include #include #include "base/Data.h" #include "base/Log.h" #include "platform/SAXParser.h" -#include "tinyxml2/tinyxml2.h" #include "tinydir/tinydir.h" +#include "tinyxml2/tinyxml2.h" + +#include +#include #ifdef MINIZIP_FROM_SYSTEM #include @@ -50,7 +54,7 @@ namespace cc { #if (CC_PLATFORM != CC_PLATFORM_MAC_IOS) && (CC_PLATFORM != CC_PLATFORM_MAC_OSX) -typedef enum { +using SAXState = enum { SAX_NONE = 0, SAX_KEY, SAX_DICT, @@ -58,39 +62,34 @@ typedef enum { SAX_REAL, SAX_STRING, SAX_ARRAY -} SAXState; +}; -typedef enum { +using SAXResult = enum { SAX_RESULT_NONE = 0, SAX_RESULT_DICT, SAX_RESULT_ARRAY -} SAXResult; +}; class DictMaker : public SAXDelegator { public: - SAXResult _resultType; - ValueMap _rootDict; + SAXResult _resultType{}; + ValueMap _rootDict; ValueVector _rootArray; std::string _curKey; ///< parsed key std::string _curValue; // parsed value - SAXState _state; + SAXState _state{}; - ValueMap *_curDict; + ValueMap * _curDict; ValueVector *_curArray; - std::stack _dictStack; + std::stack _dictStack; std::stack _arrayStack; - std::stack _stateStack; + std::stack _stateStack; public: - DictMaker() - : _resultType(SAX_RESULT_NONE), - _state(SAX_NONE) { - } - - ~DictMaker() { - } + DictMaker() = default; + ~DictMaker() override = default; ValueMap dictionaryWithContentsOfFile(const std::string &fileName) { _resultType = SAX_RESULT_DICT; @@ -125,7 +124,7 @@ public: return _rootArray; } - virtual void startElement(void *ctx, const char *name, const char **atts) override { + void startElement(void *ctx, const char *name, const char **atts) override { CC_UNUSED_PARAM(ctx); CC_UNUSED_PARAM(atts); const std::string sName(name); @@ -148,9 +147,9 @@ public: } else if (SAX_DICT == preState) { // add a new dictionary into the pre dictionary CCASSERT(!_dictStack.empty(), "The state is wrong!"); - ValueMap *preDict = _dictStack.top(); + ValueMap *preDict = _dictStack.top(); (*preDict)[_curKey] = Value(ValueMap()); - _curDict = &(*preDict)[_curKey].asValueMap(); + _curDict = &(*preDict)[_curKey].asValueMap(); } // record the dict state @@ -177,7 +176,7 @@ public: if (preState == SAX_DICT) { (*_curDict)[_curKey] = Value(ValueVector()); - _curArray = &(*_curDict)[_curKey].asValueVector(); + _curArray = &(*_curDict)[_curKey].asValueVector(); } else if (preState == SAX_ARRAY) { CCASSERT(!_arrayStack.empty(), "The state is wrong!"); ValueVector *preArray = _arrayStack.top(); @@ -192,10 +191,10 @@ public: } } - virtual void endElement(void *ctx, const char *name) override { + void endElement(void *ctx, const char *name) override { CC_UNUSED_PARAM(ctx); - SAXState curState = _stateStack.empty() ? SAX_DICT : _stateStack.top(); - const std::string sName((char *)name); + SAXState curState = _stateStack.empty() ? SAX_DICT : _stateStack.top(); + const std::string sName(const_cast(name)); if (sName == "dict") { _stateStack.pop(); _dictStack.pop(); @@ -222,19 +221,21 @@ public: } } else if (sName == "string" || sName == "integer" || sName == "real") { if (SAX_ARRAY == curState) { - if (sName == "string") + if (sName == "string") { _curArray->push_back(Value(_curValue)); - else if (sName == "integer") + } else if (sName == "integer") { _curArray->push_back(Value(atoi(_curValue.c_str()))); - else + } else { _curArray->push_back(Value(std::atof(_curValue.c_str()))); + } } else if (SAX_DICT == curState) { - if (sName == "string") + if (sName == "string") { (*_curDict)[_curKey] = Value(_curValue); - else if (sName == "integer") + } else if (sName == "integer") { (*_curDict)[_curKey] = Value(atoi(_curValue.c_str())); - else + } else { (*_curDict)[_curKey] = Value(std::atof(_curValue.c_str())); + } } _curValue.clear(); @@ -243,14 +244,14 @@ public: _state = SAX_NONE; } - virtual void textHandler(void *ctx, const char *ch, int len) override { + void textHandler(void *ctx, const char *ch, int len) override { CC_UNUSED_PARAM(ctx); if (_state == SAX_NONE) { return; } - SAXState curState = _stateStack.empty() ? SAX_DICT : _stateStack.top(); - const std::string text = std::string((char *)ch, len); + SAXState curState = _stateStack.empty() ? SAX_DICT : _stateStack.top(); + const std::string text = std::string(const_cast(ch), len); switch (_state) { case SAX_KEY: @@ -289,7 +290,7 @@ ValueMap FileUtils::getValueMapFromData(const char *filedata, int filesize) { ValueVector FileUtils::getValueVectorFromFile(const std::string &filename) { const std::string fullPath = fullPathForFilename(filename); - DictMaker tMaker; + DictMaker tMaker; return tMaker.arrayWithContentsOfFile(fullPath); } @@ -307,18 +308,19 @@ bool FileUtils::writeToFile(const ValueMap &dict, const std::string &fullPath) { } bool FileUtils::writeValueMapToFile(const ValueMap &dict, const std::string &fullPath) { - tinyxml2::XMLDocument *doc = new (std::nothrow) tinyxml2::XMLDocument(); - if (nullptr == doc) + auto *doc = new (std::nothrow) tinyxml2::XMLDocument(); + if (nullptr == doc) { return false; + } - tinyxml2::XMLDeclaration *declaration = doc->NewDeclaration("xml version=\"1.0\" encoding=\"UTF-8\""); + tinyxml2::XMLDeclaration *declaration = doc->NewDeclaration(R"(xml version="1.0" encoding="UTF-8")"); if (nullptr == declaration) { delete doc; return false; } doc->LinkEndChild(declaration); - tinyxml2::XMLElement *docType = doc->NewElement("!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\""); + tinyxml2::XMLElement *docType = doc->NewElement(R"(!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd")"); doc->LinkEndChild(docType); tinyxml2::XMLElement *rootEle = doc->NewElement("plist"); @@ -343,18 +345,19 @@ bool FileUtils::writeValueMapToFile(const ValueMap &dict, const std::string &ful } bool FileUtils::writeValueVectorToFile(const ValueVector &vecData, const std::string &fullPath) { - tinyxml2::XMLDocument *doc = new (std::nothrow) tinyxml2::XMLDocument(); - if (nullptr == doc) + auto *doc = new (std::nothrow) tinyxml2::XMLDocument(); + if (nullptr == doc) { return false; + } - tinyxml2::XMLDeclaration *declaration = doc->NewDeclaration("xml version=\"1.0\" encoding=\"UTF-8\""); + tinyxml2::XMLDeclaration *declaration = doc->NewDeclaration(R"(xml version="1.0" encoding="UTF-8")"); if (nullptr == declaration) { delete doc; return false; } doc->LinkEndChild(declaration); - tinyxml2::XMLElement *docType = doc->NewElement("!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\""); + tinyxml2::XMLElement *docType = doc->NewElement(R"(!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd")"); doc->LinkEndChild(docType); tinyxml2::XMLElement *rootEle = doc->NewElement("plist"); @@ -384,24 +387,24 @@ bool FileUtils::writeValueVectorToFile(const ValueVector &vecData, const std::st static tinyxml2::XMLElement *generateElementForObject(const Value &value, tinyxml2::XMLDocument *doc) { // object is String if (value.getType() == Value::Type::STRING) { - tinyxml2::XMLElement *node = doc->NewElement("string"); - tinyxml2::XMLText *content = doc->NewText(value.asString().c_str()); + tinyxml2::XMLElement *node = doc->NewElement("string"); + tinyxml2::XMLText * content = doc->NewText(value.asString().c_str()); node->LinkEndChild(content); return node; } // object is integer if (value.getType() == Value::Type::INTEGER) { - tinyxml2::XMLElement *node = doc->NewElement("integer"); - tinyxml2::XMLText *content = doc->NewText(value.asString().c_str()); + tinyxml2::XMLElement *node = doc->NewElement("integer"); + tinyxml2::XMLText * content = doc->NewText(value.asString().c_str()); node->LinkEndChild(content); return node; } // object is real if (value.getType() == Value::Type::FLOAT || value.getType() == Value::Type::DOUBLE) { - tinyxml2::XMLElement *node = doc->NewElement("real"); - tinyxml2::XMLText *content = doc->NewText(value.asString().c_str()); + tinyxml2::XMLElement *node = doc->NewElement("real"); + tinyxml2::XMLText * content = doc->NewText(value.asString().c_str()); node->LinkEndChild(content); return node; } @@ -413,12 +416,14 @@ static tinyxml2::XMLElement *generateElementForObject(const Value &value, tinyxm } // object is Array - if (value.getType() == Value::Type::VECTOR) + if (value.getType() == Value::Type::VECTOR) { return generateElementForArray(value.asValueVector(), doc); + } // object is Dictionary - if (value.getType() == Value::Type::MAP) + if (value.getType() == Value::Type::MAP) { return generateElementForDict(value.asValueMap(), doc); + } CC_LOG_DEBUG("This type cannot appear in property list"); return nullptr; @@ -437,8 +442,9 @@ static tinyxml2::XMLElement *generateElementForDict(const ValueMap &dict, tinyxm tmpNode->LinkEndChild(content); tinyxml2::XMLElement *element = generateElementForObject(iter.second, doc); - if (element) + if (element) { rootNode->LinkEndChild(element); + } } return rootNode; } @@ -451,8 +457,9 @@ static tinyxml2::XMLElement *generateElementForArray(const ValueVector &array, t for (const auto &value : array) { tinyxml2::XMLElement *element = generateElementForObject(value, pDoc); - if (element) + if (element) { rootNode->LinkEndChild(element); + } } return rootNode; } @@ -460,24 +467,22 @@ static tinyxml2::XMLElement *generateElementForArray(const ValueVector &array, t #else /* The subclass FileUtilsApple should override these two method. */ -ValueMap FileUtils::getValueMapFromFile(const std::string &filename) { return ValueMap(); } -ValueMap FileUtils::getValueMapFromData(const char *filedata, int filesize) { return ValueMap(); } +ValueMap FileUtils::getValueMapFromFile(const std::string &filename) { return ValueMap(); } +ValueMap FileUtils::getValueMapFromData(const char *filedata, int filesize) { return ValueMap(); } ValueVector FileUtils::getValueVectorFromFile(const std::string &filename) { return ValueVector(); } -bool FileUtils::writeToFile(const ValueMap &dict, const std::string &fullPath) { return false; } +bool FileUtils::writeToFile(const ValueMap &dict, const std::string &fullPath) { return false; } #endif /* (CC_PLATFORM != CC_PLATFORM_MAC_IOS) && (CC_PLATFORM != CC_PLATFORM_MAC_OSX) */ // Implement FileUtils -FileUtils *FileUtils::s_sharedFileUtils = nullptr; +FileUtils *FileUtils::s_sharedFileUtils = nullptr; //NOLINT void FileUtils::destroyInstance() { CC_SAFE_DELETE(s_sharedFileUtils); } void FileUtils::setDelegate(FileUtils *delegate) { - if (s_sharedFileUtils) - delete s_sharedFileUtils; - + delete s_sharedFileUtils; s_sharedFileUtils = delegate; } @@ -485,12 +490,12 @@ FileUtils::FileUtils() : _writablePath("") { } -FileUtils::~FileUtils() { -} +FileUtils::~FileUtils() = default; bool FileUtils::writeStringToFile(const std::string &dataStr, const std::string &fullPath) { - Data data; - data.fastSet((unsigned char *)dataStr.c_str(), dataStr.size()); + Data data; + char *dataP = const_cast(dataStr.data()); + data.fastSet(reinterpret_cast(dataP), dataStr.size()); bool rv = writeDataToFile(data, fullPath); @@ -500,7 +505,7 @@ bool FileUtils::writeStringToFile(const std::string &dataStr, const std::string } bool FileUtils::writeDataToFile(const Data &data, const std::string &fullPath) { - size_t size = 0; + size_t size = 0; const char *mode = "wb"; CCASSERT(!fullPath.empty() && data.getSize() != 0, "Invalid parameters."); @@ -517,7 +522,7 @@ bool FileUtils::writeDataToFile(const Data &data, const std::string &fullPath) { fclose(fp); return true; - } while (0); + } while (false); return false; } @@ -544,18 +549,21 @@ Data FileUtils::getDataFromFile(const std::string &filename) { } FileUtils::Status FileUtils::getContents(const std::string &filename, ResizableBuffer *buffer) { - if (filename.empty()) + if (filename.empty()) { return Status::NotExists; + } auto fs = FileUtils::getInstance(); std::string fullPath = fs->fullPathForFilename(filename); - if (fullPath.empty()) + if (fullPath.empty()) { return Status::NotExists; + } FILE *fp = fopen(fs->getSuitableFOpen(fullPath).c_str(), "rb"); - if (!fp) + if (!fp) { return Status::OpenFailed; + } #if defined(_MSC_VER) auto descriptor = _fileno(fp); @@ -583,8 +591,8 @@ FileUtils::Status FileUtils::getContents(const std::string &filename, ResizableB unsigned char *FileUtils::getFileDataFromZip(const std::string &zipFilePath, const std::string &filename, ssize_t *size) { unsigned char *buffer = nullptr; - unzFile file = nullptr; - *size = 0; + unzFile file = nullptr; + *size = 0; do { CC_BREAK_IF(zipFilePath.empty()); @@ -600,7 +608,7 @@ unsigned char *FileUtils::getFileDataFromZip(const std::string &zipFilePath, con #endif CC_BREAK_IF(UNZ_OK != ret); - char filePathA[260]; + char filePathA[260]; unz_file_info fileInfo; ret = unzGetCurrentFileInfo(file, &fileInfo, filePathA, sizeof(filePathA), nullptr, 0, nullptr, 0); CC_BREAK_IF(UNZ_OK != ret); @@ -608,13 +616,13 @@ unsigned char *FileUtils::getFileDataFromZip(const std::string &zipFilePath, con ret = unzOpenCurrentFile(file); CC_BREAK_IF(UNZ_OK != ret); - buffer = (unsigned char *)malloc(fileInfo.uncompressed_size); + buffer = static_cast(malloc(fileInfo.uncompressed_size)); int CC_UNUSED readedSize = unzReadCurrentFile(file, buffer, static_cast(fileInfo.uncompressed_size)); CCASSERT(readedSize == 0 || readedSize == (int)fileInfo.uncompressed_size, "the file size is wrong"); *size = fileInfo.uncompressed_size; unzCloseCurrentFile(file); - } while (0); + } while (false); if (file) { unzClose(file); @@ -625,16 +633,16 @@ unsigned char *FileUtils::getFileDataFromZip(const std::string &zipFilePath, con std::string FileUtils::getPathForFilename(const std::string &filename, const std::string &searchPath) const { std::string file = filename; - std::string file_path = ""; - size_t pos = filename.find_last_of("/"); + std::string filePath; + size_t pos = filename.find_last_of('/'); if (pos != std::string::npos) { - file_path = filename.substr(0, pos + 1); - file = filename.substr(pos + 1); + filePath = filename.substr(0, pos + 1); + file = filename.substr(pos + 1); } // searchPath + file_path std::string path = searchPath; - path += file_path; + path += filePath; path = getFullPathForDirectoryAndFilename(path, file); @@ -707,7 +715,7 @@ void FileUtils::setDefaultResourceRootPath(const std::string &path) { void FileUtils::setSearchPaths(const std::vector &searchPaths) { bool existDefaultRootPath = false; - _originalSearchPaths = searchPaths; + _originalSearchPaths = searchPaths; _fullPathCache.clear(); _searchPathArray.clear(); @@ -735,10 +743,11 @@ void FileUtils::setSearchPaths(const std::vector &searchPaths) { } } -void FileUtils::addSearchPath(const std::string &searchpath, const bool front) { +void FileUtils::addSearchPath(const std::string &searchpath, bool front) { std::string prefix; - if (!isAbsolutePath(searchpath)) + if (!isAbsolutePath(searchpath)) { prefix = _defaultResRootPath; + } std::string path = prefix + searchpath; if (!path.empty() && path[path.length() - 1] != '/') { @@ -756,7 +765,7 @@ void FileUtils::addSearchPath(const std::string &searchpath, const bool front) { std::string FileUtils::getFullPathForDirectoryAndFilename(const std::string &directory, const std::string &filename) const { // get directory+filename, safely adding '/' as necessary std::string ret = directory; - if (directory.size() && directory[directory.size() - 1] != '/') { + if (!directory.empty() && directory[directory.size() - 1] != '/') { ret += '/'; } ret += filename; @@ -772,13 +781,9 @@ std::string FileUtils::getFullPathForDirectoryAndFilename(const std::string &dir bool FileUtils::isFileExist(const std::string &filename) const { if (isAbsolutePath(filename)) { return isFileExistInternal(normalizePath(filename)); - } else { - std::string fullpath = fullPathForFilename(filename); - if (fullpath.empty()) - return false; - else - return true; } + std::string fullpath = fullPathForFilename(filename); + return !fullpath.empty(); } bool FileUtils::isAbsolutePath(const std::string &path) const { @@ -811,7 +816,7 @@ bool FileUtils::isDirectoryExist(const std::string &dirPath) const { } std::vector FileUtils::listFiles(const std::string &dirPath) const { - std::string fullpath = fullPathForFilename(dirPath); + std::string fullpath = fullPathForFilename(dirPath); std::vector files; if (isDirectoryExist(fullpath)) { tinydir_dir dir; @@ -835,7 +840,7 @@ std::vector FileUtils::listFiles(const std::string &dirPath) const #ifdef UNICODE std::wstring path = file.path; - length = WideCharToMultiByte(CP_UTF8, 0, &path[0], (int)path.size(), NULL, 0, NULL, NULL); + length = WideCharToMultiByte(CP_UTF8, 0, &path[0], (int)path.size(), NULL, 0, NULL, NULL); std::string filepath; if (length > 0) { filepath.resize(length); @@ -884,7 +889,7 @@ void FileUtils::listFilesRecursively(const std::string &dirPath, std::vector 0) { filepath.resize(length); @@ -957,9 +962,9 @@ long FileUtils::getFileSize(const std::string &filepath) { #else // default implements for unix like os - #include - #include #include + #include + #include // android doesn't have ftw.h #if (CC_PLATFORM != CC_PLATFORM_ANDROID) @@ -977,20 +982,22 @@ bool FileUtils::isDirectoryExistInternal(const std::string &dirPath) const { bool FileUtils::createDirectory(const std::string &path) { CCASSERT(!path.empty(), "Invalid path"); - if (isDirectoryExist(path)) + if (isDirectoryExist(path)) { return true; + } // Split the path - size_t start = 0; - size_t found = path.find_first_of("/\\", start); - std::string subpath; + size_t start = 0; + size_t found = path.find_first_of("/\\", start); + std::string subpath; std::vector dirs; if (found != std::string::npos) { while (true) { subpath = path.substr(start, found - start + 1); - if (!subpath.empty()) + if (!subpath.empty()) { dirs.push_back(subpath); + } start = found + 1; found = path.find_first_of("/\\", start); if (found == std::string::npos) { @@ -1002,7 +1009,7 @@ bool FileUtils::createDirectory(const std::string &path) { } } - DIR *dir = NULL; + DIR *dir = nullptr; // Create path recursively subpath = ""; @@ -1029,11 +1036,12 @@ bool FileUtils::createDirectory(const std::string &path) { namespace { #if (CC_PLATFORM != CC_PLATFORM_ANDROID) -int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) { +int unlinkCb(const char *fpath, const struct stat * /*sb*/, int /*typeflag*/, struct FTW * /*ftwbuf*/) { int rv = remove(fpath); - if (rv) + if (rv) { perror(fpath); + } return rv; } @@ -1044,18 +1052,12 @@ bool FileUtils::removeDirectory(const std::string &path) { #if !defined(CC_TARGET_OS_TVOS) #if (CC_PLATFORM != CC_PLATFORM_ANDROID) - if (nftw(path.c_str(), unlink_cb, 64, FTW_DEPTH | FTW_PHYS) == -1) - return false; - else - return true; + return nftw(path.c_str(), unlinkCb, 64, FTW_DEPTH | FTW_PHYS) != -1; #else std::string command = "rm -r "; // Path may include space. command += "\"" + path + "\""; - if (system(command.c_str()) >= 0) - return true; - else - return false; + return system(command.c_str()) >= 0; #endif // (CC_PLATFORM != CC_PLATFORM_ANDROID) #else @@ -1064,11 +1066,7 @@ bool FileUtils::removeDirectory(const std::string &path) { } bool FileUtils::removeFile(const std::string &path) { - if (remove(path.c_str())) { - return false; - } else { - return true; - } + return remove(path.c_str()) == 0; } bool FileUtils::renameFile(const std::string &oldfullpath, const std::string &newfullpath) { @@ -1096,14 +1094,15 @@ std::string FileUtils::getSuitableFOpen(const std::string &filenameUtf8) const { return filenameUtf8; } -long FileUtils::getFileSize(const std::string &filepath) { +long FileUtils::getFileSize(const std::string &filepath) { //NOLINT(google-runtime-int) CCASSERT(!filepath.empty(), "Invalid path"); std::string fullpath = filepath; if (!isAbsolutePath(filepath)) { fullpath = fullPathForFilename(filepath); - if (fullpath.empty()) + if (fullpath.empty()) { return 0; + } } struct stat info; @@ -1114,15 +1113,14 @@ long FileUtils::getFileSize(const std::string &filepath) { if (result != 0) { // Failed return -1; - } else { - return (long)(info.st_size); } + return static_cast(info.st_size); //NOLINT(google-runtime-int) } #endif std::string FileUtils::getFileExtension(const std::string &filePath) const { std::string fileExtension; - size_t pos = filePath.find_last_of('.'); + size_t pos = filePath.find_last_of('.'); if (pos != std::string::npos) { fileExtension = filePath.substr(pos, filePath.length()); @@ -1140,7 +1138,7 @@ void FileUtils::valueVectorCompact(ValueVector &valueVector) { std::string FileUtils::getFileDir(const std::string &path) const { std::string ret; - size_t pos = path.rfind("/"); + size_t pos = path.rfind('/'); if (pos != std::string::npos) { ret = path.substr(0, pos); } @@ -1150,7 +1148,7 @@ std::string FileUtils::getFileDir(const std::string &path) const { return ret; } -std::string FileUtils::normalizePath(const std::string &path) const { +std::string FileUtils::normalizePath(const std::string &path) const { //NOLINT(readability-convert-member-functions-to-static) std::string ret; // Normalize: remove . and .. ret = std::regex_replace(path, std::regex("/\\./"), "/"); @@ -1158,9 +1156,10 @@ std::string FileUtils::normalizePath(const std::string &path) const { size_t pos; while ((pos = ret.find("..")) != std::string::npos && pos > 2) { - size_t prevSlash = ret.rfind("/", pos - 2); - if (prevSlash == std::string::npos) + size_t prevSlash = ret.rfind('/', pos - 2); + if (prevSlash == std::string::npos) { break; + } ret = ret.replace(prevSlash, pos - prevSlash + 2, ""); } diff --git a/native/cocos/platform/FileUtils.h b/native/cocos/platform/FileUtils.h index 20b780ec0c..399ffe3179 100644 --- a/native/cocos/platform/FileUtils.h +++ b/native/cocos/platform/FileUtils.h @@ -25,17 +25,16 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef __CC_FILEUTILS_H__ -#define __CC_FILEUTILS_H__ +#pragma once #include -#include -#include #include +#include +#include +#include "base/Data.h" #include "base/Macros.h" #include "base/Value.h" -#include "base/Data.h" namespace cc { @@ -46,9 +45,9 @@ namespace cc { class ResizableBuffer { public: - virtual ~ResizableBuffer() {} - virtual void resize(size_t size) = 0; - virtual void *buffer() const = 0; + ~ResizableBuffer() = default; + virtual void resize(size_t size) = 0; + virtual void *buffer() const = 0; }; template @@ -56,62 +55,55 @@ class ResizableBufferAdapter {}; template class ResizableBufferAdapter> : public ResizableBuffer { - typedef std::basic_string BufferType; + using BufferType = std::basic_string; BufferType *_buffer; public: explicit ResizableBufferAdapter(BufferType *buffer) : _buffer(buffer) {} - virtual void resize(size_t size) override { + void resize(size_t size) override { _buffer->resize((size + sizeof(CharT) - 1) / sizeof(CharT)); } - virtual void *buffer() const override { + void *buffer() const override { // can not invoke string::front() if it is empty - - if (_buffer->empty()) - return nullptr; - else - return &_buffer->front(); + return _buffer->empty() ? nullptr : &_buffer->front(); } }; template class ResizableBufferAdapter> : public ResizableBuffer { - typedef std::vector BufferType; + using BufferType = std::vector; BufferType *_buffer; public: explicit ResizableBufferAdapter(BufferType *buffer) : _buffer(buffer) {} - virtual void resize(size_t size) override { + void resize(size_t size) override { _buffer->resize((size + sizeof(T) - 1) / sizeof(T)); } - virtual void *buffer() const override { + void *buffer() const override { // can not invoke vector::front() if it is empty - - if (_buffer->empty()) - return nullptr; - else - return &_buffer->front(); + return _buffer->empty() ? nullptr : &_buffer->front(); } }; template <> -class ResizableBufferAdapter : public ResizableBuffer { - typedef Data BufferType; +class ResizableBufferAdapter : public ResizableBuffer { + using BufferType = cc::Data; BufferType *_buffer; public: explicit ResizableBufferAdapter(BufferType *buffer) : _buffer(buffer) {} - virtual void resize(size_t size) override { - size_t oldSize = static_cast(_buffer->getSize()); + void resize(size_t size) override { + auto oldSize = static_cast(_buffer->getSize()); if (oldSize != size) { // need to take buffer ownership for outer memory control - auto old = _buffer->takeBuffer(); + auto old = _buffer->takeBuffer(); void *buffer = realloc(old, size); - if (buffer) - _buffer->fastSet((unsigned char *)buffer, size); + if (buffer) { + _buffer->fastSet(static_cast(buffer), size); + } } } - virtual void *buffer() const override { + void *buffer() const override { return _buffer->getBytes(); } }; @@ -168,13 +160,13 @@ public: virtual Data getDataFromFile(const std::string &filename); enum class Status { - OK = 0, - NotExists = 1, // File not exists - OpenFailed = 2, // Open file failed. - ReadFailed = 3, // Read failed - NotInitialized = 4, // FileUtils is not initializes - TooLarge = 5, // The file is too large (great than 2^32-1) - ObtainSizeFailed = 6 // Failed to obtain the file size. + OK = 0, + NotExists = 1, //NOLINT, File not exists + OpenFailed = 2, //NOLINT, Open file failed. + ReadFailed = 3, //NOLINT, Read failed + NotInitialized = 4, //NOLINT, FileUtils is not initializes + TooLarge = 5, //NOLINT, The file is too large (great than 2^32-1) + ObtainSizeFailed = 6 //NOLINT, Failed to obtain the file size. }; /** @@ -346,7 +338,7 @@ public: * * @since v2.1 */ - void addSearchPath(const std::string &path, const bool front = false); + void addSearchPath(const std::string &path, bool front = false); /** * Gets the array of search paths. @@ -550,7 +542,7 @@ public: * @param filepath The path of the file, it could be a relative or absolute path. * @return The file size. */ - virtual long getFileSize(const std::string &filepath); + virtual long getFileSize(const std::string &filepath); //NOLINT(google-runtime-int) /** Returns the full path cache. */ const std::unordered_map &getFullPathCache() const { return _fullPathCache; } @@ -643,18 +635,16 @@ protected: /** * The singleton pointer of FileUtils. */ - static FileUtils *s_sharedFileUtils; + static FileUtils *s_sharedFileUtils; //NOLINT(readability-identifier-naming) /** * Remove null value key (for iOS) */ - virtual void valueMapCompact(ValueMap &valueMap); - virtual void valueVectorCompact(ValueVector &valueVector); + virtual void valueMapCompact(ValueMap &valueMap); //NOLINT(google-runtime-references) + virtual void valueVectorCompact(ValueVector &valueVector); //NOLINT(google-runtime-references) }; // end of support group /** @} */ } // namespace cc - -#endif // __CC_FILEUTILS_H__ diff --git a/native/cocos/platform/Image.cpp b/native/cocos/platform/Image.cpp index a66e52a6f2..7fe9ea6207 100644 --- a/native/cocos/platform/Image.cpp +++ b/native/cocos/platform/Image.cpp @@ -26,10 +26,11 @@ ****************************************************************************/ #include "Image.h" -#include "base/Config.h" // CC_USE_JPEG, CC_USE_WEBP #include #include #include +#include "base/Config.h" // CC_USE_JPEG, CC_USE_WEBP + #if CC_USE_JPEG #include "jpeg/jpeglib.h" #endif // CC_USE_JPEG @@ -41,7 +42,11 @@ extern "C" { #if CC_USE_PNG - #include "png/png.h" + #if __OHOS__ + #include "png.h" + #else + #include "png/png.h" + #endif #endif //CC_USE_PNG #include "base/etc1.h" diff --git a/native/cocos/platform/android/Application-android.cpp b/native/cocos/platform/android/Application-android.cpp index 6e2da1ee88..62d25b0ad0 100644 --- a/native/cocos/platform/android/Application-android.cpp +++ b/native/cocos/platform/android/Application-android.cpp @@ -25,16 +25,16 @@ THE SOFTWARE. ****************************************************************************/ -#include "platform/Application.h" -#include #include -#include "platform/android/jni/JniImp.h" -#include "base/Scheduler.h" +#include #include "audio/include/AudioEngine.h" -#include "cocos/bindings/jswrapper/SeApi.h" +#include "base/Scheduler.h" #include "cocos/bindings/event/EventDispatcher.h" -#include "platform/android/jni/JniHelper.h" +#include "cocos/bindings/jswrapper/SeApi.h" +#include "platform/Application.h" #include "platform/android/jni/JniCocosActivity.h" +#include "platform/java/jni/JniHelper.h" +#include "platform/java/jni/JniImp.h" #include "pipeline/Define.h" #include "pipeline/RenderPipeline.h" @@ -46,7 +46,7 @@ // IDEA: using ndk-r10c will cause the next function could not be found. It may be a bug of ndk-r10c. // Here is the workaround method to fix the problem. #ifdef __aarch64__ -extern "C" size_t __ctype_get_mb_cur_max(void) { +extern "C" size_t __ctype_get_mb_cur_max(void) { //NOLINT return (size_t)sizeof(wchar_t); } #endif @@ -55,23 +55,23 @@ namespace cc { namespace { -bool setCanvasCallback(se::Object *global) { - auto viewLogicalSize = cc::Application::getInstance()->getViewLogicalSize(); +bool setCanvasCallback(se::Object * /*global*/) { + auto viewLogicalSize = cc::Application::getInstance()->getViewLogicalSize(); se::AutoHandleScope scope; - se::ScriptEngine *se = se::ScriptEngine::getInstance(); - char commandBuf[200] = {0}; + se::ScriptEngine * se = se::ScriptEngine::getInstance(); + char commandBuf[200] = {0}; sprintf(commandBuf, "window.innerWidth = %d; window.innerHeight = %d; window.windowHandler = 0x%" PRIxPTR ";", - (int)(viewLogicalSize.x), - (int)(viewLogicalSize.y), - (uintptr_t)cc::cocosApp.window); + static_cast(viewLogicalSize.x), + static_cast(viewLogicalSize.y), + reinterpret_cast(cc::cocosApp.window)); se->evalString(commandBuf); gfx::DeviceInfo deviceInfo; - deviceInfo.windowHandle = (uintptr_t)cc::cocosApp.window; - deviceInfo.width = viewLogicalSize.x; - deviceInfo.height = viewLogicalSize.y; - deviceInfo.nativeWidth = viewLogicalSize.x; - deviceInfo.nativeHeight = viewLogicalSize.y; + deviceInfo.windowHandle = reinterpret_cast(cc::cocosApp.window); + deviceInfo.width = viewLogicalSize.x; + deviceInfo.height = viewLogicalSize.y; + deviceInfo.nativeWidth = viewLogicalSize.x; + deviceInfo.nativeHeight = viewLogicalSize.y; deviceInfo.bindingMappingInfo = pipeline::bindingMappingInfo; gfx::DeviceManager::create(deviceInfo); @@ -81,14 +81,14 @@ bool setCanvasCallback(se::Object *global) { } // namespace -Application *Application::_instance = nullptr; -std::shared_ptr Application::_scheduler = nullptr; +Application * Application::_instance = nullptr; //NOLINT(readability-identifier-naming) +std::shared_ptr Application::_scheduler = nullptr; //NOLINT(readability-identifier-naming) Application::Application(int width, int height) { Application::_instance = this; - _scheduler = std::make_shared(); - _viewLogicalSize.x = width; - _viewLogicalSize.y = height; + _scheduler = std::make_shared(); + _viewLogicalSize.x = static_cast(width); + _viewLogicalSize.y = static_cast(height); } Application::~Application() { @@ -122,28 +122,30 @@ void Application::onResume() { } void Application::setPreferredFramesPerSecond(int fps) { - if (fps == 0) + if (fps == 0) { return; + } - _fps = fps; - _prefererredNanosecondsPerFrame = (long)(1.0 / _fps * NANOSECONDS_PER_SECOND); + _fps = fps; + _prefererredNanosecondsPerFrame = static_cast(1.0 / _fps * NANOSECONDS_PER_SECOND); } -std::string Application::getCurrentLanguageCode() const { +std::string Application::getCurrentLanguageCode() const { //NOLINT(readability-convert-member-functions-to-static) + return getCurrentLanguageCodeJNI(); } -bool Application::isDisplayStats() { +bool Application::isDisplayStats() { //NOLINT(readability-convert-member-functions-to-static) se::AutoHandleScope hs; - se::Value ret; - char commandBuf[100] = "cc.debug.isDisplayStats();"; + se::Value ret; + char commandBuf[100] = "cc.debug.isDisplayStats();"; se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret); return ret.toBoolean(); } -void Application::setDisplayStats(bool isShow) { +void Application::setDisplayStats(bool isShow) { //NOLINT(readability-convert-member-functions-to-static) se::AutoHandleScope hs; - char commandBuf[100] = {0}; + char commandBuf[100] = {0}; sprintf(commandBuf, "cc.debug.setDisplayStats(%s);", isShow ? "true" : "false"); se::ScriptEngine::getInstance()->evalString(commandBuf); } @@ -151,10 +153,10 @@ void Application::setDisplayStats(bool isShow) { void Application::setCursorEnabled(bool value) { } -Application::LanguageType Application::getCurrentLanguage() const { - std::string languageName = getCurrentLanguageJNI(); - const char *pLanguageName = languageName.c_str(); - LanguageType ret = LanguageType::ENGLISH; +Application::LanguageType Application::getCurrentLanguage() const { //NOLINT(readability-convert-member-functions-to-static) + std::string languageName = getCurrentLanguageJNI(); + const char * pLanguageName = languageName.c_str(); + LanguageType ret = LanguageType::ENGLISH; if (0 == strcmp("zh", pLanguageName)) { ret = LanguageType::CHINESE; @@ -198,19 +200,19 @@ Application::LanguageType Application::getCurrentLanguage() const { return ret; } -Application::Platform Application::getPlatform() const { +Application::Platform Application::getPlatform() const { //NOLINT(readability-convert-member-functions-to-static) return Platform::ANDROIDOS; } -bool Application::openURL(const std::string &url) { +bool Application::openURL(const std::string &url) { //NOLINT(readability-convert-member-functions-to-static) return openURLJNI(url); } -void Application::copyTextToClipboard(const std::string &text) { +void Application::copyTextToClipboard(const std::string &text) { //NOLINT(readability-convert-member-functions-to-static) copyTextToClipboardJNI(text); } -std::string Application::getSystemVersion() { +std::string Application::getSystemVersion() { //NOLINT(readability-convert-member-functions-to-static) return getSystemVersionJNI(); } diff --git a/native/cocos/platform/android/Device-android.cpp b/native/cocos/platform/android/Device-android.cpp index 0f310a894d..deb82b27b0 100644 --- a/native/cocos/platform/android/Device-android.cpp +++ b/native/cocos/platform/android/Device-android.cpp @@ -25,27 +25,25 @@ THE SOFTWARE. ****************************************************************************/ -#if CC_PLATFORM == CC_PLATFORM_ANDROID +#include +#include +#include +#include +#include +#include +#include "base/UTF8.h" +#include "platform/Device.h" +#include "platform/FileUtils.h" +#include "platform/android/jni/JniCocosActivity.h" +#include "platform/java/jni/JniHelper.h" - #include "platform/Device.h" - #include - #include - #include - #include - #include - #include - #include "platform/android/jni/JniCocosActivity.h" - #include "platform/FileUtils.h" - #include "base/UTF8.h" - #include "platform/android/jni/JniHelper.h" +#ifndef JCLS_HELPER + #define JCLS_HELPER "com/cocos/lib/CocosHelper" +#endif - #ifndef JCLS_HELPER - constexpr auto JCLS_HELPER = "com/cocos/lib/CocosHelper"; - #endif - - #ifndef JCLS_SENSOR - constexpr auto JCLS_SENSOR = "com/cocos/lib/CocosSensorHandler"; - #endif +#ifndef JCLS_SENSOR + #define JCLS_SENSOR "com/cocos/lib/CocosSensorHandler" +#endif namespace { cc::Device::MotionValue motionValue; @@ -70,7 +68,7 @@ int Device::getDPI() { int32_t density = AConfiguration_getDensity(config); AConfiguration_delete(config); const int stdDpi = 160; - dpi = density * stdDpi; + dpi = density * stdDpi; } return dpi; } @@ -95,7 +93,7 @@ const Device::MotionValue &Device::getDeviceMotionValue() { motionValue.accelerationZ = v[5]; motionValue.rotationRateAlpha = v[6]; - motionValue.rotationRateBeta = v[7]; + motionValue.rotationRateBeta = v[7]; motionValue.rotationRateGamma = v[8]; return motionValue; @@ -112,7 +110,7 @@ Device::Orientation Device::getDeviceOrientation() { return Orientation::PORTRAIT_UPSIDE_DOWN; case ROTATION_270: return Orientation::LANDSCAPE_LEFT; - default: + default: break; } return Orientation::PORTRAIT; @@ -137,7 +135,7 @@ float Device::getBatteryLevel() { } Device::NetworkType Device::getNetworkType() { - return (Device::NetworkType)JniHelper::callStaticIntMethod(JCLS_HELPER, "getNetworkType"); + return static_cast(JniHelper::callStaticIntMethod(JCLS_HELPER, "getNetworkType")); } cc::Vec4 Device::getSafeAreaEdge() { @@ -149,5 +147,3 @@ float Device::getDevicePixelRatio() { return 1; } } // namespace cc - -#endif // CC_PLATFORM == CC_PLATFORM_ANDROID diff --git a/native/cocos/platform/android/FileUtils-android.cpp b/native/cocos/platform/android/FileUtils-android.cpp index bd82f16c2e..b11caff56c 100644 --- a/native/cocos/platform/android/FileUtils-android.cpp +++ b/native/cocos/platform/android/FileUtils-android.cpp @@ -28,14 +28,14 @@ #if CC_PLATFORM == CC_PLATFORM_ANDROID #include "platform/android/FileUtils-android.h" - #include "platform/android/jni/JniHelper.h" - #include "platform/android/jni/JniImp.h" + #include + #include #include "android/asset_manager.h" #include "android/asset_manager_jni.h" - #include "base/ZipUtils.h" #include "base/Log.h" - #include - #include + #include "base/ZipUtils.h" + #include "platform/java/jni/JniHelper.h" + #include "platform/java/jni/JniImp.h" #define LOG_TAG "FileUtils-android.cpp" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) @@ -49,7 +49,7 @@ namespace cc { AAssetManager *FileUtilsAndroid::assetmanager = nullptr; -ZipFile *FileUtilsAndroid::obbfile = nullptr; +ZipFile * FileUtilsAndroid::obbfile = nullptr; void FileUtilsAndroid::setassetmanager(AAssetManager *a) { if (nullptr == a) { @@ -72,8 +72,7 @@ FileUtils *FileUtils::getInstance() { return s_sharedFileUtils; } -FileUtilsAndroid::FileUtilsAndroid() { -} +FileUtilsAndroid::FileUtilsAndroid() = default; FileUtilsAndroid::~FileUtilsAndroid() { if (obbfile) { @@ -127,12 +126,12 @@ bool FileUtilsAndroid::isFileExistInternal(const std::string &strFilePath) const return bFound; } -bool FileUtilsAndroid::isDirectoryExistInternal(const std::string &dirPath_) const { - if (dirPath_.empty()) { +bool FileUtilsAndroid::isDirectoryExistInternal(const std::string &testDirPath) const { + if (testDirPath.empty()) { return false; } - std::string dirPath = dirPath_; + std::string dirPath = testDirPath; if (dirPath[dirPath.length() - 1] == '/') { dirPath[dirPath.length() - 1] = '\0'; } @@ -169,25 +168,25 @@ bool FileUtilsAndroid::isAbsolutePath(const std::string &strPath) const { // 1) Files in APK, e.g. assets/path/path/file.png // 2) Files not in APK, e.g. /data/data/org.cocos2dx.hellocpp/cache/path/path/file.png, or /sdcard/path/path/file.png. // So these two situations need to be checked on Android. - if (strPath[0] == '/' || strPath.find(ASSETS_FOLDER_NAME) == 0) { - return true; - } - return false; + return strPath[0] == '/' || strPath.find(ASSETS_FOLDER_NAME) == 0; } FileUtils::Status FileUtilsAndroid::getContents(const std::string &filename, ResizableBuffer *buffer) { - if (filename.empty()) + if (filename.empty()) { return FileUtils::Status::NotExists; + } std::string fullPath = fullPathForFilename(filename); - if (fullPath.empty()) + if (fullPath.empty()) { return FileUtils::Status::NotExists; + } - if (fullPath[0] == '/') + if (fullPath[0] == '/') { return FileUtils::getContents(fullPath, buffer); + } std::string relativePath; - size_t position = fullPath.find(ASSETS_FOLDER_NAME); + size_t position = fullPath.find(ASSETS_FOLDER_NAME); if (0 == position) { // "@assets/" is at the beginning of the path and we don't want it relativePath += fullPath.substr(strlen(ASSETS_FOLDER_NAME)); @@ -196,8 +195,9 @@ FileUtils::Status FileUtilsAndroid::getContents(const std::string &filename, Res } if (obbfile) { - if (obbfile->getFileData(relativePath, buffer)) + if (obbfile->getFileData(relativePath, buffer)) { return FileUtils::Status::OK; + } } if (nullptr == assetmanager) { @@ -218,8 +218,9 @@ FileUtils::Status FileUtilsAndroid::getContents(const std::string &filename, Res AAsset_close(asset); if (readsize < size) { - if (readsize >= 0) + if (readsize >= 0) { buffer->resize(readsize); + } return FileUtils::Status::ReadFailed; } @@ -229,16 +230,14 @@ FileUtils::Status FileUtilsAndroid::getContents(const std::string &filename, Res std::string FileUtilsAndroid::getWritablePath() const { // Fix for Nexus 10 (Android 4.2 multi-user environment) // the path is retrieved through Java Context.getCacheDir() method - std::string dir(""); + std::string dir; std::string tmp = JniHelper::callStaticStringMethod(JCLS_HELPER, "getWritablePath"); if (tmp.length() > 0) { dir.append(tmp).append("/"); - return dir; - } else { - return ""; } + return ""; } } // namespace cc diff --git a/native/cocos/platform/android/FileUtils-android.h b/native/cocos/platform/android/FileUtils-android.h index 08771429c7..6b69143512 100644 --- a/native/cocos/platform/android/FileUtils-android.h +++ b/native/cocos/platform/android/FileUtils-android.h @@ -23,19 +23,15 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -****************************************************************************/ + ****************************************************************************/ +#pragma once -#ifndef __CC_FILEUTILS_ANDROID_H__ -#define __CC_FILEUTILS_ANDROID_H__ - -#if CC_PLATFORM == CC_PLATFORM_ANDROID - - #include "platform/FileUtils.h" - #include "base/Macros.h" - #include - #include - #include "jni.h" - #include "android/asset_manager.h" +#include +#include +#include "android/asset_manager.h" +#include "base/Macros.h" +#include "jni.h" +#include "platform/FileUtils.h" namespace cc { @@ -56,32 +52,28 @@ public: * @js NA * @lua NA */ - virtual ~FileUtilsAndroid(); + ~FileUtilsAndroid() override; - static void setassetmanager(AAssetManager *a); + static void setassetmanager(AAssetManager *a); static AAssetManager *getAssetManager() { return assetmanager; } - static ZipFile *getObbFile() { return obbfile; } + static ZipFile * getObbFile() { return obbfile; } /* override functions */ - bool init() override; - virtual FileUtils::Status getContents(const std::string &filename, ResizableBuffer *buffer) override; + bool init() override; + FileUtils::Status getContents(const std::string &filename, ResizableBuffer *buffer) override; - virtual std::string getWritablePath() const override; - virtual bool isAbsolutePath(const std::string &strPath) const override; + std::string getWritablePath() const override; + bool isAbsolutePath(const std::string &strPath) const override; private: - virtual bool isFileExistInternal(const std::string &strFilePath) const override; - virtual bool isDirectoryExistInternal(const std::string &dirPath) const override; + bool isFileExistInternal(const std::string &strFilePath) const override; + bool isDirectoryExistInternal(const std::string &dirPath) const override; static AAssetManager *assetmanager; - static ZipFile *obbfile; + static ZipFile * obbfile; }; // end of platform group /// @} } // namespace cc - -#endif // CC_PLATFORM == CC_PLATFORM_ANDROID - -#endif // __CC_FILEUTILS_ANDROID_H__ diff --git a/native/cocos/platform/android/java/src/com/cocos/lib/CocosActivity.java b/native/cocos/platform/android/java/src/com/cocos/lib/CocosActivity.java index cd0a6b3e03..3f09ca06d4 100644 --- a/native/cocos/platform/android/java/src/com/cocos/lib/CocosActivity.java +++ b/native/cocos/platform/android/java/src/com/cocos/lib/CocosActivity.java @@ -59,7 +59,7 @@ public class CocosActivity extends Activity implements SurfaceHolder.Callback { private CocosSensorHandler mSensorHandler; - private native void onCreateNative(Activity activity, AssetManager assetManager, String obbPath, int sdkVersion); + private native void onCreateNative(Activity activity, AssetManager resourceManager, String obbPath, int sdkVersion); private native void onSurfaceCreatedNative(Surface surface); diff --git a/native/cocos/platform/android/java/src/com/cocos/lib/CocosVideoView.java b/native/cocos/platform/android/java/src/com/cocos/lib/CocosVideoView.java index a5fad59bf5..636897f5e8 100644 --- a/native/cocos/platform/android/java/src/com/cocos/lib/CocosVideoView.java +++ b/native/cocos/platform/android/java/src/com/cocos/lib/CocosVideoView.java @@ -485,12 +485,12 @@ public class CocosVideoView extends SurfaceView { }; private MediaPlayer.OnCompletionListener mCompletionListener = - new MediaPlayer.OnCompletionListener() { - public void onCompletion(MediaPlayer mp) { - mCurrentState = State.PLAYBACK_COMPLETED; - CocosVideoView.this.sendEvent(EVENT_COMPLETED); - } - }; + new MediaPlayer.OnCompletionListener() { + public void onCompletion(MediaPlayer mp) { + mCurrentState = State.PLAYBACK_COMPLETED; + CocosVideoView.this.sendEvent(EVENT_COMPLETED); + } + }; private static final int EVENT_PLAYING = 0; @@ -502,49 +502,49 @@ public class CocosVideoView extends SurfaceView { private static final int EVENT_READY_TO_PLAY = 6; private MediaPlayer.OnErrorListener mErrorListener = - new MediaPlayer.OnErrorListener() { - public boolean onError(MediaPlayer mp, int framework_err, int impl_err) { - Log.d(TAG, "Error: " + framework_err + "," + impl_err); - mCurrentState = State.ERROR; + new MediaPlayer.OnErrorListener() { + public boolean onError(MediaPlayer mp, int framework_err, int impl_err) { + Log.d(TAG, "Error: " + framework_err + "," + impl_err); + mCurrentState = State.ERROR; - /* Otherwise, pop up an error dialog so the user knows that - * something bad has happened. Only try and pop up the dialog - * if we're attached to a window. When we're going away and no - * longer have a window, don't bother showing the user an error. - */ - if (getWindowToken() != null) { - Resources r = mActivity.getResources(); - int messageId; + /* Otherwise, pop up an error dialog so the user knows that + * something bad has happened. Only try and pop up the dialog + * if we're attached to a window. When we're going away and no + * longer have a window, don't bother showing the user an error. + */ + if (getWindowToken() != null) { + Resources r = mActivity.getResources(); + int messageId; - if (framework_err == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) { - // messageId = com.android.internal.R.string.VideoView_error_text_invalid_progressive_playback; - messageId = r.getIdentifier("VideoView_error_text_invalid_progressive_playback", "string", "android"); - } else { - // messageId = com.android.internal.R.string.VideoView_error_text_unknown; - messageId = r.getIdentifier("VideoView_error_text_unknown", "string", "android"); + if (framework_err == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) { + // messageId = com.android.internal.R.string.VideoView_error_text_invalid_progressive_playback; + messageId = r.getIdentifier("VideoView_error_text_invalid_progressive_playback", "string", "android"); + } else { + // messageId = com.android.internal.R.string.VideoView_error_text_unknown; + messageId = r.getIdentifier("VideoView_error_text_unknown", "string", "android"); + } + + int titleId = r.getIdentifier("VideoView_error_title", "string", "android"); + int buttonStringId = r.getIdentifier("VideoView_error_button", "string", "android"); + + new AlertDialog.Builder(mActivity) + .setTitle(r.getString(titleId)) + .setMessage(messageId) + .setPositiveButton(r.getString(buttonStringId), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { + /* If we get here, there is no onError listener, so + * at least inform them that the video is over. + */ + CocosVideoView.this.sendEvent(EVENT_COMPLETED); + } + }) + .setCancelable(false) + .show(); + } + return true; } - - int titleId = r.getIdentifier("VideoView_error_title", "string", "android"); - int buttonStringId = r.getIdentifier("VideoView_error_button", "string", "android"); - - new AlertDialog.Builder(mActivity) - .setTitle(r.getString(titleId)) - .setMessage(messageId) - .setPositiveButton(r.getString(buttonStringId), - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - /* If we get here, there is no onError listener, so - * at least inform them that the video is over. - */ - CocosVideoView.this.sendEvent(EVENT_COMPLETED); - } - }) - .setCancelable(false) - .show(); - } - return true; - } - }; + }; SurfaceHolder.Callback mSHCallback = new SurfaceHolder.Callback() { diff --git a/native/cocos/platform/android/jni/JniCocosActivity.cpp b/native/cocos/platform/android/jni/JniCocosActivity.cpp index e5e914863e..1c872f94e7 100644 --- a/native/cocos/platform/android/jni/JniCocosActivity.cpp +++ b/native/cocos/platform/android/jni/JniCocosActivity.cpp @@ -24,38 +24,38 @@ ****************************************************************************/ #include "JniCocosActivity.h" -#include "platform/android/jni/JniHelper.h" -#include "platform/android/FileUtils-android.h" -#include "platform/Application.h" -#include "platform/android/View.h" -#include -#include #include +#include #include #include -#include -#include #include +#include +#include +#include #include +#include "platform/Application.h" +#include "platform/android/FileUtils-android.h" +#include "platform/android/View.h" +#include "platform/java/jni/JniHelper.h" #define LOGV(...) __android_log_print(ANDROID_LOG_INFO, "CocosActivity JNI", __VA_ARGS__) -cc::Application *cocos_main(int, int) __attribute__((weak)); +cc::Application *cocos_main(int, int) __attribute__((weak)); //NOLINT namespace cc { CocosApp cocosApp; } namespace { -int messagePipe[2]; -int pipeRead = 0; -int pipeWrite = 0; -cc::Application *game = nullptr; +int messagePipe[2]; +int pipeRead = 0; +int pipeWrite = 0; +cc::Application *game = nullptr; void createGame(ANativeWindow *window) { - int width = ANativeWindow_getWidth(window); + int width = ANativeWindow_getWidth(window); int height = ANativeWindow_getHeight(window); - game = cocos_main(width, height); + game = cocos_main(width, height); game->init(); } @@ -63,7 +63,7 @@ void writeCommand(int8_t cmd) { write(pipeWrite, &cmd, sizeof(cmd)); } -int readCommand(int8_t &cmd) { +int readCommand(int8_t &cmd) { //NOLINT(google-runtime-references) return read(pipeRead, &cmd, sizeof(cmd)); } @@ -131,7 +131,7 @@ void glThreadEntry() { cc::cocosApp.cond.notify_all(); int8_t cmd = 0; - while (1) { + while (true) { if (readCommand(cmd) > 0) { preExecCmd(cmd); cc::View::engineHandleCmd(cmd); @@ -181,7 +181,7 @@ void setActivityState(int8_t cmd) { } // namespace extern "C" { - +//NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onCreateNative(JNIEnv *env, jobject obj, jobject activity, jobject assetMgr, jstring obbPath, jint sdkVersion) { if (cc::cocosApp.running) { @@ -190,14 +190,14 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onCreateNative(JNIEnv *e cc::cocosApp.sdkVersion = sdkVersion; cc::JniHelper::init(env, activity); - cc::cocosApp.obbPath = cc::JniHelper::jstring2string(obbPath); + cc::cocosApp.obbPath = cc::JniHelper::jstring2string(obbPath); cc::cocosApp.assetManager = AAssetManager_fromJava(env, assetMgr); - static_cast(cc::FileUtils::getInstance())->setassetmanager(cc::cocosApp.assetManager); + cc::FileUtilsAndroid::setassetmanager(cc::cocosApp.assetManager); if (pipe(messagePipe)) { LOGV("Can not create pipe: %s", strerror(errno)); } - pipeRead = messagePipe[0]; + pipeRead = messagePipe[0]; pipeWrite = messagePipe[1]; if (fcntl(pipeRead, F_SETFL, O_NONBLOCK) < 0) { LOGV("Can not make pipe read to non blocking mode."); @@ -211,34 +211,35 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onCreateNative(JNIEnv *e cc::cocosApp.cond.wait(lk); } } - +//NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onSurfaceCreatedNative(JNIEnv *env, jobject obj, jobject surface) { setWindow(ANativeWindow_fromSurface(env, surface)); } +//NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onStartNative(JNIEnv *env, jobject obj) { } - +//NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onPauseNative(JNIEnv *env, jobject obj) { setActivityState(APP_CMD_PAUSE); } - +//NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onResumeNative(JNIEnv *env, jobject obj) { setActivityState(APP_CMD_RESUME); } - +//NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onStopNative(JNIEnv *env, jobject obj) { } - +//NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onLowMemoryNative(JNIEnv *env, jobject obj) { writeCommand(APP_CMD_LOW_MEMORY); } - +//NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onWindowFocusChangedNative(JNIEnv *env, jobject obj, jboolean has_focus) { } - +//NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onSurfaceChangedNative(JNIEnv *env, jobject obj, jint width, jint height) { } - +//NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onSurfaceDestroyNative(JNIEnv *env, jobject obj) { setWindow(nullptr); } diff --git a/native/cocos/platform/android/jni/JniCocosSurfaceView.cpp b/native/cocos/platform/android/jni/JniCocosSurfaceView.cpp index 7854c37364..fe2aaafc5e 100644 --- a/native/cocos/platform/android/jni/JniCocosSurfaceView.cpp +++ b/native/cocos/platform/android/jni/JniCocosSurfaceView.cpp @@ -22,16 +22,16 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - -#include "platform/android/jni/JniHelper.h" -#include "platform/Application.h" -#include -#include #include +#include +#include +#include "platform/Application.h" +#include "platform/java/jni/JniHelper.h" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, "JniCocosSurfaceView JNI", __VA_ARGS__) extern "C" { +//NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosSurfaceView_nativeOnSizeChanged(JNIEnv *env, jobject thiz, jint width, jint height) { cc::EventDispatcher::dispatchResizeEvent(width, height); diff --git a/native/cocos/platform/android/jni/JniHelper.cpp b/native/cocos/platform/android/jni/JniHelper.cpp deleted file mode 100644 index 95b9baa7d9..0000000000 --- a/native/cocos/platform/android/jni/JniHelper.cpp +++ /dev/null @@ -1,321 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#include "platform/android/jni/JniHelper.h" -#include "platform/android/FileUtils-android.h" -#include -#include -#include -#include - -#include "base/UTF8.h" - -#define LOG_TAG "JniHelper" -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) -#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) - -static pthread_key_t g_key; - -jclass _getClassID(const char *className) { - if (nullptr == className) { - return nullptr; - } - - JNIEnv *env = cc::JniHelper::getEnv(); - - jstring _jstrClassName = env->NewStringUTF(className); - - jclass _clazz = (jclass)env->CallObjectMethod(cc::JniHelper::classloader, - cc::JniHelper::loadclassMethod_methodID, - _jstrClassName); - - if (nullptr == _clazz || env->ExceptionCheck()) { - LOGE("Classloader failed to find class of %s", className); - env->ExceptionClear(); - _clazz = nullptr; - } - - env->DeleteLocalRef(_jstrClassName); - - return _clazz; -} - -void _detachCurrentThread(void *a) { - cc::JniHelper::getJavaVM()->DetachCurrentThread(); -} - -namespace cc { -jmethodID JniHelper::loadclassMethod_methodID = nullptr; -jobject JniHelper::classloader = nullptr; -std::function JniHelper::classloaderCallback = nullptr; -jobject JniHelper::_activity = nullptr; -JavaVM *JniHelper::_javaVM = nullptr; - -JavaVM *JniHelper::getJavaVM() { - pthread_t thisthread = pthread_self(); - LOGD("JniHelper::getJavaVM(), pthread_self() = %ld", thisthread); - return JniHelper::_javaVM; -} - -void JniHelper::init(JNIEnv *env, jobject activity) { - env->GetJavaVM(&JniHelper::_javaVM); - JniHelper::_activity = activity; - - pthread_key_create(&g_key, _detachCurrentThread); - JniHelper::setClassLoaderFrom(activity); -} - -JNIEnv *JniHelper::cacheEnv() { - JavaVM *jvm = JniHelper::_javaVM; - JNIEnv *_env = nullptr; - // get jni environment - jint ret = jvm->GetEnv((void **)&_env, JNI_VERSION_1_4); - - switch (ret) { - case JNI_OK: - // Success! - pthread_setspecific(g_key, _env); - return _env; - - case JNI_EDETACHED: - // Thread not attached - if (jvm->AttachCurrentThread(&_env, nullptr) < 0) { - LOGE("Failed to get the environment using AttachCurrentThread()"); - - return nullptr; - } else { - // Success : Attached and obtained JNIEnv! - pthread_setspecific(g_key, _env); - return _env; - } - - case JNI_EVERSION: - // Cannot recover from this error - LOGE("JNI interface version 1.4 not supported"); - default: - LOGE("Failed to get the environment using GetEnv()"); - return nullptr; - } -} - -JNIEnv *JniHelper::getEnv() { - JNIEnv *_env = (JNIEnv *)pthread_getspecific(g_key); - if (_env == nullptr) - _env = JniHelper::cacheEnv(); - return _env; -} - -jobject JniHelper::getActivity() { - return _activity; -} - -bool JniHelper::setClassLoaderFrom(jobject activityinstance) { - JniMethodInfo _getclassloaderMethod; - if (!JniHelper::getMethodInfo_DefaultClassLoader(_getclassloaderMethod, - "android/content/Context", - "getClassLoader", - "()Ljava/lang/ClassLoader;")) { - return false; - } - - jobject _c = cc::JniHelper::getEnv()->CallObjectMethod(activityinstance, - _getclassloaderMethod.methodID); - - if (nullptr == _c) { - return false; - } - - JniMethodInfo _m; - if (!JniHelper::getMethodInfo_DefaultClassLoader(_m, - "java/lang/ClassLoader", - "loadClass", - "(Ljava/lang/String;)Ljava/lang/Class;")) { - return false; - } - - JniHelper::classloader = cc::JniHelper::getEnv()->NewGlobalRef(_c); - JniHelper::loadclassMethod_methodID = _m.methodID; - JniHelper::_activity = cc::JniHelper::getEnv()->NewGlobalRef(activityinstance); - if (JniHelper::classloaderCallback != nullptr) { - JniHelper::classloaderCallback(); - } - - return true; -} - -bool JniHelper::getStaticMethodInfo(JniMethodInfo &methodinfo, - const char *className, - const char *methodName, - const char *paramCode) { - if ((nullptr == className) || - (nullptr == methodName) || - (nullptr == paramCode)) { - return false; - } - - JNIEnv *env = JniHelper::getEnv(); - if (!env) { - LOGE("Failed to get JNIEnv"); - return false; - } - - jclass classID = _getClassID(className); - if (!classID) { - LOGE("Failed to find class %s", className); - env->ExceptionClear(); - return false; - } - - jmethodID methodID = env->GetStaticMethodID(classID, methodName, paramCode); - if (!methodID) { - LOGE("Failed to find static method id of %s", methodName); - env->ExceptionClear(); - return false; - } - - methodinfo.classID = classID; - methodinfo.env = env; - methodinfo.methodID = methodID; - return true; -} - -bool JniHelper::getMethodInfo_DefaultClassLoader(JniMethodInfo &methodinfo, - const char *className, - const char *methodName, - const char *paramCode) { - if ((nullptr == className) || - (nullptr == methodName) || - (nullptr == paramCode)) { - return false; - } - - JNIEnv *env = JniHelper::getEnv(); - if (!env) { - return false; - } - - jclass classID = env->FindClass(className); - if (!classID) { - LOGE("Failed to find class %s", className); - env->ExceptionClear(); - return false; - } - - jmethodID methodID = env->GetMethodID(classID, methodName, paramCode); - if (!methodID) { - LOGE("Failed to find method id of %s", methodName); - env->ExceptionClear(); - return false; - } - - methodinfo.classID = classID; - methodinfo.env = env; - methodinfo.methodID = methodID; - - return true; -} - -bool JniHelper::getMethodInfo(JniMethodInfo &methodinfo, - const char *className, - const char *methodName, - const char *paramCode) { - if ((nullptr == className) || - (nullptr == methodName) || - (nullptr == paramCode)) { - return false; - } - - JNIEnv *env = JniHelper::getEnv(); - if (!env) { - return false; - } - - jclass classID = _getClassID(className); - if (!classID) { - LOGE("Failed to find class %s", className); - env->ExceptionClear(); - return false; - } - - jmethodID methodID = env->GetMethodID(classID, methodName, paramCode); - if (!methodID) { - LOGE("Failed to find method id of %s", methodName); - env->ExceptionClear(); - return false; - } - - methodinfo.classID = classID; - methodinfo.env = env; - methodinfo.methodID = methodID; - - return true; -} - -std::string JniHelper::jstring2string(jstring jstr) { - if (jstr == nullptr) { - return ""; - } - - JNIEnv *env = JniHelper::getEnv(); - if (!env) { - return ""; - } - - std::string strValue = cc::StringUtils::getStringUTFCharsJNI(env, jstr); - - return strValue; -} - -jstring JniHelper::convert(JniHelper::LocalRefMapType &localRefs, cc::JniMethodInfo &t, const char *x) { - jstring ret = nullptr; - if (x) - ret = cc::StringUtils::newStringUTFJNI(t.env, x); - - localRefs[t.env].push_back(ret); - return ret; -} - -jstring JniHelper::convert(JniHelper::LocalRefMapType &localRefs, cc::JniMethodInfo &t, const std::string &x) { - return convert(localRefs, t, x.c_str()); -} - -void JniHelper::deleteLocalRefs(JNIEnv *env, JniHelper::LocalRefMapType &localRefs) { - if (!env) { - return; - } - - for (const auto &ref : localRefs[env]) { - env->DeleteLocalRef(ref); - } - localRefs[env].clear(); -} - -void JniHelper::reportError(const std::string &className, const std::string &methodName, const std::string &signature) { - LOGE("Failed to find static java method. Class name: %s, method name: %s, signature: %s ", className.c_str(), methodName.c_str(), signature.c_str()); -} - -} //namespace cc diff --git a/native/cocos/platform/android/CanvasRenderingContext2D-android.cpp b/native/cocos/platform/java/CanvasRenderingContext2D-java.cpp similarity index 74% rename from native/cocos/platform/android/CanvasRenderingContext2D-android.cpp rename to native/cocos/platform/java/CanvasRenderingContext2D-java.cpp index bd0f909d8a..e2c9e975dc 100644 --- a/native/cocos/platform/android/CanvasRenderingContext2D-android.cpp +++ b/native/cocos/platform/java/CanvasRenderingContext2D-java.cpp @@ -23,13 +23,18 @@ THE SOFTWARE. ****************************************************************************/ -#include "platform/CanvasRenderingContext2D.h" #include "base/csscolorparser.h" +#include "bindings/jswrapper/config.h" #include "math/Math.h" +#include "platform/CanvasRenderingContext2D.h" #include "cocos/bindings/jswrapper/SeApi.h" -#include "platform/android/jni/JniHelper.h" -#include "platform/android/jni/JniImp.h" +#include "platform/java/jni/JniHelper.h" +#include "platform/java/jni/JniImp.h" + +#if __OHOS__ + #include +#endif #include @@ -37,6 +42,7 @@ #define JCLS_CANVASIMPL "com/cocos/lib/CanvasRenderingContext2DImpl" #endif +//NOLINTNEXTLINE using namespace cc; enum class CanvasTextAlign { @@ -56,8 +62,8 @@ class CanvasRenderingContext2DImpl { public: CanvasRenderingContext2DImpl() { jobject obj = JniHelper::newObject(JCLS_CANVASIMPL); - _obj = JniHelper::getEnv()->NewGlobalRef(obj); - JniHelper::getEnv()->DeleteLocalRef(obj); + _obj = JniHelper::getEnv()->NewGlobalRef(obj); + ccDeleteLocalRef(JniHelper::getEnv(), obj); } ~CanvasRenderingContext2DImpl() { @@ -65,10 +71,11 @@ public: } void recreateBuffer(float w, float h) { - _bufferWidth = w; + _bufferWidth = w; _bufferHeight = h; - if (_bufferWidth < 1.0f || _bufferHeight < 1.0f) + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { return; + } JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "recreateBuffer", w, h); fillData(); } @@ -90,16 +97,18 @@ public: } void stroke() { - if (_bufferWidth < 1.0f || _bufferHeight < 1.0f) + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { return; + } JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "stroke"); fillData(); } void fill() { - if (_bufferWidth < 1.0f || _bufferHeight < 1.0f) + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { return; + } JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "fill"); fillData(); @@ -114,55 +123,67 @@ public: } void rect(float x, float y, float w, float h) { - if (_bufferWidth < 1.0f || _bufferHeight < 1.0f) + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { return; + } JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "rect", x, y, w, h); fillData(); } void clearRect(float x, float y, float w, float h) { - if (_bufferWidth < 1.0f || _bufferHeight < 1.0f) + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { return; - if (x >= _bufferWidth || y >= _bufferHeight) + } + if (x >= _bufferWidth || y >= _bufferHeight) { return; - if (x + w > _bufferWidth) + } + if (x + w > _bufferWidth) { w = _bufferWidth - x; - if (y + h > _bufferHeight) + } + if (y + h > _bufferHeight) { h = _bufferHeight - y; + } JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "clearRect", x, y, w, h); fillData(); } void fillRect(float x, float y, float w, float h) { - if (_bufferWidth < 1.0f || _bufferHeight < 1.0f) + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { return; - if (x >= _bufferWidth || y >= _bufferHeight) + } + if (x >= _bufferWidth || y >= _bufferHeight) { return; - if (x + w > _bufferWidth) + } + if (x + w > _bufferWidth) { w = _bufferWidth - x; - if (y + h > _bufferHeight) + } + if (y + h > _bufferHeight) { h = _bufferHeight - y; + } JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "fillRect", x, y, w, h); fillData(); } void fillText(const std::string &text, float x, float y, float maxWidth) { - if (text.empty() || _bufferWidth < 1.0f || _bufferHeight < 1.0f) + if (text.empty() || _bufferWidth < 1.0F || _bufferHeight < 1.0F) { return; + } JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "fillText", text, x, y, maxWidth); fillData(); } void strokeText(const std::string &text, float x, float y, float maxWidth) { - if (text.empty() || _bufferWidth < 1.0f || _bufferHeight < 1.0f) + if (text.empty() || _bufferWidth < 1.0F || _bufferHeight < 1.0F) { return; + } JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "strokeText", text, x, y, maxWidth); fillData(); } float measureText(const std::string &text) { - if (text.empty()) - return 0.0f; + if (text.empty()) { + return 0.0F; + } return JniHelper::callObjectFloatMethod(_obj, JCLS_CANVASIMPL, "measureText", text); } @@ -179,11 +200,11 @@ public: } void setTextAlign(CanvasTextAlign align) { - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setTextAlign", (int)align); + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setTextAlign", static_cast(align)); } void setTextBaseline(CanvasTextBaseline baseline) { - JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setTextBaseline", (int)baseline); + JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setTextBaseline", static_cast(baseline)); } void setFillStyle(float r, float g, float b, float a) { @@ -198,16 +219,18 @@ public: JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setLineWidth", lineWidth); } + //NOLINTNEXTLINE(readability-identifier-naming) void _fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) { - if (_bufferWidth < 1.0f || _bufferHeight < 1.0f) + if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { return; + } jbyteArray arr = JniHelper::getEnv()->NewByteArray(imageData.getSize()); JniHelper::getEnv()->SetByteArrayRegion(arr, 0, imageData.getSize(), - (const jbyte *)imageData.getBytes()); + reinterpret_cast(imageData.getBytes())); JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "_fillImageData", arr, imageWidth, imageHeight, offsetX, offsetY); - JniHelper::getEnv()->DeleteLocalRef(arr); + ccDeleteLocalRef(JniHelper::getEnv(), arr); fillData(); } @@ -217,6 +240,8 @@ public: } #define CLAMP(V, HI) std::min((V), (HI)) + + //NOLINTNEXTLINE(readability-convert-member-functions-to-static) void unMultiplyAlpha(unsigned char *ptr, ssize_t size) { // Android source data is not premultiplied alpha when API >= 19 // please refer CanvasRenderingContext2DImpl::recreateBuffer(float w, float h) @@ -226,9 +251,9 @@ public: float alpha; for (int i = 0; i < size; i += 4) { - alpha = (float)ptr[i + 3]; + alpha = static_cast(ptr[i + 3]); if (alpha > 0) { - ptr[i] = CLAMP((int)((float)ptr[i] / alpha * 255), 255); + ptr[i] = CLAMP((int)((float)ptr[i] / alpha * 255), 255); ptr[i + 1] = CLAMP((int)((float)ptr[i + 1] / alpha * 255), 255); ptr[i + 2] = CLAMP((int)((float)ptr[i + 2] / alpha * 255), 255); } @@ -237,19 +262,23 @@ public: void fillData() { jbyteArray arr = JniHelper::callObjectByteArrayMethod(_obj, JCLS_CANVASIMPL, "getDataRef"); - jsize len = JniHelper::getEnv()->GetArrayLength(arr); - jbyte *jbarray = (jbyte *)malloc(len * sizeof(jbyte)); + if (arr == nullptr) { + SE_LOGE("getDataRef return null in fillData, size: %d, %d", (int)_bufferWidth, (int)_bufferHeight); + return; + } + jsize len = JniHelper::getEnv()->GetArrayLength(arr); + auto *jbarray = static_cast(malloc(len * sizeof(jbyte))); JniHelper::getEnv()->GetByteArrayRegion(arr, 0, len, jbarray); - unMultiplyAlpha((unsigned char *)jbarray, len); - _data.fastSet((unsigned char *)jbarray, len); //IDEA: DON'T create new jbarray every time. - JniHelper::getEnv()->DeleteLocalRef(arr); + unMultiplyAlpha(reinterpret_cast(jbarray), len); + _data.fastSet(reinterpret_cast(jbarray), len); //IDEA: DON'T create new jbarray every time. + ccDeleteLocalRef(JniHelper::getEnv(), arr); } private: jobject _obj = nullptr; - Data _data; - float _bufferWidth = 0.0f; - float _bufferHeight = 0.0f; + Data _data; + float _bufferWidth = 0.0F; + float _bufferHeight = 0.0F; }; namespace { @@ -262,7 +291,7 @@ void fillRectWithColor(uint8_t *buf, uint32_t totalWidth, uint32_t totalHeight, uint8_t *p; for (uint32_t offsetY = y0; offsetY < y1; ++offsetY) { for (uint32_t offsetX = x; offsetX < (x + width); ++offsetX) { - p = buf + (totalWidth * offsetY + offsetX) * 3; + p = buf + (totalWidth * offsetY + offsetX) * 3; *p++ = r; *p++ = g; *p++ = b; @@ -273,13 +302,8 @@ void fillRectWithColor(uint8_t *buf, uint32_t totalWidth, uint32_t totalHeight, namespace cc { -CanvasGradient::CanvasGradient() { - // SE_LOGD("CanvasGradient constructor: %p\n", this); -} - -CanvasGradient::~CanvasGradient() { - // SE_LOGD("CanvasGradient destructor: %p\n", this); -} +CanvasGradient::CanvasGradient() = default; +CanvasGradient::~CanvasGradient() = default; void CanvasGradient::addColorStop(float offset, const std::string &color) { // SE_LOGD("CanvasGradient::addColorStop: %p\n", this); @@ -304,8 +328,9 @@ void CanvasRenderingContext2D::recreateBufferIfNeeded() { _isBufferSizeDirty = false; // SE_LOGD("Recreate buffer %p, w: %f, h:%f\n", this, _width, _height); _impl->recreateBuffer(_width, _height); - if (_canvasBufferUpdatedCB != nullptr) + if (_canvasBufferUpdatedCB != nullptr) { _canvasBufferUpdatedCB(_impl->getDataRef()); + } } } @@ -325,31 +350,36 @@ void CanvasRenderingContext2D::fillRect(float x, float y, float width, float hei recreateBufferIfNeeded(); _impl->fillRect(x, y, width, height); - if (_canvasBufferUpdatedCB != nullptr) + if (_canvasBufferUpdatedCB != nullptr) { _canvasBufferUpdatedCB(_impl->getDataRef()); + } } void CanvasRenderingContext2D::fillText(const std::string &text, float x, float y, float maxWidth) { // SE_LOGD("CanvasRenderingContext2D::fillText: %s, %f, %f, %f\n", text.c_str(), x, y, maxWidth); - if (text.empty()) + if (text.empty()) { return; + } recreateBufferIfNeeded(); _impl->fillText(text, x, y, maxWidth); - if (_canvasBufferUpdatedCB != nullptr) + if (_canvasBufferUpdatedCB != nullptr) { _canvasBufferUpdatedCB(_impl->getDataRef()); + } } void CanvasRenderingContext2D::strokeText(const std::string &text, float x, float y, float maxWidth) { // SE_LOGD("CanvasRenderingContext2D::strokeText: %s, %f, %f, %f\n", text.c_str(), x, y, maxWidth); - if (text.empty()) + if (text.empty()) { return; + } recreateBufferIfNeeded(); _impl->strokeText(text, x, y, maxWidth); - if (_canvasBufferUpdatedCB != nullptr) + if (_canvasBufferUpdatedCB != nullptr) { _canvasBufferUpdatedCB(_impl->getDataRef()); + } } cc::Size CanvasRenderingContext2D::measureText(const std::string &text) { @@ -357,7 +387,8 @@ cc::Size CanvasRenderingContext2D::measureText(const std::string &text) { return cc::Size(_impl->measureText(text), 0); } -CanvasGradient *CanvasRenderingContext2D::createLinearGradient(float x0, float y0, float x1, float y1) { +CanvasGradient *CanvasRenderingContext2D::createLinearGradient(float /*x0*/, float /*y0*/, float /*x1*/, float /*y1*/) { //NOLINT(readability-convert-member-functions-to-static) + return nullptr; } @@ -384,15 +415,17 @@ void CanvasRenderingContext2D::lineTo(float x, float y) { void CanvasRenderingContext2D::stroke() { _impl->stroke(); - if (_canvasBufferUpdatedCB != nullptr) + if (_canvasBufferUpdatedCB != nullptr) { _canvasBufferUpdatedCB(_impl->getDataRef()); + } } void CanvasRenderingContext2D::fill() { _impl->fill(); - if (_canvasBufferUpdatedCB != nullptr) + if (_canvasBufferUpdatedCB != nullptr) { _canvasBufferUpdatedCB(_impl->getDataRef()); + } } void CanvasRenderingContext2D::restore() { @@ -404,33 +437,33 @@ void CanvasRenderingContext2D::setCanvasBufferUpdatedCallback(const CanvasBuffer recreateBufferIfNeeded(); } -void CanvasRenderingContext2D::set_width(float width) { +void CanvasRenderingContext2D::set_width(float width) { //NOLINT(readability-identifier-naming) // SE_LOGD("CanvasRenderingContext2D::set__width: %f\n", width); if (math::IsEqualF(width, _width)) return; - _width = width; + _width = width; _isBufferSizeDirty = true; recreateBufferIfNeeded(); } -void CanvasRenderingContext2D::set_height(float height) { +void CanvasRenderingContext2D::set_height(float height) { //NOLINT(readability-identifier-naming) // SE_LOGD("CanvasRenderingContext2D::set__height: %f\n", height); if (math::IsEqualF(height, _height)) return; - _height = height; + _height = height; _isBufferSizeDirty = true; recreateBufferIfNeeded(); } -void CanvasRenderingContext2D::set_lineWidth(float lineWidth) { +void CanvasRenderingContext2D::set_lineWidth(float lineWidth) { //NOLINT(readability-identifier-naming) _lineWidth = lineWidth; _impl->setLineWidth(lineWidth); } -void CanvasRenderingContext2D::set_lineJoin(const std::string &lineJoin) { +void CanvasRenderingContext2D::set_lineJoin(const std::string &lineJoin) { //NOLINT(readability-identifier-naming) if (lineJoin.empty()) return; _impl->setLineJoin(lineJoin); } -void CanvasRenderingContext2D::set_lineCap(const std::string &lineCap) { +void CanvasRenderingContext2D::set_lineCap(const std::string &lineCap) { //NOLINT(readability-identifier-naming) if (lineCap.empty()) return; _impl->setLineCap(lineCap); } @@ -440,12 +473,12 @@ void CanvasRenderingContext2D::set_lineCap(const std::string &lineCap) { * "italic bold small-caps 25px Arial" * "italic 25px Arial" * */ -void CanvasRenderingContext2D::set_font(const std::string &font) { +void CanvasRenderingContext2D::set_font(const std::string &font) { //NOLINT(readability-identifier-naming) if (_font != font) { - _font = font; - std::string fontName = "sans-serif"; - std::string fontSizeStr = "30"; - std::regex re("\\s*((\\d+)([\\.]\\d+)?)px\\s+([^\\r\\n]*)"); + _font = font; + std::string fontName = "sans-serif"; + std::string fontSizeStr = "30"; + std::regex re(R"(\s*((\d+)([\.]\d+)?)px\s+([^\r\n]*))"); std::match_results results; if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) { fontSizeStr = results[2].str(); @@ -453,26 +486,26 @@ void CanvasRenderingContext2D::set_font(const std::string &font) { // support get font name contain space,example `times new roman` // if regex rule that does not conform to the rules,such as Chinese,it defaults to sans-serif std::match_results fontResults; - std::regex fontRe("([\\w\\s-]+|\"[\\w\\s-]+\"$)"); - std::string tmp(results[4].str()); + std::regex fontRe(R"(([\w\s-]+|"[\w\s-]+"$))"); + std::string tmp(results[4].str()); if (std::regex_match(tmp, fontResults, fontRe)) { fontName = results[4].str(); } } - float fontSize = atof(fontSizeStr.c_str()); - bool isBold = font.find("bold", 0) != std::string::npos; - bool isItalic = font.find("italic", 0) != std::string::npos; - bool isSmallCaps = font.find("small-caps", 0) != std::string::npos; - bool isOblique = font.find("oblique", 0) != std::string::npos; + double fontSize = atof(fontSizeStr.c_str()); + bool isBold = font.find("bold", 0) != std::string::npos; + bool isItalic = font.find("italic", 0) != std::string::npos; + bool isSmallCaps = font.find("small-caps", 0) != std::string::npos; + bool isOblique = font.find("oblique", 0) != std::string::npos; //font-style: italic, oblique, normal //font-weight: normal, bold //font-variant: normal, small-caps - _impl->updateFont(fontName, fontSize, isBold, isItalic, isOblique, isSmallCaps); + _impl->updateFont(fontName, static_cast(fontSize), isBold, isItalic, isOblique, isSmallCaps); } } -void CanvasRenderingContext2D::set_textAlign(const std::string &textAlign) { +void CanvasRenderingContext2D::set_textAlign(const std::string &textAlign) { //NOLINT(readability-identifier-naming) // SE_LOGD("CanvasRenderingContext2D::set_textAlign: %s\n", textAlign.c_str()); if (textAlign == "left") { _impl->setTextAlign(CanvasTextAlign::LEFT); @@ -485,7 +518,7 @@ void CanvasRenderingContext2D::set_textAlign(const std::string &textAlign) { } } -void CanvasRenderingContext2D::set_textBaseline(const std::string &textBaseline) { +void CanvasRenderingContext2D::set_textBaseline(const std::string &textBaseline) { //NOLINT(readability-identifier-naming) // SE_LOGD("CanvasRenderingContext2D::set_textBaseline: %s\n", textBaseline.c_str()); if (textBaseline == "top") { _impl->setTextBaseline(CanvasTextBaseline::TOP); @@ -501,25 +534,26 @@ void CanvasRenderingContext2D::set_textBaseline(const std::string &textBaseline) } } -void CanvasRenderingContext2D::set_fillStyle(const std::string &fillStyle) { +void CanvasRenderingContext2D::set_fillStyle(const std::string &fillStyle) { //NOLINT(readability-identifier-naming) CSSColorParser::Color color = CSSColorParser::parse(fillStyle); - _impl->setFillStyle(color.r / 255.0f, color.g / 255.0f, color.b / 255.0f, color.a); + _impl->setFillStyle(static_cast(color.r) / 255.0F, static_cast(color.g) / 255.0F, static_cast(color.b) / 255.0F, color.a); // SE_LOGD("CanvasRenderingContext2D::set_fillStyle: %s, (%d, %d, %d, %f)\n", fillStyle.c_str(), color.r, color.g, color.b, color.a); } -void CanvasRenderingContext2D::set_strokeStyle(const std::string &strokeStyle) { +void CanvasRenderingContext2D::set_strokeStyle(const std::string &strokeStyle) { //NOLINT(readability-identifier-naming) CSSColorParser::Color color = CSSColorParser::parse(strokeStyle); - _impl->setStrokeStyle(color.r / 255.0f, color.g / 255.0f, color.b / 255.0f, color.a); + _impl->setStrokeStyle(static_cast(color.r) / 255.0F, static_cast(color.g) / 255.0F, static_cast(color.b) / 255.0F, color.a); } -void CanvasRenderingContext2D::set_globalCompositeOperation(const std::string &globalCompositeOperation) { +void CanvasRenderingContext2D::set_globalCompositeOperation(const std::string &globalCompositeOperation) { //NOLINT(readability-identifier-naming) // SE_LOGE("%s isn't implemented!\n", __FUNCTION__); } -void CanvasRenderingContext2D::_fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) { +void CanvasRenderingContext2D::_fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) { //NOLINT(readability-identifier-naming) _impl->_fillImageData(imageData, imageWidth, imageHeight, offsetX, offsetY); - if (_canvasBufferUpdatedCB != nullptr) + if (_canvasBufferUpdatedCB != nullptr) { _canvasBufferUpdatedCB(_impl->getDataRef()); + } } // transform //REFINE: diff --git a/native/cocos/platform/android/jni/JniCocosKeyCodeHandler.cpp b/native/cocos/platform/java/jni/JniCocosKeyCodeHandler.cpp similarity index 84% rename from native/cocos/platform/android/jni/JniCocosKeyCodeHandler.cpp rename to native/cocos/platform/java/jni/JniCocosKeyCodeHandler.cpp index 301a788720..fc9474badd 100644 --- a/native/cocos/platform/android/jni/JniCocosKeyCodeHandler.cpp +++ b/native/cocos/platform/java/jni/JniCocosKeyCodeHandler.cpp @@ -22,18 +22,21 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - -#include "platform/android/jni/JniHelper.h" #include "platform/Application.h" +#include "platform/java/jni/JniHelper.h" +#if CC_PLATFORM == CC_PLATFORM_ANDROID + #include + #include +#elif CC_PLATFORM == CC_PLATFORM_OHOS + #include +#endif #include -#include -#include -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, "CocosKeyCodeHandler JNI", __VA_ARGS__) namespace { struct cc::KeyboardEvent keyboardEvent; // key values in web, refer to http://docs.cocos.com/creator/api/en/enums/KEY.html +#if CC_PLATFORM == CC_PLATFORM_ANDROID std::unordered_map keyCodeMap = { {AKEYCODE_BACK, 6}, {AKEYCODE_ENTER, 13}, @@ -43,22 +46,27 @@ std::unordered_map keyCodeMap = { {AKEYCODE_DPAD_LEFT, 1000}, {AKEYCODE_DPAD_RIGHT, 1001}, {AKEYCODE_DPAD_CENTER, 1005}}; - +#elif CC_PLATFORM == CC_PLATFORM_OHOS +std::unordered_map keyCodeMap = {}; +#endif +//NOLINTNEXTLINE void dispatchKeyCodeEvent(int keyCode, cc::KeyboardEvent &event) { - if (keyCodeMap.count(keyCode) > 0) + if (keyCodeMap.count(keyCode) > 0) { keyCode = keyCodeMap[keyCode]; - else + } else { keyCode = 0; + } event.key = keyCode; cc::EventDispatcher::dispatchKeyboardEvent(event); } } // namespace extern "C" { +//NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosKeyCodeHandler_handleKeyDown(JNIEnv *env, jobject obj, jint keyCode) { keyboardEvent.action = cc::KeyboardEvent::Action::PRESS; dispatchKeyCodeEvent(keyCode, keyboardEvent); } - +//NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosKeyCodeHandler_handleKeyUp(JNIEnv *env, jobject obj, jint keyCode) { keyboardEvent.action = cc::KeyboardEvent::Action::RELEASE; dispatchKeyCodeEvent(keyCode, keyboardEvent); diff --git a/native/cocos/platform/android/jni/JniCocosOrientationHelper.cpp b/native/cocos/platform/java/jni/JniCocosOrientationHelper.cpp similarity index 89% rename from native/cocos/platform/android/jni/JniCocosOrientationHelper.cpp rename to native/cocos/platform/java/jni/JniCocosOrientationHelper.cpp index 72bbdfc6c8..5436ab264e 100644 --- a/native/cocos/platform/android/jni/JniCocosOrientationHelper.cpp +++ b/native/cocos/platform/java/jni/JniCocosOrientationHelper.cpp @@ -22,17 +22,13 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - -#include "platform/android/jni/JniHelper.h" -#include "platform/Application.h" #include -#include -#include +#include "platform/Application.h" #include "platform/Device.h" - -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, "JniCocosOrientationHelper JNI", __VA_ARGS__) +#include "platform/java/jni/JniHelper.h" extern "C" { +//NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosOrientationHelper_nativeOnOrientationChanged(JNIEnv *env, jobject thiz, jint rotation) { auto orientation = cc::Device::getDeviceOrientation(); cc::EventDispatcher::dispatchOrientationChangeEvent((int)orientation); diff --git a/native/cocos/platform/android/jni/JniCocosTouchHandler.cpp b/native/cocos/platform/java/jni/JniCocosTouchHandler.cpp similarity index 91% rename from native/cocos/platform/android/jni/JniCocosTouchHandler.cpp rename to native/cocos/platform/java/jni/JniCocosTouchHandler.cpp index 0cc5be1675..766a7de98d 100644 --- a/native/cocos/platform/android/jni/JniCocosTouchHandler.cpp +++ b/native/cocos/platform/java/jni/JniCocosTouchHandler.cpp @@ -22,18 +22,15 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - -#include "platform/android/jni/JniHelper.h" -#include "platform/Application.h" #include -#include - -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, "CocosTouchHandler JNI", __VA_ARGS__) +#include "platform/Application.h" +#include "platform/java/jni/JniHelper.h" namespace { struct cc::TouchEvent touchEvent; } extern "C" { +//NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionDown(JNIEnv *env, jobject obj, jint id, jfloat x, jfloat y) { touchEvent.type = cc::TouchEvent::Type::BEGAN; @@ -41,7 +38,7 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionDown(JNI cc::EventDispatcher::dispatchTouchEvent(touchEvent); touchEvent.touches.clear(); } - +//NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionUp(JNIEnv *env, jobject obj, jint id, jfloat x, jfloat y) { touchEvent.type = cc::TouchEvent::Type::ENDED; @@ -49,15 +46,14 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionUp(JNIEn cc::EventDispatcher::dispatchTouchEvent(touchEvent); touchEvent.touches.clear(); } - +//NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionMove(JNIEnv *env, jobject obj, - jintArray ids, + jintArray ids, jfloatArray xs, jfloatArray ys) { - touchEvent.type = cc::TouchEvent::Type::MOVED; - int size = env->GetArrayLength(ids); - jint id[size]; + int size = env->GetArrayLength(ids); + jint id[size]; jfloat x[size]; jfloat y[size]; @@ -68,18 +64,18 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionMove(JNI touchEvent.touches.emplace_back(x[i], y[i], id[i]); } -cc: cc::EventDispatcher::dispatchTouchEvent(touchEvent); touchEvent.touches.clear(); } +//NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionCancel(JNIEnv *env, jobject obj, - jintArray ids, + jintArray ids, jfloatArray xs, jfloatArray ys) { touchEvent.type = cc::TouchEvent::Type::CANCELLED; - int size = env->GetArrayLength(ids); - jint id[size]; + int size = env->GetArrayLength(ids); + jint id[size]; jfloat x[size]; jfloat y[size]; diff --git a/native/cocos/platform/java/jni/JniHelper.cpp b/native/cocos/platform/java/jni/JniHelper.cpp new file mode 100644 index 0000000000..af487f8db5 --- /dev/null +++ b/native/cocos/platform/java/jni/JniHelper.cpp @@ -0,0 +1,413 @@ +/**************************************************************************** + Copyright (c) 2010-2012 cocos2d-x.org + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +#include "platform/java/jni/JniHelper.h" +#if ANDROID + #include +#else + #include "cocos/base/Log.h" +#endif +#include +#include + +#include "base/UTF8.h" + +#define CC_CACHE_CLASS_ID 0 + +#if ANDROID + #define LOG_TAG "JniHelper" + #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) + #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) +#else + #define LOGD(...) CC_LOG_DEBUG(__VA_ARGS__) + #define LOGE(...) CC_LOG_ERROR(__VA_ARGS__) +#endif + +namespace { +pthread_key_t g_key; //NOLINT +class JClassWrapper final { +public: + explicit JClassWrapper(jclass kls) { + if (kls) { + _globalKls = static_cast(cc::JniHelper::getEnv()->NewGlobalRef(static_cast(kls))); + } + } + ~JClassWrapper() { + if (_globalKls) { + cc::JniHelper::getEnv()->DeleteGlobalRef(_globalKls); + } + _globalKls = nullptr; + } + jclass operator*() const { + return _globalKls; + } + +private: + jclass _globalKls = {}; +}; +#if CC_CACHE_CLASS_ID +std::unordered_map _cachedJClasses; +#endif +}; // namespace + +jclass _getClassID(const char *className) { //NOLINT(readability-identifier-naming) + if (nullptr == className) { + return nullptr; + } +#if CC_CACHE_CLASS_ID + auto it = _cachedJClasses.find(className); + if (it != _cachedJClasses.end()) { + return *it->second; + } +#endif + + JNIEnv *env = cc::JniHelper::getEnv(); + + jstring jstrClassName = env->NewStringUTF(className); + + auto klassObj = static_cast(env->CallObjectMethod(cc::JniHelper::classloader, + cc::JniHelper::loadclassMethodMethodId, + jstrClassName)); + + if (nullptr == klassObj || env->ExceptionCheck()) { + LOGE("Classloader failed to find class of %s", className); + if (env->ExceptionCheck()) { + env->ExceptionDescribe(); + } + env->ExceptionClear(); + klassObj = nullptr; + } + + ccDeleteLocalRef(env, jstrClassName); + // LOGE("1. delete 0x%p", jstrClassName); +#if CC_CACHE_CLASS_ID + if (klassObj) { + _cachedJClasses.emplace(className, klassObj); + } +#endif + return klassObj; +} + +void cbDetachCurrentThread(void * /*a*/) { + cc::JniHelper::getJavaVM()->DetachCurrentThread(); +} + +namespace cc { +jmethodID JniHelper::loadclassMethodMethodId = nullptr; +jobject JniHelper::classloader = nullptr; +std::function JniHelper::classloaderCallback = nullptr; +jobject JniHelper::sActivity = nullptr; +JavaVM * JniHelper::sJavaVM = nullptr; + +JavaVM *JniHelper::getJavaVM() { + pthread_t thisthread = pthread_self(); + LOGD("JniHelper::getJavaVM(), pthread_self() = %ld", thisthread); + return JniHelper::sJavaVM; +} + +void JniHelper::init(JNIEnv *env, jobject activity) { + env->GetJavaVM(&JniHelper::sJavaVM); + JniHelper::sActivity = activity; + + pthread_key_create(&g_key, cbDetachCurrentThread); + auto ok = JniHelper::setClassLoaderFrom(activity); + assert(ok); +} + +JNIEnv *JniHelper::cacheEnv() { + JavaVM *jvm = JniHelper::sJavaVM; + JNIEnv *env = nullptr; + // get jni environment + jint ret = jvm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_4); + + switch (ret) { + case JNI_OK: + // Success! + pthread_setspecific(g_key, env); + return env; + + case JNI_EDETACHED: + // Thread not attached +#if CC_PLATFORM == CC_PLATFORM_ANDROID + if (jvm->AttachCurrentThread(&env, nullptr) < 0) { +#else + if (jvm->AttachCurrentThread(reinterpret_cast(&env), nullptr) < 0) { +#endif + LOGE("Failed to get the environment using AttachCurrentThread()"); + + return nullptr; + } else { + // Success : Attached and obtained JNIEnv! + pthread_setspecific(g_key, env); + return env; + } + + case JNI_EVERSION: + // Cannot recover from this error + LOGE("JNI interface version 1.4 not supported"); + default: + LOGE("Failed to get the environment using GetEnv()"); + return nullptr; + } +} + +JNIEnv *JniHelper::getEnv() { + auto *env = static_cast(pthread_getspecific(g_key)); + if (env == nullptr) { + env = JniHelper::cacheEnv(); + } + return env; +} + +jobject JniHelper::getActivity() { + return sActivity; +} + +#if CC_PLATFORM == CC_PLATFORM_OHOS +bool JniHelper::setClassLoaderFrom(jobject activityinstance) { + JniMethodInfo getclassloaderMethod; + if (!JniHelper::getMethodInfoDefaultClassLoader(getclassloaderMethod, + "ohos/app/AbilityContext", + "getClassloader", // typo ? + "()Ljava/lang/ClassLoader;")) { + return false; + } + + jobject klassLoader = cc::JniHelper::getEnv()->CallObjectMethod(activityinstance, + getclassloaderMethod.methodID); + + if (nullptr == klassLoader) { + return false; + } + + JniMethodInfo loadClass; + if (!JniHelper::getMethodInfoDefaultClassLoader(loadClass, + "java/lang/ClassLoader", + "loadClass", + "(Ljava/lang/String;)Ljava/lang/Class;")) { + return false; + } + + JniHelper::classloader = cc::JniHelper::getEnv()->NewGlobalRef(klassLoader); + JniHelper::loadclassMethodMethodId = loadClass.methodID; + JniHelper::sActivity = cc::JniHelper::getEnv()->NewGlobalRef(activityinstance); + if (JniHelper::classloaderCallback != nullptr) { + JniHelper::classloaderCallback(); + } + + return true; +} +#elif CC_PLATFORM == CC_PLATFORM_ANDROID +bool JniHelper::setClassLoaderFrom(jobject activityinstance) { + JniMethodInfo getClassloaderMethod; + if (!JniHelper::getMethodInfoDefaultClassLoader(getClassloaderMethod, + "android/content/Context", + "getClassLoader", + "()Ljava/lang/ClassLoader;")) { + return false; + } + + jobject classLoader = cc::JniHelper::getEnv()->CallObjectMethod(activityinstance, + getClassloaderMethod.methodID); + + if (nullptr == classLoader) { + return false; + } + + JniMethodInfo loadClass; + if (!JniHelper::getMethodInfoDefaultClassLoader(loadClass, + "java/lang/ClassLoader", + "loadClass", + "(Ljava/lang/String;)Ljava/lang/Class;")) { + return false; + } + + JniHelper::classloader = cc::JniHelper::getEnv()->NewGlobalRef(classLoader); + JniHelper::loadclassMethodMethodId = loadClass.methodID; + JniHelper::sActivity = cc::JniHelper::getEnv()->NewGlobalRef(activityinstance); + if (JniHelper::classloaderCallback != nullptr) { + JniHelper::classloaderCallback(); + } + + return true; +} +#endif + +bool JniHelper::getStaticMethodInfo(JniMethodInfo &methodinfo, + const char * className, + const char * methodName, + const char * paramCode) { + if ((nullptr == className) || + (nullptr == methodName) || + (nullptr == paramCode)) { + return false; + } + + JNIEnv *env = JniHelper::getEnv(); + if (!env) { + LOGE("Failed to get JNIEnv"); + return false; + } + + jclass classID = _getClassID(className); + if (!classID) { + LOGE("Failed to find class %s", className); + env->ExceptionClear(); + return false; + } + + jmethodID methodID = env->GetStaticMethodID(classID, methodName, paramCode); + if (!methodID) { + LOGE("Failed to find static method id of %s", methodName); + env->ExceptionClear(); + return false; + } + + methodinfo.classID = classID; + methodinfo.env = env; + methodinfo.methodID = methodID; + return true; +} + +//NOLINTNEXTLINE +bool JniHelper::getMethodInfoDefaultClassLoader(JniMethodInfo &methodinfo, + const char * className, + const char * methodName, + const char * paramCode) { + if ((nullptr == className) || + (nullptr == methodName) || + (nullptr == paramCode)) { + return false; + } + + JNIEnv *env = JniHelper::getEnv(); + if (!env) { + return false; + } + + jclass classID = env->FindClass(className); + if (!classID) { + LOGE("Failed to find class %s", className); + env->ExceptionClear(); + return false; + } + + jmethodID methodID = env->GetMethodID(classID, methodName, paramCode); + if (!methodID) { + LOGE("Failed to find method id of %s", methodName); + env->ExceptionClear(); + return false; + } + + methodinfo.classID = classID; + methodinfo.env = env; + methodinfo.methodID = methodID; + + return true; +} + +bool JniHelper::getMethodInfo(JniMethodInfo &methodinfo, + const char * className, + const char * methodName, + const char * paramCode) { + if ((nullptr == className) || + (nullptr == methodName) || + (nullptr == paramCode)) { + return false; + } + + JNIEnv *env = JniHelper::getEnv(); + if (!env) { + return false; + } + + jclass classID = _getClassID(className); + if (!classID) { + LOGE("Failed to find class %s", className); + env->ExceptionClear(); + return false; + } + + jmethodID methodID = env->GetMethodID(classID, methodName, paramCode); + if (!methodID) { + LOGE("Failed to find method id of %s", methodName); + env->ExceptionClear(); + return false; + } + + methodinfo.classID = classID; + methodinfo.env = env; + methodinfo.methodID = methodID; + + return true; +} + +std::string JniHelper::jstring2string(jstring jstr) { + if (jstr == nullptr) { + return ""; + } + + JNIEnv *env = JniHelper::getEnv(); + if (!env) { + return ""; + } + + std::string strValue = cc::StringUtils::getStringUTFCharsJNI(env, jstr); + + return strValue; +} + +jstring JniHelper::convert(JniHelper::LocalRefMapType *localRefs, cc::JniMethodInfo *t, const char *x) { + jstring ret = nullptr; + if (x) { + ret = cc::StringUtils::newStringUTFJNI(t->env, x); + } + + (*localRefs)[t->env].push_back(ret); + return ret; +} + +jstring JniHelper::convert(JniHelper::LocalRefMapType *localRefs, cc::JniMethodInfo *t, const std::string &x) { + return convert(localRefs, t, x.c_str()); +} + +void JniHelper::deleteLocalRefs(JNIEnv *env, JniHelper::LocalRefMapType *localRefs) { + if (!env) { + return; + } + + for (const auto &ref : (*localRefs)[env]) { + ccDeleteLocalRef(env, ref); + // LOGE("2. delete 0x%p", ref); + } + (*localRefs)[env].clear(); +} + +void JniHelper::reportError(const std::string &className, const std::string &methodName, const std::string &signature) { + LOGE("Failed to find static java method. Class name: %s, method name: %s, signature: %s ", className.c_str(), methodName.c_str(), signature.c_str()); +} + +} //namespace cc diff --git a/native/cocos/platform/android/jni/JniHelper.h b/native/cocos/platform/java/jni/JniHelper.h similarity index 57% rename from native/cocos/platform/android/jni/JniHelper.h rename to native/cocos/platform/java/jni/JniHelper.h index 0065ae5c1c..4ecb956905 100644 --- a/native/cocos/platform/android/jni/JniHelper.h +++ b/native/cocos/platform/java/jni/JniHelper.h @@ -24,15 +24,14 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - -#ifndef __ANDROID_JNI_HELPER_H__ -#define __ANDROID_JNI_HELPER_H__ +#pragma once #include -#include -#include -#include #include +#include +#include +#include +#include "base/Log.h" #include "base/Macros.h" #include "math/Vec3.h" @@ -40,51 +39,73 @@ #define JNI_METHOD2(CLASS2, FUNC2) Java_##CLASS2##_##FUNC2 #define JNI_METHOD1(CLASS1, FUNC1) JNI_METHOD2(CLASS1, FUNC1) +// ccDeleteLocalRef with classid produces warning?? +#if 0 + #define ccDeleteLocalRef(jenv, ref) \ + do { \ + jenv->DeleteLocalRef(ref); \ + CC_LOG_DEBUG("deleteLocalRef file: %s, func: %s, line: %d", __FILE__, __FUNCTION__, __LINE__); \ + } while (0) +#else + #define ccDeleteLocalRef(jenv, ref) jenv->DeleteLocalRef(ref); //NOLINT +#endif + +#define CLEAR_EXCEPTON(env) \ + do { \ + if (env->ExceptionCheck()) { \ + env->ExceptionDescribe(); \ + env->ExceptionClear(); \ + } \ + } while (false) + struct android_app; namespace cc { -typedef struct JniMethodInfo_ { - JNIEnv *env; - jclass classID; +using JniMethodInfo = struct JniMethodInfo_ { //NOLINT(readability-identifier-naming) + JNIEnv * env; + jclass classID; jmethodID methodID; -} JniMethodInfo; +}; class CC_DLL JniHelper { public: - typedef std::unordered_map> LocalRefMapType; + using LocalRefMapType = std::unordered_map>; static JavaVM *getJavaVM(); static JNIEnv *getEnv(); static jobject getActivity(); - static void init(JNIEnv *env, jobject activity); + static void init(JNIEnv *env, jobject activity); - static bool getStaticMethodInfo(JniMethodInfo &methodinfo, - const char *className, - const char *methodName, - const char *paramCode); - static bool getMethodInfo(JniMethodInfo &methodinfo, - const char *className, - const char *methodName, - const char *paramCode); + //NOLINTNEXTLINE + static bool getStaticMethodInfo(JniMethodInfo &methodInfo, + const char * className, + const char * methodName, + const char * paramCode); + + //NOLINTNEXTLINE + static bool getMethodInfo(JniMethodInfo &methodInfo, + const char * className, + const char * methodName, + const char * paramCode); static std::string jstring2string(jstring str); - static jmethodID loadclassMethod_methodID; - static jobject classloader; + static jmethodID loadclassMethodMethodId; + static jobject classloader; static std::function classloaderCallback; template static jobject newObject(const std::string &className, Ts... xs) { - jobject ret = nullptr; + jobject ret = nullptr; static const char *methodName = ""; - cc::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")V"; + cc::JniMethodInfo t; + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")V"; if (cc::JniHelper::getMethodInfo(t, className.c_str(), methodName, signature.c_str())) { LocalRefMapType localRefs; - ret = t.env->NewObject(t.classID, t.methodID, convert(localRefs, t, xs)...); - t.env->DeleteLocalRef(t.classID); - deleteLocalRefs(t.env, localRefs); + ret = t.env->NewObject(t.classID, t.methodID, convert(&localRefs, &t, xs)...); + // ccDeleteLocalRef(t.env, t.classID); + deleteLocalRefs(t.env, &localRefs); } else { reportError(className, methodName, signature); } @@ -92,35 +113,37 @@ public: } template - static void callObjectVoidMethod(jobject object, + static void callObjectVoidMethod(jobject object, const std::string &className, const std::string &methodName, Ts... xs) { cc::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")V"; + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")V"; if (cc::JniHelper::getMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; - t.env->CallVoidMethod(object, t.methodID, convert(localRefs, t, xs)...); - t.env->DeleteLocalRef(t.classID); - deleteLocalRefs(t.env, localRefs); + t.env->CallVoidMethod(object, t.methodID, convert(&localRefs, &t, xs)...); + // ccDeleteLocalRef(t.env, t.classID); + CLEAR_EXCEPTON(t.env); + deleteLocalRefs(t.env, &localRefs); } else { reportError(className, methodName, signature); } } template - static float callObjectFloatMethod(jobject object, + static float callObjectFloatMethod(jobject object, const std::string &className, const std::string &methodName, Ts... xs) { - float ret = 0.0f; + float ret = 0.0F; cc::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")F"; + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")F"; if (cc::JniHelper::getMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; - ret = t.env->CallFloatMethod(object, t.methodID, convert(localRefs, t, xs)...); - t.env->DeleteLocalRef(t.classID); - deleteLocalRefs(t.env, localRefs); + ret = t.env->CallFloatMethod(object, t.methodID, convert(&localRefs, &t, xs)...); + // ccDeleteLocalRef(t.env, t.classID); + CLEAR_EXCEPTON(t.env); + deleteLocalRefs(t.env, &localRefs); } else { reportError(className, methodName, signature); } @@ -128,18 +151,19 @@ public: } template - static jbyteArray callObjectByteArrayMethod(jobject object, + static jbyteArray callObjectByteArrayMethod(jobject object, const std::string &className, const std::string &methodName, Ts... xs) { - jbyteArray ret = nullptr; + jbyteArray ret = nullptr; cc::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")[B"; + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")[B"; if (cc::JniHelper::getMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; - ret = (jbyteArray)t.env->CallObjectMethod(object, t.methodID, convert(localRefs, t, xs)...); - t.env->DeleteLocalRef(t.classID); - deleteLocalRefs(t.env, localRefs); + ret = static_cast(t.env->CallObjectMethod(object, t.methodID, convert(&localRefs, &t, xs)...)); + // ccDeleteLocalRef(t.env, t.classID); + CLEAR_EXCEPTON(t.env); + deleteLocalRefs(t.env, &localRefs); } else { reportError(className, methodName, signature); } @@ -151,12 +175,13 @@ public: const std::string &methodName, Ts... xs) { cc::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")V"; + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")V"; if (cc::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; - t.env->CallStaticVoidMethod(t.classID, t.methodID, convert(localRefs, t, xs)...); - t.env->DeleteLocalRef(t.classID); - deleteLocalRefs(t.env, localRefs); + t.env->CallStaticVoidMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...); + // ccDeleteLocalRef(t.env, t.classID); + CLEAR_EXCEPTON(t.env); + deleteLocalRefs(t.env, &localRefs); } else { reportError(className, methodName, signature); } @@ -166,14 +191,15 @@ public: static bool callStaticBooleanMethod(const std::string &className, const std::string &methodName, Ts... xs) { - jboolean jret = JNI_FALSE; + jboolean jret = JNI_FALSE; cc::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")Z"; + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")Z"; if (cc::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; - jret = t.env->CallStaticBooleanMethod(t.classID, t.methodID, convert(localRefs, t, xs)...); - t.env->DeleteLocalRef(t.classID); - deleteLocalRefs(t.env, localRefs); + jret = t.env->CallStaticBooleanMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...); + //ccDeleteLocalRef(t.env, t.classID); + CLEAR_EXCEPTON(t.env); + deleteLocalRefs(t.env, &localRefs); } else { reportError(className, methodName, signature); } @@ -184,14 +210,15 @@ public: static int callStaticIntMethod(const std::string &className, const std::string &methodName, Ts... xs) { - jint ret = 0; + jint ret = 0; cc::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")I"; + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")I"; if (cc::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; - ret = t.env->CallStaticIntMethod(t.classID, t.methodID, convert(localRefs, t, xs)...); - t.env->DeleteLocalRef(t.classID); - deleteLocalRefs(t.env, localRefs); + ret = t.env->CallStaticIntMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...); + //ccDeleteLocalRef(t.env, t.classID); + CLEAR_EXCEPTON(t.env); + deleteLocalRefs(t.env, &localRefs); } else { reportError(className, methodName, signature); } @@ -202,14 +229,15 @@ public: static float callStaticFloatMethod(const std::string &className, const std::string &methodName, Ts... xs) { - jfloat ret = 0.0; + jfloat ret = 0.0; cc::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")F"; + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")F"; if (cc::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; - ret = t.env->CallStaticFloatMethod(t.classID, t.methodID, convert(localRefs, t, xs)...); - t.env->DeleteLocalRef(t.classID); - deleteLocalRefs(t.env, localRefs); + ret = t.env->CallStaticFloatMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...); + //ccDeleteLocalRef(t.env, t.classID); + CLEAR_EXCEPTON(t.env); + deleteLocalRefs(t.env, &localRefs); } else { reportError(className, methodName, signature); } @@ -220,26 +248,27 @@ public: static float *callStaticFloatArrayMethod(const std::string &className, const std::string &methodName, Ts... xs) { - static float ret[32]; + static float ret[32]; cc::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")[F"; + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")[F"; if (cc::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; - jfloatArray array = (jfloatArray)t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(localRefs, t, xs)...); + auto array = static_cast(t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...)); + CLEAR_EXCEPTON(t.env); jsize len = t.env->GetArrayLength(array); if (len <= 32) { - jfloat *elems = t.env->GetFloatArrayElements(array, 0); + jfloat *elems = t.env->GetFloatArrayElements(array, nullptr); if (elems) { memcpy(ret, elems, sizeof(float) * len); t.env->ReleaseFloatArrayElements(array, elems, 0); }; } - t.env->DeleteLocalRef(t.classID); - deleteLocalRefs(t.env, localRefs); + CLEAR_EXCEPTON(t.env); + // ccDeleteLocalRef(t.env, t.classID); + deleteLocalRefs(t.env, &localRefs); return &ret[0]; - } else { - reportError(className, methodName, signature); } + reportError(className, methodName, signature); return nullptr; } @@ -247,22 +276,24 @@ public: static Vec3 callStaticVec3Method(const std::string &className, const std::string &methodName, Ts... xs) { - Vec3 ret; + Vec3 ret; cc::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")[F"; + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")[F"; if (cc::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; - jfloatArray array = (jfloatArray)t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(localRefs, t, xs)...); + auto array = static_cast(t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...)); + CLEAR_EXCEPTON(t.env); jsize len = t.env->GetArrayLength(array); if (len == 3) { - jfloat *elems = t.env->GetFloatArrayElements(array, 0); - ret.x = elems[0]; - ret.y = elems[1]; - ret.z = elems[2]; + jfloat *elems = t.env->GetFloatArrayElements(array, nullptr); + ret.x = elems[0]; + ret.y = elems[1]; + ret.z = elems[2]; t.env->ReleaseFloatArrayElements(array, elems, 0); } - t.env->DeleteLocalRef(t.classID); - deleteLocalRefs(t.env, localRefs); + CLEAR_EXCEPTON(t.env); + //ccDeleteLocalRef(t.env, t.classID); + deleteLocalRefs(t.env, &localRefs); } else { reportError(className, methodName, signature); } @@ -273,14 +304,15 @@ public: static double callStaticDoubleMethod(const std::string &className, const std::string &methodName, Ts... xs) { - jdouble ret = 0.0; + jdouble ret = 0.0; cc::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")D"; + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")D"; if (cc::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; - ret = t.env->CallStaticDoubleMethod(t.classID, t.methodID, convert(localRefs, t, xs)...); - t.env->DeleteLocalRef(t.classID); - deleteLocalRefs(t.env, localRefs); + ret = t.env->CallStaticDoubleMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...); + CLEAR_EXCEPTON(t.env); + // ccDeleteLocalRef(t.env, t.classID); + deleteLocalRefs(t.env, &localRefs); } else { reportError(className, methodName, signature); } @@ -294,14 +326,14 @@ public: std::string ret; cc::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")Ljava/lang/String;"; + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")Ljava/lang/String;"; if (cc::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; - jstring jret = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(localRefs, t, xs)...); + auto jret = static_cast(t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...)); + CLEAR_EXCEPTON(t.env); ret = cc::JniHelper::jstring2string(jret); - t.env->DeleteLocalRef(t.classID); - t.env->DeleteLocalRef(jret); - deleteLocalRefs(t.env, localRefs); + ccDeleteLocalRef(t.env, jret); + deleteLocalRefs(t.env, &localRefs); } else { reportError(className, methodName, signature); } @@ -310,67 +342,68 @@ public: static bool setClassLoaderFrom(jobject activityInstance); private: - static jobject _activity; - static JavaVM *_javaVM; + static jobject sActivity; + static JavaVM *sJavaVM; static JNIEnv *cacheEnv(); - static bool getMethodInfo_DefaultClassLoader(JniMethodInfo &methodinfo, - const char *className, - const char *methodName, - const char *paramCode); + //NOLINTNEXTLINE + static bool getMethodInfoDefaultClassLoader(JniMethodInfo &methodinfo, + const char * className, + const char * methodName, + const char * paramCode); - static jstring convert(LocalRefMapType &localRefs, cc::JniMethodInfo &t, const char *x); + static jstring convert(LocalRefMapType *localRefs, cc::JniMethodInfo *t, const char *x); - static jstring convert(LocalRefMapType &localRefs, cc::JniMethodInfo &t, const std::string &x); + static jstring convert(LocalRefMapType *localRefs, cc::JniMethodInfo *t, const std::string &x); template - static T convert(LocalRefMapType &localRefs, cc::JniMethodInfo &, T x) { + static T convert(LocalRefMapType * /*localRefs*/, cc::JniMethodInfo * /*t*/, T x) { return x; } - static void deleteLocalRefs(JNIEnv *env, LocalRefMapType &localRefs); + static void deleteLocalRefs(JNIEnv *env, LocalRefMapType *localRefs); static std::string getJNISignature() { return ""; } - static std::string getJNISignature(bool) { + static std::string getJNISignature(bool /*unused*/) { return "Z"; } - static std::string getJNISignature(char) { + static std::string getJNISignature(char /*unused*/) { return "C"; } - static std::string getJNISignature(short) { + static std::string getJNISignature(int16_t /*unused*/) { return "S"; } - static std::string getJNISignature(int) { + static std::string getJNISignature(int32_t /*unused*/) { return "I"; } - static std::string getJNISignature(long) { + static std::string getJNISignature(int64_t /*unused*/) { return "J"; } - static std::string getJNISignature(float) { + static std::string getJNISignature(float /*unused*/) { return "F"; } - static std::string getJNISignature(double) { + static std::string getJNISignature(double /*unused*/) { return "D"; } - static std::string getJNISignature(jbyteArray) { + static std::string getJNISignature(jbyteArray /*unused*/) { return "[B"; } - static std::string getJNISignature(const char *) { + static std::string getJNISignature(const char * /*unused*/) { return "Ljava/lang/String;"; } - static std::string getJNISignature(const std::string &) { + static std::string getJNISignature(const std::string & /*unused*/) { return "Ljava/lang/String;"; } @@ -390,5 +423,3 @@ private: }; } // namespace cc - -#endif // __ANDROID_JNI_HELPER_H__ diff --git a/native/cocos/platform/android/jni/JniImp.cpp b/native/cocos/platform/java/jni/JniImp.cpp similarity index 75% rename from native/cocos/platform/android/jni/JniImp.cpp rename to native/cocos/platform/java/jni/JniImp.cpp index fea99d8315..905a0c54ce 100644 --- a/native/cocos/platform/android/jni/JniImp.cpp +++ b/native/cocos/platform/java/jni/JniImp.cpp @@ -24,7 +24,11 @@ ****************************************************************************/ #include "JniImp.h" -#include +#if ANDROID + #include +#else + #include +#endif #include #include "JniHelper.h" @@ -35,7 +39,7 @@ #define JCLS_HELPER "com/cocos/lib/CocosHelper" #endif -using namespace cc; +using namespace cc; //NOLINT /*********************************************************** * Functions invoke from cpp to Java. @@ -45,26 +49,26 @@ std::string getObbFilePathJNI() { return JniHelper::callStaticStringMethod(JCLS_HELPER, "getObbFilePath"); } -int getObbAssetFileDescriptorJNI(const std::string &path, long *startOffset, long *size) { +int getObbAssetFileDescriptorJNI(const std::string &path, int64_t *startOffset, int64_t *size) { JniMethodInfo methodInfo; - int fd = 0; + int fd = 0; if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_HELPER, "getObbAssetFileDescriptor", "(Ljava/lang/String;)[J")) { - jstring stringArg = methodInfo.env->NewStringUTF(path.c_str()); - jlongArray newArray = (jlongArray)methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID, stringArg); - jsize theArrayLen = methodInfo.env->GetArrayLength(newArray); + jstring stringArg = methodInfo.env->NewStringUTF(path.c_str()); + auto newArray = static_cast(methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID, stringArg)); + jsize theArrayLen = methodInfo.env->GetArrayLength(newArray); if (3 == theArrayLen) { - jboolean copy = JNI_FALSE; - jlong *array = methodInfo.env->GetLongArrayElements(newArray, ©); - fd = static_cast(array[0]); - *startOffset = array[1]; - *size = array[2]; + jboolean copy = JNI_FALSE; + jlong * array = methodInfo.env->GetLongArrayElements(newArray, ©); + fd = static_cast(array[0]); + *startOffset = array[1]; + *size = array[2]; methodInfo.env->ReleaseLongArrayElements(newArray, array, 0); } - methodInfo.env->DeleteLocalRef(methodInfo.classID); - methodInfo.env->DeleteLocalRef(stringArg); + ccDeleteLocalRef(methodInfo.env, methodInfo.classID); + ccDeleteLocalRef(methodInfo.env, stringArg); } return fd; diff --git a/native/cocos/platform/android/jni/JniImp.h b/native/cocos/platform/java/jni/JniImp.h similarity index 87% rename from native/cocos/platform/android/jni/JniImp.h rename to native/cocos/platform/java/jni/JniImp.h index 75a973762b..47daf6ec87 100644 --- a/native/cocos/platform/android/jni/JniImp.h +++ b/native/cocos/platform/java/jni/JniImp.h @@ -28,9 +28,9 @@ #include extern std::string getObbFilePathJNI(); -extern int getObbAssetFileDescriptorJNI(const std::string &path, long *startOffset, long *size); +extern int getObbAssetFileDescriptorJNI(const std::string &path, int64_t *startOffset, int64_t *size); extern std::string getCurrentLanguageJNI(); extern std::string getCurrentLanguageCodeJNI(); extern std::string getSystemVersionJNI(); -extern bool openURLJNI(const std::string &url); -extern void copyTextToClipboardJNI(const std::string &text); \ No newline at end of file +extern bool openURLJNI(const std::string &url); +extern void copyTextToClipboardJNI(const std::string &text); \ No newline at end of file diff --git a/native/cocos/platform/ohos/.gitignore b/native/cocos/platform/ohos/.gitignore new file mode 100644 index 0000000000..30023e62ce --- /dev/null +++ b/native/cocos/platform/ohos/.gitignore @@ -0,0 +1,2 @@ + +build/ diff --git a/native/cocos/platform/ohos/Application-ohos.cpp b/native/cocos/platform/ohos/Application-ohos.cpp new file mode 100644 index 0000000000..2c4fb83b9f --- /dev/null +++ b/native/cocos/platform/ohos/Application-ohos.cpp @@ -0,0 +1,210 @@ +/**************************************************************************** +Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + +http://www.cocos.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ + +#include +#include +#include +#include + +#include "audio/include/AudioEngine.h" +#include "base/Scheduler.h" +#include "cocos/bindings/event/EventDispatcher.h" +#include "cocos/bindings/jswrapper/SeApi.h" +#include "pipeline/Define.h" +#include "pipeline/RenderPipeline.h" +#include "platform/Application.h" +#include "platform/Device.h" +#include "platform/java/jni/JniHelper.h" +#include "platform/java/jni/JniImp.h" +#include "platform/ohos/jni/JniCocosAbility.h" +#include "renderer/GFXDeviceManager.h" + +#include + +#define LOGD(...) HILOG_DEBUG(LOG_APP, __VA_ARGS__) + +namespace { +bool setCanvasCallback(se::Object *global) { //NOLINT + auto viewLogicalSize = cc::Application::getInstance()->getViewLogicalSize(); + se::AutoHandleScope scope; + se::ScriptEngine * se = se::ScriptEngine::getInstance(); + char commandBuf[200] = {0}; + auto * view = cc::cocosApp.pendingWindow; + std::stringstream ss; + ss << "window.innerWidth = " << static_cast(viewLogicalSize.x) << ";" + << "window.innerHeight = " << static_cast(viewLogicalSize.y) << ";" + << "window.windowHandler = " << cc::cocosApp.pendingWindow << ";"; + se->evalString(ss.str().c_str()); + + cc::gfx::DeviceInfo deviceInfo; + deviceInfo.windowHandle = reinterpret_cast(view); + deviceInfo.width = viewLogicalSize.x; + deviceInfo.height = viewLogicalSize.y; + deviceInfo.nativeWidth = viewLogicalSize.x * cc::Device::getDevicePixelRatio(); + deviceInfo.nativeHeight = viewLogicalSize.y * cc::Device::getDevicePixelRatio(); + deviceInfo.bindingMappingInfo = cc::pipeline::bindingMappingInfo; + + cc::gfx::DeviceManager::create(deviceInfo); + + return true; +} +} // namespace + +namespace cc { + +Application * Application::_instance = nullptr; //NOLINT +std::shared_ptr Application::_scheduler = nullptr; //NOLINT + +Application::Application(int width, int height) { + Application::_instance = this; + _scheduler = std::make_shared(); + _viewLogicalSize.x = static_cast(width); + _viewLogicalSize.y = static_cast(height); +} + +Application::~Application() { +#if USE_AUDIO + AudioEngine::end(); +#endif + + pipeline::RenderPipeline::getInstance()->destroy(); + + EventDispatcher::destroy(); + se::ScriptEngine::destroyInstance(); + + gfx::DeviceManager::destroy(); + + Application::_instance = nullptr; +} + +bool Application::init() { + se::ScriptEngine *se = se::ScriptEngine::getInstance(); + se->addRegisterCallback(setCanvasCallback); + + EventDispatcher::init(); + + return true; +} + +void Application::onPause() { +} + +void Application::onResume() { +} + +void Application::setPreferredFramesPerSecond(int fps) { + if (fps == 0) { + return; + } + + _fps = fps; + _prefererredNanosecondsPerFrame = static_cast(1.0 / _fps * NANOSECONDS_PER_SECOND); //NOLINT(google-runtime-int) +} + +std::string Application::getCurrentLanguageCode() const { //NOLINT + return getCurrentLanguageCodeJNI(); +} + +bool Application::isDisplayStats() { //NOLINT + se::AutoHandleScope hs; + se::Value ret; + char commandBuf[100] = "cc.debug.isDisplayStats();"; + se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret); + return ret.toBoolean(); +} + +void Application::setDisplayStats(bool isShow) { //NOLINT + se::AutoHandleScope hs; + char commandBuf[100] = {0}; + sprintf(commandBuf, "cc.debug.setDisplayStats(%s);", isShow ? "true" : "false"); + se::ScriptEngine::getInstance()->evalString(commandBuf); +} + +void Application::setCursorEnabled(bool value) { +} + +Application::LanguageType Application::getCurrentLanguage() const { //NOLINT + std::string languageName = getCurrentLanguageJNI(); + const char * pLanguageName = languageName.c_str(); + LanguageType ret = LanguageType::ENGLISH; + + if (0 == strcmp("zh", pLanguageName)) { + ret = LanguageType::CHINESE; + } else if (0 == strcmp("en", pLanguageName)) { + ret = LanguageType::ENGLISH; + } else if (0 == strcmp("fr", pLanguageName)) { + ret = LanguageType::FRENCH; + } else if (0 == strcmp("it", pLanguageName)) { + ret = LanguageType::ITALIAN; + } else if (0 == strcmp("de", pLanguageName)) { + ret = LanguageType::GERMAN; + } else if (0 == strcmp("es", pLanguageName)) { + ret = LanguageType::SPANISH; + } else if (0 == strcmp("ru", pLanguageName)) { + ret = LanguageType::RUSSIAN; + } else if (0 == strcmp("nl", pLanguageName)) { + ret = LanguageType::DUTCH; + } else if (0 == strcmp("ko", pLanguageName)) { + ret = LanguageType::KOREAN; + } else if (0 == strcmp("ja", pLanguageName)) { + ret = LanguageType::JAPANESE; + } else if (0 == strcmp("hu", pLanguageName)) { + ret = LanguageType::HUNGARIAN; + } else if (0 == strcmp("pt", pLanguageName)) { + ret = LanguageType::PORTUGUESE; + } else if (0 == strcmp("ar", pLanguageName)) { + ret = LanguageType::ARABIC; + } else if (0 == strcmp("nb", pLanguageName)) { + ret = LanguageType::NORWEGIAN; + } else if (0 == strcmp("pl", pLanguageName)) { + ret = LanguageType::POLISH; + } else if (0 == strcmp("tr", pLanguageName)) { + ret = LanguageType::TURKISH; + } else if (0 == strcmp("uk", pLanguageName)) { + ret = LanguageType::UKRAINIAN; + } else if (0 == strcmp("ro", pLanguageName)) { + ret = LanguageType::ROMANIAN; + } else if (0 == strcmp("bg", pLanguageName)) { + ret = LanguageType::BULGARIAN; + } + return ret; +} + +Application::Platform Application::getPlatform() const { //NOLINT + return Platform::OHOS; +} + +bool Application::openURL(const std::string &url) { //NOLINT + return openURLJNI(url); +} + +void Application::copyTextToClipboard(const std::string &text) { //NOLINT + copyTextToClipboardJNI(text); +} + +std::string Application::getSystemVersion() { //NOLINT + return getSystemVersionJNI(); +} + +} // namespace cc diff --git a/native/cocos/platform/ohos/Device-ohos.cpp b/native/cocos/platform/ohos/Device-ohos.cpp new file mode 100644 index 0000000000..33ede63889 --- /dev/null +++ b/native/cocos/platform/ohos/Device-ohos.cpp @@ -0,0 +1,142 @@ +/**************************************************************************** +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 +#include +#include +#include +#include +#include "base/UTF8.h" +#include "platform/Device.h" +#include "platform/FileUtils.h" +#include "platform/java/jni/JniHelper.h" +#include "platform/ohos/jni/JniCocosAbility.h" + +#ifndef JCLS_HELPER + #define JCLS_HELPER "com/cocos/lib/CocosHelper" +#endif + +#ifndef JCLS_SENSOR + #define JCLS_SENSOR "com/cocos/lib/CocosSensorHandler" +#endif + +namespace { +cc::Device::MotionValue motionValue; + +// constant from Android API: +// reference: https://developer.android.com/reference/android/view/Surface#ROTATION_0 +enum Rotation { + ROTATION_0 = 0, + ROTATION_90, + ROTATION_180, + ROTATION_270 +}; +} // namespace + +namespace cc { + +int Device::getDPI() { + static int dpi = -1; + if (dpi == -1) { + dpi = JniHelper::callStaticIntMethod(JCLS_HELPER, "getDPI"); + } + return dpi; +} + +void Device::setAccelerometerEnabled(bool isEnabled) { + JniHelper::callStaticVoidMethod(JCLS_SENSOR, "setAccelerometerEnabled", isEnabled); +} + +void Device::setAccelerometerInterval(float interval) { + JniHelper::callStaticVoidMethod(JCLS_SENSOR, "setAccelerometerInterval", interval); +} + +const Device::MotionValue &Device::getDeviceMotionValue() { + float *v = JniHelper::callStaticFloatArrayMethod(JCLS_SENSOR, "getDeviceMotionValue"); + + if (v) { + motionValue.accelerationIncludingGravityX = v[0]; + motionValue.accelerationIncludingGravityY = v[1]; + motionValue.accelerationIncludingGravityZ = v[2]; + + motionValue.accelerationX = v[3]; + motionValue.accelerationY = v[4]; + motionValue.accelerationZ = v[5]; + + motionValue.rotationRateAlpha = v[6]; + motionValue.rotationRateBeta = v[7]; + motionValue.rotationRateGamma = v[8]; + } else { + memset(&motionValue, 0, sizeof(motionValue)); + } + return motionValue; +} + +Device::Orientation Device::getDeviceOrientation() { + int rotation = JniHelper::callStaticIntMethod(JCLS_HELPER, "getDeviceRotation"); + switch (rotation) { + case ROTATION_0: + return Orientation::PORTRAIT; + case ROTATION_90: + return Orientation::LANDSCAPE_RIGHT; + case ROTATION_180: + return Orientation::PORTRAIT_UPSIDE_DOWN; + case ROTATION_270: + default: + return Orientation::LANDSCAPE_LEFT; + } +} + +std::string Device::getDeviceModel() { + return JniHelper::callStaticStringMethod(JCLS_HELPER, "getDeviceModel"); +} + +void Device::setKeepScreenOn(bool keepScreenOn) { + // JniHelper::callStaticVoidMethod(JCLS_HELPER, "setKeepScreenOn", value); + // ANativeActivity_setWindowFlags(JniHelper::getAndroidApp()->activity, AWINDOW_FLAG_KEEP_SCREEN_ON, 0); +} + +void Device::vibrate(float duration) { + JniHelper::callStaticVoidMethod(JCLS_HELPER, "vibrate", duration); +} + +float Device::getBatteryLevel() { + return JniHelper::callStaticFloatMethod(JCLS_HELPER, "getBatteryLevel"); +} + +Device::NetworkType Device::getNetworkType() { + return static_cast(JniHelper::callStaticIntMethod(JCLS_HELPER, "getNetworkType")); +} + +cc::Vec4 Device::getSafeAreaEdge() { + float *data = JniHelper::callStaticFloatArrayMethod(JCLS_HELPER, "getSafeArea"); + return cc::Vec4(data[0], data[1], data[2], data[3]); +} + +float Device::getDevicePixelRatio() { + return 1; +} +} // namespace cc diff --git a/native/cocos/platform/ohos/FileUtils-ohos.cpp b/native/cocos/platform/ohos/FileUtils-ohos.cpp new file mode 100644 index 0000000000..8ffed0603a --- /dev/null +++ b/native/cocos/platform/ohos/FileUtils-ohos.cpp @@ -0,0 +1,248 @@ +#include "cocos/platform/ohos/FileUtils-ohos.h" +#include +#include +#include +#include +#include +#include "cocos/base/Log.h" +#include "cocos/platform/java/jni/JniHelper.h" + +#include +#include + +#define ASSETS_FOLDER_NAME "@assets/" + +#ifndef JCLS_HELPER + #define JCLS_HELPER "com/cocos/lib/CocosHelper" +#endif + +namespace cc { + +ResourceManager *FileUtilsOHOS::ohosResourceMgr = {}; +std::string FileUtilsOHOS::ohosAssetPath = {}; + +namespace { + +const std::string RAWFILE_PREFIX = "entry/resources/rawfile/"; + +void printRawfiles(ResourceManager *mgr, const std::string &path) { + auto *file = OpenRawFile(mgr, path.c_str()); + if (file) { + HILOG_DEBUG(LOG_APP, "PrintRawfile %{public}s", path.c_str()); + return; + } + + RawDir *dir = OpenRawDir(mgr, path.c_str()); + if (dir) { + auto fileCnt = GetRawFileCount(dir); + for (auto i = 0; i < fileCnt; i++) { + std::string subFile = GetRawFileName(dir, i); + auto newPath = path + "/" + subFile; + auto debugPtr = newPath.c_str(); + HILOG_ERROR(LOG_APP, " find path %{public}s", newPath.c_str()); + printRawfiles(mgr, newPath); + } + } else { + HILOG_ERROR(LOG_APP, "Invalidate path %{public}s", path.c_str()); + } +} +} // namespace + +bool FileUtilsOHOS::initResourceManager(ResourceManager *mgr, const std::string &assetPath) { + CCASSERT(mgr, "ResourceManager should not be empty!"); + ohosResourceMgr = mgr; + if (!assetPath.empty() && assetPath[assetPath.length() - 1] != '/') { + ohosAssetPath = assetPath + "/"; + } else { + ohosAssetPath = assetPath; + } + return true; +} + +ResourceManager *FileUtilsOHOS::getResourceManager() { + return ohosResourceMgr; +} + +FileUtils *FileUtils::getInstance() { + if (s_sharedFileUtils == nullptr) { + s_sharedFileUtils = new FileUtilsOHOS(); + if (!s_sharedFileUtils->init()) { + delete s_sharedFileUtils; + s_sharedFileUtils = nullptr; + CC_LOG_DEBUG("ERROR: Could not init CCFileUtilsAndroid"); + } + } + return s_sharedFileUtils; +} + +// FileUtilsOHOS::FileUtilsOHOS() { +// } +// +// FileUtilsOHOS::~FileUtilsOHOS() noexcept { +// } + +bool FileUtilsOHOS::init() { + _defaultResRootPath = ASSETS_FOLDER_NAME; + return FileUtils::init(); +} + +FileUtils::Status FileUtilsOHOS::getContents(const std::string &filename, ResizableBuffer *buffer) { + if (filename.empty()) { + return FileUtils::Status::NotExists; + } + + std::string fullPath = fullPathForFilename(filename); + if (fullPath.empty()) { + return FileUtils::Status::NotExists; + } + + if (fullPath[0] == '/') { + return FileUtils::getContents(fullPath, buffer); + } + + std::string relativePath; + size_t position = fullPath.find(ASSETS_FOLDER_NAME); + if (0 == position) { + // "@assets/" is at the beginning of the path and we don't want it + relativePath = RAWFILE_PREFIX + fullPath.substr(strlen(ASSETS_FOLDER_NAME)); + } else { + relativePath = fullPath; + } + + if (nullptr == ohosResourceMgr) { + HILOG_ERROR(LOG_APP, "... FileUtilsAndroid::assetmanager is nullptr"); + return FileUtils::Status::NotInitialized; + } + + RawFile *asset = OpenRawFile(ohosResourceMgr, relativePath.c_str()); + if (nullptr == asset) { + HILOG_DEBUG(LOG_APP, "asset (%{public}s) is nullptr", filename.c_str()); + return FileUtils::Status::OpenFailed; + } + + auto size = GetRawFileSize(asset); + buffer->resize(size); + + assert(buffer->buffer()); + + int readsize = ReadRawFile(asset, buffer->buffer(), size); + CloseRawFile(asset); + + // TODO(unknown): read error + if (readsize < size) { + if (readsize >= 0) { + buffer->resize(readsize); + } + return FileUtils::Status::ReadFailed; + } + + return FileUtils::Status::OK; +} + +bool FileUtilsOHOS::isAbsolutePath(const std::string &strPath) const { + return !strPath.empty() && (strPath[0] == '/' || strPath.find(ASSETS_FOLDER_NAME) == 0); +} + +std::string FileUtilsOHOS::getWritablePath() const { + auto tmp = cc::JniHelper::callStaticStringMethod(JCLS_HELPER, "getWritablePath"); + if (tmp.empty()) { + return "./"; + } + return tmp.append("/"); +} + +bool FileUtilsOHOS::isFileExistInternal(const std::string &strFilePath) const { + if (strFilePath.empty()) return false; + auto filePath = strFilePath; + auto fileFound = false; + + if (strFilePath[0] == '/') { // absolute path + struct stat info; + return ::stat(filePath.c_str(), &info) == 0; + } + + // relative path + if (strFilePath.find(_defaultResRootPath) == 0) { + filePath = RAWFILE_PREFIX + filePath.substr(_defaultResRootPath.length()); + } + + auto rawFile = OpenRawFile(ohosResourceMgr, filePath.c_str()); + if (rawFile != nullptr) { + CloseRawFile(rawFile); + return true; + } + return false; +} + +bool FileUtilsOHOS::isDirectoryExistInternal(const std::string &dirPath) const { + if (dirPath.empty()) return false; + std::string dirPathMf = dirPath[dirPath.length() - 1] == '/' ? dirPath.substr(0, dirPath.length() - 1) : dirPath; + + if (dirPathMf[0] == '/') { + struct stat st; + return stat(dirPathMf.c_str(), &st) == 0 && S_ISDIR(st.st_mode); + } + + if (dirPathMf.find(_defaultResRootPath) == 0) { + dirPathMf = RAWFILE_PREFIX + dirPathMf.substr(_defaultResRootPath.length(), dirPathMf.length()); + } + assert(ohosResourceMgr); + auto dir = OpenRawDir(ohosResourceMgr, dirPathMf.c_str()); + if (dir != nullptr) { + CloseRawDir(dir); + return true; + } + return false; +} + +std::string FileUtilsOHOS::expandPath(const std::string &input, bool *isRawFile) const { + if (!input.empty() && input[0] == '/') { + if (isRawFile) *isRawFile = false; + return input; + } + const auto fullpath = fullPathForFilename(input); + + if (fullpath.find(_defaultResRootPath) == 0) { + if (isRawFile) *isRawFile = true; + return RAWFILE_PREFIX + fullpath.substr(_defaultResRootPath.length(), fullpath.length()); + } + + if (isRawFile) *isRawFile = false; + + return fullpath; +} + +std::pair> FileUtilsOHOS::getFd(const std::string &path) const { + bool isRawFile = false; + const auto fullpath = expandPath(path, &isRawFile); + if (isRawFile) { + RawFile *rf = OpenRawFile(ohosResourceMgr, fullpath.c_str()); + // FIXME: try reuse file + const auto bufSize = GetRawFileSize(rf); + auto fileCache = std::vector(bufSize); + auto * buf = fileCache.data(); + // Fill buffer + const auto readBytes = ReadRawFile(rf, buf, bufSize); + assert(readBytes == bufSize); // read failure ? + auto fd = syscall(__NR_memfd_create, fullpath.c_str(), 0); + { + auto writeBytes = ::write(fd, buf, bufSize); // Write can fail? + assert(writeBytes == bufSize); + ::lseek(fd, 0, SEEK_SET); + } + if (errno != 0) { + const auto *errMsg = strerror(errno); + CC_LOG_ERROR("failed to open buffer fd %s", errMsg); + } + return std::make_pair(fd, [fd]() { + close(fd); + }); + } + + FILE *fp = fopen(fullpath.c_str(), "rb"); + return std::make_pair(fileno(fp), [fp]() { + fclose(fp); + }); +} + +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/ohos/FileUtils-ohos.h b/native/cocos/platform/ohos/FileUtils-ohos.h new file mode 100644 index 0000000000..33bb29e1a2 --- /dev/null +++ b/native/cocos/platform/ohos/FileUtils-ohos.h @@ -0,0 +1,46 @@ +#pragma once +//clang-format off +#include +//clang-format on +#include +#include +#include +#include "base/Macros.h" +#include "cocos/platform/FileUtils.h" + +namespace cc { + +class CC_DLL FileUtilsOHOS : public FileUtils { +public: + // FileUtilsOHOS(); + // virtual ~FileUtilsOHOS(); + + static bool initResourceManager(ResourceManager *mgr, const std::string &assetPath); + + static ResourceManager *getResourceManager(); + + bool init() override; + + FileUtils::Status getContents(const std::string &filename, ResizableBuffer *buffer) override; + + bool isAbsolutePath(const std::string &strPath) const override; + + std::string getWritablePath() const override; + + std::string expandPath(const std::string &input, bool *isRawFile) const; + + std::pair> getFd(const std::string &path) const; + +private: + bool isFileExistInternal(const std::string &strFilePath) const override; + + bool isDirectoryExistInternal(const std::string &dirPath) const override; + + /* weak ref, do not need release */ + static ResourceManager *ohosResourceMgr; + static std::string ohosAssetPath; + + friend class FileUtils; +}; + +} // namespace cc diff --git a/native/cocos/platform/ohos/View.cpp b/native/cocos/platform/ohos/View.cpp new file mode 100644 index 0000000000..4bf0070f34 --- /dev/null +++ b/native/cocos/platform/ohos/View.cpp @@ -0,0 +1,74 @@ +/**************************************************************************** +Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +#include "View.h" +#include "cocos/bindings/event/CustomEventTypes.h" +#include "cocos/bindings/event/EventDispatcher.h" +#include "platform/Application.h" +#include "platform/ohos//jni/JniCocosAbility.h" +#include "platform/ohos/jni/AbilityConsts.h" + +//NOLINTNEXTLINE +using namespace cc::ohos; + +namespace cc { + +void View::engineHandleCmd(int cmd) { + static bool isWindowInitialized = false; + // Handle CMD here if needed. + switch (cmd) { + case ABILITY_CMD_INIT_WINDOW: + if (!isWindowInitialized) { + isWindowInitialized = true; + return; + } else { + cc::CustomEvent event; + event.name = EVENT_RECREATE_WINDOW; + event.args->ptrVal = cocosApp.pendingWindow; + cc::EventDispatcher::dispatchCustomEvent(event); + } + break; + case ABILITY_CMD_TERM_WINDOW: { + cc::CustomEvent event; + event.name = EVENT_DESTROY_WINDOW; + cc::EventDispatcher::dispatchCustomEvent(event); + } break; + case ABILITY_CMD_RESUME: + if (Application::getInstance()) { + Application::getInstance()->onResume(); + } + break; + case ABILITY_CMD_PAUSE: + if (Application::getInstance()) { + Application::getInstance()->onPause(); + } + break; + case ABILITY_CMD_LOW_MEMORY: + cc::EventDispatcher::dispatchMemoryWarningEvent(); + break; + default: + break; + } +} + +} // namespace cc diff --git a/native/cocos/platform/ohos/View.h b/native/cocos/platform/ohos/View.h new file mode 100644 index 0000000000..0f8c4bb516 --- /dev/null +++ b/native/cocos/platform/ohos/View.h @@ -0,0 +1,38 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +#pragma once + +#include "base/Macros.h" +#include + +namespace cc { + +class TouchEvent; + +class View { +public: + static void engineHandleCmd(int cmd); +}; + +} // namespace cc diff --git a/native/cocos/platform/ohos/jni/AbilityConsts.h b/native/cocos/platform/ohos/jni/AbilityConsts.h new file mode 100644 index 0000000000..27e3fa953f --- /dev/null +++ b/native/cocos/platform/ohos/jni/AbilityConsts.h @@ -0,0 +1,26 @@ +#pragma once + +#include + +namespace cc { +namespace ohos { +enum { + ABILITY_CMD_INPUT_CHANGED, + ABILITY_CMD_INIT_WINDOW, + ABILITY_CMD_TERM_WINDOW, + ABILITY_CMD_WINDOW_RESIZED, + ABILITY_CMD_WINDOW_REDRAW_NEEDED, + ABILITY_CMD_CONTENT_RECT_CHANGED, + ABILITY_CMD_GAINED_FOCUS, + ABILITY_CMD_LOST_FOCUS, + ABILITY_CMD_CONFIG_CHANGED, + ABILITY_CMD_LOW_MEMORY, + ABILITY_CMD_START, + ABILITY_CMD_RESUME, + ABILITY_CMD_SAVE_STATE, + ABILITY_CMD_PAUSE, + ABILITY_CMD_STOP, + ABILITY_CMD_DESTROY, +}; +} // namespace ohos +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/ohos/jni/JniCocosAbility.cpp b/native/cocos/platform/ohos/jni/JniCocosAbility.cpp new file mode 100644 index 0000000000..30efe5015f --- /dev/null +++ b/native/cocos/platform/ohos/jni/JniCocosAbility.cpp @@ -0,0 +1,276 @@ +/**************************************************************************** +Copyright (c) 2020 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 "platform/ohos/jni/JniCocosAbility.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "base/Log.h" +#include "platform/Application.h" +#include "platform/android/View.h" +#include "platform/java/jni/JniHelper.h" +#include "platform/ohos/FileUtils-ohos.h" +#include "platform/ohos/jni/AbilityConsts.h" + +#define LOGV(...) HILOG_INFO(LOG_APP, __VA_ARGS__) + +extern "C" cc::Application *cocos_main(int, int) __attribute__((weak)); //NOLINT symbol name + +namespace cc { +CocosApp cocosApp; +} + +//NOLINTNEXTLINE +using namespace cc::ohos; + +namespace { +int messagePipe[2]; +int pipeRead = 0; +int pipeWrite = 0; +cc::Application *game = nullptr; + +struct CommandMsg { + int cmd; + std::function callback; +}; + +void createGame(NativeLayer *window) { + int width = NativeLayerHandle(window, NativeLayerOps::GET_WIDTH); + int height = NativeLayerHandle(window, NativeLayerOps::GET_HEIGHT); + game = cocos_main(width, height); + game->init(); +} + +void writeCommandAsync(int cmd) { + CommandMsg msg{.cmd = cmd, .callback = nullptr}; + write(pipeWrite, &msg, sizeof(msg)); +} + +void writeCommandSync(int cmd) { + std::promise fu; + CommandMsg msg{.cmd = cmd, .callback = [&fu]() { + fu.set_value(); + }}; + write(pipeWrite, &msg, sizeof(msg)); + fu.get_future().get(); +} + +int readCommand(CommandMsg *msg) { + return read(pipeRead, msg, sizeof(*msg)); +} + +void handlePauseResume(int8_t cmd) { + LOGV("activityState=%d", cmd); + cc::cocosApp.activityState = cmd; +} + +void preExecCmd(int cmd) { + switch (cmd) { + case ABILITY_CMD_INIT_WINDOW: { + LOGV("ABILITY_CMD_INIT_WINDOW"); + // cc::cocosApp.window = cc::cocosApp.pendingWindow; + cc::cocosApp.animating = true; + + if (!game) { + createGame(cc::cocosApp.pendingWindow); + } + } break; + case ABILITY_CMD_TERM_WINDOW: + LOGV("ABILITY_CMD_TERM_WINDOW"); + cc::cocosApp.animating = false; + break; + case ABILITY_CMD_RESUME: + LOGV("ABILITY_CMD_RESUME"); + handlePauseResume(cmd); + break; + case ABILITY_CMD_PAUSE: + LOGV("ABILITY_CMD_PAUSE"); + handlePauseResume(cmd); + break; + case ABILITY_CMD_DESTROY: + LOGV("ABILITY_CMD_DESTROY"); + cc::cocosApp.destroyRequested = true; + break; + default: + break; + } +} + +void postExecCmd(int cmd) { + switch (cmd) { + case ABILITY_CMD_TERM_WINDOW: + cc::cocosApp.pendingWindow = nullptr; + break; + default: + break; + } +} + +void glThreadEntry() { + cc::cocosApp.glThreadPromise.set_value(); + cc::cocosApp.running = true; + + int cmd = 0; + CommandMsg msg; + while (true) { + if (readCommand(&msg) > 0) { + cmd = msg.cmd; + preExecCmd(cmd); + cc::View::engineHandleCmd(cmd); + postExecCmd(cmd); + if (msg.callback) { + msg.callback(); + } + } + + if (!cc::cocosApp.animating) continue; + + if (game) { + // Handle java events send by UI thread. Input events are handled here too. + cc::JniHelper::callStaticVoidMethod("com.cocos.lib.CocosHelper", + "flushTasksOnGameThread"); + game->tick(); + } + + if (cc::cocosApp.destroyRequested) break; + } + + close(pipeRead); + close(pipeWrite); + + delete game; + game = nullptr; +} + +inline void termAndSetPendingWindow(NativeLayer *window) { + if (cc::cocosApp.pendingWindow) { + writeCommandSync(ABILITY_CMD_TERM_WINDOW); + } + cc::cocosApp.pendingWindow = window; +} + +inline void initWithPendingWindow() { + if (cc::cocosApp.pendingWindow) { + writeCommandSync(ABILITY_CMD_INIT_WINDOW); + } +} + +inline void setActivityState(int cmd) { + writeCommandSync(cmd); +} +} // namespace + +extern "C" { +//NOLINTNEXTLINE JNI function name +JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_onCreateNative(JNIEnv *env, jobject obj, jobject ability, + jstring assetPath, jobject resourceManager, + jint sdkVersion) { + if (cc::cocosApp.running) { + return; + } + + jboolean isCopy = false; + const char *assetPathStr = env->GetStringUTFChars(assetPath, &isCopy); + + cc::cocosApp.sdkVersion = sdkVersion; + cc::JniHelper::init(env, ability); + cc::cocosApp.resourceManager = InitNativeResourceManager(env, resourceManager); + cc::FileUtilsOHOS::initResourceManager(cc::cocosApp.resourceManager, assetPathStr); + + if (isCopy) { + env->ReleaseStringUTFChars(assetPath, assetPathStr); + assetPathStr = nullptr; + } + + if (pipe(messagePipe)) { + LOGV("Can not create pipe: %s", strerror(errno)); + } + pipeRead = messagePipe[0]; + pipeWrite = messagePipe[1]; + if (fcntl(pipeRead, F_SETFL, O_NONBLOCK) < 0) { + LOGV("Can not make pipe read to non blocking mode."); + } + + std::thread glThread(glThreadEntry); + glThread.detach(); + + cc::cocosApp.glThreadPromise.get_future().get(); +} + +JNIEXPORT void JNICALL +Java_com_cocos_lib_CocosAbilitySlice_onSurfaceCreatedNative(JNIEnv *env, jobject obj, jobject surface) { //NOLINT JNI function name + // termAndSetPendingWindow(GetNativeLayer(env, surface)); +} +JNIEXPORT void JNICALL +Java_com_cocos_lib_CocosAbilitySlice_onSurfaceChangedNative(JNIEnv *env, jobject obj, jobject surface, jint width, //NOLINT JNI function name + jint height) { //NOLINT JNI function name + termAndSetPendingWindow(GetNativeLayer(env, surface)); + initWithPendingWindow(); +} + +JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_onSurfaceDestroyNative(JNIEnv *env, jobject obj) { //NOLINT JNI function name + termAndSetPendingWindow(nullptr); +} + +JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_onStartNative(JNIEnv *env, jobject obj) { //NOLINT JNI function name +} + +JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_onPauseNative(JNIEnv *env, jobject obj) { //NOLINT JNI function name + setActivityState(ABILITY_CMD_PAUSE); +} + +JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_onResumeNative(JNIEnv *env, jobject obj) { //NOLINT JNI function name + setActivityState(ABILITY_CMD_RESUME); +} + +JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_onStopNative(JNIEnv *env, jobject obj) { //NOLINT JNI function name +} + +JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_onLowMemoryNative(JNIEnv *env, jobject obj) { //NOLINT JNI function name + writeCommandSync(ABILITY_CMD_LOW_MEMORY); +} + +JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_onOrientationChangedNative(JNIEnv *env, jobject obj, jint orientation, jint width, jint height) { //NOLINT JNI function name + static jint pOrientation = 0; + static jint pWidth = 0; + static jint pHeight = 0; + if (game && (pOrientation != orientation || pWidth != width || pHeight != height)) { + cc::EventDispatcher::dispatchResizeEvent(width, height); + pOrientation = orientation; + pHeight = height; + pWidth = width; + } +} + +JNIEXPORT void JNICALL +Java_com_cocos_lib_CocosAbilitySlice_onWindowFocusChangedNative(JNIEnv *env, jobject obj, jboolean has_focus) { //NOLINT JNI function name +} +} diff --git a/native/cocos/platform/ohos/jni/JniCocosAbility.h b/native/cocos/platform/ohos/jni/JniCocosAbility.h new file mode 100644 index 0000000000..4f6f8d76eb --- /dev/null +++ b/native/cocos/platform/ohos/jni/JniCocosAbility.h @@ -0,0 +1,57 @@ +/**************************************************************************** +Copyright (c) 2020 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 +#include + + +#include + +namespace cc { + +struct CocosApp { + ResourceManager *resourceManager = nullptr; + // NativeLayer *window = nullptr; + int sdkVersion = 0; + + std::promise glThreadPromise; + + NativeLayer *pendingWindow = nullptr; + bool destroyRequested = false; + bool animating = true; + bool running = false; + bool surfaceInited = false; + + // Current state of the app's activity. May be either APP_CMD_RESUME, APP_CMD_PAUSE. + int activityState = 0; +}; + +extern CocosApp cocosApp; + +} // namespace cc diff --git a/native/cocos/platform/ohos/libcocos/build.gradle b/native/cocos/platform/ohos/libcocos/build.gradle new file mode 100644 index 0000000000..6287da93db --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/build.gradle @@ -0,0 +1,13 @@ +apply plugin: 'com.huawei.ohos.library' +ohos { + compileSdkVersion 5 + defaultConfig { + compatibleSdkVersion 5 + } +} + +dependencies { +/// implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation("com.squareup.okhttp3:okhttp:3.12.13") + testCompile'junit:junit:4.12' +} diff --git a/native/cocos/platform/ohos/libcocos/libs/okhttp-3.12.7.jar b/native/cocos/platform/ohos/libcocos/libs/okhttp-3.12.7.jar new file mode 100644 index 0000000000..0eb82665dd Binary files /dev/null and b/native/cocos/platform/ohos/libcocos/libs/okhttp-3.12.7.jar differ diff --git a/native/cocos/platform/ohos/libcocos/libs/okio-1.15.0.jar b/native/cocos/platform/ohos/libcocos/libs/okio-1.15.0.jar new file mode 100644 index 0000000000..4e0e47ab18 Binary files /dev/null and b/native/cocos/platform/ohos/libcocos/libs/okio-1.15.0.jar differ diff --git a/native/cocos/platform/ohos/libcocos/proguard-project.txt b/native/cocos/platform/ohos/libcocos/proguard-project.txt new file mode 100644 index 0000000000..165ce03c33 --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/proguard-project.txt @@ -0,0 +1,24 @@ +# To enable ProGuard in your project, edit project.properties +# to define the proguard.config property as described in that file. +# +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in ${sdk.dir}/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the ProGuard +# include property in project.properties. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: +# Proguard engine for release +-keep public class com.cocos.** { *; } +-dontwarn com.cocos.** + +# Proguard okhttp for release +-keep class okhttp3.** { *; } +-dontwarn okhttp3.** + +-keep class okio.** { *; } +-dontwarn okio.** + diff --git a/native/cocos/platform/ohos/libcocos/src/main/config.json b/native/cocos/platform/ohos/libcocos/src/main/config.json new file mode 100644 index 0000000000..2c3cc57b94 --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/config.json @@ -0,0 +1,34 @@ +{ + "app": { + "bundleName": "com.cocos.libcocos", + "vendor": "cocos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 5, + "target": 5, + "releaseType": "Beta1" + } + }, + "deviceConfig": { + "default": { + "network": { + "cleartextTraffic": true + } + } + }, + "module": { + "package": "com.cocos.lib", + "deviceType": [ + "phone", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "libcocos", + "moduleType": "har" + } + } +} \ No newline at end of file diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CanvasRenderingContext2DImpl.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CanvasRenderingContext2DImpl.java new file mode 100644 index 0000000000..8c798025bb --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CanvasRenderingContext2DImpl.java @@ -0,0 +1,483 @@ +/**************************************************************************** + * Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. + * + * http://www.cocos.com + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + ****************************************************************************/ + +package com.cocos.lib; + +import ohos.agp.render.Canvas; +import ohos.agp.render.Paint; +import ohos.agp.render.Path; +import ohos.agp.render.Texture; +import ohos.agp.text.Font; +import ohos.agp.utils.Color; +import ohos.app.Context; +import ohos.global.resource.RawFileEntry; +import ohos.global.resource.Resource; +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import ohos.media.image.PixelMap; +import ohos.media.image.common.AlphaType; +import ohos.media.image.common.PixelFormat; +import ohos.media.image.common.Rect; + +import java.io.File; +import java.io.FileOutputStream; +import java.lang.ref.WeakReference; +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.IntBuffer; +import java.util.HashMap; + +public class CanvasRenderingContext2DImpl { + + public static final String TAG = "CanvasContext2D"; + public static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0, TAG); + + public static final int TEXT_ALIGN_LEFT = 0; + public static final int TEXT_ALIGN_CENTER = 1; + public static final int TEXT_ALIGN_RIGHT = 2; + + public static final int TEXT_BASELINE_TOP = 0; + public static final int TEXT_BASELINE_MIDDLE = 1; + public static final int TEXT_BASELINE_BOTTOM = 2; + public static final int TEXT_BASELINE_ALPHABETIC = 3; + + public static WeakReference sContext; + public Paint mTextPaint; + public Paint mLinePaint; + public Path mLinePath; + public Canvas mCanvas = new Canvas(); + public Texture mTexture; + public int mTextAlign = TEXT_ALIGN_LEFT; + public int mTextBaseline = TEXT_BASELINE_BOTTOM; + public int mFillStyleR = 0; + public int mFillStyleG = 0; + public int mFillStyleB = 0; + public int mFillStyleA = 255; + + public int mStrokeStyleR = 0; + public int mStrokeStyleG = 0; + public int mStrokeStyleB = 0; + public int mStrokeStyleA = 255; + + public String mFontName = "Arial"; + public float mFontSize = 40.0f; + public float mLineWidth = 0.0f; + public static float _sApproximatingOblique = -0.25f;//please check paint api documentation + public boolean mIsBoldFont = false; + public boolean mIsItalicFont = false; + public boolean mIsObliqueFont = false; + public boolean mIsSmallCapsFontVariant = false; + public String mLineCap = "butt"; + public String mLineJoin = "miter"; + + + public class Point { + Point(float x, float y) { + this.x = x; + this.y = y; + } + + Point(Point pt) { + this.x = pt.x; + this.y = pt.y; + } + + public float x; + public float y; + } + + static void init(Context context) { + sContext = new WeakReference<>(context); + } + + static void destroy() { + sContext = null; + } + + public static HashMap sTypefaceCache = new HashMap<>(); + + // url is a full path started with '@assets/' + public static void loadTypeface(String familyName, String url) { + Context ctx = sContext.get(); + if (!sTypefaceCache.containsKey(familyName)) { + try { + Font.Builder typeface = null; + + if (url.startsWith("/")) { + typeface = new Font.Builder(url); + } else if (ctx != null) { + final String prefix = "@assets/"; + if (url.startsWith(prefix)) { + url = url.substring(prefix.length()); + } + // TODO: 是否可以直接通过 rawfile 创建 font? + File fontTmpFile = CocosHelper.copyOutResFile(ctx, url, "fontFile"); + typeface = new Font.Builder(fontTmpFile); + } + + if (typeface != null) { + sTypefaceCache.put(familyName, typeface); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + // REFINE:: native should clear font cache before exiting game. + public static void clearTypefaceCache() { + sTypefaceCache.clear(); + } + + public static Paint newPaint(String fontName, int fontSize, boolean enableBold, boolean enableItalic, boolean obliqueFont, boolean smallCapsFontVariant) { + Paint paint = new Paint(); + paint.setTextSize(fontSize); + paint.setAntiAlias(true); + paint.setSubpixelAntiAlias(true); + + String key = fontName; + if (enableBold) { + key += "-Bold"; + paint.setFakeBoldText(true); + } + if (enableItalic) { + key += "-Italic"; + } + + Font.Builder typeFace; + if (sTypefaceCache.containsKey(key)) { + typeFace = sTypefaceCache.get(key); + } else { + typeFace = new Font.Builder(fontName); + int style = Font.REGULAR; + typeFace.makeItalic(enableItalic); + typeFace.setWeight(enableBold ? Font.BOLD : Font.REGULAR); + } + paint.setFont(typeFace.build()); + + if (obliqueFont) { + // TODO: skewX 缺少接口 +// paint.setTextSkewX(_sApproximatingOblique); + } + return paint; + } + + public CanvasRenderingContext2DImpl() { + // Log.d(TAG, "constructor"); + } + + public void recreateBuffer(float w, float h) { + // Log.d(TAG, "recreateBuffer:" + w + ", " + h); + PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions(); + initializationOptions.alphaType = AlphaType.UNPREMUL; + initializationOptions.pixelFormat = PixelFormat.ARGB_8888; + initializationOptions.editable = true; // allow writePixels + initializationOptions.size = new ohos.media.image.common.Size((int) Math.ceil(w), (int) Math.ceil(h)); + + PixelMap pixelMap = PixelMap.create(initializationOptions); + mTexture = new Texture(pixelMap); + // NOTE: PixelMap.resetConfig does not change pixel data or nor reallocate memory for pixel data + + mCanvas.setTexture(mTexture); + } + + public void beginPath() { + if (mLinePath == null) { + mLinePath = new Path(); + } + mLinePath.reset(); + } + + public void closePath() { + mLinePath.close(); + } + + public void moveTo(float x, float y) { + mLinePath.moveTo(x, y); + } + + public void lineTo(float x, float y) { + mLinePath.lineTo(x, y); + } + + public void stroke() { + if (mLinePaint == null) { + mLinePaint = new Paint(); + mLinePaint.setAntiAlias(true); + } + + if (mLinePath == null) { + mLinePath = new Path(); + } + + Color strokeColor = new Color(Color.argb(mStrokeStyleA, mStrokeStyleR, mStrokeStyleG, mStrokeStyleB)); + mLinePaint.setColor(strokeColor); + mLinePaint.setStyle(Paint.Style.STROKE_STYLE); + mLinePaint.setStrokeWidth(mLineWidth); + this.setStrokeCap(mLinePaint); + this.setStrokeJoin(mLinePaint); + mCanvas.drawPath(mLinePath, mLinePaint); + } + + public void setStrokeCap(Paint paint) { + switch (mLineCap) { + case "butt": + paint.setStrokeCap(Paint.StrokeCap.BUTT_CAP); + break; + case "round": + paint.setStrokeCap(Paint.StrokeCap.ROUND_CAP); + break; + case "square": + paint.setStrokeCap(Paint.StrokeCap.SQUARE_CAP); + break; + } + } + + public void setStrokeJoin(Paint paint) { + switch (mLineJoin) { + case "bevel": + paint.setStrokeJoin(Paint.Join.BEVEL_JOIN); + break; + case "round": + paint.setStrokeJoin(Paint.Join.ROUND_JOIN); + break; + case "miter": + paint.setStrokeJoin(Paint.Join.MITER_JOIN); + break; + } + } + + public void fill() { + if (mLinePaint == null) { + mLinePaint = new Paint(); + } + + if (mLinePath == null) { + mLinePath = new Path(); + } + + Color fillColor = new Color(Color.argb(mFillStyleA, mFillStyleR, mFillStyleG, mFillStyleB)); + mLinePaint.setColor(fillColor); + mLinePaint.setStyle(Paint.Style.FILL_STYLE); + mCanvas.drawPath(mLinePath, mLinePaint); + // workaround: draw a hairline to cover the border + mLinePaint.setStrokeWidth(0); + this.setStrokeCap(mLinePaint); + this.setStrokeJoin(mLinePaint); + mLinePaint.setStyle(Paint.Style.STROKE_STYLE); + mCanvas.drawPath(mLinePath, mLinePaint); + mLinePaint.setStrokeWidth(mLineWidth); + } + + public void setLineCap(String lineCap) { + mLineCap = lineCap; + } + + public void setLineJoin(String lineJoin) { + mLineJoin = lineJoin; + } + + public void saveContext() { + mCanvas.save(); + } + + public void restoreContext() { + // If there is no saved state, this method should do nothing. + if (mCanvas.getSaveCount() > 1) { + mCanvas.restore(); + } + } + + public void rect(float x, float y, float w, float h) { + beginPath(); + moveTo(x, y); + lineTo(x, y + h); + lineTo(x + w, y + h); + lineTo(x + w, y); + closePath(); + } + + public void clearRect(float x, float y, float w, float h) { +// mTexture.getPixelMap().writePixels(Color.TRANSPARENT.getValue()); + PixelMap pm = mTexture.getPixelMap(); + if (pm.isReleased() || !pm.isEditable()) { + return; + } + Rect region = new Rect((int) x, (int) y, (int) w, (int) h); + int fillSize = (int) (w * h); + IntBuffer buffer = IntBuffer.allocate(fillSize); + for (int i = 0; i < fillSize; i++) { + buffer.put(Color.TRANSPARENT.getValue()); + } + pm.writePixels(buffer.array(), 0, (int) w, region); + } + + public void createTextPaintIfNeeded() { + if (mTextPaint == null) { + mTextPaint = newPaint(mFontName, (int) mFontSize, mIsBoldFont, mIsItalicFont, mIsObliqueFont, mIsSmallCapsFontVariant); + } + } + + public void fillRect(float x, float y, float w, float h) { + PixelMap pm = mTexture.getPixelMap(); + if (pm.isReleased() || !pm.isEditable()) { + return; + } + // Log.d(TAG, "fillRect: " + x + ", " + y + ", " + ", " + w + ", " + h); + int pixelValue = (mFillStyleA & 0xff) << 24 | (mFillStyleR & 0xff) << 16 | (mFillStyleG & 0xff) << 8 | (mFillStyleB & 0xff); + int fillSize = (int) (w * h); + int[] buffer = new int[fillSize]; + IntBuffer fillColors = IntBuffer.wrap(buffer); + for (int i = 0; i < fillSize; ++i) { + buffer[i] = pixelValue; + } + Rect region = new Rect((int) x, (int) y, (int) w, (int) h); + pm.writePixels(buffer, 0, (int) w, region); + } + + public void scaleX(Paint textPaint, String text, float maxWidth) { + if (maxWidth < Float.MIN_VALUE) return; + float measureWidth = this.measureText(text); + if ((measureWidth - maxWidth) < Float.MIN_VALUE) return; + float scaleX = maxWidth / measureWidth; + // TODO: font scale +// textPaint.setTextScaleX(scaleX); + } + + public void fillText(String text, float x, float y, float maxWidth) { + createTextPaintIfNeeded(); + Color fillColor = new Color(Color.argb(mFillStyleA, mFillStyleR, mFillStyleG, mFillStyleB)); + mTextPaint.setColor(fillColor); + mTextPaint.setStyle(Paint.Style.FILL_STYLE); + scaleX(mTextPaint, text, maxWidth); + Point pt = convertDrawPoint(new Point(x, y), text); + mCanvas.drawText(mTextPaint, text, pt.x, pt.y); + } + + public void strokeText(String text, float x, float y, float maxWidth) { + createTextPaintIfNeeded(); + Color strokeColor = new Color(Color.argb(mStrokeStyleA, mStrokeStyleR, mStrokeStyleG, mStrokeStyleB)); + mTextPaint.setColor(strokeColor); + mTextPaint.setStyle(Paint.Style.STROKE_STYLE); + mTextPaint.setStrokeWidth(mLineWidth); + scaleX(mTextPaint, text, maxWidth); + Point pt = convertDrawPoint(new Point(x, y), text); + mCanvas.drawText(mTextPaint, text, pt.x, pt.y); + } + + public float measureText(String text) { + createTextPaintIfNeeded(); + return mTextPaint.measureText(text); + } + + public void updateFont(String fontName, float fontSize, boolean bold, boolean italic, boolean oblique, boolean smallCaps) { + mFontName = fontName; + mFontSize = fontSize; + mIsBoldFont = bold; + mIsItalicFont = italic; + mIsObliqueFont = oblique; + mIsSmallCapsFontVariant = smallCaps; + mTextPaint = null; // Reset paint to re-create paint object in createTextPaintIfNeeded + } + + public void setTextAlign(int align) { + mTextAlign = align; + } + + public void setTextBaseline(int baseline) { + mTextBaseline = baseline; + } + + public void setFillStyle(float r, float g, float b, float a) { + mFillStyleR = (int) (r * 255.0f); + mFillStyleG = (int) (g * 255.0f); + mFillStyleB = (int) (b * 255.0f); + mFillStyleA = (int) (a * 255.0f); + } + + public void setStrokeStyle(float r, float g, float b, float a) { + mStrokeStyleR = (int) (r * 255.0f); + mStrokeStyleG = (int) (g * 255.0f); + mStrokeStyleB = (int) (b * 255.0f); + mStrokeStyleA = (int) (a * 255.0f); + } + + public void setLineWidth(float lineWidth) { + mLineWidth = lineWidth; + } + + @SuppressWarnings("unused") + public void _fillImageData(byte[] imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) { + int fillSize = (int) (imageWidth * imageHeight); + int[] fillColors = new int[fillSize]; + IntBuffer imageIntBuffer = ByteBuffer.wrap(imageData).asIntBuffer(); + for (int i = 0; i < fillSize; ++i) { + // r g b a -> a r g b + fillColors[i] = Integer.rotateRight(imageIntBuffer.get(i), 8); + } + Rect dstRect = new Rect((int) offsetX, (int) offsetY, (int) imageWidth, (int) imageHeight); + mTexture.getPixelMap().writePixels(fillColors, 0, (int) imageWidth, dstRect); + } + + public Point convertDrawPoint(final Point point, String text) { + // The parameter 'point' is located at left-bottom position. + // Need to adjust 'point' according 'text align' & 'text base line'. + Point ret = new Point(point); + createTextPaintIfNeeded(); + Paint.FontMetrics fm = mTextPaint.getFontMetrics(); + float width = measureText(text); + + if (mTextAlign == TEXT_ALIGN_CENTER) { + ret.x -= width / 2; + } else if (mTextAlign == TEXT_ALIGN_RIGHT) { + ret.x -= width; + } + + // Canvas.drawText accepts the y parameter as the baseline position, not the most bottom + if (mTextBaseline == TEXT_BASELINE_TOP) { + ret.y += -fm.ascent; + } else if (mTextBaseline == TEXT_BASELINE_MIDDLE) { + ret.y += (fm.descent - fm.ascent) / 2 - fm.descent; + } else if (mTextBaseline == TEXT_BASELINE_BOTTOM) { + ret.y += -fm.descent; + } + + return ret; + } + + @SuppressWarnings("unused") + public byte[] getDataRef() { + if (mTexture != null && mTexture.getPixelMap() != null) { + final int len = mTexture.getWidth() * mTexture.getHeight() * 4; + final byte[] pixels = new byte[len]; + final ByteBuffer buf = ByteBuffer.wrap(pixels); + buf.order(ByteOrder.nativeOrder()); + mTexture.getPixelMap().readPixels(buf); + return pixels; + } + HiLog.error(LABEL, "getDataRef return null"); + return null; + } +} diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosAbilitySlice.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosAbilitySlice.java new file mode 100644 index 0000000000..799a7d0fc0 --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosAbilitySlice.java @@ -0,0 +1,280 @@ +/**************************************************************************** + * Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. + * + * http://www.cocos.com + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + ****************************************************************************/ + +package com.cocos.lib; + +import ohos.aafwk.ability.AbilitySlice; +import ohos.aafwk.content.Intent; +import ohos.agp.components.Component; +import ohos.agp.components.StackLayout; +import ohos.agp.components.surfaceprovider.SurfaceProvider; +import ohos.agp.graphics.Surface; +import ohos.agp.graphics.SurfaceOps; +import ohos.agp.window.service.WindowManager; +import ohos.bundle.AbilityInfo; +import ohos.global.resource.ResourceManager; +import ohos.multimodalinput.event.KeyEvent; +import ohos.multimodalinput.event.TouchEvent; +import ohos.system.version.SystemVersion; + +import java.io.File; +import java.util.Optional; + +public class CocosAbilitySlice extends AbilitySlice implements SurfaceOps.Callback, Component.TouchEventListener , Component.KeyEventListener, Component.FocusChangedListener { + private boolean mDestroyed; + private StackLayout mRootLayout; + private SurfaceProvider mSurfaceProvider; + private Optional mSurface = Optional.empty(); + private CocosTouchHandler mTouchHandler; + private CocosWebViewHelper mWebViewHelper = null; + private CocosVideoHelper mVideoHelper = null; + private CocosOrientationHelper mOrientationHelper = null; + + private boolean engineInit = false; + + private CocosKeyCodeHandler mKeyCodeHandler; + private CocosSensorHandler mSensorHandler; + + + private native void onCreateNative(AbilitySlice activity, String assetPath, ResourceManager resourceManager, int sdkVersion); + + private native void onSurfaceCreatedNative(Surface surface); + + private native void onSurfaceChangedNative(Surface surface, int width, int height); + + private native void onSurfaceDestroyNative(); + + private native void onPauseNative(); + + private native void onResumeNative(); + + private native void onStopNative(); + + private native void onStartNative(); + + private native void onLowMemoryNative(); + + private native void onOrientationChangedNative(int orientation, int width, int height); + + private native void onWindowFocusChangedNative(boolean hasFocus); + + @Override + protected void onStart(Intent savedInstanceState) { + super.onStart(savedInstanceState); + GlobalObject.setAbilitySlice(this); + CocosHelper.registerBatteryLevelReceiver(this); + CocosHelper.init(this); + CanvasRenderingContext2DImpl.init(this); + onLoadNativeLibraries(); + + getWindow().setTransparent(true); // required for surface provider + + this.getWindow().addFlags(WindowManager.LayoutConfig.MARK_ALLOW_EXTEND_LAYOUT); + this.getWindow().addFlags(WindowManager.LayoutConfig.MARK_FULL_SCREEN); + +// getContext().setDisplayOrientation(AbilityInfo.DisplayOrientation.UNSPECIFIED); +// getWindow().addFlags(WindowManager.LayoutConfig.INPUT_ADJUST_PAN); +// getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING); + + initView(); + + onCreateNative(this, getAssetPath(), getResourceManager(), SystemVersion.getApiVersion()); + + mKeyCodeHandler = new CocosKeyCodeHandler(this); + mSensorHandler = new CocosSensorHandler(); + + mTouchHandler = new CocosTouchHandler(); + + mOrientationHelper = new CocosOrientationHelper(this); + + Thread.currentThread().setName("Cocos-UI"); + CocosHelper.runOnGameThread(()->{ + Thread.currentThread().setName("Cocos-JS"); + }); + } + private String getAssetPath() { + return getApplicationContext().getFilesDir().getPath(); + } + + @Override + protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) { + super.onOrientationChanged(displayOrientation); +// CocosHelper.runOnGameThread(() -> +// onOrientationChangedNative(displayOrientation.ordinal(), mSurfaceProvider.getWidth(), mSurfaceProvider.getHeight()) +// ); + } + + private static String getAbsolutePath(File file) { + return (file != null) ? file.getAbsolutePath() : null; + } + + protected void initView() { + // gles view + StackLayout.LayoutConfig config = new StackLayout.LayoutConfig(StackLayout.LayoutConfig.MATCH_PARENT, StackLayout.LayoutConfig.MATCH_PARENT); + + mSurfaceProvider = new SurfaceProvider(getContext()); + mSurfaceProvider.getSurfaceOps().get().addCallback(this); + mSurfaceProvider.pinToZTop(false); + + mRootLayout = new StackLayout(getContext()); + mRootLayout.setLayoutConfig(config); + + StackLayout.LayoutConfig layoutConfigSurfaceProvider = new StackLayout.LayoutConfig(StackLayout.LayoutConfig.MATCH_PARENT, StackLayout.LayoutConfig.MATCH_PARENT); + + mRootLayout.addComponent(mSurfaceProvider, layoutConfigSurfaceProvider); + mSurfaceProvider.setKeyEventListener(this); + mSurfaceProvider.setFocusable(Component.FOCUS_ENABLE); + mSurfaceProvider.setTouchFocusable(true); + mSurfaceProvider.setFocusChangedListener(this); + mSurfaceProvider.setTouchEventListener(this); + mSurfaceProvider.setLayoutRefreshedListener(component -> { + // dispatch resize event + CocosHelper.runOnGameThread(()->{ + onOrientationChangedNative(getDisplayOrientation(), component.getWidth(), component.getHeight()); + }); + }); + mSurfaceProvider.requestFocus(); + + if (mWebViewHelper == null) { + mWebViewHelper = new CocosWebViewHelper(mRootLayout); + } + + if (mVideoHelper == null) { + mVideoHelper = new CocosVideoHelper(this, mRootLayout); + } + + setUIContent(mRootLayout); + } + + public SurfaceProvider getSurfaceView() { + return this.mSurfaceProvider; + } + + @Override + protected void onStop() { + mDestroyed = true; + if (mSurfaceProvider != null) { + onSurfaceDestroyNative(); + mSurfaceProvider = null; + } + super.onStop(); + } + + @Override + protected void onInactive() { + super.onInactive(); + mSensorHandler.onPause(); + mOrientationHelper.onPause(); + onPauseNative(); + } + + @Override + protected void onActive() { + super.onActive(); + onStartNative(); + mSensorHandler.onResume(); + mOrientationHelper.onResume(); + onResumeNative(); + + } + + @Override + protected void onBackground() { + super.onBackground(); + onStopNative(); + } + + // TODO: low memory listener +// @Override +// public void onLowMemory() { +// super.onLowMemory(); +// if (!mDestroyed) { +// onLowMemoryNative(); +// } +// } + + @Override + public void onFocusChange(Component component, boolean b) { + //NOTICE: may not be equivalent to onWindowFocusChanged on Android + if (!mDestroyed) { + onWindowFocusChangedNative(b); + } + } + + @Override + public void surfaceCreated(SurfaceOps holder) { + if (!mDestroyed) { + mSurface = Optional.of(holder.getSurface()); + onSurfaceCreatedNative(holder.getSurface()); + engineInit = true; + } + } + + @Override + public void surfaceChanged(SurfaceOps surfaceOps, int format, int width, int height) { + if (!mDestroyed) { + mSurface = Optional.of(surfaceOps.getSurface()); + onSurfaceChangedNative(surfaceOps.getSurface(), width, height); + } + } + + @Override + public void surfaceDestroyed(SurfaceOps surfaceOps) { + mRootLayout = null; + if (!mDestroyed) { + onSurfaceDestroyNative(); + engineInit = false; + } + mSurface = Optional.empty(); + } + + private void onLoadNativeLibraries() { + try { + //TODO: Read library name from configuration + System.loadLibrary("cocos"); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + return mKeyCodeHandler.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event); + } + + @Override + public boolean onKeyUp(int keyCode, KeyEvent event) { + return mKeyCodeHandler.onKeyUp(keyCode, event) || super.onKeyUp(keyCode, event); + } + + @Override + public boolean onTouchEvent(Component component, TouchEvent touchEvent) { + return mTouchHandler.onTouchEvent(touchEvent); + } + + @Override + public boolean onKeyEvent(Component component, KeyEvent keyEvent) { + return false; + } +} diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosDownloader.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosDownloader.java new file mode 100644 index 0000000000..879a957b38 --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosDownloader.java @@ -0,0 +1,341 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +package com.cocos.lib; + + +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import okhttp3.*; + +import java.io.*; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.LinkedList; +import java.util.Map; +import java.util.Queue; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; + +public class CocosDownloader { + + private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0, "CocosDownloader"); + + private int _id; + private OkHttpClient _httpClient = null; + + private String _tempFileNameSuffix; + private int _countOfMaxProcessingTasks; + private final ConcurrentHashMap _taskMap = new ConcurrentHashMap<>(); + private final Queue _taskQueue = new LinkedList<>(); + private int _runningTaskCount = 0; + private static final ConcurrentHashMap _resumingSupport = new ConcurrentHashMap<>(); + + private void onProgress(final int id, final long downloadBytes, final long downloadNow, final long downloadTotal) { + CocosHelper.runOnGameThread(() -> + nativeOnProgress(_id, id, downloadBytes, downloadNow, downloadTotal) + ); + } + + private void onFinish(final int id, final int errCode, final String errStr, final byte[] data) { + Call task =_taskMap.get(id); + if (null == task) return; + _taskMap.remove(id); + _runningTaskCount -= 1; + CocosHelper.runOnGameThread(() -> + nativeOnFinish(_id, id, errCode, errStr, data) + ); + runNextTaskIfExists(); + } + + @SuppressWarnings("unused") + public static CocosDownloader createDownloader(int id, int timeoutInSeconds, String tempFileSuffix, int maxProcessingTasks) { + CocosDownloader downloader = new CocosDownloader(); + downloader._id = id; + + if (timeoutInSeconds > 0) { + downloader._httpClient = new OkHttpClient().newBuilder() + .followRedirects(true) + .followSslRedirects(true) + .callTimeout(timeoutInSeconds, TimeUnit.SECONDS) + .build(); + } else { + downloader._httpClient = new OkHttpClient().newBuilder() + .followRedirects(true) + .followSslRedirects(true) + .build(); + } + + + downloader._tempFileNameSuffix = tempFileSuffix; + downloader._countOfMaxProcessingTasks = maxProcessingTasks; + return downloader; + } + + @SuppressWarnings("unused") + public static void createTask(final CocosDownloader downloader, int id_, String url_, String path_, String []header_) { + final int id = id_; + final String url = url_; + final String path = path_; + final String[] header = header_; + + Runnable taskRunnable = new Runnable() { + String domain = null; + String host = null; + File tempFile = null; + File finalFile = null; + long downloadStart = 0; + + @Override + public void run() { + Call task = null; + + do { + if (path.length() > 0) { + try { + URI uri = new URI(url); + domain = uri.getHost(); + } catch (URISyntaxException | NullPointerException e) { + e.printStackTrace(); + break; + } + + // file task + tempFile = new File(path + downloader._tempFileNameSuffix); + if (tempFile.isDirectory()) break; + + File parent = tempFile.getParentFile(); + if (!parent.isDirectory() && !parent.mkdirs()) break; + + finalFile = new File(path); + if (finalFile.isDirectory()) break; + long fileLen = tempFile.length(); + + host = domain.startsWith("www.") ? domain.substring(4) : domain; + if (fileLen > 0) { + if (_resumingSupport.containsKey(host) && _resumingSupport.get(host)) { + downloadStart = fileLen; + } else { + // Remove previous downloaded context + try { + PrintWriter writer = new PrintWriter(tempFile); + writer.print(""); + writer.close(); + } + // Not found then nothing to do + catch (FileNotFoundException e) { + } + } + } + } + + final Request.Builder builder = new Request.Builder().url(url); + for (int i = 0; i < header.length / 2; i++) { + builder.addHeader(header[i * 2], header[(i * 2) + 1]); + } + if (downloadStart > 0) { + builder.addHeader("RANGE", "bytes=" + downloadStart + "-"); + } + + final Request request = builder.build(); + task = downloader._httpClient.newCall(request); + task.enqueue(new Callback() { + @Override + public void onFailure(Call call, IOException e) { + downloader.onFinish(id, 0, e.toString(), null); + } + + @Override + public void onResponse(Call call, Response response) throws IOException { + InputStream is = null; + byte[] buf = new byte[4096]; + FileOutputStream fos = null; + + try { + + if(!(response.code() >= 200 && response.code() <= 206)) { + // it is encourage to delete the tmp file when requested range not satisfiable. + if (response.code() == 416) { + File file = new File(path + downloader._tempFileNameSuffix); + if (file.exists() && file.isFile()) { + file.delete(); + } + } + downloader.onFinish(id, -2, response.message(), null); + return; + } + + long total = response.body().contentLength(); + if (path.length() > 0 && !_resumingSupport.containsKey(host)) { + if (total > 0) { + _resumingSupport.put(host, true); + } else { + _resumingSupport.put(host, false); + } + } + + long current = downloadStart; + is = response.body().byteStream(); + + if (path.length() > 0) { + if (downloadStart > 0) { + fos = new FileOutputStream(tempFile, true); + } else { + fos = new FileOutputStream(tempFile, false); + } + + int len; + while ((len = is.read(buf)) != -1) { + current += len; + fos.write(buf, 0, len); + downloader.onProgress(id, len, current, total); + } + fos.flush(); + + String errStr = null; + do { + // rename temp file to final file, if final file exist, remove it + if (finalFile.exists()) { + if (finalFile.isDirectory()) { + break; + } + if (!finalFile.delete()) { + errStr = "Can't remove old file:" + finalFile.getAbsolutePath(); + break; + } + } + tempFile.renameTo(finalFile); + } while (false); + + if (errStr == null) { + downloader.onFinish(id, 0, null, null); + downloader.runNextTaskIfExists(); + } + else + downloader.onFinish(id, 0, errStr, null); + } else { + // 非文件 + ByteArrayOutputStream buffer; + if(total > 0) { + buffer = new ByteArrayOutputStream((int) total); + } else { + buffer = new ByteArrayOutputStream(4096); + } + + int len; + while ((len = is.read(buf)) != -1) { + current += len; + buffer.write(buf, 0, len); + downloader.onProgress(id, len, current, total); + } + downloader.onFinish(id, 0, null, buffer.toByteArray()); + downloader.runNextTaskIfExists(); + } + } catch (IOException e) { + e.printStackTrace(); + downloader.onFinish(id, 0, e.toString(), null); + } finally { + try { + if (is != null) { + is.close(); + } + if (fos != null) { + fos.close(); + } + } catch (IOException e) { + HiLog.error(LABEL, e.toString()); + } + } + } + }); + } while (false); + + if (null == task) { + final String errStr = "Can't create DownloadTask for " + url; + CocosHelper.runOnGameThread(() -> + downloader.nativeOnFinish(downloader._id, id, 0, errStr, null) + ); + } else { + downloader._taskMap.put(id, task); + } + } + }; + downloader.enqueueTask(taskRunnable); + } + + public static void abort(final CocosDownloader downloader, final int id) { + CocosHelper.runOnUIThread(() -> { + for (Map.Entry entry : downloader._taskMap.entrySet()) { + Object key = entry.getKey(); + Call task = entry.getValue(); + if (null != task && Integer.parseInt(key.toString()) == id) { + task.cancel(); + downloader._taskMap.remove(id); + downloader.runNextTaskIfExists(); + break; + } + } + }); + } + + @SuppressWarnings("unused") + public static void cancelAllRequests(final CocosDownloader downloader) { + CocosHelper.runOnUIThread(() -> { + for (Map.Entry entry : downloader._taskMap.entrySet()) { + Call task = entry.getValue(); + if (null != task) { + task.cancel(); + } + } + }); + } + + + private void enqueueTask(Runnable taskRunnable) { + synchronized (_taskQueue) { + if (_runningTaskCount < _countOfMaxProcessingTasks) { + CocosHelper.runOnUIThread(taskRunnable); + _runningTaskCount++; + } else { + _taskQueue.add(taskRunnable); + } + } + } + + private void runNextTaskIfExists() { + synchronized (_taskQueue) { + while (_runningTaskCount < _countOfMaxProcessingTasks && + CocosDownloader.this._taskQueue.size() > 0) { + + Runnable taskRunnable = CocosDownloader.this._taskQueue.poll(); + CocosHelper.runOnUIThread(taskRunnable); + _runningTaskCount += 1; + } + } + } + + native void nativeOnProgress(int id, int taskId, long dl, long dlnow, long dltotal); + native void nativeOnFinish(int id, int taskId, int errCode, String errStr, final byte[] data); +} diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosEditBoxAbility.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosEditBoxAbility.java new file mode 100644 index 0000000000..4aac97efc8 --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosEditBoxAbility.java @@ -0,0 +1,421 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +package com.cocos.lib; + + +import ohos.aafwk.ability.AbilitySlice; +import ohos.aafwk.content.Intent; +import ohos.accessibility.ability.AccessibleAbility; +import ohos.accessibility.ability.SoftKeyBoardController; +import ohos.agp.components.*; +import ohos.agp.utils.Color; +import ohos.agp.utils.Rect; +import ohos.agp.window.service.DisplayAttributes; +import ohos.agp.window.service.DisplayManager; +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import ohos.multimodalinput.event.TouchEvent; + +import java.lang.ref.WeakReference; + + +public class CocosEditBoxAbility extends AbilitySlice { + + // a color of dark green, was used for confirm button background + private static final Color DARK_GREEN = new Color(Color.getIntColor("#1fa014")); + private static final Color DARK_GREEN_PRESS = new Color(Color.getIntColor("#008e26")); + private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0, "CocosEditBoxAbility"); + + private static WeakReference sThis = null; + private CocosTextHelper mTextField = null; + private Button mButton = null; + private String mButtonTitle = null; + private boolean mConfirmHold = true; + private boolean mIsMultiLine; + + + /*************************************************************************************** + Inner class. + **************************************************************************************/ + class CocosTextHelper { + private final HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP, 0, "Cocos2dxEditBox"); + private Text.TextObserver mTextWatcher = null; + private TextField mTextFieldLocal; + private int mVisibleHeight = 0; + private ComponentContainer mLayout; + + public CocosTextHelper(TextField tf) { + mTextFieldLocal = tf; + DisplayAttributes displayAttrib = DisplayManager.getInstance().getDefaultDisplay(tf.getContext()).get().getRealAttributes(); + + mTextWatcher = new Text.TextObserver() { + @Override + public void onTextUpdated(String s, int i, int i1, int i2) { + CocosEditBoxAbility.this.onKeyboardInput(s); + } + }; + tf.setAdjustInputPanel(true); + + mTextField = this; + + mLayout = (ComponentContainer) findComponentById(ResourceTable.Id_editbox_container); + mLayout.setLayoutRefreshedListener(new Component.LayoutRefreshedListener() { + @Override + public void onRefreshed(Component component) { + HiLog.debug(LABEL, "onRefreshed"); + Rect rect = new Rect(); + boolean result = mTextFieldLocal.getWindowVisibleRect(rect); + if (!result) { + HiLog.debug(LABEL, "getWindowVisibleRect fail"); + return; + } + + int tempVisibleHeight = rect.bottom; + + if (tempVisibleHeight == 0) { + HiLog.debug(LABEL, "invaild rect"); + } else if (mVisibleHeight == 0) { + mVisibleHeight = tempVisibleHeight; + } else { + if (tempVisibleHeight > mVisibleHeight && (Math.abs(tempVisibleHeight - mVisibleHeight) > 200)) { + HiLog.debug(LABEL, "input method down, the height is 0"); + mTextFieldLocal.setText("input method down, the height is 0"); + mVisibleHeight = tempVisibleHeight; + onBoardDown(); + return; + } + if (tempVisibleHeight < mVisibleHeight && (Math.abs(tempVisibleHeight - mVisibleHeight) > 200)) { + HiLog.debug(LABEL, "input method up, the height is" + Math.abs(tempVisibleHeight - mVisibleHeight)); + mTextFieldLocal.setText("input method up, the height is ---" + Math.abs(tempVisibleHeight - mVisibleHeight)); + onBoardUp(Math.abs(tempVisibleHeight - mVisibleHeight)); + mVisibleHeight = tempVisibleHeight; + return; + } + + } + } + }); + } + + + private void onBoardUp(int boardHeight) { + HiLog.debug(LABEL, "onBoardUp, the height is ++++" + boardHeight); + ComponentContainer.LayoutConfig layoutConfig = mTextFieldLocal.getLayoutConfig(); + layoutConfig.setMarginBottom(boardHeight);//835 + mTextFieldLocal.setLayoutConfig(layoutConfig); + } + + private void onBoardDown() { + HiLog.debug(LABEL, "onBoardDown"); + ComponentContainer.LayoutConfig layoutConfig = mTextFieldLocal.getLayoutConfig(); + layoutConfig.setMarginBottom(0); + mTextFieldLocal.setLayoutConfig(layoutConfig); + } + + /*************************************************************************************** + Public functions. + **************************************************************************************/ + + public void show(String defaultValue, int maxLength, boolean isMultiline, boolean confirmHold, String confirmType, String inputType) { + mIsMultiLine = isMultiline; + // TODO: truncate +// this.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)}); +// mTextField.setTruncationMode(Text.TruncationMode.ELLIPSIS_AT_END); + + mTextFieldLocal.setText(defaultValue); + this.setConfirmType(confirmType); +// this.setInputType(inputType, mIsMultiLine); // FIXME: should enable + this.addListeners(); + } + + public void hide() { + mTextFieldLocal.clearFocus(); + this.removeListeners(); + } + + /*************************************************************************************** + Private functions. + **************************************************************************************/ + + private void setConfirmType(final String confirmType) { + if (confirmType.contentEquals("done")) { + mTextFieldLocal.setInputMethodOption(InputAttribute.ENTER_KEY_TYPE_UNSPECIFIED); + mButtonTitle = "Done"; //TODO: read from ResourceTable + } else if (confirmType.contentEquals("next")) { + mTextFieldLocal.setInputMethodOption(InputAttribute.ENTER_KEY_TYPE_UNSPECIFIED); + mButtonTitle = "Done"; //TODO: read from ResourceTable + } else if (confirmType.contentEquals("search")) { + mTextFieldLocal.setInputMethodOption(InputAttribute.ENTER_KEY_TYPE_SEARCH); + mButtonTitle = "Search"; //TODO: read from ResourceTable + } else if (confirmType.contentEquals("go")) { + mTextFieldLocal.setInputMethodOption(InputAttribute.ENTER_KEY_TYPE_GO); + mButtonTitle = "Go"; //TODO: read from ResourceTable + } else if (confirmType.contentEquals("send")) { + mTextFieldLocal.setInputMethodOption(InputAttribute.ENTER_KEY_TYPE_SEND); + mButtonTitle = "Send"; //TODO: read from ResourceTable + } else { + mButtonTitle = null; + HiLog.error(TAG, "unknown confirm type " + confirmType); + } + } + + private void setInputType(final String inputType, boolean isMultiLine) { + if (inputType.contentEquals("text")) { + if (isMultiLine) { +// this.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE); + mTextFieldLocal.setTextInputType(InputAttribute.PATTERN_TEXT); + mTextFieldLocal.setMultipleLine(true); + } else { + mTextFieldLocal.setTextInputType(InputAttribute.PATTERN_TEXT); + mTextFieldLocal.setMultipleLine(false); + } + } else if (inputType.contentEquals("email")) { +// this.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS); + mTextFieldLocal.setTextInputType(InputAttribute.PATTERN_TEXT); + } else if (inputType.contentEquals("number")) { +// this.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED); + mTextFieldLocal.setTextInputType(InputAttribute.PATTERN_NUMBER); + } else if (inputType.contentEquals("phone")) { +// this.setInputType(InputType.TYPE_CLASS_PHONE); + mTextFieldLocal.setTextInputType(InputAttribute.PATTERN_TEXT); + } else if (inputType.contentEquals("password")) { +// this.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); + mTextFieldLocal.setTextInputType(InputAttribute.PATTERN_PASSWORD); + } else { + HiLog.error(TAG, "unknown input type " + inputType); + } + } + + private void addListeners() { + + mTextFieldLocal.setEditorActionListener(new Text.EditorActionListener() { + @Override + public boolean onTextEditorAction(int i) { + //TODO: + return false; + } + }); + + mTextFieldLocal.addTextObserver(mTextWatcher); + } + + private void removeListeners() { +// this.setOnEditorActionListener(null); + mTextFieldLocal.removeTextObserver(mTextWatcher); + } + + } + + @Override + protected void onStart(Intent intent) { + super.onStart(intent); + + getKeyBoard().setShowMode(AccessibleAbility.SHOW_MODE_AUTO); + getAbility().setAbilitySliceAnimator(null); // remove animation + + //FIXME: todo +// getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); // android +// getWindow().setInputPanelDisplayType(Dis); // ohos + + sThis = new WeakReference(this); +// getWindow().setInputPanelDisplayType(WindowManager.LayoutConfig.INPUT_ADJUST_PAN); + + setUIContent(ResourceTable.Layout_editbox_layout); + delayShow(intent); + + + } + + private void delayShow(final Intent intent) { + CocosHelper.runOnUIThread(new Runnable() { + @Override + public void run() { + CocosEditBoxAbility.this.addItems(); + CocosEditBoxAbility.this.show(intent.getStringParam("defaultValue"), + intent.getIntParam("maxLength", 60), + intent.getBooleanParam("isMultiline", false), + intent.getBooleanParam("confirmHold", true), + intent.getStringParam("confirmType"), + intent.getStringParam("inputType")); + + } + }); + } + + + + + /*************************************************************************************** + Public functions. + **************************************************************************************/ + + /*************************************************************************************** + Private functions. + **************************************************************************************/ + private void addItems() { + mTextField = new CocosTextHelper(getTextField()); + mButton = (Button) findComponentById(ResourceTable.Id_editbox_enterBtn); + + mButton.setTouchEventListener(new Component.TouchEventListener() { + @Override + public boolean onTouchEvent(Component component, TouchEvent touchEvent) { + CocosEditBoxAbility.this.onKeyboardConfirm(CocosEditBoxAbility.this.getTextField().getText()); + if (!CocosEditBoxAbility.this.mConfirmHold && touchEvent.getAction() == TouchEvent.PRIMARY_POINT_DOWN) + CocosEditBoxAbility.this.hide(); + return true; + } + }); + // When touch area outside EditText and soft keyboard, then hide. + Component layout = findComponentById(ResourceTable.Id_editbox_container); + layout.setTouchEventListener(new Component.TouchEventListener() { + @Override + public boolean onTouchEvent(Component component, TouchEvent touchEvent) { + if(touchEvent.getAction() == TouchEvent.PRIMARY_POINT_DOWN) { + CocosEditBoxAbility.this.hide(); + } + return true; + } + }); +// layout.setLayoutRefreshedListener(new Component.LayoutRefreshedListener() { +// @Override +// public void onRefreshed(Component component) { +// // detect keyboard re-layout? +// HiLog.debug(LABEL, component.getClass().getSimpleName()); +// } +// }); + } + + private TextField getTextField() { + return (TextField)findComponentById(ResourceTable.Id_editbox_textField); + } + + private void hide() { +// Utils.hideVirtualButton(); // TODO: hide virtual button + this.closeKeyboard(); + } + + public void show(String defaultValue, int maxLength, boolean isMultiline, boolean confirmHold, String confirmType, String inputType) { + TextField tf = getTextField(); + mConfirmHold = confirmHold; + mTextField.show(defaultValue, maxLength, isMultiline, confirmHold, confirmType, inputType); + int editPaddingBottom = tf.getPaddingBottom(); + int editPadding = tf.getPaddingTop(); + tf.setPadding(editPadding, editPadding, editPadding, editPaddingBottom); + + + mButton.setText(mButtonTitle); +// if (mButtonTitle == null || mButton.length() == 0) { +// mButton.setPadding(0, 0, 0, 0); +// mButtonParams.setMargins(0, 0, 0, 0); +// mButtonLayout.setVisibility(Component.INVISIBLE); +// } else { +// int buttonTextPadding = mEditText.getPaddingBottom() / 2; +// mButton.setPadding(editPadding, buttonTextPadding, editPadding, buttonTextPadding); +// mButtonParams.setMargins(0, buttonTextPadding, 2, 0); +// mButtonLayout.setVisibility(Component.VISIBLE); +// } + + this.openKeyboard(); + } + + private void closeKeyboard() { + TextField tf = getTextField(); + CocosHelper.runOnUIThread(tf::clearFocus); + this.onKeyboardComplete(tf.getText()); + + } + + private void openKeyboard() { + TextField tf = getTextField(); + CocosHelper.runOnUIThread(() -> { + tf.requestFocus(); + tf.simulateClick(); + }); + } + + private SoftKeyBoardController getKeyBoard() { + return ((AccessibleAbility)getAbility()).getSoftKeyBoardController(); + } + + /*************************************************************************************** + Functions invoked by CPP. + **************************************************************************************/ + + @SuppressWarnings("unused") + private static void showNative(String defaultValue, int maxLength, boolean isMultiline, boolean confirmHold, String confirmType, String inputType) { + + CocosHelper.runOnUIThread(() -> { + Intent i = new Intent(); + i.setParam("defaultValue", defaultValue); + i.setParam("maxLength", maxLength); + i.setParam("isMultiline", isMultiline); + i.setParam("confirmHold", confirmHold); + i.setParam("confirmType", confirmType); + i.setParam("inputType", inputType); + CocosEditBoxAbility ability = new CocosEditBoxAbility(); + GlobalObject.getAbilitySlice().present(ability, i); + }); + } + + @SuppressWarnings("unused") + private static void hideNative() { + CocosHelper.runOnUIThread(() -> { + if(null != CocosEditBoxAbility.sThis) { + CocosEditBoxAbility ability = CocosEditBoxAbility.sThis.get(); + if(ability != null) { + ability.hide(); + ability.terminate(); + CocosEditBoxAbility.sThis = null; + } + } + }); + } + + /*************************************************************************************** + Native functions invoked by UI. + **************************************************************************************/ + private void onKeyboardInput(String text) { + CocosHelper.runOnGameThread(() -> + CocosEditBoxAbility.onKeyboardInputNative(text) + ); + } + + private void onKeyboardComplete(String text) { + CocosHelper.runOnGameThread(() -> + CocosEditBoxAbility.onKeyboardCompleteNative(text) + ); + } + + private void onKeyboardConfirm(String text) { + CocosHelper.runOnGameThread(() -> + CocosEditBoxAbility.onKeyboardConfirmNative(text) + ); + } + + private static native void onKeyboardInputNative(String text); + + private static native void onKeyboardCompleteNative(String text); + + private static native void onKeyboardConfirmNative(String text); +} diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosHandler.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosHandler.java new file mode 100644 index 0000000000..17c904418b --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosHandler.java @@ -0,0 +1,106 @@ +/**************************************************************************** +Copyright (c) 2010-2013 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. + ****************************************************************************/ + +package com.cocos.lib; + +import ohos.agp.window.dialog.CommonDialog; +import ohos.agp.window.dialog.IDialog; +import ohos.eventhandler.EventHandler; +import ohos.eventhandler.EventRunner; +import ohos.eventhandler.InnerEvent; + +import java.lang.ref.WeakReference; + +public class CocosHandler extends EventHandler { + // =========================================================== + // Constants + // =========================================================== + public final static int HANDLER_SHOW_DIALOG = 1; + + // =========================================================== + // Fields + // =========================================================== + private WeakReference mActivity; + + // =========================================================== + // Constructors + // =========================================================== + public CocosHandler(CocosAbilitySlice activity) { + super(EventRunner.getMainEventRunner()); + this.mActivity = new WeakReference(activity); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + @Override + public void processEvent(InnerEvent msg) { + switch (msg.eventId) { + case CocosHandler.HANDLER_SHOW_DIALOG: + showDialog(msg); + break; + } + } + + private void showDialog(InnerEvent msg) { + CocosAbilitySlice theActivity = this.mActivity.get(); + DialogMessage dialogMessage = (DialogMessage)msg.object; + + CommonDialog dialog = new CommonDialog(theActivity.getContext()); + dialog.setTitleText(dialogMessage.title) + .setContentText(dialogMessage.message) + .setButton(IDialog.BUTTON1, "OK", new IDialog.ClickedListener() { + @Override + public void onClick(IDialog iDialog, int i) { + + } + }); + dialog.show(); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static class DialogMessage { + public String title; + public String message; + + public DialogMessage(String title, String message) { + this.title = title; + this.message = message; + } + } +} diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosHelper.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosHelper.java new file mode 100644 index 0000000000..96c6f60802 --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosHelper.java @@ -0,0 +1,342 @@ +/**************************************************************************** + 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. + ****************************************************************************/ +package com.cocos.lib; + +import ohos.aafwk.ability.AbilitySlice; +import ohos.aafwk.content.Intent; +import ohos.aafwk.content.Operation; +import ohos.agp.text.Font; +import ohos.agp.window.service.Display; +import ohos.agp.window.service.DisplayManager; +import ohos.app.Context; +import ohos.app.dispatcher.TaskDispatcher; +import ohos.batterymanager.BatteryInfo; +import ohos.event.commonevent.*; +import ohos.global.resource.RawFileEntry; +import ohos.global.resource.Resource; +import ohos.miscservices.pasteboard.PasteData; +import ohos.miscservices.pasteboard.SystemPasteboard; +import ohos.net.NetManager; +import ohos.rpc.RemoteException; +import ohos.system.DeviceInfo; +import ohos.system.version.SystemVersion; +import ohos.utils.net.Uri; +import ohos.vibrator.agent.VibratorAgent; +import ohos.vibrator.bean.VibrationPattern; +import ohos.wifi.WifiDevice; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.*; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.FutureTask; + + +public class CocosHelper { + // =========================================================== + // Constants + // =========================================================== + private static final String TAG = CocosHelper.class.getSimpleName(); + + // =========================================================== + // Fields + // =========================================================== + + private static AbilitySlice sAbilitySlice; + private static VibratorAgent sVibrateService; + private static Optional sBatteryReceiver = Optional.empty(); + private static Thread sUIThread = null; + + public static final int NETWORK_TYPE_NONE = 0; + public static final int NETWORK_TYPE_LAN = 1; + public static final int NETWORK_TYPE_WWAN = 2; + + // The absolute path to the OBB if it exists. + private static String sObbFilePath = ""; + + + private static List sTaskOnGameThread = Collections.synchronizedList(new ArrayList<>()); + + /** + * Battery receiver to getting battery level. + */ + static class BatteryReceiver extends CommonEventSubscriber { + public float sBatteryLevel = 0.0f; + + public BatteryReceiver(CommonEventSubscribeInfo subscribeInfo) { + super(subscribeInfo); + } + + @Override + public void onReceiveEvent(CommonEventData commonEventData) { + Intent intent = commonEventData.getIntent(); + if (intent != null) { + int capacity = intent.getIntParam(BatteryInfo.OHOS_BATTERY_CAPACITY, 100); + float level = capacity / 100.0f; + sBatteryLevel = Math.min(Math.max(level, 0.0f), 1.0f); + } + + } + } + + static void registerBatteryLevelReceiver(Context context) { + if (sBatteryReceiver.isPresent()) return; + + MatchingSkills ms = new MatchingSkills(); + ms.addEvent(CommonEventSupport.COMMON_EVENT_BATTERY_CHANGED); + CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(ms); + sBatteryReceiver = Optional.of(new BatteryReceiver(subscribeInfo)); + try { + CommonEventManager.subscribeCommonEvent(sBatteryReceiver.get()); + } catch (RemoteException e) { + e.printStackTrace(); + } + } + + @SuppressWarnings("unused") + static void unregisterBatteryLevelReceiver(Context context) { + if (sBatteryReceiver.isPresent()) { + try { + CommonEventManager.unsubscribeCommonEvent(sBatteryReceiver.get()); + } catch (RemoteException e) { + e.printStackTrace(); + } + sBatteryReceiver = Optional.empty(); + } + } + + public static void runOnGameThread(final Runnable runnable) { + sTaskOnGameThread.add(runnable); + } + + @SuppressWarnings("unused") + static void flushTasksOnGameThread() { + while (sTaskOnGameThread.size() > 0) { + Runnable r = sTaskOnGameThread.remove(0); + if (r != null) { + r.run(); + } + } + } + + @SuppressWarnings("unused") + public static int getNetworkType() { + + NetManager netManager = NetManager.getInstance(sAbilitySlice.getContext()); + if (!netManager.hasDefaultNet()) return NETWORK_TYPE_NONE; + + WifiDevice wifiDevice = WifiDevice.getInstance(sAbilitySlice.getContext()); + if (null == wifiDevice) return NETWORK_TYPE_NONE; + + if (wifiDevice.isWifiActive() && wifiDevice.isConnected()) { + return NETWORK_TYPE_LAN; + } + return NETWORK_TYPE_WWAN; + } + + // =========================================================== + // Constructors + // =========================================================== + + private static boolean sInited = false; + + public static void init(final AbilitySlice activity) { + sAbilitySlice = activity; + if (!sInited) { + CocosHelper.sVibrateService = new VibratorAgent(); + CocosHelper.sUIThread = Thread.currentThread(); + sInited = true; + } + + } + + @SuppressWarnings("unused") + public static float getBatteryLevel() { + return sBatteryReceiver.map(x -> x.sBatteryLevel).orElse(1.0f); + } + + @SuppressWarnings("unused") + public static String getObbFilePath() { + return CocosHelper.sObbFilePath; + } + + public static String getWritablePath() { + return sAbilitySlice.getApplicationContext().getFilesDir().getAbsolutePath(); + } + + @SuppressWarnings("unused") + public static String getCurrentLanguage() { + return Locale.getDefault().getLanguage(); + } + + @SuppressWarnings("unused") + public static String getCurrentLanguageCode() { + return Locale.getDefault().toString(); + } + + @SuppressWarnings("unused") + public static String getDeviceModel() { + return DeviceInfo.getModel(); + } + + @SuppressWarnings("unused") + public static String getSystemVersion() { + return SystemVersion.getVersion(); + } + + @SuppressWarnings("unused") + public static void vibrate(float durSec) { + List vlist = sVibrateService.getVibratorIdList(); + if (vlist.isEmpty()) return; + int durationMs = (int) (1000 * durSec); + int vibrateId = -1; + for (Integer vId : vlist) { + // TODO: choose preferred vibration effect + if (sVibrateService.isEffectSupport(vId, VibrationPattern.VIBRATOR_TYPE_CAMERA_CLICK)) { + vibrateId = vId; + break; + } + } + if (vibrateId < 0) { + sVibrateService.startOnce(durationMs); + } else { + sVibrateService.startOnce(durationMs, vibrateId); + } + } + + @SuppressWarnings("unused") + public static boolean openURL(String url) { + runOnUIThread(new Runnable() { + @Override + public void run() { + Intent i = new Intent(); + Operation operation = new Intent.OperationBuilder() + .withUri(Uri.parse(url)) + .build(); + i.setOperation(operation); + sAbilitySlice.startAbility(i); + } + }); + return true; + } + + @SuppressWarnings("unused") + public static void copyTextToClipboard(final String text) { + runOnUIThread(new Runnable() { + @Override + public void run() { + PasteData pasteData = PasteData.creatPlainTextData(text); + SystemPasteboard.getSystemPasteboard(sAbilitySlice.getContext()).setPasteData(pasteData); + } + }); + } + + public static void runOnUIThread(final Runnable r, boolean forceDelay) { + if (Thread.currentThread().getId() == sUIThread.getId() && !forceDelay) { + r.run(); + } else { + TaskDispatcher dispatcher = sAbilitySlice.getUITaskDispatcher(); + dispatcher.asyncDispatch(r); + } + } + + public static void runOnUIThread(final Runnable r) { + runOnUIThread(r, false); + } + + public static void ruOnUIThreadSync(final Runnable r) { + CountDownLatch cd = new CountDownLatch(1); + runOnUIThread(() -> { + r.run(); + cd.countDown(); + }); + try { + cd.await(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + public static int getDeviceRotation() { + try { + DisplayManager mgr = DisplayManager.getInstance(); + Optional display = mgr.getDefaultDisplay(sAbilitySlice.getContext()); + return display.map(Display::getRotation).orElse(0); + } catch (NullPointerException e) { + e.printStackTrace(); + } + // 0 indicates no rotation, + // 1 indicates 90 degrees, + // 2 indicates 180 degrees, + // 3 indicates 270 degrees. + return 0; + } + + public static float[] getSafeArea() { + return new float[]{0, 0, 0, 0}; + } + + @SuppressWarnings("unused") + public static int getDPI() { + Optional disp = DisplayManager.getInstance().getDefaultDisplay(getContext()); + if (disp.isPresent()) { + return (int) disp.get().getAttributes().xDpi; + } + return -1; + } + + public static Context getContext() { + return sAbilitySlice.getContext(); + } + + public static File copyOutResFile(Context ctx, String path, String tmpName) throws IOException{ + File fontTmpFile; + FileOutputStream fontOutputStream=null; + Resource resource = null; + if(!path.startsWith("resources/rawfile/")){ + path = "resources/rawfile/" + path; + } + RawFileEntry entry = ctx.getResourceManager().getRawFileEntry(path); + try { + fontTmpFile = File.createTempFile(tmpName, "-tmp"); + fontOutputStream = new FileOutputStream(fontTmpFile); + resource = entry.openRawFile(); + byte[] buf = new byte[4096]; + while (resource.available() > 0) { + int readBytes = resource.read(buf, 0, 4096); + if (readBytes > 0) + fontOutputStream.write(buf, 0, readBytes); + } + } finally { + if(fontOutputStream!=null) + fontOutputStream.close(); + if(resource != null) + resource.close(); + } + return fontTmpFile; + } +} diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosHttpURLConnection.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosHttpURLConnection.java new file mode 100644 index 0000000000..e2faea71ed --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosHttpURLConnection.java @@ -0,0 +1,432 @@ +/**************************************************************************** + Copyright (c) 2010-2014 cocos2d-x.org + Copyright (c) 2014-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. + ****************************************************************************/ +package com.cocos.lib; + + +import ohos.global.resource.RawFileEntry; +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.ProtocolException; +import java.net.URL; +import java.security.KeyStore; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; +import java.util.zip.GZIPInputStream; +import java.util.zip.InflaterInputStream; + +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; + +public class CocosHttpURLConnection { + private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0, "CocosHttpURLConnection"); + private static final String POST_METHOD = "POST"; + private static final String PUT_METHOD = "PUT"; + + @SuppressWarnings("unused") + static HttpURLConnection createHttpURLConnection(String linkURL) { + URL url; + HttpURLConnection urlConnection; + try { + url = new URL(linkURL); + urlConnection = (HttpURLConnection) url.openConnection(); + //Accept-Encoding + urlConnection.setRequestProperty("Accept-Encoding", "identity"); + urlConnection.setDoInput(true); + } catch (Exception e) { + e.printStackTrace(); + HiLog.error(LABEL, "createHttpURLConnection:" + e.toString()); + return null; + } + + return urlConnection; + } + + @SuppressWarnings("unused") + static void setReadAndConnectTimeout(HttpURLConnection urlConnection, int readMiliseconds, int connectMiliseconds) { + urlConnection.setReadTimeout(readMiliseconds); + urlConnection.setConnectTimeout(connectMiliseconds); + } + + @SuppressWarnings("unused") + static void setRequestMethod(HttpURLConnection urlConnection, String method) { + try { + urlConnection.setRequestMethod(method); + if (method.equalsIgnoreCase(POST_METHOD) || method.equalsIgnoreCase(PUT_METHOD)) { + urlConnection.setDoOutput(true); + } + } catch (ProtocolException e) { + HiLog.error(LABEL, "setRequestMethod:" + e.toString()); + } + + } + + @SuppressWarnings("unused") + static void setVerifySSL(HttpURLConnection urlConnection, String sslFilename) { + if (!(urlConnection instanceof HttpsURLConnection)) + return; + + + HttpsURLConnection httpsURLConnection = (HttpsURLConnection) urlConnection; + + try { + InputStream caInput = null; + FileInputStream fileInputStream = null; + if (sslFilename.startsWith("/")) { + caInput = new BufferedInputStream(new FileInputStream(sslFilename)); + } else { + String assetString = "assets/"; + String assetsfilenameString = sslFilename.substring(assetString.length()); + RawFileEntry fileEntry = CocosHelper.getContext().getResourceManager().getRawFileEntry(assetsfilenameString); + fileInputStream = new FileInputStream(fileEntry.openRawFileDescriptor().getFileDescriptor()); + caInput = new BufferedInputStream(fileInputStream); + } + + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + Certificate ca; + ca = cf.generateCertificate(caInput); + System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN()); + caInput.close(); + if (fileInputStream != null) fileInputStream.close(); + + // Create a KeyStore containing our trusted CAs + String keyStoreType = KeyStore.getDefaultType(); + KeyStore keyStore = KeyStore.getInstance(keyStoreType); + keyStore.load(null, null); + keyStore.setCertificateEntry("ca", ca); + + // Create a TrustManager that trusts the CAs in our KeyStore + String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); + TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); + tmf.init(keyStore); + + // Create an SSLContext that uses our TrustManager + SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, tmf.getTrustManagers(), null); + + httpsURLConnection.setSSLSocketFactory(context.getSocketFactory()); + } catch (Exception e) { + e.printStackTrace(); + HiLog.error(LABEL, "setVerifySSL:" + e.toString()); + } + } + + + @SuppressWarnings("unused") + static void addRequestHeader(HttpURLConnection urlConnection, String key, String value) { + urlConnection.setRequestProperty(key, value); + } + + @SuppressWarnings("unused") + static int connect(HttpURLConnection http) { + int suc = 0; + + try { + http.connect(); + } catch (Exception e) { + e.printStackTrace(); + HiLog.error(LABEL, "connect" + e.toString()); + suc = 1; + } + + return suc; + } + + @SuppressWarnings("unused") + static void disconnect(HttpURLConnection http) { + http.disconnect(); + } + + @SuppressWarnings("unused") + static void sendRequest(HttpURLConnection http, byte[] byteArray) { + try { + OutputStream out = http.getOutputStream(); + if (null != byteArray) { + out.write(byteArray); + out.flush(); + } + out.close(); + } catch (Exception e) { + e.printStackTrace(); + HiLog.error(LABEL, "sendRequest:" + e.toString()); + } + } + + @SuppressWarnings("unused") + static String getResponseHeaders(HttpURLConnection http) { + Map> headers = http.getHeaderFields(); + if (null == headers) { + return null; + } + + String header = ""; + + for (Entry> entry : headers.entrySet()) { + String key = entry.getKey(); + if (null == key) { + header += listToString(entry.getValue(), ",") + "\n"; + } else { + header += key + ":" + listToString(entry.getValue(), ",") + "\n"; + } + } + + return header; + } + + @SuppressWarnings("unused") + static String getResponseHeaderByIdx(HttpURLConnection http, int idx) { + Map> headers = http.getHeaderFields(); + if (null == headers) { + return null; + } + + String header = null; + + int counter = 0; + for (Entry> entry : headers.entrySet()) { + if (counter == idx) { + String key = entry.getKey(); + if (null == key) { + header = listToString(entry.getValue(), ",") + "\n"; + } else { + header = key + ":" + listToString(entry.getValue(), ",") + "\n"; + } + break; + } + counter++; + } + + return header; + } + + @SuppressWarnings("unused") + static String getResponseHeaderByKey(HttpURLConnection http, String key) { + if (null == key) { + return null; + } + + Map> headers = http.getHeaderFields(); + if (null == headers) { + return null; + } + + String header = null; + + for (Entry> entry : headers.entrySet()) { + if (key.equalsIgnoreCase(entry.getKey())) { + if ("set-cookie".equalsIgnoreCase(key)) { + header = combinCookies(entry.getValue(), http.getURL().getHost()); + } else { + header = listToString(entry.getValue(), ","); + } + break; + } + } + + return header; + } + + @SuppressWarnings("unused") + static int getResponseHeaderByKeyInt(HttpURLConnection http, String key) { + String value = http.getHeaderField(key); + + if (null == value) { + return 0; + } else { + return Integer.parseInt(value); + } + } + + @SuppressWarnings("unused") + static byte[] getResponseContent(HttpURLConnection http) { + InputStream in; + try { + in = http.getInputStream(); + String contentEncoding = http.getContentEncoding(); + if (contentEncoding != null) { + if (contentEncoding.equalsIgnoreCase("gzip")) { + in = new GZIPInputStream(http.getInputStream()); //reads 2 bytes to determine GZIP stream! + } else if (contentEncoding.equalsIgnoreCase("deflate")) { + in = new InflaterInputStream(http.getInputStream()); + } + } + } catch (IOException e) { + in = http.getErrorStream(); + } catch (Exception e) { + e.printStackTrace(); + HiLog.error(LABEL, "1 getResponseContent: " + e.toString()); + return null; + } + + try { + byte[] buffer = new byte[1024]; + int size = 0; + ByteArrayOutputStream bytestream = new ByteArrayOutputStream(); + while ((size = in.read(buffer, 0, 1024)) != -1) { + bytestream.write(buffer, 0, size); + } + byte retbuffer[] = bytestream.toByteArray(); + bytestream.close(); + return retbuffer; + } catch (Exception e) { + e.printStackTrace(); + HiLog.error(LABEL, "2 getResponseContent:" + e.toString()); + } + + return null; + } + + @SuppressWarnings("unused") + static int getResponseCode(HttpURLConnection http) { + int code = 0; + try { + code = http.getResponseCode(); + } catch (Exception e) { + e.printStackTrace(); + HiLog.error(LABEL, "getResponseCode:" + e.toString()); + } + return code; + } + + @SuppressWarnings("unused") + static String getResponseMessage(HttpURLConnection http) { + String msg; + try { + msg = http.getResponseMessage(); + } catch (Exception e) { + e.printStackTrace(); + msg = e.toString(); + HiLog.error(LABEL, "getResponseMessage: " + msg); + } + + return msg; + } + + public static String listToString(List list, String strInterVal) { + if (list == null) { + return null; + } + StringBuilder result = new StringBuilder(); + boolean flag = false; + for (String str : list) { + if (flag) { + result.append(strInterVal); + } + if (null == str) { + str = ""; + } + result.append(str); + flag = true; + } + return result.toString(); + } + + public static String combinCookies(List list, String hostDomain) { + StringBuilder sbCookies = new StringBuilder(); + String domain = hostDomain; + String tailmatch = "FALSE"; + String path = "/"; + String secure = "FALSE"; + String key = null; + String value = null; + String expires = null; + for (String str : list) { + String[] parts = str.split(";"); + for (String part : parts) { + int firstIndex = part.indexOf("="); + if (-1 == firstIndex) + continue; + + String[] item = {part.substring(0, firstIndex), part.substring(firstIndex + 1)}; + if ("expires".equalsIgnoreCase(item[0].trim())) { + expires = str2Seconds(item[1].trim()); + } else if ("path".equalsIgnoreCase(item[0].trim())) { + path = item[1]; + } else if ("secure".equalsIgnoreCase(item[0].trim())) { + secure = item[1]; + } else if ("domain".equalsIgnoreCase(item[0].trim())) { + domain = item[1]; + } else if ("version".equalsIgnoreCase(item[0].trim()) || "max-age".equalsIgnoreCase(item[0].trim())) { + //do nothing + } else { + key = item[0]; + value = item[1]; + } + } + + if (null == domain) { + domain = "none"; + } + + sbCookies.append(domain); + sbCookies.append('\t'); + sbCookies.append(tailmatch); //access + sbCookies.append('\t'); + sbCookies.append(path); //path + sbCookies.append('\t'); + sbCookies.append(secure); //secure + sbCookies.append('\t'); + sbCookies.append(expires); //expires + sbCookies.append("\t"); + sbCookies.append(key); //key + sbCookies.append("\t"); + sbCookies.append(value); //value + sbCookies.append('\n'); + } + + return sbCookies.toString(); + } + + private static String str2Seconds(String strTime) { + Calendar c = Calendar.getInstance(); + long milliseconds = 0; + + try { + c.setTime(new SimpleDateFormat("EEE, dd-MMM-yy hh:mm:ss zzz", Locale.US).parse(strTime)); + milliseconds = c.getTimeInMillis() / 1000; + } catch (ParseException e) { + HiLog.error(LABEL, "str2Seconds: " + e.toString()); + } + + return Long.toString(milliseconds); + } +} diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosJavascriptJavaBridge.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosJavascriptJavaBridge.java new file mode 100644 index 0000000000..1153ba12b9 --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosJavascriptJavaBridge.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2013-2016 Chukong Technologies Inc. + * Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + * + * 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. + */ + +package com.cocos.lib; + +public class CocosJavascriptJavaBridge { + @SuppressWarnings("unused") + public static native int evalString(String value); +} diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosKeyCodeHandler.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosKeyCodeHandler.java new file mode 100644 index 0000000000..fc5b58687e --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosKeyCodeHandler.java @@ -0,0 +1,78 @@ +/**************************************************************************** + Copyright (c) 2010-2013 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. + ****************************************************************************/ +package com.cocos.lib; + + +import ohos.multimodalinput.event.KeyEvent; + +public class CocosKeyCodeHandler { + private CocosAbilitySlice mAct; + @SuppressWarnings("unused") + public native void handleKeyDown(final int keyCode); + @SuppressWarnings("unused") + public native void handleKeyUp(final int keyCode); + + public CocosKeyCodeHandler(CocosAbilitySlice act) { + mAct = act; + } + + public boolean onKeyDown(final int keyCode, final KeyEvent event) { + switch (keyCode) { + case KeyEvent.KEY_BACK: +// CocosVideoHelper.mVideoHandler.sendEmptyMessage(CocosVideoHelper.KeyEventBack); + case KeyEvent.KEY_MENU: + case KeyEvent.KEY_DPAD_LEFT: + case KeyEvent.KEY_DPAD_RIGHT: + case KeyEvent.KEY_DPAD_UP: + case KeyEvent.KEY_DPAD_DOWN: + case KeyEvent.KEY_ENTER: + case KeyEvent.KEY_MEDIA_PLAY_PAUSE: + case KeyEvent.KEY_DPAD_CENTER: + CocosHelper.runOnGameThread(() -> handleKeyDown(keyCode)); + return true; + default: + return false; + } + } + + public boolean onKeyUp(final int keyCode, KeyEvent event) { + switch (keyCode) { + case KeyEvent.KEY_BACK: + case KeyEvent.KEY_MENU: + case KeyEvent.KEY_DPAD_LEFT: + case KeyEvent.KEY_DPAD_RIGHT: + case KeyEvent.KEY_DPAD_UP: + case KeyEvent.KEY_DPAD_DOWN: + case KeyEvent.KEY_ENTER: + case KeyEvent.KEY_MEDIA_PLAY_PAUSE: + case KeyEvent.KEY_DPAD_CENTER: + CocosHelper.runOnGameThread(() -> handleKeyDown(keyCode)); + return true; + default: + return false; + } + } +} diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosLocalStorage.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosLocalStorage.java new file mode 100644 index 0000000000..ee5a6a1cbb --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosLocalStorage.java @@ -0,0 +1,116 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +package com.cocos.lib; + +import ohos.data.DatabaseHelper; +import ohos.data.rdb.*; +import ohos.data.resultset.ResultSet; + +public class CocosLocalStorage { + + private static String DATABASE_NAME = "jsb.storage.db"; + private static String TABLE_NAME = "data"; + private static final int DATABASE_VERSION = 1; + + private static DatabaseHelper mDatabaseOpenHelper = null; + private static RdbStore mDatabase = null; + + private static RdbOpenCallback rdbOpenCallback = new RdbOpenCallback() { + @Override + public void onCreate(RdbStore rdbStore) { + rdbStore.executeSql("CREATE TABLE IF NOT EXISTS "+TABLE_NAME+"(key TEXT PRIMARY KEY,value TEXT);"); + } + + @Override + public void onUpgrade(RdbStore rdbStore, int i, int i1) { + + } + }; + + public static boolean init(String dbName, String tableName) { + if (GlobalObject.getAbilitySlice() != null) { + DATABASE_NAME = dbName; + TABLE_NAME = tableName; + mDatabaseOpenHelper = new DatabaseHelper(GlobalObject.getAbilitySlice()); + StoreConfig cfg = StoreConfig.newDefaultConfig(DATABASE_NAME); + mDatabase = mDatabaseOpenHelper.getRdbStore(cfg, DATABASE_VERSION, rdbOpenCallback, null); + return true; + } + return false; + } + + private static String getTableName() { + return DATABASE_NAME + "." + TABLE_NAME; + } + + public static void destroy() { + if (mDatabase != null) { + mDatabaseOpenHelper.deleteRdbStore(DATABASE_NAME); + } + } + + public static void setItem(String key, String value) { + ValuesBucket valuesBucket = new ValuesBucket(); + valuesBucket.putString("key", key); + valuesBucket.putString("value", value); + mDatabase.insert(TABLE_NAME, valuesBucket); + } + + public static String getItem(String key) { + String[] columes = new String[] {"value"}; + RdbPredicates rdbPredicates = new RdbPredicates(TABLE_NAME).equalTo("key", key); + ResultSet resultSet = mDatabase.query(rdbPredicates, columes); + if(resultSet.goToNextRow()) { + return resultSet.getString(0); + } + return null; + } + + public static void removeItem(String key) { + RdbPredicates rdbPredicates = new RdbPredicates(TABLE_NAME).equalTo("key", key); + mDatabase.delete(rdbPredicates); + } + + public static void clear() { + RdbPredicates rdbPredicates = new RdbPredicates(TABLE_NAME); + mDatabase.delete(rdbPredicates); + } + @SuppressWarnings("unused") + public static String getKey(int nIndex) { + + ResultSet result = mDatabase.querySql("SELECT key from "+TABLE_NAME + " LIMIT 1 OFFSET " + nIndex, null); + if(result.goToNextRow()){ + return result.getString(result.getColumnIndexForName("key")); + } + return null; + } + + public static int getLength() { + ResultSet result = mDatabase.querySql("SELECT count(key) as cnt FROM "+TABLE_NAME, null); + if(result.goToNextRow()) { + return result.getInt(result.getColumnIndexForName("cnt")); + } + return 0; + } +} diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosOrientationHelper.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosOrientationHelper.java new file mode 100644 index 0000000000..a1171a5643 --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosOrientationHelper.java @@ -0,0 +1,84 @@ +/**************************************************************************** + * Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. + * + * http://www.cocos.com + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + ****************************************************************************/ + +package com.cocos.lib; + + +import ohos.app.Context; +import ohos.sensor.agent.CategoryOrientationAgent; +import ohos.sensor.agent.SensorAgent; +import ohos.sensor.bean.CategoryOrientation; +import ohos.sensor.data.CategoryOrientationData; +import ohos.sensor.listener.ICategoryOrientationDataCallback; + +public class CocosOrientationHelper implements ICategoryOrientationDataCallback { + + private int mCurrentOrientation; + private CategoryOrientationAgent agent; + private CategoryOrientation orientation; + + private final int matrix_length = 9; + private final int rotationVectorLength = 9; + + public CocosOrientationHelper(Context context) { + agent = new CategoryOrientationAgent(); + orientation = agent.getSingleSensor(CategoryOrientation.SENSOR_TYPE_ORIENTATION); + mCurrentOrientation = CocosHelper.getDeviceRotation(); + } + + public void onPause() { + agent.releaseSensorDataCallback(this, orientation); + } + + public void onResume() { + boolean ok = agent.setSensorDataCallback(this, orientation, SensorAgent.SENSOR_SAMPLING_RATE_GAME); + } + + + private static native void nativeOnOrientationChanged(int rotation); + + @Override + public void onSensorDataModified(CategoryOrientationData data) { + final int curOrientation = CocosHelper.getDeviceRotation(); + if (curOrientation != mCurrentOrientation) { + mCurrentOrientation = curOrientation; + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + nativeOnOrientationChanged(mCurrentOrientation); + } + }); + } + } + + @Override + public void onAccuracyDataModified(CategoryOrientation categoryOrientation, int i) { + + } + + @Override + public void onCommandCompleted(CategoryOrientation categoryOrientation) { + + } +} diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosReflectionHelper.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosReflectionHelper.java new file mode 100644 index 0000000000..ff073355f2 --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosReflectionHelper.java @@ -0,0 +1,77 @@ +/**************************************************************************** +Copyright (c) 2016 cocos2d-x.org +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. + ****************************************************************************/ +package com.cocos.lib; + +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +public class CocosReflectionHelper { + private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0, "CocosReflection"); + public static T getConstantValue(final Class aClass, final String constantName) { + try { + return (T)aClass.getDeclaredField(constantName).get(null); + } catch (NoSuchFieldException e) { + HiLog.error(LABEL, "can not find " + constantName + " in " + aClass.getName()); + } + catch (IllegalAccessException e) { + HiLog.error(LABEL, constantName + " is not accessable"); + } + catch (IllegalArgumentException e) { + HiLog.error(LABEL, "arguments error when get " + constantName); + } + catch (Exception e) { + HiLog.error(LABEL, "can not get constant" + constantName); + } + + return null; + } + @SuppressWarnings("unused") + public static T invokeInstanceMethod(final Object instance, final String methodName, + final Class[] parameterTypes, final Object[] parameters) { + + final Class aClass = instance.getClass(); + try { + final Method method = aClass.getMethod(methodName, parameterTypes); + return (T)method.invoke(instance, parameters); + } catch (NoSuchMethodException e) { + HiLog.error(LABEL, "can not find " + methodName + " in " + aClass.getName()); + } + catch (IllegalAccessException e) { + HiLog.error(LABEL, methodName + " is not accessible"); + } + catch (IllegalArgumentException e) { + HiLog.error(LABEL, "arguments are error when invoking " + methodName); + } + catch (InvocationTargetException e) { + HiLog.error(LABEL, "an exception was thrown by the invoked method when invoking " + methodName); + } + + return null; + } +} diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosSensorHandler.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosSensorHandler.java new file mode 100644 index 0000000000..766af8df6e --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosSensorHandler.java @@ -0,0 +1,156 @@ +/**************************************************************************** + Copyright (c) 2010-2013 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. + ****************************************************************************/ +package com.cocos.lib; + + +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import ohos.sensor.agent.CategoryMotionAgent; +import ohos.sensor.agent.SensorAgent; +import ohos.sensor.bean.CategoryMotion; +import ohos.sensor.data.CategoryMotionData; +import ohos.sensor.listener.ICategoryMotionDataCallback; + +public class CocosSensorHandler implements ICategoryMotionDataCallback { + // =========================================================== + // Constants + // =========================================================== + + private static final HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP, 0, "CocosSensorHandler"); + private static CocosSensorHandler mSensorHandler; + + private final CategoryMotionAgent mSensorManager; + private final CategoryMotion mAcceleration; + private final CategoryMotion mAccelerationIncludingGravity; + private final CategoryMotion mGyroscope; + private static float[] sDeviceMotionValues = new float[9]; + private boolean mEnabled = false; + private long mMaxIntervalNanoSeconds = 0; + // =========================================================== + // Constructors + // =========================================================== + + public CocosSensorHandler() { + mSensorManager = new CategoryMotionAgent(); + mAcceleration = mSensorManager.getSingleSensor(CategoryMotion.SENSOR_TYPE_ACCELEROMETER); + mAccelerationIncludingGravity = mSensorManager.getSingleSensor(CategoryMotion.SENSOR_TYPE_LINEAR_ACCELERATION); + mGyroscope = mSensorManager.getSingleSensor(CategoryMotion.SENSOR_TYPE_GYROSCOPE); + mSensorHandler = this; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + public void enable() { + if(mMaxIntervalNanoSeconds == 0) { + mSensorManager.setSensorDataCallback(this, mAcceleration, SensorAgent.SENSOR_SAMPLING_RATE_FASTEST); + mSensorManager.setSensorDataCallback(this, mAccelerationIncludingGravity, SensorAgent.SENSOR_SAMPLING_RATE_FASTEST); + mSensorManager.setSensorDataCallback(this, mGyroscope, SensorAgent.SENSOR_SAMPLING_RATE_FASTEST); + }else { + mSensorManager.setSensorDataCallback(this, mAcceleration, SensorAgent.SENSOR_SAMPLING_RATE_FASTEST, mMaxIntervalNanoSeconds); + mSensorManager.setSensorDataCallback(this, mAccelerationIncludingGravity, SensorAgent.SENSOR_SAMPLING_RATE_FASTEST, mMaxIntervalNanoSeconds); + mSensorManager.setSensorDataCallback(this, mGyroscope, SensorAgent.SENSOR_SAMPLING_RATE_FASTEST, mMaxIntervalNanoSeconds); + } + mEnabled = true; + } + + + public void disable() { + mSensorManager.releaseSensorDataCallback(this, mAcceleration); + mSensorManager.releaseSensorDataCallback(this, mAccelerationIncludingGravity); + mSensorManager.releaseSensorDataCallback(this, mGyroscope); + mEnabled = false; + } + + public void setInterval(float intervalSeconds) { + mMaxIntervalNanoSeconds = (long)(1000_000_000L * intervalSeconds); + if(mEnabled) { + disable(); + enable(); + } + } + + public void onPause() { + disable(); + } + + public void onResume() { + enable(); + } + + public static void setAccelerometerInterval(float interval) { + mSensorHandler.setInterval(interval); + } + + public static void setAccelerometerEnabled(boolean enabled) { + if(enabled == mSensorHandler.mEnabled) { + return; + } + if (enabled) { + mSensorHandler.enable(); + } else { + mSensorHandler.disable(); + } + } + + @SuppressWarnings("unused") + public static float[] getDeviceMotionValue() { + return sDeviceMotionValues; + } + + @Override + public void onSensorDataModified(CategoryMotionData sensorEvent) { + CategoryMotion type = sensorEvent.getSensor(); + if(type == null) return; + final int sensorId = type.getSensorId(); + if (sensorId == mAcceleration.getSensorId()) { + sDeviceMotionValues[0] = sensorEvent.values[0]; + sDeviceMotionValues[1] = sensorEvent.values[1]; + // Issue https://github.com/cocos-creator/2d-tasks/issues/2532 + // use negative event.acceleration.z to match iOS value + sDeviceMotionValues[2] = -sensorEvent.values[2]; + } else if (sensorId == mAccelerationIncludingGravity.getSensorId()) { + sDeviceMotionValues[3] = sensorEvent.values[0]; + sDeviceMotionValues[4] = sensorEvent.values[1]; + sDeviceMotionValues[5] = sensorEvent.values[2]; + } else if (sensorId == mGyroscope.getSensorId()) { + // The unit is rad/s, need to be converted to deg/s + sDeviceMotionValues[6] = (float) Math.toDegrees(sensorEvent.values[0]); + sDeviceMotionValues[7] = (float) Math.toDegrees(sensorEvent.values[1]); + sDeviceMotionValues[8] = (float) Math.toDegrees(sensorEvent.values[2]); + } + } + + @Override + public void onAccuracyDataModified(CategoryMotion categoryMotion, int i) { + + } + + @Override + public void onCommandCompleted(CategoryMotion categoryMotion) { + + } +} diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosTouchHandler.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosTouchHandler.java new file mode 100644 index 0000000000..1b5323244c --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosTouchHandler.java @@ -0,0 +1,135 @@ +/**************************************************************************** + Copyright (c) 2010-2013 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. + ****************************************************************************/ +package com.cocos.lib; + + +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import ohos.multimodalinput.event.MmiPoint; +import ohos.multimodalinput.event.TouchEvent; + +public class CocosTouchHandler { + public final static HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP,0, "CocosTouchHandler"); + private boolean mStopHandleTouchAndKeyEvents = false; + + public CocosTouchHandler() { + + } + + boolean onTouchEvent(TouchEvent pMotionEvent) { + // these data are used in ACTION_MOVE and ACTION_CANCEL + final int pointerNumber = pMotionEvent.getPointerCount(); + final int[] ids = new int[pointerNumber]; + final float[] xs = new float[pointerNumber]; + final float[] ys = new float[pointerNumber]; + + for (int i = 0; i < pointerNumber; i++) { + ids[i] = pMotionEvent.getPointerId(i); + MmiPoint pos = pMotionEvent.getPointerPosition(i); + xs[i] = pos.getX(); + ys[i] = pos.getY(); + } + + int action = pMotionEvent.getAction(); + + HiLog.debug(TAG, "Touch event: " + action); + switch (action) { + case TouchEvent.PRIMARY_POINT_DOWN: + case TouchEvent.OTHER_POINT_DOWN: + if (mStopHandleTouchAndKeyEvents) { +// Cocos2dxEditBox.complete(); + return true; + } + + final int indexPointerDown = pMotionEvent.getIndex(); + final int idPointerDown = pMotionEvent.getPointerId(indexPointerDown); + MmiPoint pos = pMotionEvent.getPointerPosition(indexPointerDown); + final float xPointerDown = pos.getX(); + final float yPointerDown = pos.getY(); + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + handleActionDown(idPointerDown, xPointerDown, yPointerDown); + } + }); + break; + + case TouchEvent.POINT_MOVE: + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + handleActionMove(ids, xs, ys); + } + }); + + break; + + case TouchEvent.PRIMARY_POINT_UP: + case TouchEvent.OTHER_POINT_UP: + + final int indexPointUp = pMotionEvent.getIndex(); + final int idPointerUp = pMotionEvent.getPointerId(indexPointUp); + MmiPoint posUP = pMotionEvent.getPointerPosition(indexPointUp); + final float xPointerUp = posUP.getX(); + final float yPointerUp = posUP.getY(); + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + handleActionUp(idPointerUp, xPointerUp, yPointerUp); + } + }); + + break; + + case TouchEvent.CANCEL: + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + handleActionCancel(ids, xs, ys); + } + }); + break; + default: + HiLog.debug(TAG, "Unhandled touch event: " + action); + break; + } + + return true; + } + @SuppressWarnings("unused") + public void setStopHandleTouchAndKeyEvents(boolean value) { + mStopHandleTouchAndKeyEvents = value; + } + + native void handleActionDown(final int id, final float x, final float y); + + native void handleActionMove(final int[] ids, final float[] xPointerList, final float[] yPointerList); + + native void handleActionUp(final int id, final float x, final float y); + + native void handleActionCancel(final int[] ids, final float[] xPointerList, final float[] yPointerList); + +} diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosVideoHelper.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosVideoHelper.java new file mode 100644 index 0000000000..a36e726674 --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosVideoHelper.java @@ -0,0 +1,442 @@ +/**************************************************************************** +Copyright (c) 2014-2016 Chukong Technologies Inc. +Copyright (c) 2017-2020 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. + ****************************************************************************/ + +package com.cocos.lib; + +import com.cocos.lib.CocosVideoView.OnVideoEventListener; +import ohos.aafwk.ability.AbilitySlice; +import ohos.agp.components.Component; +import ohos.agp.components.StackLayout; +import ohos.eventhandler.EventHandler; +import ohos.eventhandler.EventRunner; +import ohos.eventhandler.InnerEvent; +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import ohos.media.image.common.Rect; + +import java.lang.ref.WeakReference; +import java.util.WeakHashMap; + +public class CocosVideoHelper { + + private StackLayout mRootLayout = null; + private AbilitySlice mActivity = null; + private static WeakHashMap sVideoViews = null; + static VideoHandler mVideoHandler = null; + + private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0, "CocosVideoHelper"); + + CocosVideoHelper(AbilitySlice activity, StackLayout layout) + { + mActivity = activity; + mRootLayout = layout; + + mVideoHandler = new VideoHandler(this); + sVideoViews = new WeakHashMap<>(); + } + + private static int videoTag = 0; + private final static int VideoTaskCreate = 0; + private final static int VideoTaskRemove = 1; + private final static int VideoTaskSetSource = 2; + private final static int VideoTaskSetRect = 3; + private final static int VideoTaskStart = 4; + private final static int VideoTaskPause = 5; + private final static int VideoTaskResume = 6; + private final static int VideoTaskStop = 7; + private final static int VideoTaskSeek = 8; + private final static int VideoTaskSetVisible = 9; + private final static int VideoTaskRestart = 10; + private final static int VideoTaskKeepRatio = 11; + private final static int VideoTaskFullScreen = 12; + private final static int VideoTaskSetVolume = 13; + + final static int KeyEventBack = 1000; + + static class VideoHandler extends EventHandler { + WeakReference mReference; + + VideoHandler(CocosVideoHelper helper){ + super(EventRunner.getMainEventRunner()); + mReference = new WeakReference(helper); + } + + @Override + public void processEvent(InnerEvent event) { + CocosVideoHelper helper = mReference.get(); + Message msg = (Message) event.object; + switch (msg.what) { + case VideoTaskCreate: { + helper._createVideoView(msg.arg1); + break; + } + case VideoTaskRemove: { + CocosHelper.ruOnUIThreadSync(()->helper._removeVideoView(msg.arg1)); + break; + } + case VideoTaskSetSource: { + helper._setVideoURL(msg.arg1, msg.arg2, (String)msg.obj); + break; + } + case VideoTaskStart: { + helper._startVideo(msg.arg1); + break; + } + case VideoTaskSetRect: { + Rect rect = (Rect)msg.obj; + CocosHelper.ruOnUIThreadSync( + ()->helper._setVideoRect(msg.arg1, rect.minX, rect.minY, rect.width , rect.height) + ); + break; + } + case VideoTaskFullScreen:{ + if (msg.arg2 == 1) { + CocosHelper.ruOnUIThreadSync(()->helper._setFullScreenEnabled(msg.arg1, true)); + } else { + CocosHelper.ruOnUIThreadSync(()->helper._setFullScreenEnabled(msg.arg1, false)); + } + break; + } + case VideoTaskPause: { + helper._pauseVideo(msg.arg1); + break; + } + + case VideoTaskStop: { + helper._stopVideo(msg.arg1); + break; + } + case VideoTaskSeek: { + helper._seekVideoTo(msg.arg1, msg.arg2); + break; + } + case VideoTaskSetVisible: { + if (msg.arg2 == 1) { + CocosHelper.ruOnUIThreadSync(()->helper._setVideoVisible(msg.arg1, true)); + } else { + CocosHelper.ruOnUIThreadSync(()->helper._setVideoVisible(msg.arg1, false)); + } + break; + } + case VideoTaskKeepRatio: { + if (msg.arg2 == 1) { + CocosHelper.ruOnUIThreadSync(()->helper._setVideoKeepRatio(msg.arg1, true)); + } else { + CocosHelper.ruOnUIThreadSync(()->helper._setVideoKeepRatio(msg.arg1, false)); + } + break; + } + case KeyEventBack: { + helper.onBackKeyEvent(); + break; + } + case VideoTaskSetVolume: { + float volume = (float) msg.arg2 / 10; + helper._setVolume(msg.arg1, volume); + break; + } + default: + break; + } + + super.processEvent(event); + } + } + + public static native void nativeExecuteVideoCallback(int index,int event); + + OnVideoEventListener videoEventListener = new OnVideoEventListener() { + + @Override + public void onVideoEvent(int tag,int event) { + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + nativeExecuteVideoCallback(tag, event); + } + }); + } + }; + + static class Message { + public int what =0; + public int arg1 = 0; + public int arg2 = 0; + public Object obj = null; + } + + public static int createVideoWidget() { + Message msg = new Message(); + msg.what = VideoTaskCreate; + msg.arg1 = videoTag; + dispatchMessage(msg); + + return videoTag++; + } + + private static void dispatchMessage(Message msg) { + InnerEvent event = InnerEvent.get(msg.what, msg.arg1, msg); + mVideoHandler.distributeEvent(event); + } + + + private void _createVideoView(int index) { + CocosVideoView videoView = new CocosVideoView(mActivity,index); + sVideoViews.put(index, videoView); + StackLayout.LayoutConfig lParams = new StackLayout.LayoutConfig( + StackLayout.LayoutConfig.MATCH_CONTENT, + StackLayout.LayoutConfig.MATCH_CONTENT); + CocosHelper.runOnUIThread(()->{ + mRootLayout.addComponent(videoView, lParams); + }); + videoView.setVideoViewEventListener(videoEventListener); + } + + public static void removeVideoWidget(int index){ + Message msg = new Message(); + msg.what = VideoTaskRemove; + msg.arg1 = index; + dispatchMessage(msg); + } + + private void _removeVideoView(int index) { + CocosVideoView view = sVideoViews.get(index); + if (view != null) { + view.stopPlayback(); + sVideoViews.remove(index); + mRootLayout.removeComponent(view); + } + } + + public static void setVideoUrl(int index, int videoSource, String videoUrl) { + Message msg = new Message(); + msg.what = VideoTaskSetSource; + msg.arg1 = index; + msg.arg2 = videoSource; + msg.obj = videoUrl; + dispatchMessage(msg); + } + + private void _setVideoURL(int index, int videoSource, String videoUrl) { + CocosVideoView videoView = sVideoViews.get(index); + if (videoView != null) { + switch (videoSource) { + case 0: + videoView.setVideoFileName(videoUrl); + break; + case 1: + videoView.setVideoURL(videoUrl); + break; + default: + break; + } + } + } + + public static void setVideoRect(int index, int left, int top, int maxWidth, int maxHeight) { + Message msg = new Message(); + msg.what = VideoTaskSetRect; + msg.arg1 = index; + msg.obj = new Rect(left, top, maxWidth, maxHeight); + dispatchMessage(msg); + } + + private void _setVideoRect(int index, int left, int top, int maxWidth, int maxHeight) { + CocosVideoView videoView = sVideoViews.get(index); + if (videoView != null) { + videoView.setVideoRect(left, top, maxWidth, maxHeight); + } + } + + public static void setFullScreenEnabled(int index, boolean enabled) { + Message msg = new Message(); + msg.what = VideoTaskFullScreen; + msg.arg1 = index; + if (enabled) { + msg.arg2 = 1; + } else { + msg.arg2 = 0; + } + dispatchMessage(msg); + } + + private void _setFullScreenEnabled(int index, boolean enabled) { + CocosVideoView videoView = sVideoViews.get(index); + if (videoView != null) { + videoView.setFullScreenEnabled(enabled); + } + } + + private void onBackKeyEvent() { + for(Integer key : sVideoViews.keySet()) { + CocosVideoView videoView = sVideoViews.get(key); + if (videoView != null) { + videoView.setFullScreenEnabled(false); + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + nativeExecuteVideoCallback(key, KeyEventBack); + } + }); + } + } + } + + public static void startVideo(int index) { + Message msg = new Message(); + msg.what = VideoTaskStart; + msg.arg1 = index; + dispatchMessage(msg); + } + + private void _startVideo(int index) { + CocosVideoView videoView = sVideoViews.get(index); + if (videoView != null) { + videoView.start(); + } + } + + public static void pauseVideo(int index) { + Message msg = new Message(); + msg.what = VideoTaskPause; + msg.arg1 = index; + dispatchMessage(msg); + } + + private void _pauseVideo(int index) { + CocosVideoView videoView = sVideoViews.get(index); + if (videoView != null) { + videoView.pause(); + } + } + + public static void stopVideo(int index) { + Message msg = new Message(); + msg.what = VideoTaskStop; + msg.arg1 = index; + dispatchMessage(msg); + } + + private void _stopVideo(int index) { + CocosVideoView videoView = sVideoViews.get(index); + if (videoView != null) { + videoView.stop(); + } + } + + public static void seekVideoTo(int index,int msec) { + Message msg = new Message(); + msg.what = VideoTaskSeek; + msg.arg1 = index; + msg.arg2 = msec; + dispatchMessage(msg); + } + + private void _seekVideoTo(int index,int msec) { + CocosVideoView videoView = sVideoViews.get(index); + if (videoView != null) { + videoView.seekTo(msec); + } + } + + public static float getCurrentTime(final int index) { + CocosVideoView video = sVideoViews.get(index); + float currentPosition = -1; + if (video != null) { + currentPosition = video.getCurrentPosition() / 1000.0f; + } + return currentPosition; + } + + public static float getDuration(final int index) { + CocosVideoView video = sVideoViews.get(index); + float duration = -1; + if (video != null) { + duration = video.getDuration() / 1000.0f; + } + if (duration <= 0) { + HiLog.error(LABEL, "Video player's duration is not ready to get now!"); + } + return duration; + } + + public static void setVideoVisible(int index, boolean visible) { + Message msg = new Message(); + msg.what = VideoTaskSetVisible; + msg.arg1 = index; + if (visible) { + msg.arg2 = 1; + } else { + msg.arg2 = 0; + } + dispatchMessage(msg); + } + + private void _setVideoVisible(int index, boolean visible) { + CocosVideoView videoView = sVideoViews.get(index); + if (videoView != null) { + if (visible) { + videoView.fixSizeAsync(); + videoView.setVisibility(Component.VISIBLE); + } else { + videoView.setVisibility(Component.INVISIBLE); + } + } + } + + public static void setVideoKeepRatioEnabled(int index, boolean enable) { + Message msg = new Message(); + msg.what = VideoTaskKeepRatio; + msg.arg1 = index; + if (enable) { + msg.arg2 = 1; + } else { + msg.arg2 = 0; + } + dispatchMessage(msg); + } + + private void _setVideoKeepRatio(int index, boolean enable) { + CocosVideoView videoView = sVideoViews.get(index); + if (videoView != null) { + videoView.setKeepRatio(enable); + } + } + + private void _setVolume(final int index, final float volume) { + CocosVideoView videoView = sVideoViews.get(index); + if (videoView != null) { + videoView.setVolume(volume); + } + } + + public static void setVolume(final int index, final float volume) { + Message msg = new Message(); + msg.what = VideoTaskSetVolume; + msg.arg1 = index; + msg.arg2 = (int) (volume * 10); + dispatchMessage(msg); + } +} diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosVideoView.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosVideoView.java new file mode 100644 index 0000000000..20d6c41b01 --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosVideoView.java @@ -0,0 +1,633 @@ +/* + * Copyright (C) 2006 The Android Open Source Project + * Copyright (c) 2014-2016 Chukong Technologies Inc. + * Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.cocos.lib; + +import ohos.aafwk.ability.AbilitySlice; +import ohos.aafwk.ability.Lifecycle; +import ohos.aafwk.ability.LifecycleStateObserver; +import ohos.aafwk.content.Intent; +import ohos.agp.components.Component; +import ohos.agp.components.StackLayout; +import ohos.agp.components.surfaceprovider.SurfaceProvider; +import ohos.agp.graphics.SurfaceOps; +import ohos.agp.utils.Rect; +import ohos.agp.window.dialog.BaseDialog; +import ohos.agp.window.dialog.PopupDialog; +import ohos.agp.window.dialog.ToastDialog; +import ohos.global.resource.RawFileDescriptor; +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import ohos.media.audio.AudioManager; +import ohos.media.common.Source; +import ohos.media.player.Player; +import ohos.multimodalinput.event.TouchEvent; + +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public class CocosVideoView extends SurfaceProvider implements Component.TouchEventListener, LifecycleStateObserver { + + // =========================================================== + // Internal classes and interfaces. + // =========================================================== + + public interface OnVideoEventListener { + void onVideoEvent(int tag, int event); + } + + private enum State { + IDLE, + ERROR, + INITIALIZED, + PREPARING, + PREPARED, + STARTED, + PAUSED, + STOPPED, + PLAYBACK_COMPLETED, + } + + // =========================================================== + // Constants + // =========================================================== + private static final String AssetResourceRoot = "@assets/"; + private static final String OHOSResourceRoot = "entry/resources/rawfile/"; + + // =========================================================== + // Fields + // =========================================================== + + private HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP, 0, "CocosVideoView"); + + private Source mVideoUri; + private int mDuration; + private int mPosition; + + private State mCurrentState = State.IDLE; + + // All the stuff we need for playing and showing a video + private Player mMediaPlayer = null; + private int mVideoWidth = 0; + private int mVideoHeight = 0; + + private OnVideoEventListener mOnVideoEventListener; + + // recording the seek position while preparing + private int mSeekWhenPrepared = 0; + + protected AbilitySlice mAbility = null; + + protected int mViewLeft = 0; + protected int mViewTop = 0; + protected int mViewWidth = 0; + protected int mViewHeight = 0; + + protected int mVisibleLeft = 0; + protected int mVisibleTop = 0; + protected int mVisibleWidth = 0; + protected int mVisibleHeight = 0; + + protected boolean mFullScreenEnabled = false; + + private boolean mIsAssetRouse = false; + private String mVideoFilePath = null; + + private int mViewTag = 0; + private boolean mKeepRatio = false; + private boolean mMetaUpdated = false; + + // MediaPlayer will be released when surface view is destroyed, so should record the position, + // and use it to play after MedialPlayer is created again. + private int mPositionBeforeRelease = 0; + + // =========================================================== + // Constructors + // =========================================================== + + public CocosVideoView(AbilitySlice activity, int tag) { + super(activity); + + mViewTag = tag; + mAbility = activity; + mMediaPlayer = new Player(getContext()); + mMediaPlayer.setPlayerCallback(mPlayerCallback); + initVideoView(); + + pinToZTop(true); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public void setVideoRect(int left, int top, int maxWidth, int maxHeight) { + if (mViewLeft == left && mViewTop == top && mViewWidth == maxWidth && mViewHeight == maxHeight) + return; + + mViewLeft = left; + mViewTop = top; + mViewWidth = maxWidth; + mViewHeight = maxHeight; + + fixSize(mViewLeft, mViewTop, mViewWidth, mViewHeight); + } + + public void setFullScreenEnabled(boolean enabled) { + if (mFullScreenEnabled != enabled) { + mFullScreenEnabled = enabled; + fixSizeAsync(); + } + } + + public void setVolume(float volume) { + if (mMediaPlayer != null) { + mMediaPlayer.setVolume(volume); + } + } + + public void setKeepRatio(boolean enabled) { + mKeepRatio = enabled; + fixSizeAsync(); + } + + public void setVideoURL(String url) { + mIsAssetRouse = false; + setVideoURI(new Source(url), null); + } + + public void setVideoFileName(String path) { + if (path.startsWith(AssetResourceRoot)) { + path = path.replaceFirst(AssetResourceRoot, OHOSResourceRoot); + } + + if (path.startsWith("/")) { + mIsAssetRouse = false; + setVideoURI(new Source(path), null); + } else { + + mVideoFilePath = path; + mIsAssetRouse = true; + setVideoURI(new Source(path), null); + } + } + + public int getCurrentPosition() { + if (!(mCurrentState == State.IDLE || + mCurrentState == State.ERROR || + mCurrentState == State.INITIALIZED || + mCurrentState == State.STOPPED || + mMediaPlayer == null)) { + mPosition = mMediaPlayer.getCurrentTime(); + } + return mPosition; + } + + public int getDuration() { + if (!(mCurrentState == State.IDLE || + mCurrentState == State.ERROR || + mCurrentState == State.INITIALIZED || + mCurrentState == State.STOPPED || + mMediaPlayer == null)) { + mDuration = mMediaPlayer.getDuration(); + } + + return mDuration; + } + + /** + * Register a callback to be invoked when some video event triggered. + * + * @param l The callback that will be run + */ + public void setVideoViewEventListener(OnVideoEventListener l) { + mOnVideoEventListener = l; + } + + // =========================================================== + // Overrides + // =========================================================== + + @Override + public void setVisibility(int visibility) { + super.setVisibility(visibility); + } + + @Override + public boolean onTouchEvent(Component component, TouchEvent touchEvent) { + if ((touchEvent.getAction() & TouchEvent.PRIMARY_POINT_UP) == TouchEvent.PRIMARY_POINT_UP) { + this.sendEvent(EVENT_CLICKED); + } + return true; + } + + // =========================================================== + // Public functions + // =========================================================== + + public void stop() { + if (!(mCurrentState == State.IDLE || mCurrentState == State.INITIALIZED || mCurrentState == State.ERROR || mCurrentState == State.STOPPED) + && mMediaPlayer != null) { + mCurrentState = State.STOPPED; + mMediaPlayer.stop(); + this.sendEvent(EVENT_STOPPED); + + // after the video is stop, it shall prepare to be playable again + try { + mMediaPlayer.prepare(); + this.showFirstFrame(); + } catch (Exception ex) { + } + } + } + + public void stopPlayback() { + this.release(); + } + + public void start() { + if ((mCurrentState == State.PREPARED || + mCurrentState == State.PAUSED || + mCurrentState == State.PLAYBACK_COMPLETED) && + mMediaPlayer != null) { + + mCurrentState = State.STARTED; + mMediaPlayer.play(); + this.sendEvent(EVENT_PLAYING); + } + } + + public void pause() { + if ((mCurrentState == State.STARTED || mCurrentState == State.PLAYBACK_COMPLETED) && + mMediaPlayer != null) { + mCurrentState = State.PAUSED; + mMediaPlayer.pause(); + this.sendEvent(EVENT_PAUSED); + } + } + + public void seekTo(int ms) { + if (mCurrentState == State.IDLE || mCurrentState == State.INITIALIZED || + mCurrentState == State.STOPPED || mCurrentState == State.ERROR || + mMediaPlayer == null) { + return; + } + + boolean rewindResult = mMediaPlayer.rewindTo(ms * 1000); + System.out.println("Player seek to " + ms + "ms, " + getCurrentPosition() + "ms/"+getDuration() + "ms, rewind result "+ rewindResult); + } + + public void fixSizeAsync() { + CocosHelper.ruOnUIThreadSync(this::fixSizeUIThread); + } + + private void fixSizeUIThread() { + if (mFullScreenEnabled) { + Rect rect = mAbility.getWindow().getBoundRect(); + fixSize(rect.left, rect.top, rect.getWidth(), rect.getHeight()); + } else { + if(mViewWidth == 0 || mViewHeight == 0) { + CocosHelper.runOnUIThread(this::fixSizeUIThread, true); + return; + } + fixSize(mViewLeft, mViewTop, mViewWidth, mViewHeight); + } + } + + public void fixSize(int left, int top, int width, int height) { + if (mVideoWidth == 0 || mVideoHeight == 0) { + mVisibleLeft = left; + mVisibleTop = top; + mVisibleWidth = width; + mVisibleHeight = height; + } else if (width != 0 && height != 0) { + if (mKeepRatio && !mFullScreenEnabled) { + if (mVideoWidth * height > width * mVideoHeight) { + mVisibleWidth = width; + mVisibleHeight = width * mVideoHeight / mVideoWidth; + } else if (mVideoWidth * height < width * mVideoHeight) { + mVisibleWidth = height * mVideoWidth / mVideoHeight; + mVisibleHeight = height; + } + mVisibleLeft = left + (width - mVisibleWidth) / 2; + mVisibleTop = top + (height - mVisibleHeight) / 2; + } else { + mVisibleLeft = left; + mVisibleTop = top; + mVisibleWidth = width; + mVisibleHeight = height; + } + } else { + mVisibleLeft = left; + mVisibleTop = top; + mVisibleWidth = mVideoWidth; + mVisibleHeight = mVideoHeight; + } + + setComponentSize(mVideoWidth, mVideoHeight); + + StackLayout.LayoutConfig lParams = new StackLayout.LayoutConfig(StackLayout.LayoutConfig.MATCH_CONTENT, + StackLayout.LayoutConfig.MATCH_CONTENT); + lParams.setMarginLeft(mVisibleLeft); + lParams.setMarginTop(mVisibleTop); + lParams.width = mVisibleWidth; + lParams.height = mVisibleHeight; + setLayoutConfig(lParams); + } + + public int resolveAdjustedSize(int desiredSize, int measureSpec) { + int result = desiredSize; + int specMode = EstimateSpec.getMode(measureSpec); + int specSize = EstimateSpec.getSize(measureSpec); + + switch (specMode) { + case EstimateSpec.UNCONSTRAINT: + /* Parent says we can be as big as we want. Just don't be larger + * than max size imposed on ourselves. + */ + result = desiredSize; + break; + + case EstimateSpec.NOT_EXCEED: + /* Parent says we can be as big as we want, up to specSize. + * Don't be larger than specSize, and don't be larger than + * the max size imposed on ourselves. + */ + result = Math.min(desiredSize, specSize); + break; + + case EstimateSpec.PRECISE: + // No choice. Do what we are told. + result = specSize; + break; + } + + return result; + } + + // =========================================================== + // Private functions + // =========================================================== + + private void initVideoView() { + mVideoWidth = 0; + mVideoHeight = 0; + if(this.getSurfaceOps().isPresent()) { + getSurfaceOps().get().addCallback(new SurfaceOps.Callback() { + @Override + public void surfaceCreated(SurfaceOps surfaceOps) { + CocosVideoView.this.mMediaPlayer.setVideoSurface(surfaceOps.getSurface()); + openVideo(); + } + + @Override + public void surfaceChanged(SurfaceOps surfaceOps, int i, int i1, int i2) { + CocosVideoView.this.mMediaPlayer.setVideoSurface(surfaceOps.getSurface()); + } + + @Override + public void surfaceDestroyed(SurfaceOps surfaceOps) { + // after we return from this we can't use the surface any more + mPositionBeforeRelease = getCurrentPosition(); + CocosVideoView.this.doRelease(); + } + }); + } + mCurrentState = State.IDLE; + setTouchEventListener(this); + setFocusable(FOCUS_ADAPTABLE); + setTouchFocusable(true); + } + + /** + * @hide + */ + private void setVideoURI(Source uri, Map headers) { + mVideoUri = uri; + mVideoWidth = 0; + mVideoHeight = 0; + } + + private void openVideo() { + if (!getSurfaceOps().isPresent() || getSurfaceOps().get().getSurface() == null) { + // not ready for playback just yet, will try again later + return; + } + if (mIsAssetRouse) { + if (mVideoFilePath == null) + return; + } else if (mVideoUri == null) { + return; + } + +// this.pausePlaybackService(); + + try { + mMediaPlayer.setSurfaceOps(getSurfaceOps().get()); +// mMediaPlayer.setAudioStreamType(AudioManager.AudioVolumeType.STREAM_MUSIC.getValue()); + getSurfaceOps().get().setKeepScreenOn(true); + + if (mIsAssetRouse) { + RawFileDescriptor afd = mAbility.getResourceManager().getRawFileEntry(mVideoFilePath).openRawFileDescriptor(); + mMediaPlayer.setSource(afd); + } else { + mMediaPlayer.setSource(mVideoUri); + } + mCurrentState = State.INITIALIZED; + + + // Use Prepare() instead of PrepareAsync to make things easy. +// CompletableFuture.runAsync(()->{ + mMediaPlayer.prepare(); + CocosHelper.ruOnUIThreadSync(this::showFirstFrame); +// }); +// mMediaPlayer.prepareAsync(); + } catch (IOException ex) { + HiLog.error(TAG, "Unable to open content: " + mVideoUri + ex); + mCurrentState = State.ERROR; + mPlayerCallback.onError(Player.PLAYER_ERROR_UNKNOWN, 0); + } catch (IllegalArgumentException ex) { + HiLog.error(TAG, "Unable to open content: " + mVideoUri + ex); + mCurrentState = State.ERROR; + mPlayerCallback.onError(Player.PLAYER_ERROR_UNKNOWN, 0); + } + } + + private final Player.IPlayerCallback mPlayerCallback = new Player.IPlayerCallback() { + @Override + public void onPrepared() { + mVideoWidth = mMediaPlayer.getVideoWidth(); + mVideoHeight = mMediaPlayer.getVideoHeight(); + + if (mVideoWidth != 0 && mVideoHeight != 0) { + fixSizeAsync(); + } + + if (!mMetaUpdated) { + CocosVideoView.this.sendEvent(EVENT_META_LOADED); + CocosVideoView.this.sendEvent(EVENT_READY_TO_PLAY); + mMetaUpdated = true; + } + + mCurrentState = State.PREPARED; + + if (mPositionBeforeRelease > 0) { + CocosVideoView.this.start(); + CocosVideoView.this.seekTo(mPositionBeforeRelease); + mPositionBeforeRelease = 0; + } + } + + @Override + public void onMessage(int i, int i1) { + HiLog.debug(TAG, "Message "+ i + ", "+ i1); + } + + String translateErrorMessage(int errorType, int errorCode) { + String msg = ""; + switch (errorType) { + case Player.PLAYER_ERROR_UNKNOWN: + msg += "type: PLAYER_ERROR_UNKNOWN, "; + break; + case Player.PLAYER_ERROR_SERVER_DIED: + msg += "type: PLAYER_ERROR_SERVER_DIED, "; + break; + default: + msg += "type: " + errorType+ ", "; + break; + } + switch (errorCode) { + case Player.PLAYER_ERROR_IO: + msg += "code: PLAYER_ERROR_IO"; + break; + case Player.PLAYER_ERROR_MALFORMED: + msg += "code: PLAYER_ERROR_MALFORMED"; + break; + case Player.PLAYER_ERROR_UNSUPPORTED: + msg += "code: PLAYER_ERROR_UNSUPPORTED"; + break; + case Player.PLAYER_ERROR_TIMED_OUT: + msg += "code: PLAYER_ERROR_TIMED_OUT"; + break; + case Player.PLAYER_ERROR_SYSTEM: + msg += "code: PLAYER_ERROR_SYSTEM"; + default: + msg += "code: " + errorCode+ ", "; + break; + } + return msg; + } + + @Override + public void onError(int errorType, int errorCode) { + mCurrentState = State.ERROR; + + //TODO: i18n + CocosHelper.runOnUIThread(()->{ + ToastDialog dialog = new ToastDialog(getContext()); + dialog.setText("Video:" + translateErrorMessage(errorType, errorCode)); + dialog.setDuration(5000); + dialog.show(); + }); + } + + @Override + public void onResolutionChanged(int i, int i1) { + + } + + @Override + public void onPlayBackComplete() { + mCurrentState = State.PLAYBACK_COMPLETED; + CocosVideoView.this.sendEvent(EVENT_COMPLETED); + } + + @Override + public void onRewindToComplete() { + System.out.println("rewind complete"); + } + + @Override + public void onBufferingChange(int i) { + + } + + @Override + public void onNewTimedMetaData(Player.MediaTimedMetaData mediaTimedMetaData) { + + } + + @Override + public void onMediaTimeIncontinuity(Player.MediaTimeInfo mediaTimeInfo) { + + } + }; + + @Override + public void onStateChanged(Lifecycle.Event event, Intent intent) { + switch (event) { + case ON_START: + break; + case ON_ACTIVE: + mMediaPlayer.play(); + break; + case ON_INACTIVE: + mMediaPlayer.pause(); + break; + case ON_BACKGROUND: + mMediaPlayer.stop(); + break; + case ON_STOP: + mMediaPlayer.release(); + break; + } + } + + private static final int EVENT_PLAYING = 0; + private static final int EVENT_PAUSED = 1; + private static final int EVENT_STOPPED = 2; + private static final int EVENT_COMPLETED = 3; + private static final int EVENT_META_LOADED = 4; + private static final int EVENT_CLICKED = 5; + private static final int EVENT_READY_TO_PLAY = 6; + + /* + * release the media player in any state + */ + private void doRelease() { + if (mMediaPlayer != null) { + mMediaPlayer.release(); + mMediaPlayer = null; + mCurrentState = State.IDLE; + } + } + + private void showFirstFrame() { + mMediaPlayer.rewindTo(1); + } + + private void sendEvent(int event) { + if (this.mOnVideoEventListener != null) { + this.mOnVideoEventListener.onVideoEvent(this.mViewTag, event); + } + } + +} diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosWebView.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosWebView.java new file mode 100644 index 0000000000..90dc06e583 --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosWebView.java @@ -0,0 +1,138 @@ +/**************************************************************************** + Copyright (c) 2017-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +package com.cocos.lib; + + +import ohos.agp.components.PositionLayout; +import ohos.agp.components.webengine.*; +import ohos.app.Context; +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; + +import java.net.URI; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.FutureTask; + + +public class CocosWebView extends WebView { + private static final HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP, 0, CocosWebViewHelper.class.getSimpleName()); + + private int mViewTag; + private String mJSScheme; + + public CocosWebView(Context context, int viewTag) { + super(context); + this.mViewTag = viewTag; + this.mJSScheme = ""; + this.setWebAgent(new Cocos2dxWebViewClient()); + + + WebConfig cfg = getWebConfig(); + cfg.setJavaScriptPermit(true); + cfg.setDataAbilityPermit(true); + cfg.setLoadsImagesPermit(true); + cfg.setWebStoragePermit(true); + cfg.setViewPortFitScreen(true); + cfg.setTextAutoSizing(true); + +// setTouchFocusable(true); +// setFocusable(FOCUS_ENABLE); +// requestFocus(); + } + + public void setJavascriptInterfaceScheme(String scheme) { + this.mJSScheme = scheme != null ? scheme : ""; + } + + public void setScalesPageToFit(boolean scalesPageToFit) { + this.getWebConfig().setViewPortFitScreen(scalesPageToFit); + } + + class Cocos2dxWebViewClient extends WebAgent { + @Override + public boolean isNeedLoadUrl(WebView view, ResourceRequest request) { + String urlString = request.getRequestUrl().toString(); + try { + URI uri = new URI(request.getRequestUrl().toString()); + if (uri.getScheme().equals(mJSScheme)) { + CocosHelper.runOnGameThread( + () -> CocosWebViewHelper._onJsCallback(mViewTag, urlString) + ); + return true; + } + } catch (Exception e) { + HiLog.debug(TAG, "Failed to create URI from url"); + } + + FutureTask shouldStartLoadingCB = new FutureTask<>( + ()-> CocosWebViewHelper._shouldStartLoading(mViewTag, urlString) + ); + + // run worker on cocos thread + CocosHelper.runOnGameThread(shouldStartLoadingCB); + // wait for result from cocos thread + + try { + return shouldStartLoadingCB.get(); + } catch (InterruptedException ex) { + HiLog.debug(TAG, "'shouldOverrideUrlLoading' failed"); + } catch (ExecutionException e) { + e.printStackTrace(); + } + return true; + } + + @Override + public void onPageLoaded(WebView view, final String url) { + super.onPageLoaded(view, url); + + CocosHelper.runOnGameThread( + () -> CocosWebViewHelper._didFinishLoading(mViewTag, url) + ); + } + + @Override + public void onError(WebView view, ResourceRequest request, ResourceError error) { + super.onError(view, request, error); + final String failingUrl = request.getRequestUrl().toString(); + CocosHelper.runOnGameThread( + () -> CocosWebViewHelper._didFailLoading(mViewTag, failingUrl) + ); + } + } + + public void setWebViewRect(int left, int top, int maxWidth, int maxHeight) { + PositionLayout.LayoutConfig layoutParams = new PositionLayout.LayoutConfig( + PositionLayout.LayoutConfig.MATCH_CONTENT, + PositionLayout.LayoutConfig.MATCH_CONTENT); + layoutParams.setMarginLeft(left); + layoutParams.setMarginTop(top); + layoutParams.width = maxWidth; + layoutParams.height = maxHeight; + this.setLayoutConfig(layoutParams); + + } +} diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosWebViewHelper.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosWebViewHelper.java new file mode 100644 index 0000000000..bc3f689689 --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/CocosWebViewHelper.java @@ -0,0 +1,306 @@ +/**************************************************************************** + Copyright (c) 2010-2011 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. + ****************************************************************************/ +package com.cocos.lib; + + +import ohos.agp.colors.RgbColor; +import ohos.agp.components.Component; +import ohos.agp.components.DirectionalLayout; +import ohos.agp.components.StackLayout; + +import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.FutureTask; + + +public class CocosWebViewHelper { + private static final String TAG = CocosWebViewHelper.class.getSimpleName(); + + private static StackLayout sLayout; + + private static ConcurrentHashMap webViews; + private static int viewTag = 0; + + public CocosWebViewHelper(StackLayout layout) { + + CocosWebViewHelper.sLayout = layout; + + CocosWebViewHelper.webViews = new ConcurrentHashMap(); + } + + private static native boolean shouldStartLoading(int index, String message); + private static native void didFinishLoading(int index, String message); + private static native void didFailLoading(int index, String message); + private static native void onJsCallback(int index, String message); + + public static boolean _shouldStartLoading(int index, String message) { return shouldStartLoading(index, message); } + public static void _didFinishLoading(int index, String message) { didFinishLoading(index, message); } + public static void _didFailLoading(int index, String message) { didFailLoading(index, message); } + public static void _onJsCallback(int index, String message) { onJsCallback(index, message); } + + public static int createWebView() { + final int index = viewTag; + CocosHelper.runOnUIThread(new Runnable() { + @Override + public void run() { + CocosWebView webView = new CocosWebView(CocosHelper.getContext(), index); + DirectionalLayout.LayoutConfig lParams = new DirectionalLayout.LayoutConfig( + DirectionalLayout.LayoutConfig.MATCH_CONTENT, + DirectionalLayout.LayoutConfig.MATCH_CONTENT); + sLayout.addComponent(webView, lParams); + + webViews.put(index, webView); + } + }); + return viewTag++; + } + + public static void removeWebView(final int index) { + CocosHelper.runOnUIThread(new Runnable() { + @Override + public void run() { + CocosWebView webView = webViews.get(index); + if (webView != null) { + webViews.remove(index); + sLayout.removeComponent(webView); + webView.release(); + webView = null; + } + } + }); + } + + public static void setVisible(final int index, final boolean visible) { + CocosHelper.runOnUIThread(new Runnable() { + @Override + public void run() { + CocosWebView webView = webViews.get(index); + if (webView != null) { + webView.setVisibility(visible ? Component.VISIBLE : Component.HIDE); + } + } + }); + } + + public static void setWebViewRect(final int index, final int left, final int top, final int maxWidth, final int maxHeight) { + CocosHelper.runOnUIThread(new Runnable() { + @Override + public void run() { + CocosWebView webView = webViews.get(index); + if (webView != null) { + webView.setWebViewRect(left, top, maxWidth, maxHeight); + } + } + }); + } + + public static void setBackgroundTransparent(final int index, final boolean isTransparent) { + CocosHelper.runOnUIThread(new Runnable() { + @Override + public void run() { + CocosWebView webView = webViews.get(index); + if (webView != null) { + RgbColor color = isTransparent ? new RgbColor(255, 255, 255, 0 ): new RgbColor(255, 255, 255, 255); +// Element bg = webView.getResourceManager().getElement(isTransparent ? ResourceTable.Graphic_bg_webview_transparent : ResourceTable.Graphic_bg_webview_white); + webView.setWebViewBackground(color); + + } + } + }); + } + + public static void setJavascriptInterfaceScheme(final int index, final String scheme) { + CocosHelper.runOnUIThread(new Runnable() { + @Override + public void run() { + CocosWebView webView = webViews.get(index); + if (webView != null) { + webView.setJavascriptInterfaceScheme(scheme); + } + } + }); + } + + public static void loadData(final int index, final String data, final String mimeType, final String encoding, final String baseURL) { + CocosHelper.runOnUIThread(new Runnable() { + @Override + public void run() { + CocosWebView webView = webViews.get(index); + if (webView != null) { + webView.load(data, mimeType, encoding, baseURL, null); + } + } + }); + } + + public static void loadHTMLString(final int index, final String data, final String baseUrl) { + CocosHelper.runOnUIThread(new Runnable() { + @Override + public void run() { + CocosWebView webView = webViews.get(index); + if (webView != null) { + webView.load(data, null, null, baseUrl, null); + } + } + }); + } + + public static void loadUrl(final int index, final String url) { + CocosHelper.runOnUIThread(new Runnable() { + @Override + public void run() { + CocosWebView webView = webViews.get(index); + if (webView != null) { + webView.load(url); + } + } + }); + } + + public static void loadFile(final int index, final String filePath) { + CocosHelper.runOnUIThread(new Runnable() { + @Override + public void run() { + CocosWebView webView = webViews.get(index); + if (webView != null) { + webView.load(filePath); + } + } + }); + } + + public static void stopLoading(final int index) { + CocosHelper.runOnUIThread(new Runnable() { + @Override + public void run() { + CocosWebView webView = webViews.get(index); + if (webView != null) { + // FIXME: stop + // webView.abo(); + } + } + }); + + } + + public static void reload(final int index) { + CocosHelper.runOnUIThread(new Runnable() { + @Override + public void run() { + CocosWebView webView = webViews.get(index); + if (webView != null) { + webView.reload(); + } + } + }); + } + + public static T callInMainThread(Callable call) throws ExecutionException, InterruptedException { + FutureTask task = new FutureTask(call); + CocosHelper.runOnUIThread(task); + return task.get(); + } + + public static boolean canGoBack(final int index) throws InterruptedException { + Callable callable = new Callable() { + @Override + public Boolean call() throws Exception { + CocosWebView webView = webViews.get(index); + return webView != null && webView.getNavigator().canGoBack(); + } + }; + try { + return callInMainThread(callable); + } catch (ExecutionException e) { + return false; + } + } + + public static boolean canGoForward(final int index) throws InterruptedException { + Callable callable = new Callable() { + @Override + public Boolean call() throws Exception { + CocosWebView webView = webViews.get(index); + return webView != null && webView.getNavigator().canGoForward(); + } + }; + try { + return callInMainThread(callable); + } catch (ExecutionException e) { + return false; + } + } + + public static void goBack(final int index) { + CocosHelper.runOnUIThread(new Runnable() { + @Override + public void run() { + CocosWebView webView = webViews.get(index); + if (webView != null) { + webView.getNavigator().goBack(); + } + } + }); + } + + public static void goForward(final int index) { + CocosHelper.runOnUIThread(new Runnable() { + @Override + public void run() { + CocosWebView webView = webViews.get(index); + if (webView != null) { + webView.getNavigator().goForward(); + } + } + }); + } + + public static void evaluateJS(final int index, final String js) { + CocosHelper.runOnUIThread(new Runnable() { + @Override + public void run() { + CocosWebView webView = webViews.get(index); + if (webView != null) { + // webView.load("javascript:" + js); + webView.executeJs(js, null);; + } + } + }); + } + + public static void setScalesPageToFit(final int index, final boolean scalesPageToFit) { + CocosHelper.runOnUIThread(new Runnable() { + @Override + public void run() { + CocosWebView webView = webViews.get(index); + if (webView != null) { + webView.setScalesPageToFit(scalesPageToFit); + } + } + }); + } +} diff --git a/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/GlobalObject.java b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/GlobalObject.java new file mode 100644 index 0000000000..23e5b09dbf --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/java/com/cocos/lib/GlobalObject.java @@ -0,0 +1,38 @@ +/**************************************************************************** + Copyright (c) 2020 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. + ****************************************************************************/ +package com.cocos.lib; + +import ohos.aafwk.ability.AbilitySlice; + +public class GlobalObject { + private static AbilitySlice sActivity = null; + + public static void setAbilitySlice(AbilitySlice activity) { + GlobalObject.sActivity = activity; + } + + public static AbilitySlice getAbilitySlice() { + return GlobalObject.sActivity; + } +} \ No newline at end of file diff --git a/native/cocos/platform/ohos/libcocos/src/main/res/.keep b/native/cocos/platform/ohos/libcocos/src/main/res/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/native/cocos/platform/ohos/libcocos/src/main/resources/base/element/strings.json b/native/cocos/platform/ohos/libcocos/src/main/resources/base/element/strings.json new file mode 100644 index 0000000000..cdf35da11a --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/resources/base/element/strings.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "done", + "value": "Done" + } + ] +} \ No newline at end of file diff --git a/native/cocos/platform/ohos/libcocos/src/main/resources/base/graphic/bg_common_unpress_btn.xml b/native/cocos/platform/ohos/libcocos/src/main/resources/base/graphic/bg_common_unpress_btn.xml new file mode 100644 index 0000000000..e4cd162ca3 --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/resources/base/graphic/bg_common_unpress_btn.xml @@ -0,0 +1,15 @@ + + + + + + + + \ No newline at end of file diff --git a/native/cocos/platform/ohos/libcocos/src/main/resources/base/graphic/bg_webview_transparent.xml b/native/cocos/platform/ohos/libcocos/src/main/resources/base/graphic/bg_webview_transparent.xml new file mode 100644 index 0000000000..f500037e8e --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/resources/base/graphic/bg_webview_transparent.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/native/cocos/platform/ohos/libcocos/src/main/resources/base/graphic/bg_webview_white.xml b/native/cocos/platform/ohos/libcocos/src/main/resources/base/graphic/bg_webview_white.xml new file mode 100644 index 0000000000..47bd35f3fd --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/resources/base/graphic/bg_webview_white.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/native/cocos/platform/ohos/libcocos/src/main/resources/base/graphic/darkgreen_roundrect.xml b/native/cocos/platform/ohos/libcocos/src/main/resources/base/graphic/darkgreen_roundrect.xml new file mode 100644 index 0000000000..a3ae2e14d6 --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/resources/base/graphic/darkgreen_roundrect.xml @@ -0,0 +1,12 @@ + + + + + + + + \ No newline at end of file diff --git a/native/cocos/platform/ohos/libcocos/src/main/resources/base/layout/editbox_layout.xml b/native/cocos/platform/ohos/libcocos/src/main/resources/base/layout/editbox_layout.xml new file mode 100644 index 0000000000..c55dfa3e22 --- /dev/null +++ b/native/cocos/platform/ohos/libcocos/src/main/resources/base/layout/editbox_layout.xml @@ -0,0 +1,44 @@ + + + + + + +