mirror of
https://github.com/cocos/cocos4.git
synced 2026-11-21 08:02:39 +08:00
Vendored
+2
-2
@@ -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.
|
||||
|
||||
@@ -172,3 +172,15 @@ build/*
|
||||
out
|
||||
|
||||
CMakeSettings.json
|
||||
|
||||
cocos/platform/ohos/libcocos/build/.transforms
|
||||
cocos/platform/ohos/libcocos/build
|
||||
|
||||
**/.gradle
|
||||
**/.settings
|
||||
**/.project
|
||||
|
||||
.clangd/**
|
||||
|
||||
|
||||
**/*~
|
||||
|
||||
+172
-58
@@ -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
|
||||
$<$<BOOL:USE_SE_JSC>:${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
|
||||
|
||||
+169
-167
@@ -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 <condition_variable>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
|
||||
#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<std::string, std::list<int>> AudioEngine::_audioPathIDMap;
|
||||
std::unordered_map<std::string, std::list<int>> AudioEngine::sAudioPathIDMap;
|
||||
//profileName,ProfileHelper
|
||||
std::unordered_map<std::string, AudioEngine::ProfileHelper> AudioEngine::_audioPathProfileHelperMap;
|
||||
unsigned int AudioEngine::_maxInstances = MAX_AUDIOINSTANCES;
|
||||
AudioEngine::ProfileHelper *AudioEngine::_defaultProfileHelper = nullptr;
|
||||
std::unordered_map<int, AudioEngine::AudioInfo> AudioEngine::_audioIDInfoMap;
|
||||
AudioEngineImpl *AudioEngine::_audioEngineImpl = nullptr;
|
||||
std::unordered_map<std::string, AudioEngine::ProfileHelper> AudioEngine::sAudioPathProfileHelperMap;
|
||||
unsigned int AudioEngine::sMaxInstances = MAX_AUDIOINSTANCES;
|
||||
AudioEngine::ProfileHelper * AudioEngine::sDefaultProfileHelper = nullptr;
|
||||
std::unordered_map<int, AudioEngine::AudioInfo> AudioEngine::sAudioIDInfoMap;
|
||||
AudioEngineImpl * AudioEngine::sAudioEngineImpl = nullptr;
|
||||
|
||||
uint32_t AudioEngine::_onPauseListenerID = 0;
|
||||
uint32_t AudioEngine::_onResumeListenerID = 0;
|
||||
std::vector<int> AudioEngine::_breakAudioID;
|
||||
uint32_t AudioEngine::sOnPauseListenerID = 0;
|
||||
uint32_t AudioEngine::sOnResumeListenerID = 0;
|
||||
std::vector<int> 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<std::thread> _workers;
|
||||
std::vector<std::thread> _workers;
|
||||
std::queue<std::function<void()>> _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<std::chrono::microseconds>(currTime - profileHelper->lastPlayTime).count() / 1000000.0;
|
||||
auto delay = static_cast<float>(std::chrono::duration_cast<std::chrono::microseconds>(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<int> 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<void(int, const std::string &)> &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<void(bool isSuccess)> callback) {
|
||||
void AudioEngine::preload(const std::string &filePath, const std::function<void(bool isSuccess)> &callback) {
|
||||
if (!isEnabled()) {
|
||||
callback(false);
|
||||
return;
|
||||
@@ -532,7 +534,7 @@ void AudioEngine::preload(const std::string &filePath, std::function<void(bool i
|
||||
|
||||
lazyInit();
|
||||
|
||||
if (_audioEngineImpl) {
|
||||
if (sAudioEngineImpl) {
|
||||
if (!FileUtils::getInstance()->isFileExist(filePath)) {
|
||||
if (callback) {
|
||||
callback(false);
|
||||
@@ -540,32 +542,32 @@ void AudioEngine::preload(const std::string &filePath, std::function<void(bool i
|
||||
return;
|
||||
}
|
||||
|
||||
_audioEngineImpl->preload(filePath, callback);
|
||||
sAudioEngineImpl->preload(filePath, callback);
|
||||
}
|
||||
}
|
||||
|
||||
void AudioEngine::addTask(const std::function<void()> &task) {
|
||||
lazyInit();
|
||||
|
||||
if (_audioEngineImpl && s_threadPool) {
|
||||
s_threadPool->addTask(task);
|
||||
if (sAudioEngineImpl && sThreadPool) {
|
||||
sThreadPool->addTask(task);
|
||||
}
|
||||
}
|
||||
|
||||
int AudioEngine::getPlayingAudioCount() {
|
||||
return static_cast<int>(_audioIDInfoMap.size());
|
||||
return static_cast<int>(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;
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ THE SOFTWARE.
|
||||
#include "audio/android/tinysndfile.h"
|
||||
#include "platform/FileUtils.h"
|
||||
|
||||
#include <assert.h>
|
||||
#include <cassert>
|
||||
|
||||
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<int64_t>(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<unsigned char *>(malloc(bufSize));
|
||||
sf_count_t readFrames = sf_readf_short(handle, reinterpret_cast<int16_t *>(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<float>(1.0F * info.frames / _result.sampleRate); //NOLINT
|
||||
|
||||
free(buf);
|
||||
ret = true;
|
||||
} while (false);
|
||||
|
||||
if (handle != NULL)
|
||||
if (handle != nullptr) {
|
||||
sf_close(handle);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
@@ -28,57 +28,57 @@
|
||||
|
||||
#include <unistd.h>
|
||||
// for native asset manager
|
||||
#include <sys/types.h>
|
||||
#include <android/asset_manager.h>
|
||||
#include <android/asset_manager_jni.h>
|
||||
#include <unordered_map>
|
||||
#include <android/log.h>
|
||||
#include <thread>
|
||||
#include <sys/types.h>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
|
||||
#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<void()> &func) {
|
||||
void performFunctionInCallerThread(const std::function<void()> &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<off_t>(startV);
|
||||
*length = static_cast<off_t>(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<void(in
|
||||
void AudioEngineImpl::preload(const std::string &filePath, const std::function<void(bool)> &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);
|
||||
}
|
||||
|
||||
@@ -24,18 +24,18 @@
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include <SLES/OpenSLES.h>
|
||||
#include <SLES/OpenSLES_Android.h>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <functional>
|
||||
#include <SLES/OpenSLES.h>
|
||||
#include <SLES/OpenSLES_Android.h>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
#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<void(int, const std::string &)> &callback);
|
||||
bool setCurrentTime(int audioID, float time);
|
||||
void setFinishCallback(int audioID, const std::function<void(int, const std::string &)> &callback);
|
||||
|
||||
void uncache(const std::string &filePath);
|
||||
void uncacheAll();
|
||||
@@ -83,7 +83,7 @@ private:
|
||||
SLObjectItf _outputMixObject;
|
||||
|
||||
//audioID,AudioInfo
|
||||
std::unordered_map<int, IAudioPlayer *> _audioPlayers;
|
||||
std::unordered_map<int, IAudioPlayer *> _audioPlayers;
|
||||
std::unordered_map<int, std::function<void(int, const std::string &)>> _callbackMap;
|
||||
|
||||
// UrlAudioPlayers which need to resumed while entering foreground
|
||||
@@ -96,4 +96,4 @@ private:
|
||||
bool _lazyInitLoop;
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace cc
|
||||
|
||||
@@ -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 <sys/system_properties.h>
|
||||
#include <stdlib.h>
|
||||
#include <algorithm> // for std::find_if
|
||||
#include <cstdlib>
|
||||
#include <utility>
|
||||
|
||||
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<PcmData>();
|
||||
auto isSucceed = std::make_shared<bool>(false);
|
||||
auto pcmData = std::make_shared<PcmData>();
|
||||
auto isSucceed = std::make_shared<bool>(false);
|
||||
auto isReturnFromCache = std::make_shared<bool>(false);
|
||||
auto isPreloadFinished = std::make_shared<bool>(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<PreloadCallbackParam> 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<std::mutex> lk(_pcmCacheMutex);
|
||||
@@ -277,7 +278,7 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload
|
||||
ALOGV("decode %s", (ret ? "succeed" : "failed"));
|
||||
|
||||
std::lock_guard<std::mutex> 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>(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<AudioFileInfo &>(info);
|
||||
size_t judgeCount = sizeof(__audioFileIndicator) / sizeof(__audioFileIndicator[0]);
|
||||
size_t pos = audioFileInfo.url.rfind(".");
|
||||
auto & audioFileInfo = const_cast<AudioFileInfo &>(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<std::mutex> 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<std::mutex> 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);
|
||||
}
|
||||
|
||||
@@ -29,9 +29,9 @@ THE SOFTWARE.
|
||||
#include "audio/android/OpenSLHelper.h"
|
||||
#include "audio/android/PcmData.h"
|
||||
|
||||
#include <unordered_map>
|
||||
#include <memory>
|
||||
#include <condition_variable>
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace cc {
|
||||
// Manage PcmAudioPlayer& UrlAudioPlayer
|
||||
@@ -54,11 +54,11 @@ public:
|
||||
|
||||
IAudioPlayer *getAudioPlayer(const std::string &audioFilePath);
|
||||
|
||||
typedef std::function<void(bool /* succeed */, PcmData /* data */)> PreloadCallback;
|
||||
using PreloadCallback = std::function<void(bool, PcmData)>;
|
||||
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> 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<std::string, PcmData> _pcmCache;
|
||||
std::mutex _pcmCacheMutex;
|
||||
std::mutex _pcmCacheMutex;
|
||||
|
||||
struct PreloadCallbackParam {
|
||||
PreloadCallback callback;
|
||||
bool isPreloadInPlay2d;
|
||||
bool isPreloadInPlay2d;
|
||||
};
|
||||
|
||||
std::unordered_map<std::string, std::vector<PreloadCallbackParam>> _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;
|
||||
|
||||
@@ -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 <stdio.h>
|
||||
// #endif
|
||||
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
#include <cassert>
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
|
||||
#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<const char *>(&ONE)) == 1;
|
||||
}
|
||||
|
||||
// "swab" conflicts with OS X <string.h>
|
||||
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<int16_t>(little2u(reinterpret_cast<unsigned char *>(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<FILE *>(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<FILE *>(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<FILE *>(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<FILE *>(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<SNDFILE *>(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<long>(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<int>(samplerate);
|
||||
handle->info.channels = static_cast<int>(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<long>(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<long>(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<long>(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<size_t>(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<unsigned char *>(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<const int *>(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<const float *>(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<const uint8_t *>(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:
|
||||
|
||||
@@ -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 <stdio.h>
|
||||
#include <sys/cdefs.h>
|
||||
#include <cstdio>
|
||||
|
||||
__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
|
||||
|
||||
@@ -27,12 +27,12 @@
|
||||
#ifndef __AUDIO_ENGINE_INL_H_
|
||||
#define __AUDIO_ENGINE_INL_H_
|
||||
|
||||
#include <unordered_map>
|
||||
#include <list>
|
||||
#include <unordered_map>
|
||||
|
||||
#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<void(int, const std::string &)> &callback);
|
||||
bool setCurrentTime(int audioID, float time);
|
||||
void setFinishCallback(int audioID, const std::function<void(int, const std::string &)> &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<void(bool)> 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<int, AudioPlayer *> _audioPlayers;
|
||||
std::mutex _threadMutex;
|
||||
std::mutex _threadMutex;
|
||||
|
||||
bool _lazyInitLoop;
|
||||
|
||||
int _currentAudioID;
|
||||
int _currentAudioID;
|
||||
std::weak_ptr<Scheduler> _scheduler;
|
||||
};
|
||||
} // namespace cc
|
||||
|
||||
@@ -373,7 +373,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;
|
||||
@@ -385,7 +385,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();
|
||||
@@ -393,15 +393,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;
|
||||
@@ -420,7 +420,7 @@ ALuint AudioEngineImpl::findValidSource() {
|
||||
}
|
||||
|
||||
void AudioEngineImpl::setVolume(int audioID, float volume) {
|
||||
if (!_checkAudioIdValid(audioID)) {
|
||||
if (!checkAudioIdValid(audioID)) {
|
||||
return;
|
||||
}
|
||||
auto player = _audioPlayers[audioID];
|
||||
@@ -437,7 +437,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];
|
||||
@@ -463,7 +463,7 @@ void AudioEngineImpl::setLoop(int audioID, bool loop) {
|
||||
}
|
||||
|
||||
bool AudioEngineImpl::pause(int audioID) {
|
||||
if (!_checkAudioIdValid(audioID)) {
|
||||
if (!checkAudioIdValid(audioID)) {
|
||||
return false;
|
||||
}
|
||||
bool ret = true;
|
||||
@@ -479,7 +479,7 @@ bool AudioEngineImpl::pause(int audioID) {
|
||||
}
|
||||
|
||||
bool AudioEngineImpl::resume(int audioID) {
|
||||
if (!_checkAudioIdValid(audioID)) {
|
||||
if (!checkAudioIdValid(audioID)) {
|
||||
return false;
|
||||
}
|
||||
bool ret = true;
|
||||
@@ -495,7 +495,7 @@ bool AudioEngineImpl::resume(int audioID) {
|
||||
}
|
||||
|
||||
void AudioEngineImpl::stop(int audioID) {
|
||||
if (!_checkAudioIdValid(audioID)) {
|
||||
if (!checkAudioIdValid(audioID)) {
|
||||
return;
|
||||
}
|
||||
auto player = _audioPlayers[audioID];
|
||||
@@ -515,7 +515,7 @@ void AudioEngineImpl::stopAll() {
|
||||
}
|
||||
|
||||
float AudioEngineImpl::getDuration(int audioID) {
|
||||
if (!_checkAudioIdValid(audioID)) {
|
||||
if (!checkAudioIdValid(audioID)) {
|
||||
return 0.0f;
|
||||
}
|
||||
auto player = _audioPlayers[audioID];
|
||||
@@ -537,7 +537,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;
|
||||
@@ -559,7 +559,7 @@ float AudioEngineImpl::getCurrentTime(int audioID) {
|
||||
}
|
||||
|
||||
bool AudioEngineImpl::setCurrentTime(int audioID, float time) {
|
||||
if (!_checkAudioIdValid(audioID)) {
|
||||
if (!checkAudioIdValid(audioID)) {
|
||||
return false;
|
||||
}
|
||||
bool ret = false;
|
||||
@@ -594,7 +594,7 @@ bool AudioEngineImpl::setCurrentTime(int audioID, float time) {
|
||||
}
|
||||
|
||||
void AudioEngineImpl::setFinishCallback(int audioID, const std::function<void(int, const std::string &)> &callback) {
|
||||
if (!_checkAudioIdValid(audioID)) {
|
||||
if (!checkAudioIdValid(audioID)) {
|
||||
return;
|
||||
}
|
||||
_audioPlayers[audioID]->_finishCallbak = callback;
|
||||
@@ -625,7 +625,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;
|
||||
}
|
||||
|
||||
@@ -666,6 +666,6 @@ void AudioEngineImpl::uncacheAll() {
|
||||
_audioCaches.clear();
|
||||
}
|
||||
|
||||
bool AudioEngineImpl::_checkAudioIdValid(int audioID) {
|
||||
bool AudioEngineImpl::checkAudioIdValid(int audioID) {
|
||||
return _audioPlayers.find(audioID) != _audioPlayers.end();
|
||||
}
|
||||
|
||||
@@ -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 <chrono>
|
||||
#include <functional>
|
||||
#include <list>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <chrono>
|
||||
|
||||
#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<int>(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<void(bool isSuccess)> callback);
|
||||
static void preload(const std::string &filePath, const std::function<void(bool isSuccess)> &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<int, AudioInfo> _audioIDInfoMap;
|
||||
static std::unordered_map<int, AudioInfo> sAudioIDInfoMap;
|
||||
|
||||
//audio file path,audio IDs
|
||||
static std::unordered_map<std::string, std::list<int>> _audioPathIDMap;
|
||||
static std::unordered_map<std::string, std::list<int>> sAudioPathIDMap;
|
||||
|
||||
//profileName,ProfileHelper
|
||||
static std::unordered_map<std::string, ProfileHelper> _audioPathProfileHelperMap;
|
||||
static std::unordered_map<std::string, ProfileHelper> 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<int> _breakAudioID;
|
||||
static uint32_t sOnPauseListenerID;
|
||||
static uint32_t sOnResumeListenerID;
|
||||
static std::vector<int> sBreakAudioID;
|
||||
|
||||
static void onEnterBackground(const CustomEvent &);
|
||||
static void onEnterForeground(const CustomEvent &);
|
||||
|
||||
+35
-30
@@ -26,13 +26,13 @@
|
||||
|
||||
#define LOG_TAG "AudioCache"
|
||||
|
||||
#include "audio/win32/AudioCache.h"
|
||||
#include "audio/oalsoft/AudioCache.h"
|
||||
#include <thread>
|
||||
#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<bool>(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<bool>(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<ALsizei>(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<uint32_t>(sampleRate * QUEUEBUFFER_TIME_STEP * QUEUEBUFFER_NUM));
|
||||
|
||||
std::vector<char> adjustFrameBuf;
|
||||
|
||||
if (decoder->seek(totalFrames)) {
|
||||
char *tmpBuf = (char *)malloc(framesToReadOnce * bytesPerFrame);
|
||||
auto *tmpBuf = static_cast<char *>(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<char *>(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<ALsizei>(dataSize), static_cast<ALsizei>(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<char *>(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);
|
||||
@@ -26,18 +26,20 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <functional>
|
||||
#ifdef OPENAL_PLAIN_INCLUDES
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#if defined(OPENAL_PLAIN_INCLUDES)
|
||||
#include <al.h>
|
||||
#else
|
||||
#elif CC_PLATFORM == CC_PLATFORM_WINDOWS
|
||||
#include <OpenalSoft/al.h>
|
||||
#elif CC_PLATFORM == CC_PLATFORM_OHOS
|
||||
#include <AL/al.h>
|
||||
#endif
|
||||
#include "audio/oalsoft/AudioMacros.h"
|
||||
#include "base/Macros.h"
|
||||
#include "audio/win32/AudioMacros.h"
|
||||
|
||||
namespace cc {
|
||||
class AudioEngineImpl;
|
||||
+12
-6
@@ -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);
|
||||
@@ -26,9 +26,13 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <cstdint>
|
||||
|
||||
#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;
|
||||
};
|
||||
|
||||
+16
-8
@@ -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;
|
||||
}
|
||||
|
||||
+43
-25
@@ -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 <unistd.h>
|
||||
#endif
|
||||
|
||||
#include <sys/stat.h>
|
||||
#include <cstdlib>
|
||||
|
||||
#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<FileUtilsOHOS *>(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<unsigned char *>(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 {
|
||||
+14
-8
@@ -26,7 +26,9 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "audio/win32/AudioDecoder.h"
|
||||
#include "audio/oalsoft/AudioDecoder.h"
|
||||
|
||||
#include <functional>
|
||||
|
||||
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<int, std::function<void()>> _fdAndDeleter;
|
||||
#endif
|
||||
|
||||
friend class AudioDecoderManager;
|
||||
};
|
||||
+40
-14
@@ -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<long>(offset), whence); //NOLINT
|
||||
}
|
||||
|
||||
ov_callbacks ogg_callbacks = { //NOLINT
|
||||
static_cast<size_t (*)(void *, size_t, size_t, void *)>(cc::ohosRead),
|
||||
static_cast<int (*)(void *, ogg_int64_t, int)>(ohosSeek_wrap),
|
||||
static_cast<int (*)(void *)>(cc::ohosClose),
|
||||
static_cast<long (*)(void *)>(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<uint32_t>(vi->rate);
|
||||
_channelCount = vi->channels;
|
||||
_bytesPerFrame = vi->channels * sizeof(short);
|
||||
_totalFrames = static_cast<uint32_t>(ov_pcm_total(&_vf, -1));
|
||||
_isOpened = true;
|
||||
_sampleRate = static_cast<uint32_t>(vi->rate);
|
||||
_channelCount = vi->channels;
|
||||
_bytesPerFrame = vi->channels * sizeof(int16_t);
|
||||
_totalFrames = static_cast<uint32_t>(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<uint32_t>(bytesRead / _bytesPerFrame);
|
||||
}
|
||||
|
||||
+12
-8
@@ -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;
|
||||
|
||||
+106
-95
@@ -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 <windows.h>
|
||||
#if CC_PLATFORM == CC_PLATFORM_WINDOWS
|
||||
#include <windows.h>
|
||||
|
||||
// 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<void(bool)> callback) {
|
||||
AudioCache *AudioEngineImpl::preload(const std::string &filePath, const std::function<void(bool)> &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<void(int, const std::string &)> &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();
|
||||
}
|
||||
+22
-22
@@ -28,9 +28,9 @@
|
||||
|
||||
#include <unordered_map>
|
||||
|
||||
#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<void(int, const std::string &)> &callback);
|
||||
bool setCurrentTime(int audioID, float time);
|
||||
void setFinishCallback(int audioID, const std::function<void(int, const std::string &)> &callback);
|
||||
|
||||
void uncache(const std::string &filePath);
|
||||
void uncacheAll();
|
||||
AudioCache *preload(const std::string &filePath, std::function<void(bool)> callback);
|
||||
void update(float dt);
|
||||
void uncache(const std::string &filePath);
|
||||
void uncacheAll();
|
||||
AudioCache *preload(const std::string &filePath, const std::function<void(bool)> &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<int, AudioPlayer *> _audioPlayers;
|
||||
std::mutex _threadMutex;
|
||||
std::mutex _threadMutex;
|
||||
|
||||
bool _lazyInitLoop;
|
||||
|
||||
int _currentAudioID;
|
||||
int _currentAudioID;
|
||||
std::weak_ptr<Scheduler> _scheduler;
|
||||
};
|
||||
} // namespace cc
|
||||
@@ -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; \
|
||||
}
|
||||
+55
-51
@@ -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<std::mutex> 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<char *>(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<int>(_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
|
||||
@@ -26,15 +26,17 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#ifdef OPENAL_PLAIN_INCLUDES
|
||||
#include <al.h>
|
||||
#else
|
||||
#elif CC_PLATFORM == CC_PLATFORM_WINDOWS
|
||||
#include <OpenalSoft/al.h>
|
||||
#elif CC_PLATFORM == CC_PLATFORM_OHOS
|
||||
#include <AL/al.h>
|
||||
#endif
|
||||
#include "base/Macros.h"
|
||||
|
||||
@@ -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<int16_t *>(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
|
||||
@@ -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
|
||||
@@ -0,0 +1,73 @@
|
||||
#include "cocos/audio/ohos/FsCallback.h"
|
||||
|
||||
#include <rawfile/raw_dir.h>
|
||||
#include <rawfile/raw_file.h>
|
||||
#include "cocos/platform/ohos/FileUtils-ohos.h"
|
||||
|
||||
namespace {
|
||||
inline cc::FileUtilsOHOS *getFU() {
|
||||
return static_cast<cc::FileUtilsOHOS *>(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<FatFd *>(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<FatFd *>(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<FatFd *>(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<FatFd *>(datasource);
|
||||
if (fatFd->isRawFile) {
|
||||
return GetRawFileOffset(fatFd->file.rf);
|
||||
}
|
||||
return ftell(fatFd->file.fp);
|
||||
}
|
||||
} // namespace cc
|
||||
@@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
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
|
||||
@@ -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<unsigned char *>(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<unsigned char *>(realloc(_bytes, sizeof(unsigned char) * _size));
|
||||
}
|
||||
|
||||
void Data::clear() {
|
||||
free(_bytes);
|
||||
_bytes = nullptr;
|
||||
|
||||
@@ -27,9 +27,9 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "base/Macros.h"
|
||||
#include <cstdint> // for ssize_t on android
|
||||
#include <string> // 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;
|
||||
|
||||
+40
-17
@@ -47,29 +47,31 @@
|
||||
|
||||
#elif (CC_PLATFORM == CC_PLATFORM_ANDROID)
|
||||
#include <android/log.h>
|
||||
#elif CC_PLATFORM == CC_PLATFORM_OHOS
|
||||
#include <hilog/log.h>
|
||||
#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<std::string> 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
|
||||
|
||||
+10
-10
@@ -25,8 +25,8 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "Macros.h"
|
||||
#include <string>
|
||||
#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 { \
|
||||
|
||||
@@ -52,6 +52,14 @@ typedef SSIZE_T ssize_t;
|
||||
"%s function:%s line:%d", \
|
||||
__FILE__, __FUNCTION__, __LINE__); \
|
||||
}
|
||||
#elif (CC_PLATFORM == CC_PLATFORM_OHOS)
|
||||
#include <hilog/log.h>
|
||||
#define CC_ASSERT(cond) \
|
||||
if (!(cond)) { \
|
||||
HILOG_ERROR(LOG_APP, \
|
||||
"assert %{public}s function:%{public}s line:%{public}d", \
|
||||
__FILE__, __FUNCTION__, __LINE__); \
|
||||
}
|
||||
#else
|
||||
#include <assert.h>
|
||||
#define CC_ASSERT(cond) assert(cond)
|
||||
|
||||
@@ -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);
|
||||
};
|
||||
|
||||
|
||||
+21
-21
@@ -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<char *>(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<char16_t> &str, char16_t
|
||||
*
|
||||
* Return value: the trimmed string.
|
||||
* */
|
||||
static void trimUTF16VectorFromIndex(std::vector<char16_t> &str, int index) {
|
||||
static void trimUTF16VectorFromIndex(std::vector<char16_t> &str, int index) { //NOLINT
|
||||
int size = static_cast<int>(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<const UTF8 *>(in.c_str());
|
||||
const auto *end = reinterpret_cast<const UTF8 *>(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<const unsigned short *>(env->GetStringChars(srcjStr, nullptr));
|
||||
auto * unicodeChar = static_cast<const uint16_t *>(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<const char16_t *>(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<const jchar *>(utf16Str.data()), utf16Str.length());
|
||||
return stringText;
|
||||
}
|
||||
#endif
|
||||
@@ -274,8 +274,8 @@ std::vector<char16_t> getChar16VectorFromUTF16String(const std::u16string &utf16
|
||||
return std::vector<char16_t>(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<const UTF8 *>(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<const UTF8 *>(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<const char *>(sequenceUtf8), lengthChar);
|
||||
sequenceUtf8 += lengthChar;
|
||||
|
||||
_str.push_back(charUTF8);
|
||||
|
||||
+14
-14
@@ -27,18 +27,18 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "base/Macros.h"
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#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 <typename T>
|
||||
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<char16_t> &str);
|
||||
CC_DLL void trimUTF16Vector(std::vector<char16_t> &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.
|
||||
|
||||
@@ -27,10 +27,14 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "base/Macros.h"
|
||||
#include "base/TypeDef.h"
|
||||
#include <cerrno>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "base/Macros.h"
|
||||
#include "base/TypeDef.h"
|
||||
/** @file ccUtils.h
|
||||
Misc free functions
|
||||
*/
|
||||
|
||||
namespace cc {
|
||||
namespace utils {
|
||||
|
||||
@@ -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 <type_traits>
|
||||
#include "cocos/bindings/jswrapper/SeApi.h"
|
||||
#include "cocos/bindings/manual/jsb_conversions.h"
|
||||
#include "cocos/ui/webview/WebView.h"
|
||||
#if USE_WEBVIEW > 0
|
||||
#include <type_traits>
|
||||
#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);
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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<std::string, unsigned> __jsbFunctionInvokedRecords;
|
||||
unsigned int jsbInvocationCount = 0;
|
||||
std::map<std::string, unsigned> jsbFunctionInvokedRecords;
|
||||
#endif
|
||||
|
||||
#define RETRUN_VAL_IF_FAIL(cond, val) \
|
||||
@@ -59,38 +59,39 @@ std::map<std::string, unsigned> __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<v8::Value> &info) {
|
||||
void seLogCallback(const v8::FunctionCallbackInfo<v8::Value> &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<v8::Value> &info) {
|
||||
void seForceGC(const v8::FunctionCallbackInfo<v8::Value> & /*info*/) {
|
||||
ScriptEngine::getInstance()->garbageCollect();
|
||||
}
|
||||
|
||||
std::string stackTraceToString(v8::Local<v8::StackTrace> 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<v8::StackFrame> frame = stack->GetFrame(v8::Isolate::GetCurrent(), i);
|
||||
v8::Local<v8::String> script = frame->GetScriptName();
|
||||
std::string scriptName;
|
||||
v8::Local<v8::StackFrame> frame = stack->GetFrame(v8::Isolate::GetCurrent(), i);
|
||||
v8::Local<v8::String> script = frame->GetScriptName();
|
||||
std::string scriptName;
|
||||
if (!script.IsEmpty()) {
|
||||
scriptName = *v8::String::Utf8Value(v8::Isolate::GetCurrent(), script);
|
||||
}
|
||||
|
||||
v8::Local<v8::String> 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<v8::StackTrace> 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<int>(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<int>(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<v8::Message> message, v8::Local<v8::Value> data) {
|
||||
ScriptEngine *thiz = getInstance();
|
||||
v8::Local<v8::String> msg = message->Get();
|
||||
Value msgVal;
|
||||
void ScriptEngine::onMessageCallback(v8::Local<v8::Message> message, v8::Local<v8::Value> /*data*/) {
|
||||
ScriptEngine * thiz = getInstance();
|
||||
v8::Local<v8::String> 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<v8::Message> message, v8::Local<v
|
||||
}
|
||||
|
||||
void ScriptEngine::onPromiseRejectCallback(v8::PromiseRejectMessage msg) {
|
||||
v8::Isolate *isolate = getInstance()->_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<v8::String> 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<v8::String> 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<v8::Object> obj = value->ToObject(isolate->GetCurrentContext()).ToLocalChecked();
|
||||
v8::Local<v8::Array> 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<v8::String> 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<internal::PrivateData *>(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<int>(_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<int>(__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<int>(__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<v8::String> source = v8::String::NewFromUtf8(_isolate, scriptStr.c_str(), v8::NewStringType::kNormal);
|
||||
if (source.IsEmpty())
|
||||
if (source.IsEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
v8::MaybeLocal<v8::String> 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<v8::Script> 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<v8::Script> v8Script = maybeScript.ToLocalChecked();
|
||||
v8::Local<v8::Script> v8Script = maybeScript.ToLocalChecked();
|
||||
v8::MaybeLocal<v8::Value> 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<v8::StackTrace> stack = v8::StackTrace::CurrentStackTrace(_isolate, __jsbStackFrameLimit, v8::StackTrace::kOverview);
|
||||
v8::HandleScope hs(_isolate);
|
||||
v8::Local<v8::StackTrace> 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<int>(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<v8::String> code = v8::String::NewFromUtf8(_isolate, scriptBuffer.c_str(), v8::NewStringType::kNormal, (int)scriptBuffer.length()).ToLocalChecked();
|
||||
v8::Local<v8::Value> scriptPath = v8::String::NewFromUtf8(_isolate, path.data(), v8::NewStringType::kNormal).ToLocalChecked();
|
||||
std::string scriptBuffer = _fileOperationDelegate.onGetStringFromFile(path);
|
||||
v8::Local<v8::String> code = v8::String::NewFromUtf8(_isolate, scriptBuffer.c_str(), v8::NewStringType::kNormal, static_cast<int>(scriptBuffer.length())).ToLocalChecked();
|
||||
v8::Local<v8::Value> 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<v8::Context> parsing_context = v8::Local<v8::Context>::New(_isolate, _context);
|
||||
v8::Context::Scope parsing_scope(parsing_context);
|
||||
v8::TryCatch tryCatch(_isolate);
|
||||
v8::Local<v8::UnboundScript> v8_script = v8::ScriptCompiler::CompileUnboundScript(_isolate, &source, v8::ScriptCompiler::kEagerCompile)
|
||||
.ToLocalChecked();
|
||||
v8::ScriptOrigin origin(scriptPath);
|
||||
v8::ScriptCompiler::Source source(code, origin);
|
||||
v8::Local<v8::Context> parsingContext = v8::Local<v8::Context>::New(_isolate, _context);
|
||||
v8::Context::Scope parsingScope(parsingContext);
|
||||
v8::TryCatch tryCatch(_isolate);
|
||||
v8::Local<v8::UnboundScript> 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<v8::String> dummyBytecodeSource = v8::String::NewFromUtf8(_isolate, "\" \"", v8::NewStringType::kNormal).ToLocalChecked();
|
||||
v8::ScriptCompiler::Source dummySource(dummyBytecodeSource);
|
||||
v8::Local<v8::UnboundScript> dummyFunction = v8::ScriptCompiler::CompileUnboundScript(_isolate, &dummySource, v8::ScriptCompiler::kEagerCompile).ToLocalChecked();
|
||||
v8::ScriptCompiler::CachedData *dummyData = v8::ScriptCompiler::CreateCodeCache(dummyFunction);
|
||||
v8::HandleScope scope(_isolate);
|
||||
v8::Local<v8::String> dummyBytecodeSource = v8::String::NewFromUtf8(_isolate, "\" \"", v8::NewStringType::kNormal).ToLocalChecked();
|
||||
v8::ScriptCompiler::Source dummySource(dummyBytecodeSource);
|
||||
v8::Local<v8::UnboundScript> 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<v8::Value> scriptPath = v8::String::NewFromUtf8(_isolate, path_bc.data(), v8::NewStringType::kNormal).ToLocalChecked();
|
||||
v8::Local<v8::Integer> offset = v8::Int32::New(_isolate, 0);
|
||||
v8::Local<v8::Integer> column = v8::Int32::New(_isolate, 0);
|
||||
v8::Local<v8::Value> scriptPath = v8::String::NewFromUtf8(_isolate, pathBc.data(), v8::NewStringType::kNormal).ToLocalChecked();
|
||||
v8::Local<v8::Integer> offset = v8::Int32::New(_isolate, 0);
|
||||
v8::Local<v8::Integer> column = v8::Int32::New(_isolate, 0);
|
||||
v8::Local<v8::Boolean> 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<int>(cachedData.getSize()));
|
||||
v8::Local<v8::String> dummyCode;
|
||||
|
||||
// generate dummy code
|
||||
@@ -847,40 +908,40 @@ bool ScriptEngine::runByteCodeFile(const std::string &path_bc, Value *ret /* = n
|
||||
std::vector<char> 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::UnboundScript> v8_script = v8::ScriptCompiler::CompileUnboundScript(_isolate, &source, v8::ScriptCompiler::kConsumeCodeCache)
|
||||
.ToLocalChecked();
|
||||
v8::TryCatch tryCatch(_isolate);
|
||||
v8::Local<v8::UnboundScript> 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<v8::Script> runnable_script = v8_script->BindToCurrentContext();
|
||||
v8::MaybeLocal<v8::Value> result = runnable_script->Run(_context.Get(_isolate));
|
||||
v8::Local<v8::Script> runnableScript = v8Script->BindToCurrentContext();
|
||||
v8::MaybeLocal<v8::Value> 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<v8::Context> ScriptEngine::_getContext() const {
|
||||
v8::Local<v8::Context> 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 {
|
||||
|
||||
@@ -30,8 +30,8 @@
|
||||
|
||||
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8
|
||||
|
||||
#include "Base.h"
|
||||
#include "../Value.h"
|
||||
#include "Base.h"
|
||||
|
||||
#include <thread>
|
||||
|
||||
@@ -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<v8::Context> _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<v8::Context> _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<v8::Message> message, v8::Local<v8::Value> 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<RegisterCallback> _registerCallbackArray;
|
||||
std::vector<RegisterCallback> _permRegisterCallbackArray;
|
||||
std::vector<std::function<void()>> _beforeInitHookArray;
|
||||
std::vector<std::function<void()>> _afterInitHookArray;
|
||||
std::vector<std::function<void()>> _beforeCleanupHookArray;
|
||||
std::vector<std::function<void()>> _afterCleanupHookArray;
|
||||
std::vector<RegisterCallback> _registerCallbackArray;
|
||||
std::vector<RegisterCallback> _permRegisterCallbackArray;
|
||||
std::vector<std::function<void()>> _beforeInitHookArray;
|
||||
std::vector<std::function<void()>> _afterInitHookArray;
|
||||
std::vector<std::function<void()>> _beforeCleanupHookArray;
|
||||
std::vector<std::function<void()>> _afterCleanupHookArray;
|
||||
|
||||
v8::Persistent<v8::Context> _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;
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -38,16 +38,16 @@ extern "C" {
|
||||
(!defined(_MSC_VER) || _MSC_VER < 1600) && !defined(__WINE__)
|
||||
#include <BaseTsd.h>
|
||||
#include <stddef.h>
|
||||
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 <stdint.h>
|
||||
#include <cstdint>
|
||||
#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
|
||||
}
|
||||
|
||||
@@ -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 <android/log.h>
|
||||
#include <vector>
|
||||
#if CC_PLATFORM == CC_PLATFORM_ANDROID
|
||||
#include <android/log.h>
|
||||
#elif CC_PLATFORM == CC_PLATFORM_OHOS
|
||||
#include <hilog/log.h>
|
||||
#endif
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<ValueType> ValueTypes;
|
||||
using ValueTypes = std::vector<ValueType>;
|
||||
|
||||
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<jstring>(_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<int>(m_returnType));
|
||||
_mError = JSJ_ERR_TYPE_NOT_SUPPORT;
|
||||
SE_LOGD("Return type '%d' is not supported", static_cast<int>(_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<jstring>(_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<int>(m_returnType));
|
||||
_mError = JSJ_ERR_TYPE_NOT_SUPPORT;
|
||||
SE_LOGD("Return type '%d' is not supported", static_cast<int>(_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<void **>(&_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<void **>(&_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<jclass>(_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<JavaScriptJavaBridge *>(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<int>(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<jobject> 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));
|
||||
|
||||
|
||||
@@ -25,17 +25,18 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cassert>
|
||||
#include <type_traits>
|
||||
#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 <assert.h>
|
||||
#include <type_traits>
|
||||
|
||||
#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<std::string> *ret);
|
||||
bool seval_to_std_vector_int(const se::Value &v, std::vector<int> *ret);
|
||||
bool seval_to_std_vector_uint16(const se::Value &v, std::vector<uint16_t> *ret);
|
||||
bool seval_to_std_vector_float(const se::Value &v, std::vector<float> *ret);
|
||||
bool seval_to_std_vector_Vec2(const se::Value &v, std::vector<cc::Vec2> *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<std::string> *ret); //NOLINT
|
||||
bool seval_to_std_vector_int(const se::Value &v, std::vector<int> *ret); //NOLINT
|
||||
bool seval_to_std_vector_uint16(const se::Value &v, std::vector<uint16_t> *ret); //NOLINT
|
||||
bool seval_to_std_vector_float(const se::Value &v, std::vector<float> *ret); //NOLINT
|
||||
bool seval_to_std_vector_Vec2(const se::Value &v, std::vector<cc::Vec2> *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<std::string, std::string> *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<std::string, std::string> *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 <typename T>
|
||||
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 <typename T>
|
||||
@@ -283,9 +284,9 @@ seval_to_std_vector(const se::Value &v, std::vector<T> *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<T> *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<T> *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<std::string, T> *ret) {
|
||||
se::Object *obj = v.toObject();
|
||||
|
||||
std::vector<std::string> 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<std::string, T> *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<std::string> &v, se::Value *ret);
|
||||
bool std_vector_int_to_seval(const std::vector<int> &v, se::Value *ret);
|
||||
bool std_vector_uint16_to_seval(const std::vector<uint16_t> &v, se::Value *ret);
|
||||
bool std_vector_float_to_seval(const std::vector<float> &v, se::Value *ret);
|
||||
bool std_map_string_string_to_seval(const std::map<std::string, std::string> &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<std::string> &v, se::Value *ret); //NOLINT
|
||||
bool std_vector_int_to_seval(const std::vector<int> &v, se::Value *ret); //NOLINT
|
||||
bool std_vector_uint16_to_seval(const std::vector<uint16_t> &v, se::Value *ret); //NOLINT
|
||||
bool std_vector_float_to_seval(const std::vector<float> &v, se::Value *ret); //NOLINT
|
||||
bool std_map_string_string_to_seval(const std::map<std::string, std::string> &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 T>
|
||||
typename std::enable_if<!std::is_base_of<cc::Ref, T>::value, bool>::type
|
||||
native_ptr_to_seval(T *v_c, se::Value *ret, bool *isReturnCachedValue = nullptr) {
|
||||
typedef typename std::decay<typename std::remove_const<T>::type>::type DecayT;
|
||||
DecayT *v = const_cast<DecayT *>(v_c);
|
||||
DecayT * v = const_cast<DecayT *>(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<T>(v);
|
||||
@@ -461,7 +461,7 @@ template <typename T>
|
||||
typename std::enable_if<!std::is_base_of<cc::Ref, T>::value && !std::is_pointer<T>::value, bool>::type
|
||||
native_ptr_to_seval(T &v_ref, se::Value *ret, bool *isReturnCachedValue = nullptr) {
|
||||
typedef typename std::decay<typename std::remove_const<decltype(v_ref)>::type>::type DecayT;
|
||||
DecayT *v = const_cast<DecayT *>(&v_ref);
|
||||
DecayT * v = const_cast<DecayT *>(&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<DecayT>(v);
|
||||
@@ -500,8 +500,8 @@ bool native_ptr_to_rooted_seval(const typename std::enable_if<!std::is_base_of<c
|
||||
return true;
|
||||
}
|
||||
|
||||
se::Object *obj = nullptr;
|
||||
auto iter = se::NativePtrToObjectMap::find((void *)v);
|
||||
se::Object *obj = nullptr;
|
||||
auto iter = se::NativePtrToObjectMap::find((void *)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
|
||||
se::Class *cls = JSBClassType::findClass<T>(v);
|
||||
assert(cls != nullptr);
|
||||
@@ -530,15 +530,15 @@ template <typename T>
|
||||
typename std::enable_if<!std::is_base_of<cc::Ref, T>::value, bool>::type
|
||||
native_ptr_to_seval(T *vp, se::Class *cls, se::Value *ret, bool *isReturnCachedValue = nullptr) {
|
||||
typedef typename std::decay<typename std::remove_const<T>::type>::type DecayT;
|
||||
DecayT *v = const_cast<DecayT *>(vp);
|
||||
DecayT * v = const_cast<DecayT *>(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 T>
|
||||
typename std::enable_if<!std::is_base_of<cc::Ref, T>::value, bool>::type
|
||||
native_ptr_to_seval(T &v_ref, se::Class *cls, se::Value *ret, bool *isReturnCachedValue = nullptr) {
|
||||
typedef typename std::decay<typename std::remove_const<decltype(v_ref)>::type>::type DecayT;
|
||||
DecayT *v = const_cast<DecayT *>(&v_ref);
|
||||
DecayT * v = const_cast<DecayT *>(&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<!std::is_base_of<cc::Ref
|
||||
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
|
||||
assert(cls != nullptr);
|
||||
obj = se::Object::createObjectWithClass(cls);
|
||||
@@ -633,15 +633,15 @@ template <typename T>
|
||||
typename std::enable_if<std::is_base_of<cc::Ref, T>::value, bool>::type
|
||||
native_ptr_to_seval(T *vp, se::Value *ret, bool *isReturnCachedValue = nullptr) {
|
||||
typedef typename std::decay<typename std::remove_const<T>::type>::type DecayT;
|
||||
DecayT *v = const_cast<DecayT *>(vp);
|
||||
DecayT * v = const_cast<DecayT *>(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<T>(v);
|
||||
@@ -669,15 +669,15 @@ template <typename T>
|
||||
typename std::enable_if<std::is_base_of<cc::Ref, T>::value, bool>::type
|
||||
native_ptr_to_seval(T *vp, se::Class *cls, se::Value *ret, bool *isReturnCachedValue = nullptr) {
|
||||
typedef typename std::decay<typename std::remove_const<T>::type>::type DecayT;
|
||||
DecayT *v = const_cast<DecayT *>(vp);
|
||||
DecayT * v = const_cast<DecayT *>(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 <typename T>
|
||||
bool std_vector_to_seval(const std::vector<T> &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 <typename T, bool is_reference>
|
||||
struct HolderType {
|
||||
using type = typename std::remove_const<T>::type;
|
||||
using type = typename std::remove_const<T>::type;
|
||||
using local_type = typename std::conditional_t<is_reference && is_jsb_object_v<T>, std::add_pointer_t<type>, 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<type, local_type>(data);
|
||||
@@ -775,20 +775,20 @@ struct HolderType {
|
||||
|
||||
template <>
|
||||
struct HolderType<const char *, false> {
|
||||
using type = const char *;
|
||||
using type = const char *;
|
||||
using local_type = std::string;
|
||||
local_type data;
|
||||
local_type data;
|
||||
std::remove_const_t<type> *ptr = nullptr;
|
||||
inline type value() { return data.c_str(); }
|
||||
inline type value() { return data.c_str(); }
|
||||
};
|
||||
|
||||
template <typename R, typename... ARGS>
|
||||
struct HolderType<std::function<R(ARGS...)>, true> {
|
||||
using type = std::function<R(ARGS...)>;
|
||||
using type = std::function<R(ARGS...)>;
|
||||
using local_type = std::function<R(ARGS...)>;
|
||||
local_type data;
|
||||
local_type data;
|
||||
std::remove_const_t<type> *ptr = nullptr;
|
||||
inline type value() { return data; }
|
||||
inline type value() { return data; }
|
||||
};
|
||||
|
||||
///////////////////////////////////convertion//////////////////////////////////////////////////////////
|
||||
@@ -805,7 +805,7 @@ template <typename T>
|
||||
inline typename std::enable_if_t<std::is_enum<T>::value, bool>
|
||||
sevalue_to_native(const se::Value &from, T *to, se::Object *ctx) {
|
||||
typename std::underlying_type_t<T> tmp;
|
||||
bool ret = sevalue_to_native(from, &tmp, ctx);
|
||||
bool ret = sevalue_to_native(from, &tmp, ctx);
|
||||
if (ret) *to = static_cast<T>(tmp);
|
||||
return ret;
|
||||
}
|
||||
@@ -835,14 +835,14 @@ bool sevalue_to_native(const se::Value &from, std::array<uint8_t, CNT> *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];
|
||||
@@ -1049,15 +1049,15 @@ inline bool sevalue_to_native(const se::Value &from, std::vector<unsigned char>
|
||||
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);
|
||||
@@ -1084,13 +1084,13 @@ inline bool sevalue_to_native(const se::Value &from, std::function<R(Args...)> *
|
||||
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();
|
||||
}
|
||||
@@ -1134,7 +1134,6 @@ inline bool sevalue_to_native(const se::Value &from, HolderType<T, is_reference>
|
||||
#else
|
||||
template <typename T>
|
||||
inline typename std::enable_if<is_jsb_object_v<T>, bool>::type sevalue_to_native(const se::Value &from, HolderType<T, true> *holder, se::Object *ctx) {
|
||||
|
||||
void *ptr = from.toObject()->getPrivateData();
|
||||
if (ptr) {
|
||||
holder->data = static_cast<T *>(ptr);
|
||||
@@ -1259,7 +1258,7 @@ nativevalue_to_se(const T &from, se::Value &to, se::Object *ctx) {
|
||||
template <typename T, typename allocator>
|
||||
inline bool nativevalue_to_se(const std::vector<T, allocator> &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);
|
||||
@@ -1288,7 +1287,7 @@ inline bool nativevalue_to_se(const std::vector<uint8_t> &from, se::Value &to, s
|
||||
template <typename T, size_t N>
|
||||
inline bool nativevalue_to_se(const std::array<T, N> &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);
|
||||
@@ -1483,7 +1482,7 @@ inline bool nativevalue_to_se(const cc::network::DownloadTask &v, se::Value &ret
|
||||
template <typename T>
|
||||
bool nativevalue_to_se(const spine::Vector<T> &v, se::Value &ret, se::Object *) {
|
||||
se::HandleObject obj(se::Object::createArrayObject(v.size()));
|
||||
bool ok = true;
|
||||
bool ok = true;
|
||||
|
||||
spine::Vector<T> tmpv = v;
|
||||
for (uint32_t i = 0, count = (uint32_t)tmpv.size(); i < count; i++) {
|
||||
@@ -1505,7 +1504,7 @@ bool nativevalue_to_se(const spine::Vector<T> &v, se::Value &ret, se::Object *)
|
||||
template <typename T>
|
||||
bool nativevalue_to_se(const spine::Vector<T *> &v, se::Value &ret, se::Object *) {
|
||||
se::HandleObject obj(se::Object::createArrayObject(v.size()));
|
||||
bool ok = true;
|
||||
bool ok = true;
|
||||
|
||||
spine::Vector<T *> tmpv = v;
|
||||
for (uint32_t i = 0, count = (uint32_t)tmpv.size(); i < count; i++) {
|
||||
@@ -1529,9 +1528,9 @@ bool sevalue_to_native(const se::Value &v, spine::Vector<T *> *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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -38,35 +38,33 @@
|
||||
#include "xxtea/xxtea.h"
|
||||
|
||||
#if CC_PLATFORM == CC_PLATFORM_ANDROID
|
||||
#include "platform/android/jni/JniImp.h"
|
||||
#include "platform/java/jni/JniImp.h"
|
||||
#endif
|
||||
|
||||
#include <chrono>
|
||||
#include <regex>
|
||||
#include <sstream>
|
||||
|
||||
using cc::Application;
|
||||
using cc::FileUtils;
|
||||
using cc::LegacyThreadPool;
|
||||
using namespace cc; //NOLINT
|
||||
|
||||
static LegacyThreadPool *threadPool = nullptr;
|
||||
static LegacyThreadPool *gThreadPool = nullptr;
|
||||
|
||||
static std::shared_ptr<cc::network::Downloader> localDownloader = nullptr;
|
||||
static std::map<std::string, std::function<void(const std::string &, unsigned char *, uint)>> localDownloaderHandlers;
|
||||
static uint64_t localDownloaderTaskId = 1000000;
|
||||
static std::shared_ptr<cc::network::Downloader> gLocalDownloader = nullptr;
|
||||
static std::map<std::string, std::function<void(const std::string &, unsigned char *, uint)>> gLocalDownloaderHandlers;
|
||||
static uint64_t gLocalDownloaderTaskId = 1000000;
|
||||
|
||||
static cc::network::Downloader *localDownloaderInstance() {
|
||||
if (!localDownloader) {
|
||||
localDownloader = std::make_shared<cc::network::Downloader>();
|
||||
localDownloader->onDataTaskSuccess = [=](const cc::network::DownloadTask & task,
|
||||
const std::vector<unsigned char> &data) {
|
||||
static cc::network::Downloader *localDownloader() {
|
||||
if (!gLocalDownloader) {
|
||||
gLocalDownloader = std::make_shared<cc::network::Downloader>();
|
||||
gLocalDownloader->onDataTaskSuccess = [=](const cc::network::DownloadTask & task,
|
||||
const std::vector<unsigned char> &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;
|
||||
}
|
||||
@@ -76,28 +74,28 @@ static cc::network::Downloader *localDownloaderInstance() {
|
||||
|
||||
(callback->second)("", imageData, static_cast<uint>(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, const std::function<void(const std::string &, unsigned char *, int)> &callback) {
|
||||
std::stringstream ss;
|
||||
ss << "jsb_loadimage_" << (localDownloaderTaskId++);
|
||||
ss << "jsb_loadimage_" << (gLocalDownloaderTaskId++);
|
||||
std::string key = ss.str();
|
||||
auto task = localDownloaderInstance()->createDownloadDataTask(url, key);
|
||||
localDownloaderHandlers.emplace(std::make_pair(task->identifier, callback));
|
||||
auto task = localDownloader()->createDownloadDataTask(url, key);
|
||||
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,9 +116,11 @@ bool jsb_set_extend_property(const char *ns, const char *clsName) {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::unordered_map<std::string, se::Value> moduleCache;
|
||||
namespace {
|
||||
|
||||
bool require(se::State &s) {
|
||||
std::unordered_map<std::string, se::Value> gModuleCache;
|
||||
|
||||
static bool require(se::State &s) { //NOLINT
|
||||
const auto &args = s.args();
|
||||
int argc = static_cast<int>(args.size());
|
||||
assert(argc >= 1);
|
||||
@@ -130,7 +130,7 @@ bool require(se::State &s) {
|
||||
}
|
||||
SE_BIND_FUNC(require)
|
||||
|
||||
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());
|
||||
|
||||
@@ -171,10 +171,10 @@ bool doModuleRequire(const std::string &path, se::Value *ret, const std::string
|
||||
}
|
||||
|
||||
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(), static_cast<int>(ret->getType()));
|
||||
// printf("Found cache: %s, value: %d\n", fullPath.c_str(), (int)ret->getType());
|
||||
return true;
|
||||
}
|
||||
std::string currentScriptFileDir = FileUtils::getInstance()->getFileDir(fullPath);
|
||||
@@ -191,30 +191,24 @@ bool doModuleRequire(const std::string &path, se::Value *ret, const std::string
|
||||
// fwrite(scriptBuffer.c_str(), scriptBuffer.length(), 1, fp);
|
||||
// fclose(fp);
|
||||
|
||||
std::string relativePath;
|
||||
|
||||
#if CC_PLATFORM == CC_PLATFORM_MAC_OSX || CC_PLATFORM == CC_PLATFORM_MAC_IOS
|
||||
|
||||
std::string relativePathKey;
|
||||
|
||||
std::string reletivePath = fullPath;
|
||||
#if CC_PLATFORM == CC_PLATFORM_MAC_OSX
|
||||
relativePathKey = "/Contents/Resources";
|
||||
const std::string reletivePathKey = "/Contents/Resources";
|
||||
#else
|
||||
relativePathKey = ".app";
|
||||
const std::string reletivePathKey = ".app";
|
||||
#endif
|
||||
|
||||
size_t pos = fullPath.find(relativePathKey);
|
||||
size_t pos = reletivePath.find(reletivePathKey);
|
||||
if (pos != std::string::npos) {
|
||||
relativePath = fullPath.substr(pos + relativePathKey.length() + 1);
|
||||
reletivePath = reletivePath.substr(pos + reletivePathKey.length() + 1);
|
||||
}
|
||||
#else
|
||||
relativePath = fullPath;
|
||||
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(), static_cast<ssize_t>(scriptBuffer.length()), nullptr, relativePath.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;
|
||||
@@ -222,15 +216,14 @@ bool doModuleRequire(const std::string &path, se::Value *ret, const std::string
|
||||
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;
|
||||
@@ -241,7 +234,7 @@ bool doModuleRequire(const std::string &path, se::Value *ret, const std::string
|
||||
return false;
|
||||
}
|
||||
|
||||
bool moduleRequire(se::State &s) {
|
||||
static bool moduleRequire(se::State &s) { //NOLINT
|
||||
const auto &args = s.args();
|
||||
int argc = static_cast<int>(args.size());
|
||||
assert(argc >= 2);
|
||||
@@ -251,24 +244,25 @@ bool moduleRequire(se::State &s) {
|
||||
return doModuleRequire(args[0].toString(), &s.rval(), args[1].toString());
|
||||
}
|
||||
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 jscGarbageCollect(se::State &s) {
|
||||
static bool jsc_garbageCollect(se::State &s) { //NOLINT
|
||||
se::ScriptEngine::getInstance()->garbageCollect();
|
||||
return true;
|
||||
}
|
||||
SE_BIND_FUNC(jscGarbageCollect)
|
||||
SE_BIND_FUNC(jsc_garbageCollect)
|
||||
|
||||
static bool jscDumpNativePtrToSeObjectMap(se::State &s) {
|
||||
CC_LOG_DEBUG(">>> total: %d, Dump (native -> jsobj) map begin", static_cast<int>(se::NativePtrToObjectMap::size()));
|
||||
static bool jsc_dumpNativePtrToSeObjectMap(se::State &s) { //NOLINT
|
||||
CC_LOG_DEBUG(">>> total: %d, Dump (native -> jsobj) map begin", (int)se::NativePtrToObjectMap::size());
|
||||
|
||||
struct NamePtrStruct {
|
||||
const char *name;
|
||||
@@ -303,25 +297,25 @@ static bool jscDumpNativePtrToSeObjectMap(se::State &s) {
|
||||
for (const auto &e : namePtrArray) {
|
||||
CC_LOG_DEBUG("%s: %p", e.name, e.ptr);
|
||||
}
|
||||
CC_LOG_DEBUG(">>> total: %d, nonRefMap: %d, Dump (native -> jsobj) map end", static_cast<int>(se::NativePtrToObjectMap::size()), static_cast<int>(se::NonRefNativePtrCreatedByCtorMap::size()));
|
||||
CC_LOG_DEBUG(">>> total: %d, nonRefMap: %d, Dump (native -> jsobj) map end", (int)se::NativePtrToObjectMap::size(), (int)se::NonRefNativePtrCreatedByCtorMap::size());
|
||||
return true;
|
||||
}
|
||||
SE_BIND_FUNC(jscDumpNativePtrToSeObjectMap)
|
||||
SE_BIND_FUNC(jsc_dumpNativePtrToSeObjectMap)
|
||||
|
||||
static bool jscDumpRoot(se::State &s) {
|
||||
static bool jsc_dumpRoot(se::State &s) { //NOLINT
|
||||
assert(false);
|
||||
return true;
|
||||
}
|
||||
SE_BIND_FUNC(jscDumpRoot)
|
||||
SE_BIND_FUNC(jsc_dumpRoot)
|
||||
|
||||
static bool jsbCorePlatform(se::State &s) {
|
||||
static bool JSBCore_platform(se::State &s) { //NOLINT
|
||||
Application::Platform platform = Application::getInstance()->getPlatform();
|
||||
s.rval().setInt32(static_cast<int32_t>(platform));
|
||||
return true;
|
||||
}
|
||||
SE_BIND_FUNC(jsbCorePlatform)
|
||||
SE_BIND_FUNC(JSBCore_platform)
|
||||
|
||||
static bool jsbCoreOs(se::State &s) {
|
||||
static bool JSBCore_os(se::State &s) { //NOLINT
|
||||
se::Value os;
|
||||
|
||||
// osx, ios, android, windows, linux, etc..
|
||||
@@ -335,14 +329,16 @@ static bool jsbCoreOs(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;
|
||||
return true;
|
||||
}
|
||||
SE_BIND_FUNC(jsbCoreOs)
|
||||
SE_BIND_FUNC(JSBCore_os)
|
||||
|
||||
static bool jsbCoreGetCurrentLanguage(se::State &s) {
|
||||
static bool JSBCore_getCurrentLanguage(se::State &s) { //NOLINT
|
||||
std::string languageStr;
|
||||
Application::LanguageType language = Application::getInstance()->getCurrentLanguage();
|
||||
switch (language) {
|
||||
@@ -410,36 +406,30 @@ static bool jsbCoreGetCurrentLanguage(se::State &s) {
|
||||
s.rval().setString(languageStr);
|
||||
return true;
|
||||
}
|
||||
SE_BIND_FUNC(jsbCoreGetCurrentLanguage)
|
||||
SE_BIND_FUNC(JSBCore_getCurrentLanguage)
|
||||
|
||||
static bool jsbCoreGetCurrentLanguageCode(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(jsbCoreGetCurrentLanguageCode)
|
||||
SE_BIND_FUNC(JSBCore_getCurrentLanguageCode)
|
||||
|
||||
static bool jsbGetOsVersion(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(jsbGetOsVersion)
|
||||
SE_BIND_FUNC(JSB_getOSVersion)
|
||||
|
||||
static bool jsbCoreRestartVm(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(jsbCoreRestartVm)
|
||||
SE_BIND_FUNC(JSB_core_restartVM)
|
||||
|
||||
static bool jsbCloseWindow(se::State &s) {
|
||||
Application::getInstance()->close();
|
||||
return true;
|
||||
}
|
||||
SE_BIND_FUNC(jsbCloseWindow)
|
||||
|
||||
static bool jsbIsObjectValid(se::State &s) {
|
||||
static bool JSB_isObjectValid(se::State &s) { //NOLINT
|
||||
const auto &args = s.args();
|
||||
int argc = static_cast<int>(args.size());
|
||||
if (argc == 1) {
|
||||
@@ -452,9 +442,9 @@ static bool jsbIsObjectValid(se::State &s) {
|
||||
SE_REPORT_ERROR("Invalid number of arguments: %d. Expecting: 1", argc);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(jsbIsObjectValid)
|
||||
SE_BIND_FUNC(JSB_isObjectValid)
|
||||
|
||||
static bool jsbSetCursorEnabled(se::State &s) {
|
||||
static bool JSB_setCursorEnabled(se::State &s) { //NOLINT
|
||||
const auto &args = s.args();
|
||||
int argc = static_cast<int>(args.size());
|
||||
SE_PRECONDITION2(argc == 1, false, "Invalid number of arguments");
|
||||
@@ -466,9 +456,9 @@ static bool jsbSetCursorEnabled(se::State &s) {
|
||||
Application::getInstance()->setCursorEnabled(value);
|
||||
return true;
|
||||
}
|
||||
SE_BIND_FUNC(jsbSetCursorEnabled)
|
||||
SE_BIND_FUNC(JSB_setCursorEnabled)
|
||||
|
||||
static bool jsbSaveByteCode(se::State &s) {
|
||||
static bool JSB_saveByteCode(se::State &s) { //NOLINT
|
||||
const auto &args = s.args();
|
||||
int argc = static_cast<int>(args.size());
|
||||
SE_PRECONDITION2(argc == 2, false, "Invalid number of arguments");
|
||||
@@ -482,9 +472,9 @@ static bool jsbSaveByteCode(se::State &s) {
|
||||
s.rval().setBoolean(ok);
|
||||
return true;
|
||||
}
|
||||
SE_BIND_FUNC(jsbSaveByteCode)
|
||||
SE_BIND_FUNC(JSB_saveByteCode)
|
||||
|
||||
static bool getOrCreatePlainObjectR(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;
|
||||
@@ -500,14 +490,15 @@ static bool getOrCreatePlainObjectR(const char *name, se::Object *parent, se::Ob
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool jsPerformanceNow(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<std::chrono::microseconds>(now - se::ScriptEngine::getInstance()->getStartTime()).count();
|
||||
s.rval().setNumber(static_cast<double>(micro) * 0.001);
|
||||
return true;
|
||||
}
|
||||
SE_BIND_FUNC(jsPerformanceNow)
|
||||
SE_BIND_FUNC(js_performance_now)
|
||||
|
||||
namespace {
|
||||
struct ImageInfo {
|
||||
uint32_t length = 0;
|
||||
uint32_t width = 0;
|
||||
@@ -551,7 +542,7 @@ uint8_t *convertI2RGBA(uint32_t length, uint8_t *src) {
|
||||
return dst;
|
||||
}
|
||||
|
||||
struct ImageInfo *createImageInfo(cc::Image *img) {
|
||||
struct ImageInfo *createImageInfo(Image *img) {
|
||||
auto *imgInfo = new struct ImageInfo();
|
||||
imgInfo->length = static_cast<uint32_t>(img->getDataLen());
|
||||
imgInfo->width = img->getWidth();
|
||||
@@ -595,8 +586,9 @@ struct ImageInfo *createImageInfo(cc::Image *img) {
|
||||
|
||||
return imgInfo;
|
||||
}
|
||||
} // 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);
|
||||
@@ -606,9 +598,9 @@ bool jsb_global_load_image(const std::string &path, const se::Value &callbackVal
|
||||
std::shared_ptr<se::Value> callbackPtr = std::make_shared<se::Value>(callbackVal);
|
||||
|
||||
auto initImageFunc = [path, callbackPtr](const std::string &fullPath, unsigned char *imageData, int imageBytes) {
|
||||
auto *img = new (std::nothrow) cc::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
|
||||
@@ -634,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); //NOLINT
|
||||
ulong_to_seval(reinterpret_cast<ptrdiff_t>(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));
|
||||
@@ -660,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 = cc::base64Decode(reinterpret_cast<const unsigned char *>(base64Data), static_cast<unsigned int>(dataLen), &imageData);
|
||||
imageBytes = base64Decode(reinterpret_cast<const unsigned char *>(base64Data), static_cast<unsigned int>(dataLen), &imageData);
|
||||
if (imageBytes <= 0 || imageData == nullptr) {
|
||||
SE_REPORT_ERROR("Decode base64 image data failed!");
|
||||
return false;
|
||||
@@ -681,7 +673,7 @@ bool jsb_global_load_image(const std::string &path, const se::Value &callbackVal
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool jsLoadImage(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;
|
||||
@@ -696,29 +688,28 @@ static bool jsLoadImage(se::State &s) {
|
||||
|
||||
return jsb_global_load_image(path, callbackVal);
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", static_cast<int>(argc), 2);
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(jsLoadImage)
|
||||
SE_BIND_FUNC(js_loadImage)
|
||||
|
||||
static bool jsDestroyImage(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) {
|
||||
char *data = nullptr;
|
||||
ok &= seval_to_ulong(args[0], reinterpret_cast<unsigned long *>(&data)); //NOLINT google-runtime-int
|
||||
unsigned long data = 0; //NOLINT
|
||||
ok &= seval_to_ulong(args[0], &data);
|
||||
SE_PRECONDITION2(ok, false, "js_destroyImage : Error processing arguments");
|
||||
free(data);
|
||||
|
||||
free(reinterpret_cast<char *>(data));
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", static_cast<int>(argc), 1);
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(jsDestroyImage)
|
||||
SE_BIND_FUNC(js_destroyImage)
|
||||
|
||||
static bool jsbOpenUrl(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;
|
||||
@@ -730,12 +721,12 @@ static bool jsbOpenUrl(se::State &s) {
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", static_cast<int>(argc), 1);
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(jsbOpenUrl)
|
||||
SE_BIND_FUNC(JSB_openURL)
|
||||
|
||||
static bool jsbCopyTextToClipboard(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;
|
||||
@@ -747,12 +738,12 @@ static bool jsbCopyTextToClipboard(se::State &s) {
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", static_cast<int>(argc), 1);
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(jsbCopyTextToClipboard)
|
||||
SE_BIND_FUNC(JSB_copyTextToClipboard)
|
||||
|
||||
static bool jsbSetPreferredFramesPerSecond(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;
|
||||
@@ -765,13 +756,13 @@ static bool jsbSetPreferredFramesPerSecond(se::State &s) {
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", static_cast<int>(argc), 1);
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(jsbSetPreferredFramesPerSecond)
|
||||
SE_BIND_FUNC(JSB_setPreferredFramesPerSecond)
|
||||
|
||||
#if CC_USE_EDITBOX
|
||||
static bool jsbShowInputBox(se::State &s) {
|
||||
static bool JSB_showInputBox(se::State &s) { //NOLINT
|
||||
const auto &args = s.args();
|
||||
size_t argc = args.size();
|
||||
if (argc == 1) {
|
||||
@@ -842,75 +833,74 @@ static bool jsbShowInputBox(se::State &s) {
|
||||
}
|
||||
}
|
||||
|
||||
cc::EditBox::show(showInfo);
|
||||
EditBox::show(showInfo);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", static_cast<int>(argc), 1);
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(jsbShowInputBox);
|
||||
SE_BIND_FUNC(JSB_showInputBox);
|
||||
|
||||
static bool jsbHideInputBox(se::State &s) {
|
||||
cc::EditBox::hide();
|
||||
static bool JSB_hideInputBox(se::State &s) { //NOLINT
|
||||
EditBox::hide();
|
||||
return true;
|
||||
}
|
||||
SE_BIND_FUNC(jsbHideInputBox)
|
||||
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));
|
||||
|
||||
getOrCreatePlainObjectR("jsb", global, &__jsbObj);
|
||||
getOrCreatePlainObject_r("jsb", global, &__jsbObj);
|
||||
|
||||
auto *glContextCls = se::Class::create("WebGLRenderingContext", global, nullptr, nullptr);
|
||||
auto glContextCls = se::Class::create("WebGLRenderingContext", global, nullptr, nullptr);
|
||||
glContextCls->install();
|
||||
|
||||
__jsbObj->defineFunction("garbageCollect", _SE(jscGarbageCollect));
|
||||
__jsbObj->defineFunction("dumpNativePtrToSeObjectMap", _SE(jscDumpNativePtrToSeObjectMap));
|
||||
__jsbObj->defineFunction("garbageCollect", _SE(jsc_garbageCollect));
|
||||
__jsbObj->defineFunction("dumpNativePtrToSeObjectMap", _SE(jsc_dumpNativePtrToSeObjectMap));
|
||||
|
||||
__jsbObj->defineFunction("loadImage", _SE(jsLoadImage));
|
||||
__jsbObj->defineFunction("openURL", _SE(jsbOpenUrl));
|
||||
__jsbObj->defineFunction("copyTextToClipboard", _SE(jsbCopyTextToClipboard));
|
||||
__jsbObj->defineFunction("setPreferredFramesPerSecond", _SE(jsbSetPreferredFramesPerSecond));
|
||||
__jsbObj->defineFunction("destroyImage", _SE(jsDestroyImage));
|
||||
__jsbObj->defineFunction("loadImage", _SE(js_loadImage));
|
||||
__jsbObj->defineFunction("openURL", _SE(JSB_openURL));
|
||||
__jsbObj->defineFunction("copyTextToClipboard", _SE(JSB_copyTextToClipboard));
|
||||
__jsbObj->defineFunction("setPreferredFramesPerSecond", _SE(JSB_setPreferredFramesPerSecond));
|
||||
__jsbObj->defineFunction("destroyImage", _SE(js_destroyImage));
|
||||
#if CC_USE_EDITBOX
|
||||
__jsbObj->defineFunction("showInputBox", _SE(jsbShowInputBox));
|
||||
__jsbObj->defineFunction("hideInputBox", _SE(jsbHideInputBox));
|
||||
__jsbObj->defineFunction("showInputBox", _SE(JSB_showInputBox));
|
||||
__jsbObj->defineFunction("hideInputBox", _SE(JSB_hideInputBox));
|
||||
#endif
|
||||
__jsbObj->defineFunction("setCursorEnabled", _SE(jsbSetCursorEnabled));
|
||||
__jsbObj->defineFunction("saveByteCode", _SE(jsbSaveByteCode));
|
||||
global->defineFunction("__getPlatform", _SE(jsbCorePlatform));
|
||||
global->defineFunction("__getOS", _SE(jsbCoreOs));
|
||||
global->defineFunction("__getOSVersion", _SE(jsbGetOsVersion));
|
||||
global->defineFunction("__getCurrentLanguage", _SE(jsbCoreGetCurrentLanguage));
|
||||
global->defineFunction("__getCurrentLanguageCode", _SE(jsbCoreGetCurrentLanguageCode));
|
||||
global->defineFunction("__restartVM", _SE(jsbCoreRestartVm));
|
||||
global->defineFunction("__isObjectValid", _SE(jsbIsObjectValid));
|
||||
global->defineFunction("__close", _SE(jsbCloseWindow));
|
||||
__jsbObj->defineFunction("setCursorEnabled", _SE(JSB_setCursorEnabled));
|
||||
__jsbObj->defineFunction("saveByteCode", _SE(JSB_saveByteCode));
|
||||
global->defineFunction("__getPlatform", _SE(JSBCore_platform));
|
||||
global->defineFunction("__getOS", _SE(JSBCore_os));
|
||||
global->defineFunction("__getOSVersion", _SE(JSB_getOSVersion));
|
||||
global->defineFunction("__getCurrentLanguage", _SE(JSBCore_getCurrentLanguage));
|
||||
global->defineFunction("__getCurrentLanguageCode", _SE(JSBCore_getCurrentLanguageCode));
|
||||
global->defineFunction("__restartVM", _SE(JSB_core_restartVM));
|
||||
global->defineFunction("__isObjectValid", _SE(JSB_isObjectValid));
|
||||
|
||||
se::HandleObject performanceObj(se::Object::createPlainObject());
|
||||
performanceObj->defineFunction("now", _SE(jsPerformanceNow));
|
||||
performanceObj->defineFunction("now", _SE(js_performance_now));
|
||||
global->setProperty("performance", se::Value(performanceObj));
|
||||
|
||||
se::ScriptEngine::getInstance()->clearException();
|
||||
|
||||
se::ScriptEngine::getInstance()->addBeforeCleanupHook([]() {
|
||||
delete threadPool;
|
||||
threadPool = nullptr;
|
||||
delete gThreadPool;
|
||||
gThreadPool = nullptr;
|
||||
|
||||
cc::PoolManager::getInstance()->getCurrentPool()->clear();
|
||||
PoolManager::getInstance()->getCurrentPool()->clear();
|
||||
});
|
||||
|
||||
se::ScriptEngine::getInstance()->addAfterCleanupHook([]() {
|
||||
cc::PoolManager::getInstance()->getCurrentPool()->clear();
|
||||
PoolManager::getInstance()->getCurrentPool()->clear();
|
||||
|
||||
moduleCache.clear();
|
||||
gModuleCache.clear();
|
||||
|
||||
SAFE_DEC_REF(__jsbObj);
|
||||
SAFE_DEC_REF(__glObj);
|
||||
|
||||
@@ -29,28 +29,28 @@
|
||||
|
||||
template <typename T, class... Args>
|
||||
inline typename std::enable_if<std::is_base_of<cc::Object, T>::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>(args)...));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
inline typename std::enable_if<std::is_base_of<cc::Object, T>::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 <typename T, class... Args>
|
||||
inline typename std::enable_if<!std::is_base_of<cc::Object, T>::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>(args)...);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
inline typename std::enable_if<!std::is_base_of<cc::Object, T>::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)
|
||||
|
||||
@@ -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 <chrono>
|
||||
#include <regex>
|
||||
#include <sstream>
|
||||
|
||||
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<void(const uint8_t *, size_t)> &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<uint32_t>(fileData.getSize()),
|
||||
reinterpret_cast<unsigned char *>(xxteaKey.data()),
|
||||
static_cast<uint32_t>(xxteaKey.size()), reinterpret_cast<uint32_t *>(&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<uint8_t *>(fileData.getBytes()), static_cast<uint32_t>(fileData.getSize()),
|
||||
reinterpret_cast<unsigned char *>(xxteaKey.data()),
|
||||
static_cast<uint32_t>(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<const char *>(data), dataLen);
|
||||
free(data);
|
||||
return ret;
|
||||
}
|
||||
std::string ret(reinterpret_cast<const char *>(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();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -25,19 +25,19 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "base/CoreStd.h"
|
||||
#include "base/memory/Memory.h"
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#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
|
||||
@@ -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);
|
||||
|
||||
@@ -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 <regex>
|
||||
|
||||
|
||||
@@ -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 <regex>
|
||||
|
||||
#ifndef JCLS_CANVASIMPL
|
||||
#define JCLS_CANVASIMPL "com/cocos/lib/CanvasRenderingContext2DImpl"
|
||||
#endif
|
||||
|
||||
using namespace cc; //NOLINT
|
||||
|
||||
static std::unordered_map<std::string, std::string> gFontFamilyNameMap;
|
||||
|
||||
const std::unordered_map<std::string, std::string> &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<std::string::const_iterator> 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;
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+62
-63
@@ -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 <mutex>
|
||||
#include <platform/Application.h>
|
||||
#include <mutex>
|
||||
|
||||
#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<int, cc::network::DownloaderAndroid *> sDownloaderMap;
|
||||
std::mutex sDownloaderMutex;
|
||||
std::unordered_map<int, cc::network::DownloaderJava *> 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<std::mutex> guard(sDownloaderMutex);
|
||||
sDownloaderMap.insert(std::make_pair(id, downloaderPtr));
|
||||
}
|
||||
|
||||
static void _eraseDownloaderAndroid(int id) {
|
||||
static void eraseDownloaderJava(int id) {
|
||||
std::lock_guard<std::mutex> 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<std::mutex> 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<const DownloadTask> 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<const DownloadTask> &task) {
|
||||
DownloadTaskAndroid *coTask = new DownloadTaskAndroid;
|
||||
IDownloadTask *DownloaderJava::createCoTask(std::shared_ptr<const DownloadTask> &task) {
|
||||
auto *coTask = new DownloadTaskAndroid;
|
||||
coTask->task = task;
|
||||
|
||||
JniMethodInfo methodInfo;
|
||||
@@ -147,33 +146,33 @@ IDownloadTask *DownloaderAndroid::createCoTask(std::shared_ptr<const DownloadTas
|
||||
JCLS_DOWNLOADER,
|
||||
"createTask",
|
||||
"(" JARG_DOWNLOADER "I" JARG_STR JARG_STR "[" JARG_STR ")V")) {
|
||||
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, NULL);
|
||||
const std::map<std::string, std::string> &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<std::string, std::string> &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<IDownloadTask> &task) {
|
||||
void DownloaderJava::abort(const std::unique_ptr<IDownloadTask> &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<IDownloadTask> &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<IDownloadTask> &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<int64_t(void *, int64_t)> transferDataToBuffer;
|
||||
onTaskProgress(*coTask->task, dl, dlNow, dlTotal, transferDataToBuffer);
|
||||
}
|
||||
|
||||
void DownloaderAndroid::_onFinish(int taskId, int errCode, const char *errStr, const std::vector<unsigned char> &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<unsigned char> &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<uint8_t> 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<unsigned char> 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);
|
||||
}
|
||||
@@ -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<const DownloadTask> &task) override;
|
||||
IDownloadTask *createCoTask(std::shared_ptr<const DownloadTask> &task) override;
|
||||
|
||||
virtual void abort(const std::unique_ptr<IDownloadTask> &task) override;
|
||||
void abort(const std::unique_ptr<IDownloadTask> &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<unsigned char> &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<unsigned char> &data);
|
||||
|
||||
protected:
|
||||
int _id;
|
||||
_jobject *_impl;
|
||||
int _id;
|
||||
_jobject * _impl;
|
||||
std::unordered_map<int, DownloadTaskAndroid *> _taskMap;
|
||||
};
|
||||
} // namespace network
|
||||
@@ -25,23 +25,25 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#include <memory>
|
||||
|
||||
#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<DownloaderImpl>(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<int64_t(void *buffer, int64_t len)> & /*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<unsigned char> &data) {
|
||||
if (DownloadTask::ERROR_NO_ERROR != errorCode) {
|
||||
if (onTaskError) {
|
||||
@@ -111,11 +113,11 @@ Downloader::~Downloader() {
|
||||
}
|
||||
|
||||
std::shared_ptr<const DownloadTask> Downloader::createDownloadDataTask(const std::string &srcUrl, const std::string &identifier /* = ""*/) {
|
||||
DownloadTask *task_ = new (std::nothrow) DownloadTask();
|
||||
std::shared_ptr<const DownloadTask> task(task_);
|
||||
auto * iTask = new (std::nothrow) DownloadTask();
|
||||
std::shared_ptr<const DownloadTask> 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<const DownloadTask> 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<const DownloadTask> Downloader::createDownloadFileTask(const std::string &srcUrl,
|
||||
const std::string &storagePath,
|
||||
std::shared_ptr<const DownloadTask> Downloader::createDownloadFileTask(const std::string & srcUrl,
|
||||
const std::string & storagePath,
|
||||
const std::map<std::string, std::string> &header,
|
||||
const std::string &identifier /* = ""*/) {
|
||||
DownloadTask *task_ = new (std::nothrow) DownloadTask();
|
||||
std::shared_ptr<const DownloadTask> task(task_);
|
||||
const std::string & identifier /* = ""*/) {
|
||||
auto * iTask = new (std::nothrow) DownloadTask();
|
||||
std::shared_ptr<const DownloadTask> 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<const DownloadTask> 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;
|
||||
}
|
||||
|
||||
+128
-127
@@ -26,42 +26,40 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#if (CC_PLATFORM == CC_PLATFORM_ANDROID)
|
||||
#include "network/HttpClient.h"
|
||||
|
||||
#include "network/HttpClient.h"
|
||||
#include <cerrno>
|
||||
#include <cstdio>
|
||||
#include <queue>
|
||||
#include <sstream>
|
||||
|
||||
#include <queue>
|
||||
#include <sstream>
|
||||
#include <stdio.h>
|
||||
#include <errno.h>
|
||||
#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<std::string> HttpRequestHeaders;
|
||||
typedef HttpRequestHeaders::iterator HttpRequestHeadersIter;
|
||||
typedef std::vector<std::string> HttpCookies;
|
||||
typedef HttpCookies::iterator HttpCookiesIter;
|
||||
using HttpRequestHeaders = std::vector<std::string>;
|
||||
using HttpRequestHeadersIter = HttpRequestHeaders::iterator;
|
||||
using HttpCookies = std::vector<std::string>;
|
||||
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<char> *recvBuffer = (std::vector<char> *)response->getResponseData();
|
||||
auto *recvBuffer = static_cast<std::vector<char> *>(response->getResponseData());
|
||||
recvBuffer->clear();
|
||||
recvBuffer->insert(recvBuffer->end(), (char *)buffer, ((char *)buffer) + sizes);
|
||||
recvBuffer->insert(recvBuffer->end(), static_cast<char *>(buffer), (static_cast<char *>(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<char> *recvBuffer = (std::vector<char> *)response->getResponseHeader();
|
||||
auto *recvBuffer = static_cast<std::vector<char> *>(response->getResponseHeader());
|
||||
recvBuffer->clear();
|
||||
recvBuffer->insert(recvBuffer->end(), (char *)buffer, (char *)buffer + sizes);
|
||||
recvBuffer->insert(recvBuffer->end(), static_cast<char *>(buffer), static_cast<char *>(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<jstring>(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<const jbyte *>(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<jstring>(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<jbyteArray>(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<jstring>(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<jstring>(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<CookiesInfo> 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<std::string> 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<int>(request->getTimeout() * 1000),
|
||||
static_cast<int>(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<jbyte *>(malloc(sizeof(jbyte) * len));
|
||||
env->GetByteArrayRegion(jba, 0, len, str);
|
||||
|
||||
*ppData = str;
|
||||
*ppData = reinterpret_cast<char *>(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<char> *recvBuffer = (std::vector<char> *)response->getResponseData();
|
||||
auto *recvBuffer = static_cast<std::vector<char> *>(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)
|
||||
@@ -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 <algorithm>
|
||||
#include <atomic>
|
||||
@@ -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);
|
||||
|
||||
@@ -41,8 +41,13 @@
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#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 {
|
||||
|
||||
@@ -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 {
|
||||
@@ -83,7 +84,7 @@ public:
|
||||
};
|
||||
|
||||
// This class is useful for internal usage.
|
||||
static Application *getInstance() { return instance; }
|
||||
static Application *getInstance() { return Application::instance; }
|
||||
|
||||
Application(int width, int height);
|
||||
virtual ~Application();
|
||||
@@ -97,10 +98,9 @@ public:
|
||||
void tick();
|
||||
void restartVM();
|
||||
|
||||
inline std::shared_ptr<Scheduler> getScheduler() const { return Application::scheduler; } //NOLINT(readability-convert-member-functions-to-static)
|
||||
void close();
|
||||
|
||||
inline std::shared_ptr<Scheduler> getScheduler() const { return scheduler; } // NOLINT
|
||||
|
||||
/**
|
||||
* @brief Sets the preferred frame rate for main loop callback.
|
||||
* @param fps The preferred frame rate for main loop callback.
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
+123
-124
@@ -27,14 +27,18 @@
|
||||
|
||||
#include "platform/FileUtils.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <stack>
|
||||
|
||||
#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 <cerrno>
|
||||
#include <cstring>
|
||||
|
||||
#ifdef MINIZIP_FROM_SYSTEM
|
||||
#include <minizip/unzip.h>
|
||||
@@ -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<ValueMap *> _dictStack;
|
||||
std::stack<ValueMap *> _dictStack;
|
||||
std::stack<ValueVector *> _arrayStack;
|
||||
std::stack<SAXState> _stateStack;
|
||||
std::stack<SAXState> _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<char *>(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<char *>(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<char *>(dataStr.data());
|
||||
data.fastSet(reinterpret_cast<unsigned char *>(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<unsigned char *>(malloc(fileInfo.uncompressed_size));
|
||||
int CC_UNUSED readedSize = unzReadCurrentFile(file, buffer, static_cast<unsigned>(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<std::string> &searchPaths) {
|
||||
bool existDefaultRootPath = false;
|
||||
_originalSearchPaths = searchPaths;
|
||||
_originalSearchPaths = searchPaths;
|
||||
|
||||
_fullPathCache.clear();
|
||||
_searchPathArray.clear();
|
||||
@@ -735,10 +743,11 @@ void FileUtils::setSearchPaths(const std::vector<std::string> &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<std::string> FileUtils::listFiles(const std::string &dirPath) const {
|
||||
std::string fullpath = fullPathForFilename(dirPath);
|
||||
std::string fullpath = fullPathForFilename(dirPath);
|
||||
std::vector<std::string> files;
|
||||
if (isDirectoryExist(fullpath)) {
|
||||
tinydir_dir dir;
|
||||
@@ -835,7 +840,7 @@ std::vector<std::string> 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<std
|
||||
|
||||
#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);
|
||||
@@ -957,9 +962,9 @@ long FileUtils::getFileSize(const std::string &filepath) {
|
||||
|
||||
#else
|
||||
// default implements for unix like os
|
||||
#include <sys/types.h>
|
||||
#include <errno.h>
|
||||
#include <dirent.h>
|
||||
#include <sys/types.h>
|
||||
#include <cerrno>
|
||||
|
||||
// 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<std::string> 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<long>(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, "");
|
||||
}
|
||||
|
||||
@@ -25,17 +25,16 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#ifndef __CC_FILEUTILS_H__
|
||||
#define __CC_FILEUTILS_H__
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <unordered_map>
|
||||
#include <type_traits>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#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 <typename T>
|
||||
@@ -56,62 +55,55 @@ class ResizableBufferAdapter {};
|
||||
|
||||
template <typename CharT, typename Traits, typename Allocator>
|
||||
class ResizableBufferAdapter<std::basic_string<CharT, Traits, Allocator>> : public ResizableBuffer {
|
||||
typedef std::basic_string<CharT, Traits, Allocator> BufferType;
|
||||
using BufferType = std::basic_string<CharT, Traits, Allocator>;
|
||||
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 <typename T, typename Allocator>
|
||||
class ResizableBufferAdapter<std::vector<T, Allocator>> : public ResizableBuffer {
|
||||
typedef std::vector<T, Allocator> BufferType;
|
||||
using BufferType = std::vector<T, Allocator>;
|
||||
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<Data> : public ResizableBuffer {
|
||||
typedef Data BufferType;
|
||||
class ResizableBufferAdapter<cc::Data> : 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<size_t>(_buffer->getSize());
|
||||
void resize(size_t size) override {
|
||||
auto oldSize = static_cast<size_t>(_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<unsigned char *>(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<std::string, std::string> &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__
|
||||
|
||||
@@ -26,10 +26,11 @@
|
||||
****************************************************************************/
|
||||
|
||||
#include "Image.h"
|
||||
#include "base/Config.h" // CC_USE_JPEG, CC_USE_WEBP
|
||||
#include <cassert>
|
||||
#include <cctype>
|
||||
#include <string>
|
||||
#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"
|
||||
|
||||
@@ -33,8 +33,8 @@
|
||||
#include "cocos/bindings/jswrapper/SeApi.h"
|
||||
#include "platform/Application.h"
|
||||
#include "platform/android/jni/JniCocosActivity.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 "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
|
||||
|
||||
@@ -25,27 +25,25 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#if CC_PLATFORM == CC_PLATFORM_ANDROID
|
||||
#include <android/log.h>
|
||||
#include <android/sensor.h>
|
||||
#include <android/window.h>
|
||||
#include <android_native_app_glue.h>
|
||||
#include <jni.h>
|
||||
#include <cstring>
|
||||
#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 <cstring>
|
||||
#include <android/log.h>
|
||||
#include <jni.h>
|
||||
#include <android_native_app_glue.h>
|
||||
#include <android/window.h>
|
||||
#include <android/sensor.h>
|
||||
#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<Device::NetworkType>(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
|
||||
|
||||
@@ -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 <sys/stat.h>
|
||||
#include <cstdlib>
|
||||
#include "android/asset_manager.h"
|
||||
#include "android/asset_manager_jni.h"
|
||||
#include "base/ZipUtils.h"
|
||||
#include "base/Log.h"
|
||||
#include <stdlib.h>
|
||||
#include <sys/stat.h>
|
||||
#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
|
||||
|
||||
@@ -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 <string>
|
||||
#include <vector>
|
||||
#include "jni.h"
|
||||
#include "android/asset_manager.h"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#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__
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ public class CocosKeyCodeHandler {
|
||||
CocosHelper.runOnGameThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
handleKeyDown(keyCode);
|
||||
handleKeyUp(keyCode);
|
||||
}
|
||||
});
|
||||
return true;
|
||||
|
||||
@@ -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()
|
||||
{
|
||||
|
||||
@@ -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 <jni.h>
|
||||
#include <android/log.h>
|
||||
#include <android/asset_manager_jni.h>
|
||||
#include <android/log.h>
|
||||
#include <android/native_window_jni.h>
|
||||
#include <android_native_app_glue.h>
|
||||
#include <thread>
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
#include <jni.h>
|
||||
#include <unistd.h>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#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::FileUtilsAndroid *>(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);
|
||||
}
|
||||
|
||||
@@ -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 <jni.h>
|
||||
#include <android/log.h>
|
||||
#include <android/keycodes.h>
|
||||
#include <android/log.h>
|
||||
#include <jni.h>
|
||||
#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);
|
||||
|
||||
@@ -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 <android/log.h>
|
||||
#include <string.h>
|
||||
#include <pthread.h>
|
||||
#include <android_native_app_glue.h>
|
||||
|
||||
#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<void()> 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
|
||||
+117
-83
@@ -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 <hilog/log.h>
|
||||
#endif
|
||||
|
||||
#include <regex>
|
||||
|
||||
@@ -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<int>(align));
|
||||
}
|
||||
|
||||
void setTextBaseline(CanvasTextBaseline baseline) {
|
||||
JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setTextBaseline", (int)baseline);
|
||||
JniHelper::callObjectVoidMethod(_obj, JCLS_CANVASIMPL, "setTextBaseline", static_cast<int>(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<const jbyte *>(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<float>(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<jbyte *>(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<unsigned char *>(jbarray), len);
|
||||
_data.fastSet(reinterpret_cast<unsigned char *>(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<std::string::const_iterator> 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<std::string::const_iterator> 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<float>(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<float>(color.r) / 255.0F, static_cast<float>(color.g) / 255.0F, static_cast<float>(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<float>(color.r) / 255.0F, static_cast<float>(color.g) / 255.0F, static_cast<float>(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:
|
||||
+17
-9
@@ -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 <android/keycodes.h>
|
||||
#include <android/log.h>
|
||||
#elif CC_PLATFORM == CC_PLATFORM_OHOS
|
||||
#include <hilog/log.h>
|
||||
#endif
|
||||
#include <jni.h>
|
||||
#include <android/log.h>
|
||||
#include <android/keycodes.h>
|
||||
|
||||
#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<int, int> keyCodeMap = {
|
||||
{AKEYCODE_BACK, 6},
|
||||
{AKEYCODE_ENTER, 13},
|
||||
@@ -43,22 +46,27 @@ std::unordered_map<int, int> keyCodeMap = {
|
||||
{AKEYCODE_DPAD_LEFT, 1000},
|
||||
{AKEYCODE_DPAD_RIGHT, 1001},
|
||||
{AKEYCODE_DPAD_CENTER, 1005}};
|
||||
|
||||
#elif CC_PLATFORM == CC_PLATFORM_OHOS
|
||||
std::unordered_map<int, int> 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);
|
||||
+3
-7
@@ -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 <jni.h>
|
||||
#include <android/log.h>
|
||||
#include <android/keycodes.h>
|
||||
#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);
|
||||
+12
-16
@@ -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 <jni.h>
|
||||
#include <android/log.h>
|
||||
|
||||
#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];
|
||||
|
||||
@@ -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 <android/log.h>
|
||||
#else
|
||||
#include "cocos/base/Log.h"
|
||||
#endif
|
||||
#include <pthread.h>
|
||||
#include <cstring>
|
||||
|
||||
#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<jclass>(cc::JniHelper::getEnv()->NewGlobalRef(static_cast<jobject>(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<const char *, JClassWrapper> _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<jclass>(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<void()> 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<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 CC_PLATFORM == CC_PLATFORM_ANDROID
|
||||
if (jvm->AttachCurrentThread(&env, nullptr) < 0) {
|
||||
#else
|
||||
if (jvm->AttachCurrentThread(reinterpret_cast<void **>(&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<JNIEnv *>(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
|
||||
+144
-113
@@ -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 <jni.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <unordered_map>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
#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<JNIEnv *, std::vector<jobject>> LocalRefMapType;
|
||||
using LocalRefMapType = std::unordered_map<JNIEnv *, std::vector<jobject>>;
|
||||
|
||||
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<void()> classloaderCallback;
|
||||
|
||||
template <typename... Ts>
|
||||
static jobject newObject(const std::string &className, Ts... xs) {
|
||||
jobject ret = nullptr;
|
||||
jobject ret = nullptr;
|
||||
static const char *methodName = "<init>";
|
||||
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 <typename... Ts>
|
||||
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 <typename... Ts>
|
||||
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 <typename... Ts>
|
||||
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<jbyteArray>(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<jfloatArray>(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<jfloatArray>(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<jstring>(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 <typename T>
|
||||
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__
|
||||
+18
-14
@@ -24,7 +24,11 @@
|
||||
****************************************************************************/
|
||||
|
||||
#include "JniImp.h"
|
||||
#include <android/log.h>
|
||||
#if ANDROID
|
||||
#include <android/log.h>
|
||||
#else
|
||||
#include <hilog/log.h>
|
||||
#endif
|
||||
#include <jni.h>
|
||||
#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<jlongArray>(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<int>(array[0]);
|
||||
*startOffset = array[1];
|
||||
*size = array[2];
|
||||
jboolean copy = JNI_FALSE;
|
||||
jlong * array = methodInfo.env->GetLongArrayElements(newArray, ©);
|
||||
fd = static_cast<int>(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;
|
||||
+3
-3
@@ -28,9 +28,9 @@
|
||||
#include <string>
|
||||
|
||||
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);
|
||||
extern bool openURLJNI(const std::string &url);
|
||||
extern void copyTextToClipboardJNI(const std::string &text);
|
||||
@@ -0,0 +1,2 @@
|
||||
|
||||
build/
|
||||
@@ -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 <cstring>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
#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 <hilog/log.h>
|
||||
|
||||
#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<int>(viewLogicalSize.x) << ";"
|
||||
<< "window.innerHeight = " << static_cast<int>(viewLogicalSize.y) << ";"
|
||||
<< "window.windowHandler = " << cc::cocosApp.pendingWindow << ";";
|
||||
se->evalString(ss.str().c_str());
|
||||
|
||||
cc::gfx::DeviceInfo deviceInfo;
|
||||
deviceInfo.windowHandle = reinterpret_cast<uintptr_t>(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<Scheduler> Application::_scheduler = nullptr; //NOLINT
|
||||
|
||||
Application::Application(int width, int height) {
|
||||
Application::_instance = this;
|
||||
_scheduler = std::make_shared<Scheduler>();
|
||||
_viewLogicalSize.x = static_cast<float>(width);
|
||||
_viewLogicalSize.y = static_cast<float>(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<long>(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
|
||||
@@ -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 <hilog/log.h>
|
||||
#include <jni.h>
|
||||
#include <native_layer.h>
|
||||
#include <native_layer_jni.h>
|
||||
#include <cstring>
|
||||
#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<Device::NetworkType>(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
|
||||
@@ -0,0 +1,248 @@
|
||||
#include "cocos/platform/ohos/FileUtils-ohos.h"
|
||||
#include <hilog/log.h>
|
||||
#include <sys/stat.h>
|
||||
#include <cstdio>
|
||||
#include <regex>
|
||||
#include <string>
|
||||
#include "cocos/base/Log.h"
|
||||
#include "cocos/platform/java/jni/JniHelper.h"
|
||||
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#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<int, std::function<void()>> 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<char>(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
|
||||
@@ -0,0 +1,46 @@
|
||||
#pragma once
|
||||
//clang-format off
|
||||
#include <cstdint>
|
||||
//clang-format on
|
||||
#include <rawfile/raw_dir.h>
|
||||
#include <rawfile/raw_file.h>
|
||||
#include <rawfile/resource_manager.h>
|
||||
#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<int, std::function<void()>> 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
|
||||
@@ -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
|
||||
@@ -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 <cstdint>
|
||||
|
||||
namespace cc {
|
||||
|
||||
class TouchEvent;
|
||||
|
||||
class View {
|
||||
public:
|
||||
static void engineHandleCmd(int cmd);
|
||||
};
|
||||
|
||||
} // namespace cc
|
||||
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
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
|
||||
@@ -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 <fcntl.h>
|
||||
#include <hilog/log.h>
|
||||
#include <jni.h>
|
||||
#include <native_layer.h>
|
||||
#include <native_layer_jni.h>
|
||||
#include <netdb.h>
|
||||
#include <platform/FileUtils.h>
|
||||
#include <unistd.h>
|
||||
#include <future>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#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<void()> 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<void> 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
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user