From fe85f150d976cc4f8efe1b319e65dc2af0e4ade6 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 5 Aug 2016 18:13:48 +0800 Subject: [PATCH] Upgrade cocos/platform to v3.13 --- native/cocos/platform/CCApplication.h | 1 - native/cocos/platform/CCApplicationProtocol.h | 8 +- native/cocos/platform/CCDevice.h | 3 +- native/cocos/platform/CCFileUtils.cpp | 208 +-- native/cocos/platform/CCFileUtils.h | 170 +- native/cocos/platform/CCGLView.cpp | 16 +- native/cocos/platform/CCImage.cpp | 1650 +++++++++-------- native/cocos/platform/CCImage.h | 36 +- native/cocos/platform/CCPlatformConfig.h | 16 +- native/cocos/platform/CCPlatformDefine.h | 1 - native/cocos/platform/CCPlatformMacros.h | 19 +- native/cocos/platform/CCSAXParser.cpp | 2 +- native/cocos/platform/CCSAXParser.h | 3 +- native/cocos/platform/CCStdC.h | 1 - native/cocos/platform/android/Android.mk | 2 - .../android/CCApplication-android.cpp | 20 +- .../platform/android/CCApplication-android.h | 16 +- .../platform/android/CCDevice-android.cpp | 74 +- .../platform/android/CCFileUtils-android.cpp | 328 +--- .../platform/android/CCFileUtils-android.h | 24 +- .../platform/android/CCGLViewImpl-android.cpp | 3 +- .../android/CCPlatformDefine-android.h | 3 +- .../com.android.vending.expansion.zipfile.jar | Bin 0 -> 12370 bytes .../cocos2dx/lib/Cocos2dxAccelerometer.java | 106 +- .../org/cocos2dx/lib/Cocos2dxActivity.java | 163 +- .../src/org/cocos2dx/lib/Cocos2dxBitmap.java | 35 +- .../src/org/cocos2dx/lib/Cocos2dxEditBox.java | 43 +- .../cocos2dx/lib/Cocos2dxEditBoxHelper.java | 216 ++- .../cocos2dx/lib/Cocos2dxGLSurfaceView.java | 234 ++- .../src/org/cocos2dx/lib/Cocos2dxHandler.java | 36 +- .../src/org/cocos2dx/lib/Cocos2dxHelper.java | 489 +++-- .../lib/Cocos2dxHttpURLConnection.java | 27 +- .../cocos2dx/lib/Cocos2dxLocalStorage.java | 20 +- .../src/org/cocos2dx/lib/Cocos2dxMusic.java | 152 +- .../org/cocos2dx/lib/Cocos2dxRenderer.java | 25 +- .../src/org/cocos2dx/lib/Cocos2dxSound.java | 134 +- .../lib/Cocos2dxTextInputWrapper.java | 54 +- .../org/cocos2dx/lib/Cocos2dxTypefaces.java | 28 +- .../org/cocos2dx/lib/Cocos2dxVideoHelper.java | 118 +- .../org/cocos2dx/lib/Cocos2dxVideoView.java | 53 +- .../src/org/cocos2dx/lib/Cocos2dxWebView.java | 54 +- .../cocos2dx/lib/Cocos2dxWebViewHelper.java | 100 +- .../src/org/cocos2dx/lib/ResizeLayout.java | 41 +- .../platform/android/javaactivity-android.cpp | 32 +- ...org_cocos2dx_lib_Cocos2dxAccelerometer.cpp | 3 +- .../Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp | 13 +- .../Java_org_cocos2dx_lib_Cocos2dxHelper.cpp | 62 +- .../Java_org_cocos2dx_lib_Cocos2dxHelper.h | 5 +- ...Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp | 20 +- .../cocos/platform/android/jni/JniHelper.cpp | 115 +- native/cocos/platform/android/jni/JniHelper.h | 152 +- native/cocos/platform/apple/CCDevice-apple.mm | 2 +- .../cocos/platform/apple/CCFileUtils-apple.h | 14 +- .../cocos/platform/apple/CCFileUtils-apple.mm | 497 ++--- native/cocos/platform/apple/CCLock-apple.cpp | 11 +- native/cocos/platform/apple/CCLock-apple.h | 9 +- native/cocos/platform/apple/CCThread-apple.mm | 1 - .../platform/desktop/CCGLViewImpl-desktop.cpp | 114 +- .../platform/desktop/CCGLViewImpl-desktop.h | 4 +- native/cocos/platform/ios/CCApplication-ios.h | 22 +- .../cocos/platform/ios/CCApplication-ios.mm | 18 +- native/cocos/platform/ios/CCCommon-ios.mm | 5 +- native/cocos/platform/ios/CCDevice-ios.mm | 28 +- .../platform/ios/CCDirectorCaller-ios.mm | 20 +- native/cocos/platform/ios/CCEAGLView-ios.h | 3 +- native/cocos/platform/ios/CCEAGLView-ios.mm | 67 +- native/cocos/platform/ios/CCES2Renderer-ios.h | 5 +- native/cocos/platform/ios/CCES2Renderer-ios.m | 5 +- native/cocos/platform/ios/CCGLViewImpl-ios.mm | 18 +- native/cocos/platform/mac/CCApplication-mac.h | 28 +- .../cocos/platform/mac/CCApplication-mac.mm | 31 +- native/cocos/platform/mac/CCCommon-mac.mm | 3 +- native/cocos/platform/mac/CCDevice-mac.mm | 43 +- .../platform/win32/CCApplication-win32.cpp | 64 +- .../platform/win32/CCApplication-win32.h | 7 +- .../cocos/platform/win32/CCCommon-win32.cpp | 22 +- .../cocos/platform/win32/CCDevice-win32.cpp | 11 +- .../platform/win32/CCFileUtils-win32.cpp | 274 +-- .../cocos/platform/win32/CCFileUtils-win32.h | 22 +- native/cocos/platform/win32/CCGL-win32.h | 1 - native/cocos/platform/win32/CCStdC-win32.h | 2 +- native/cocos/platform/win32/CCUtils-win32.cpp | 108 ++ native/cocos/platform/win32/CCUtils-win32.h | 41 + native/cocos/platform/win32/compat/stdint.h | 3 +- .../cocos/platform/win32/inet_pton_mingw.cpp | 3 +- 85 files changed, 3546 insertions(+), 3094 deletions(-) create mode 100644 native/cocos/platform/android/java/libs/com.android.vending.expansion.zipfile.jar create mode 100644 native/cocos/platform/win32/CCUtils-win32.cpp create mode 100644 native/cocos/platform/win32/CCUtils-win32.h diff --git a/native/cocos/platform/CCApplication.h b/native/cocos/platform/CCApplication.h index de7b5c25db..913a8e3c65 100644 --- a/native/cocos/platform/CCApplication.h +++ b/native/cocos/platform/CCApplication.h @@ -45,4 +45,3 @@ THE SOFTWARE. /// @endcond #endif /* __PLATFORM_CCAPPLICATION_H__*/ - diff --git a/native/cocos/platform/CCApplicationProtocol.h b/native/cocos/platform/CCApplicationProtocol.h index 04b83f6328..145788ae51 100644 --- a/native/cocos/platform/CCApplicationProtocol.h +++ b/native/cocos/platform/CCApplicationProtocol.h @@ -136,6 +136,13 @@ public: */ virtual Platform getTargetPlatform() = 0; + /** + @brief Get application version. + * @js NA + * @lua NA + */ + virtual std::string getVersion() = 0; + /** @brief Open url in default browser. @param String with url to open. @@ -152,4 +159,3 @@ public: NS_CC_END #endif // __CC_APPLICATION_PROTOCOL_H__ - diff --git a/native/cocos/platform/CCDevice.h b/native/cocos/platform/CCDevice.h index e022fd22a6..d86f2c7047 100644 --- a/native/cocos/platform/CCDevice.h +++ b/native/cocos/platform/CCDevice.h @@ -95,7 +95,7 @@ public: /** * Gets texture data for text. */ - static Data getTextureDataForText(const std::string& text, const FontDefinition& textDefinition, TextAlign align, int &width, int &height, bool& hasPremultipliedAlpha); + static Data getTextureDataForText(const char * text, const FontDefinition& textDefinition, TextAlign align, int &width, int &height, bool& hasPremultipliedAlpha); private: CC_DISALLOW_IMPLICIT_CONSTRUCTORS(Device); @@ -107,4 +107,3 @@ private: NS_CC_END #endif /* __CCDEVICE_H__ */ - diff --git a/native/cocos/platform/CCFileUtils.cpp b/native/cocos/platform/CCFileUtils.cpp index b308866439..9341252503 100644 --- a/native/cocos/platform/CCFileUtils.cpp +++ b/native/cocos/platform/CCFileUtils.cpp @@ -23,7 +23,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCFileUtils.h" +#include "platform/CCFileUtils.h" #include @@ -346,7 +346,7 @@ ValueMap FileUtils::getValueMapFromData(const char* filedata, int filesize) ValueVector FileUtils::getValueVectorFromFile(const std::string& filename) { - const std::string fullPath = fullPathForFilename(filename.c_str()); + const std::string fullPath = fullPathForFilename(filename); DictMaker tMaker; return tMaker.arrayWithContentsOfFile(fullPath); } @@ -572,18 +572,18 @@ bool FileUtils::writeStringToFile(const std::string& dataStr, const std::string& Data data; data.fastSet((unsigned char*)dataStr.c_str(), dataStr.size()); - bool ret = writeDataToFile(data, fullPath); - data.fastSet(nullptr, 0); + bool rv = writeDataToFile(data, fullPath); - return ret; + data.fastSet(nullptr, 0); + return rv; } -bool FileUtils::writeDataToFile(const Data& retData, const std::string& fullPath) +bool FileUtils::writeDataToFile(const Data& data, const std::string& fullPath) { size_t size = 0; const char* mode = "wb"; - CCASSERT(!fullPath.empty() && retData.getSize() != 0, "Invalid parameters."); + CCASSERT(!fullPath.empty() && data.getSize() != 0, "Invalid parameters."); auto fileutils = FileUtils::getInstance(); do @@ -591,9 +591,9 @@ bool FileUtils::writeDataToFile(const Data& retData, const std::string& fullPath // Read the file from hardware FILE *fp = fopen(fileutils->getSuitableFOpen(fullPath).c_str(), mode); CC_BREAK_IF(!fp); - size = retData.getSize(); + size = data.getSize(); - fwrite(retData.getBytes(), size, 1, fp); + fwrite(data.getBytes(), size, 1, fp); fclose(fp); @@ -615,117 +615,72 @@ void FileUtils::purgeCachedEntries() _fullPathCache.clear(); } -static Data getData(const std::string& filename, bool forString) -{ - if (filename.empty()) - { - return Data::Null; - } - - Data ret; - unsigned char* buffer = nullptr; - size_t size = 0; - size_t readsize; - const char* mode = nullptr; - - if (forString) - mode = "rt"; - else - mode = "rb"; - - auto fileutils = FileUtils::getInstance(); - do - { - // Read the file from hardware - std::string fullPath = fileutils->fullPathForFilename(filename); - if (fullPath.empty()) { - break; - } - FILE *fp = fopen(fileutils->getSuitableFOpen(fullPath).c_str(), mode); - CC_BREAK_IF(!fp); - fseek(fp,0,SEEK_END); - size = ftell(fp); - fseek(fp,0,SEEK_SET); - - if (forString) - { - buffer = (unsigned char*)malloc(sizeof(unsigned char) * (size + 1)); - buffer[size] = '\0'; - } - else - { - buffer = (unsigned char*)malloc(sizeof(unsigned char) * size); - } - - readsize = fread(buffer, sizeof(unsigned char), size, fp); - fclose(fp); - - if (forString && readsize < size) - { - buffer[readsize] = '\0'; - } - } while (0); - - if (nullptr == buffer || 0 == readsize) - { - CCLOG("Get data from file %s failed", filename.c_str()); - if (buffer) - free(buffer); - } - else - { - ret.fastSet(buffer, readsize); - } - - return ret; -} - std::string FileUtils::getStringFromFile(const std::string& filename) { - Data data = getData(filename, true); - if (data.isNull()) - return ""; - - std::string ret((const char*)data.getBytes()); - return ret; + std::string s; + getContents(filename, &s); + return s; } Data FileUtils::getDataFromFile(const std::string& filename) { - return getData(filename, false); + Data d; + getContents(filename, &d); + return d; +} + + +FileUtils::Status FileUtils::getContents(const std::string& filename, ResizableBuffer* buffer) +{ + if (filename.empty()) + return Status::NotExists; + + auto fs = FileUtils::getInstance(); + + std::string fullPath = fs->fullPathForFilename(filename); + if (fullPath.empty()) + return Status::NotExists; + + FILE *fp = fopen(fs->getSuitableFOpen(fullPath).c_str(), "rb"); + if (!fp) + return Status::OpenFailed; + +#if defined(_MSC_VER) + auto descriptor = _fileno(fp); +#else + auto descriptor = fileno(fp); +#endif + struct stat statBuf; + if (fstat(descriptor, &statBuf) == -1) { + fclose(fp); + return Status::ReadFailed; + } + size_t size = statBuf.st_size; + + buffer->resize(size); + size_t readsize = fread(buffer->buffer(), 1, size, fp); + fclose(fp); + + if (readsize < size) { + buffer->resize(readsize); + return Status::ReadFailed; + } + + return Status::OK; } unsigned char* FileUtils::getFileData(const std::string& filename, const char* mode, ssize_t *size) { - unsigned char * buffer = nullptr; CCASSERT(!filename.empty() && size != nullptr && mode != nullptr, "Invalid parameters."); - if (filename.empty() || mode == nullptr || size == nullptr) { + (void)(mode); // mode is unused, as we do not support text mode any more... + + Data d; + if (getContents(filename, &d) != Status::OK) { + *size = 0; return nullptr; } - *size = 0; - do - { - // read the file from hardware - const std::string fullPath = fullPathForFilename(filename); - FILE *fp = fopen(getSuitableFOpen(fullPath).c_str(), mode); - CC_BREAK_IF(!fp); - fseek(fp,0,SEEK_END); - *size = ftell(fp); - fseek(fp,0,SEEK_SET); - buffer = (unsigned char*)malloc(*size); - *size = fread(buffer,sizeof(unsigned char), *size,fp); - fclose(fp); - } while (0); - - if (!buffer) - { - std::string msg = "Get data from file("; - msg.append(filename).append(") failed!"); - - CCLOG("%s", msg.c_str()); - } - return buffer; + return d.takeBuffer(size); } unsigned char* FileUtils::getFileDataFromZip(const std::string& zipFilePath, const std::string& filename, ssize_t *size) @@ -738,7 +693,7 @@ unsigned char* FileUtils::getFileDataFromZip(const std::string& zipFilePath, con { CC_BREAK_IF(zipFilePath.empty()); - file = unzOpen(zipFilePath.c_str()); + file = unzOpen(FileUtils::getInstance()->getSuitableFOpen(zipFilePath).c_str()); CC_BREAK_IF(!file); // FIXME: Other platforms should use upstream minizip like mingw-w64 @@ -920,35 +875,9 @@ void FileUtils::setWritablePath(const std::string& writablePath) _writablePath = writablePath; } -void FileUtils::setDefaultResourceRootPath(const std::string& resRootPath) +void FileUtils::setDefaultResourceRootPath(const std::string& path) { - if (resRootPath.empty() || _defaultResRootPath == resRootPath) - return; - - if (!_searchPathArray.empty() && !_defaultResRootPath.empty()) - { - auto tmp = _defaultResRootPath.length(); - std::vector newSearchPathArray; - for (auto& iter : _searchPathArray) - { - if (iter.find(_defaultResRootPath) == 0) - { - if (iter.length() == tmp) - newSearchPathArray.push_back(""); - else - newSearchPathArray.push_back(iter.substr(tmp)); - } - else - newSearchPathArray.push_back(iter); - } - - _defaultResRootPath = resRootPath; - setSearchPaths(newSearchPathArray); - } - else - { - _defaultResRootPath = resRootPath; - } + _defaultResRootPath = path; } void FileUtils::setSearchPaths(const std::vector& searchPaths) @@ -1088,7 +1017,7 @@ bool FileUtils::isDirectoryExist(const std::string& dirPath) const for (const auto& resolutionIt : _searchResolutionsOrderArray) { // searchPath + file_path + resourceDirectory - fullpath = searchIt + dirPath + resolutionIt; + fullpath = fullPathForFilename(searchIt + dirPath + resolutionIt); if (isDirectoryExistInternal(fullpath)) { _fullPathCache.insert(std::make_pair(dirPath, fullpath)); @@ -1230,12 +1159,6 @@ bool FileUtils::createDirectory(const std::string& path) bool FileUtils::removeDirectory(const std::string& path) { - if (!path.empty() && path[path.size() - 1] != '/') - { - CCLOGERROR("Fail to remove directory, path must terminate with '/': %s", path.c_str()); - return false; - } - std::string command = "rm -r "; // Path may include space. command += "\"" + path + "\""; @@ -1351,4 +1274,3 @@ void FileUtils::valueVectorCompact(ValueVector &valueVector) } NS_CC_END - diff --git a/native/cocos/platform/CCFileUtils.h b/native/cocos/platform/CCFileUtils.h index 2942ac891a..f5cddd0972 100644 --- a/native/cocos/platform/CCFileUtils.h +++ b/native/cocos/platform/CCFileUtils.h @@ -28,6 +28,7 @@ THE SOFTWARE. #include #include #include +#include #include "platform/CCPlatformMacros.h" #include "base/ccTypes.h" @@ -41,6 +42,76 @@ NS_CC_BEGIN * @{ */ + +class ResizableBuffer { +public: + virtual ~ResizableBuffer() {} + virtual void resize(size_t size) = 0; + virtual void* buffer() const = 0; +}; + +template +class ResizableBufferAdapter { }; + + +template +class ResizableBufferAdapter< std::basic_string > : public ResizableBuffer { + typedef std::basic_string BufferType; + BufferType* _buffer; +public: + explicit ResizableBufferAdapter(BufferType* buffer) : _buffer(buffer) {} + virtual void resize(size_t size) override { + _buffer->resize((size + sizeof(CharT) - 1) / sizeof(CharT)); + } + virtual void* buffer() const override { + // can not invoke string::front() if it is empty + + if (_buffer->empty()) + return nullptr; + else + return &_buffer->front(); + } +}; + +template +class ResizableBufferAdapter< std::vector > : public ResizableBuffer { + typedef std::vector BufferType; + BufferType* _buffer; +public: + explicit ResizableBufferAdapter(BufferType* buffer) : _buffer(buffer) {} + virtual void resize(size_t size) override { + _buffer->resize((size + sizeof(T) - 1) / sizeof(T)); + } + virtual void* buffer() const override { + // can not invoke vector::front() if it is empty + + if (_buffer->empty()) + return nullptr; + else + return &_buffer->front(); + } +}; + + +template<> +class ResizableBufferAdapter : public ResizableBuffer { + typedef Data BufferType; + BufferType* _buffer; +public: + explicit ResizableBufferAdapter(BufferType* buffer) : _buffer(buffer) {} + virtual void resize(size_t size) override { + if (static_cast(_buffer->getSize()) < size) { + auto old = _buffer->getBytes(); + void* buffer = realloc(old, size); + if (buffer) + _buffer->fastSet((unsigned char*)buffer, size); + } + } + virtual void* buffer() const override { + return _buffer->getBytes(); + } +}; + /** Helper class to handle file operations. */ class CC_DLL FileUtils { @@ -93,6 +164,85 @@ 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. + }; + + /** + * Gets whole file contents as string from a file. + * + * Unlike getStringFromFile, these getContents methods: + * - read file in binary mode (does not convert CRLF to LF). + * - does not truncate the string when '\0' is found (returned string of getContents may have '\0' in the middle.). + * + * The template version of can accept cocos2d::Data, std::basic_string and std::vector. + * + * @code + * std::string sbuf; + * FileUtils::getInstance()->getContents("path/to/file", &sbuf); + * + * std::vector vbuf; + * FileUtils::getInstance()->getContents("path/to/file", &vbuf); + * + * Data dbuf; + * FileUtils::getInstance()->getContents("path/to/file", &dbuf); + * @endcode + * + * Note: if you read to std::vector and std::basic_string where T is not 8 bit type, + * you may get 0 ~ sizeof(T)-1 bytes padding. + * + * - To write a new buffer class works with getContents, just extend ResizableBuffer. + * - To write a adapter for existing class, write a specialized ResizableBufferAdapter for that class, see follow code. + * + * @code + * NS_CC_BEGIN // ResizableBufferAdapter needed in cocos2d namespace. + * template<> + * class ResizableBufferAdapter : public ResizableBuffer { + * public: + * ResizableBufferAdapter(AlreadyExistsBuffer* buffer) { + * // your code here + * } + * virtual void resize(size_t size) override { + * // your code here + * } + * virtual void* buffer() const override { + * // your code here + * } + * }; + * NS_CC_END + * @endcode + * + * @param[in] filename The resource file name which contains the path. + * @param[out] buffer The buffer where the file contents are store to. + * @return Returns: + * - Status::OK when there is no error, the buffer is filled with the contents of file. + * - Status::NotExists when file not exists, the buffer will not changed. + * - Status::OpenFailed when cannot open file, the buffer will not changed. + * - Status::ReadFailed when read end up before read whole, the buffer will fill with already read bytes. + * - Status::NotInitialized when FileUtils is not initializes, the buffer will not changed. + * - Status::TooLarge when there file to be read is too large (> 2^32-1), the buffer will not changed. + * - Status::ObtainSizeFailed when failed to obtain the file size, the buffer will not changed. + */ + template < + typename T, + typename Enable = typename std::enable_if< + std::is_base_of< ResizableBuffer, ResizableBufferAdapter >::value + >::type + > + Status getContents(const std::string& filename, T* buffer) { + ResizableBufferAdapter buf(buffer); + return getContents(filename, &buf); + } + virtual Status getContents(const std::string& filename, ResizableBuffer* buffer); + /** * Gets resource file data * @@ -200,7 +350,7 @@ public: /** * Sets the filenameLookup dictionary. * - * @param pFilenameLookupDict The dictionary for replacing filename. + * @param filenameLookupDict The dictionary for replacing filename. * @since v2.1 */ virtual void setFilenameLookupDictionary(const ValueMap& filenameLookupDict); @@ -208,7 +358,7 @@ public: /** * Gets full path from a file name and the path of the relative file. * @param filename The file name. - * @param pszRelativeFile The path of the relative file. + * @param relativeFile The path of the relative file. * @return The full path. * e.g. filename: hello.png, pszRelativeFile: /User/path1/path2/hello.plist * Return: /User/path1/path2/hello.pvr (If there a a key(hello.png)-value(hello.pvr) in FilenameLookup dictionary. ) @@ -275,7 +425,7 @@ public: * * @since v2.1 */ - virtual void addSearchPath(const std::string & path, const bool front=false); + void addSearchPath(const std::string & path, const bool front=false); /** * Gets the array of search paths. @@ -371,7 +521,7 @@ public: * Windows fopen can't support UTF-8 filename * Need convert all parameters fopen and other 3rd-party libs * - * @param filename std::string name file for conversion from utf-8 + * @param filenameUtf8 std::string name file for conversion from utf-8 * @return std::string ansi filename in current locale */ virtual std::string getSuitableFOpen(const std::string& filenameUtf8) const; @@ -531,12 +681,6 @@ protected: * @return The full path of the file, if the file can't be found, it will return an empty string. */ virtual std::string getFullPathForDirectoryAndFilename(const std::string& directory, const std::string& filename) const; - - /** - * Remove null value key (for iOS) - */ - virtual void valueMapCompact(ValueMap& valueMap); - virtual void valueVectorCompact(ValueVector& valueVector); /** Dictionary used to lookup filenames based on a key. * It is used internally by the following methods: @@ -584,6 +728,11 @@ protected: */ static FileUtils* s_sharedFileUtils; + /** + * Remove null value key (for iOS) + */ + virtual void valueMapCompact(ValueMap& valueMap); + virtual void valueVectorCompact(ValueVector& valueVector); }; // end of support group @@ -592,4 +741,3 @@ protected: NS_CC_END #endif // __CC_FILEUTILS_H__ - diff --git a/native/cocos/platform/CCGLView.cpp b/native/cocos/platform/CCGLView.cpp index 993cc80ce9..e80b7772d4 100644 --- a/native/cocos/platform/CCGLView.cpp +++ b/native/cocos/platform/CCGLView.cpp @@ -149,10 +149,16 @@ void GLView::updateDesignResolutionSize() _viewPortRect.setRect((_screenSize.width - viewPortW) / 2, (_screenSize.height - viewPortH) / 2, viewPortW, viewPortH); // reset director's member variables to fit visible rect - auto director = Director::DirectorInstance; + auto director = Director::getInstance(); director->_winSizeInPoints = getDesignResolutionSize(); director->_isStatusLabelUpdated = true; director->setProjection(director->getProjection()); + + // Github issue #16139 + // A default viewport is needed in order to display the FPS, + // since the FPS are rendered in the Director, and there is no viewport there. + // Everything, including the FPS should renderer in the Scene. + glViewport(0, 0, _screenSize.width, _screenSize.height); } } @@ -183,7 +189,7 @@ const Size& GLView::getFrameSize() const void GLView::setFrameSize(float width, float height) { - _designResolutionSize = _screenSize = Size(width, height); + _screenSize = Size(width, height); } Rect GLView::getVisibleRect() const @@ -306,7 +312,7 @@ void GLView::handleTouchesBegin(int num, intptr_t ids[], float xs[], float ys[]) } touchEvent._eventCode = EventTouch::EventCode::BEGAN; - auto dispatcher = Director::DirectorInstance->getEventDispatcher(); + auto dispatcher = Director::getInstance()->getEventDispatcher(); dispatcher->dispatchEvent(&touchEvent); } @@ -363,7 +369,7 @@ void GLView::handleTouchesMove(int num, intptr_t ids[], float xs[], float ys[], } touchEvent._eventCode = EventTouch::EventCode::MOVED; - auto dispatcher = Director::DirectorInstance->getEventDispatcher(); + auto dispatcher = Director::getInstance()->getEventDispatcher(); dispatcher->dispatchEvent(&touchEvent); } @@ -417,7 +423,7 @@ void GLView::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num } touchEvent._eventCode = eventCode; - auto dispatcher = Director::DirectorInstance->getEventDispatcher(); + auto dispatcher = Director::getInstance()->getEventDispatcher(); dispatcher->dispatchEvent(&touchEvent); for (auto& touch : touchEvent._touches) diff --git a/native/cocos/platform/CCImage.cpp b/native/cocos/platform/CCImage.cpp index bcba7994ab..fc822a90a6 100644 --- a/native/cocos/platform/CCImage.cpp +++ b/native/cocos/platform/CCImage.cpp @@ -34,6 +34,26 @@ THE SOFTWARE. extern "C" { + // To resolve link error when building 32bits with Xcode 6. + // More information please refer to the discussion in https://github.com/cocos2d/cocos2d-x/pull/6986 +#if defined (__unix) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) +#ifndef __ENABLE_COMPATIBILITY_WITH_UNIX_2003__ +#define __ENABLE_COMPATIBILITY_WITH_UNIX_2003__ +#include + FILE *fopen$UNIX2003( const char *filename, const char *mode ) + { + return fopen(filename, mode); + } + size_t fwrite$UNIX2003( const void *a, size_t b, size_t c, FILE *d ) + { + return fwrite(a, b, c, d); + } + char *strerror$UNIX2003( int errnum ) + { + return strerror(errnum); + } +#endif +#endif #if CC_USE_PNG #include "png/png.h" @@ -55,14 +75,14 @@ extern "C" #include "base/TGAlib.h" #include "base/ccMacros.h" -#include "CCCommon.h" -#include "CCStdC.h" -#include "CCFileUtils.h" +#include "platform/CCCommon.h" +#include "platform/CCStdC.h" +#include "platform/CCFileUtils.h" #include "base/CCConfiguration.h" #include "base/ccUtils.h" #include "base/ZipUtils.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) -#include "android/CCFileUtils-android.h" +#include "platform/android/CCFileUtils-android.h" #endif #define CC_GL_ATC_RGB_AMD 0x8C92 @@ -266,7 +286,6 @@ namespace int offset; }tImageSource; - #ifdef CC_USE_PNG static void pngReadCallback(png_structp png_ptr, png_bytep data, png_size_t length) { @@ -538,806 +557,6 @@ bool Image::isCompressed() return Texture2D::getPixelFormatInfoMap().at(_renderFormat).compressed; } -namespace -{ - bool testFormatForPvr2TCSupport(PVR2TexturePixelFormat format) - { - return true; - } - - bool testFormatForPvr3TCSupport(PVR3TexturePixelFormat format) - { - switch (format) { - case PVR3TexturePixelFormat::BGRA8888: - return Configuration::getInstance()->supportsBGRA8888(); - - case PVR3TexturePixelFormat::PVRTC2BPP_RGB: - case PVR3TexturePixelFormat::PVRTC2BPP_RGBA: - case PVR3TexturePixelFormat::PVRTC4BPP_RGB: - case PVR3TexturePixelFormat::PVRTC4BPP_RGBA: - case PVR3TexturePixelFormat::ETC1: - case PVR3TexturePixelFormat::RGBA8888: - case PVR3TexturePixelFormat::RGBA4444: - case PVR3TexturePixelFormat::RGBA5551: - case PVR3TexturePixelFormat::RGB565: - case PVR3TexturePixelFormat::RGB888: - case PVR3TexturePixelFormat::A8: - case PVR3TexturePixelFormat::L8: - case PVR3TexturePixelFormat::LA88: - return true; - - default: - return false; - } - } -} - -bool Image::initWithPVRv2Data(const unsigned char * data, ssize_t dataLen) -{ - int dataLength = 0, dataOffset = 0, dataSize = 0; - int blockSize = 0, widthBlocks = 0, heightBlocks = 0; - int width = 0, height = 0; - - //Cast first sizeof(PVRTexHeader) bytes of data stream as PVRTexHeader - const PVRv2TexHeader *header = static_cast(static_cast(data)); - - //Make sure that tag is in correct formatting - if (memcmp(&header->pvrTag, gPVRTexIdentifier, strlen(gPVRTexIdentifier)) != 0) - { - return false; - } - - Configuration *configuration = Configuration::getInstance(); - - //can not detect the premultiplied alpha from pvr file, use _PVRHaveAlphaPremultiplied instead. - _hasPremultipliedAlpha = _PVRHaveAlphaPremultiplied; - - unsigned int flags = CC_SWAP_INT32_LITTLE_TO_HOST(header->flags); - PVR2TexturePixelFormat formatFlags = static_cast(flags & PVR_TEXTURE_FLAG_TYPE_MASK); - bool flipped = (flags & (unsigned int)PVR2TextureFlag::VerticalFlip) ? true : false; - if (flipped) - { - CCLOG("cocos2d: WARNING: Image is flipped. Regenerate it using PVRTexTool"); - } - - if (! configuration->supportsNPOT() && - (static_cast(header->width) != ccNextPOT(header->width) - || static_cast(header->height) != ccNextPOT(header->height))) - { - CCLOG("cocos2d: ERROR: Loading an NPOT texture (%dx%d) but is not supported on this device", header->width, header->height); - return false; - } - - if (!testFormatForPvr2TCSupport(formatFlags)) - { - CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags); - return false; - } - - if (v2_pixel_formathash.find(formatFlags) == v2_pixel_formathash.end()) - { - CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags); - return false; - } - - auto it = Texture2D::getPixelFormatInfoMap().find(getDevicePixelFormat(v2_pixel_formathash.at(formatFlags))); - - if (it == Texture2D::getPixelFormatInfoMap().end()) - { - CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags); - return false; - } - - _renderFormat = it->first; - int bpp = it->second.bpp; - - //Reset num of mipmaps - _numberOfMipmaps = 0; - - //Get size of mipmap - _width = width = CC_SWAP_INT32_LITTLE_TO_HOST(header->width); - _height = height = CC_SWAP_INT32_LITTLE_TO_HOST(header->height); - - //Get ptr to where data starts.. - dataLength = CC_SWAP_INT32_LITTLE_TO_HOST(header->dataLength); - - //Move by size of header - _dataLen = dataLen - sizeof(PVRv2TexHeader); - _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); - memcpy(_data, (unsigned char*)data + sizeof(PVRv2TexHeader), _dataLen); - - // Calculate the data size for each texture level and respect the minimum number of blocks - while (dataOffset < dataLength) - { - switch (formatFlags) { - case PVR2TexturePixelFormat::PVRTC2BPP_RGBA: - if (!Configuration::getInstance()->supportsPVRTC()) - { - CCLOG("cocos2d: Hardware PVR decoder not present. Using software decoder"); - _unpack = true; - _mipmaps[_numberOfMipmaps].len = width*height*4; - _mipmaps[_numberOfMipmaps].address = new (std::nothrow) unsigned char[width*height*4]; - PVRTDecompressPVRTC(_data+dataOffset,width,height,_mipmaps[_numberOfMipmaps].address, true); - bpp = 2; - } - blockSize = 8 * 4; // Pixel by pixel block size for 2bpp - widthBlocks = width / 8; - heightBlocks = height / 4; - break; - case PVR2TexturePixelFormat::PVRTC4BPP_RGBA: - if (!Configuration::getInstance()->supportsPVRTC()) - { - CCLOG("cocos2d: Hardware PVR decoder not present. Using software decoder"); - _unpack = true; - _mipmaps[_numberOfMipmaps].len = width*height*4; - _mipmaps[_numberOfMipmaps].address = new (std::nothrow) unsigned char[width*height*4]; - PVRTDecompressPVRTC(_data+dataOffset,width,height,_mipmaps[_numberOfMipmaps].address, false); - bpp = 4; - } - blockSize = 4 * 4; // Pixel by pixel block size for 4bpp - widthBlocks = width / 4; - heightBlocks = height / 4; - break; - case PVR2TexturePixelFormat::BGRA8888: - if (Configuration::getInstance()->supportsBGRA8888() == false) - { - CCLOG("cocos2d: Image. BGRA8888 not supported on this device"); - return false; - } - default: - blockSize = 1; - widthBlocks = width; - heightBlocks = height; - break; - } - - // Clamp to minimum number of blocks - if (widthBlocks < 2) - { - widthBlocks = 2; - } - if (heightBlocks < 2) - { - heightBlocks = 2; - } - - dataSize = widthBlocks * heightBlocks * ((blockSize * bpp) / 8); - int packetLength = (dataLength - dataOffset); - packetLength = packetLength > dataSize ? dataSize : packetLength; - - //Make record to the mipmaps array and increment counter - if(!_unpack) - { - _mipmaps[_numberOfMipmaps].address = _data + dataOffset; - _mipmaps[_numberOfMipmaps].len = packetLength; - } - _numberOfMipmaps++; - - dataOffset += packetLength; - - //Update width and height to the next lower power of two - width = MAX(width >> 1, 1); - height = MAX(height >> 1, 1); - } - - if(_unpack) - { - _data = _mipmaps[0].address; - _dataLen = _mipmaps[0].len; - } - - return true; -} - -bool Image::initWithPVRv3Data(const unsigned char * data, ssize_t dataLen) -{ - if (static_cast(dataLen) < sizeof(PVRv3TexHeader)) - { - return false; - } - - const PVRv3TexHeader *header = static_cast(static_cast(data)); - - // validate version - if (CC_SWAP_INT32_BIG_TO_HOST(header->version) != 0x50565203) - { - CCLOG("cocos2d: WARNING: pvr file version mismatch"); - return false; - } - - // parse pixel format - PVR3TexturePixelFormat pixelFormat = static_cast(header->pixelFormat); - - if (!testFormatForPvr3TCSupport(pixelFormat)) - { - CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant", - static_cast(pixelFormat)); - return false; - } - - - if (v3_pixel_formathash.find(pixelFormat) == v3_pixel_formathash.end()) - { - CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant", - static_cast(pixelFormat)); - return false; - } - - auto it = Texture2D::getPixelFormatInfoMap().find(getDevicePixelFormat(v3_pixel_formathash.at(pixelFormat))); - - if (it == Texture2D::getPixelFormatInfoMap().end()) - { - CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant", - static_cast(pixelFormat)); - return false; - } - - _renderFormat = it->first; - int bpp = it->second.bpp; - - // flags - int flags = CC_SWAP_INT32_LITTLE_TO_HOST(header->flags); - - // PVRv3 specifies premultiply alpha in a flag -- should always respect this in PVRv3 files - if (flags & (unsigned int)PVR3TextureFlag::PremultipliedAlpha) - { - _hasPremultipliedAlpha = true; - } - else - { - _hasPremultipliedAlpha = false; - } - - // sizing - int width = CC_SWAP_INT32_LITTLE_TO_HOST(header->width); - int height = CC_SWAP_INT32_LITTLE_TO_HOST(header->height); - _width = width; - _height = height; - int dataOffset = 0, dataSize = 0; - int blockSize = 0, widthBlocks = 0, heightBlocks = 0; - - _dataLen = dataLen - (sizeof(PVRv3TexHeader) + header->metadataLength); - _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); - memcpy(_data, static_cast(data) + sizeof(PVRv3TexHeader) + header->metadataLength, _dataLen); - - _numberOfMipmaps = header->numberOfMipmaps; - CCASSERT(_numberOfMipmaps < MIPMAP_MAX, "Image: Maximum number of mimpaps reached. Increase the CC_MIPMAP_MAX value"); - - for (int i = 0; i < _numberOfMipmaps; i++) - { - switch ((PVR3TexturePixelFormat)pixelFormat) - { - case PVR3TexturePixelFormat::PVRTC2BPP_RGB : - case PVR3TexturePixelFormat::PVRTC2BPP_RGBA : - if (!Configuration::getInstance()->supportsPVRTC()) - { - CCLOG("cocos2d: Hardware PVR decoder not present. Using software decoder"); - _unpack = true; - _mipmaps[i].len = width*height*4; - _mipmaps[i].address = new (std::nothrow) unsigned char[width*height*4]; - PVRTDecompressPVRTC(_data+dataOffset,width,height,_mipmaps[i].address, true); - bpp = 2; - } - blockSize = 8 * 4; // Pixel by pixel block size for 2bpp - widthBlocks = width / 8; - heightBlocks = height / 4; - break; - case PVR3TexturePixelFormat::PVRTC4BPP_RGB : - case PVR3TexturePixelFormat::PVRTC4BPP_RGBA : - if (!Configuration::getInstance()->supportsPVRTC()) - { - CCLOG("cocos2d: Hardware PVR decoder not present. Using software decoder"); - _unpack = true; - _mipmaps[i].len = width*height*4; - _mipmaps[i].address = new (std::nothrow) unsigned char[width*height*4]; - PVRTDecompressPVRTC(_data+dataOffset,width,height,_mipmaps[i].address, false); - bpp = 4; - } - blockSize = 4 * 4; // Pixel by pixel block size for 4bpp - widthBlocks = width / 4; - heightBlocks = height / 4; - break; - case PVR3TexturePixelFormat::ETC1: - if (!Configuration::getInstance()->supportsETC()) - { - CCLOG("cocos2d: Hardware ETC1 decoder not present. Using software decoder"); - int bytePerPixel = 3; - unsigned int stride = width * bytePerPixel; - _unpack = true; - _mipmaps[i].len = width*height*bytePerPixel; - _mipmaps[i].address = new (std::nothrow) unsigned char[width*height*bytePerPixel]; - if (etc1_decode_image(static_cast(_data+dataOffset), static_cast(_mipmaps[i].address), width, height, bytePerPixel, stride) != 0) - { - return false; - } - } - blockSize = 4 * 4; // Pixel by pixel block size for 4bpp - widthBlocks = width / 4; - heightBlocks = height / 4; - break; - case PVR3TexturePixelFormat::BGRA8888: - if (! Configuration::getInstance()->supportsBGRA8888()) - { - CCLOG("cocos2d: Image. BGRA8888 not supported on this device"); - return false; - } - default: - blockSize = 1; - widthBlocks = width; - heightBlocks = height; - break; - } - - // Clamp to minimum number of blocks - if (widthBlocks < 2) - { - widthBlocks = 2; - } - if (heightBlocks < 2) - { - heightBlocks = 2; - } - - dataSize = widthBlocks * heightBlocks * ((blockSize * bpp) / 8); - auto packetLength = _dataLen - dataOffset; - packetLength = packetLength > dataSize ? dataSize : packetLength; - - if(!_unpack) - { - _mipmaps[i].address = _data + dataOffset; - _mipmaps[i].len = static_cast(packetLength); - } - - dataOffset += packetLength; - CCASSERT(dataOffset <= _dataLen, "CCTexurePVR: Invalid length"); - - - width = MAX(width >> 1, 1); - height = MAX(height >> 1, 1); - } - - if (_unpack) - { - _data = _mipmaps[0].address; - _dataLen = _mipmaps[0].len; - } - - return true; -} - -bool Image::initWithETCData(const unsigned char * data, ssize_t dataLen) -{ - const etc1_byte* header = static_cast(data); - - //check the data - if (! etc1_pkm_is_valid(header)) - { - return false; - } - - _width = etc1_pkm_get_width(header); - _height = etc1_pkm_get_height(header); - - if (0 == _width || 0 == _height) - { - return false; - } - - if (Configuration::getInstance()->supportsETC()) - { - //old opengl version has no define for GL_ETC1_RGB8_OES, add macro to make compiler happy. -#ifdef GL_ETC1_RGB8_OES - _renderFormat = Texture2D::PixelFormat::ETC; - _dataLen = dataLen - ETC_PKM_HEADER_SIZE; - _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); - memcpy(_data, static_cast(data) + ETC_PKM_HEADER_SIZE, _dataLen); - return true; -#endif - } - else - { - CCLOG("cocos2d: Hardware ETC1 decoder not present. Using software decoder"); - - //if it is not gles or device do not support ETC, decode texture by software - int bytePerPixel = 3; - unsigned int stride = _width * bytePerPixel; - _renderFormat = Texture2D::PixelFormat::RGB888; - - _dataLen = _width * _height * bytePerPixel; - _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); - - if (etc1_decode_image(static_cast(data) + ETC_PKM_HEADER_SIZE, static_cast(_data), _width, _height, bytePerPixel, stride) != 0) - { - _dataLen = 0; - if (_data != nullptr) - { - free(_data); - } - return false; - } - - return true; - } - return false; -} - -bool Image::initWithTGAData(tImageTGA* tgaData) -{ - bool ret = false; - - do - { - CC_BREAK_IF(tgaData == nullptr); - - // tgaLoadBuffer only support type 2, 3, 10 - if (2 == tgaData->type || 10 == tgaData->type) - { - // true color - // unsupported RGB555 - if (tgaData->pixelDepth == 16) - { - _renderFormat = Texture2D::PixelFormat::RGB5A1; - } - else if(tgaData->pixelDepth == 24) - { - _renderFormat = Texture2D::PixelFormat::RGB888; - } - else if(tgaData->pixelDepth == 32) - { - _renderFormat = Texture2D::PixelFormat::RGBA8888; - } - else - { - CCLOG("Image WARNING: unsupported true color tga data pixel format. FILE: %s", _filePath.c_str()); - break; - } - } - else if(3 == tgaData->type) - { - // gray - if (8 == tgaData->pixelDepth) - { - _renderFormat = Texture2D::PixelFormat::I8; - } - else - { - // actually this won't happen, if it happens, maybe the image file is not a tga - CCLOG("Image WARNING: unsupported gray tga data pixel format. FILE: %s", _filePath.c_str()); - break; - } - } - - _width = tgaData->width; - _height = tgaData->height; - _data = tgaData->imageData; - _dataLen = _width * _height * tgaData->pixelDepth / 8; - _fileType = Format::TGA; - - _hasPremultipliedAlpha = false; - - ret = true; - - }while(false); - - if (ret) - { - if (FileUtils::getInstance()->getFileExtension(_filePath) != ".tga") - { - CCLOG("Image WARNING: the image file suffix is not tga, but parsed as a tga image file. FILE: %s", _filePath.c_str()); - } - } - else - { - if (tgaData && tgaData->imageData != nullptr) - { - free(tgaData->imageData); - _data = nullptr; - } - } - - return ret; -} - -bool Image::initWithPVRData(const unsigned char * data, ssize_t dataLen) -{ - return initWithPVRv2Data(data, dataLen) || initWithPVRv3Data(data, dataLen); -} - -bool Image::initWithRawData(const unsigned char * data, ssize_t dataLen, int width, int height, int bitsPerComponent, bool preMulti) -{ - bool ret = false; - do - { - CC_BREAK_IF(0 == width || 0 == height); - - _height = height; - _width = width; - _hasPremultipliedAlpha = preMulti; - _renderFormat = Texture2D::PixelFormat::RGBA8888; - - // only RGBA8888 supported - int bytesPerComponent = 4; - _dataLen = height * width * bytesPerComponent; - _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); - CC_BREAK_IF(! _data); - memcpy(_data, data, _dataLen); - - ret = true; - } while (0); - - return ret; -} - - -#if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) -bool Image::saveToFile(const std::string& filename, bool isToRGB) -{ - //only support for Texture2D::PixelFormat::RGB888 or Texture2D::PixelFormat::RGBA8888 uncompressed data - if (isCompressed() || (_renderFormat != Texture2D::PixelFormat::RGB888 && _renderFormat != Texture2D::PixelFormat::RGBA8888)) - { - CCLOG("cocos2d: Image: saveToFile is only support for Texture2D::PixelFormat::RGB888 or Texture2D::PixelFormat::RGBA8888 uncompressed data for now"); - return false; - } - - std::string fileExtension = FileUtils::getInstance()->getFileExtension(filename); - - if (fileExtension == ".png") - { - return saveImageToPNG(filename, isToRGB); - } - else if (fileExtension == ".jpg") - { - return saveImageToJPG(filename); - } - else - { - CCLOG("cocos2d: Image: saveToFile no support file extension(only .png or .jpg) for file: %s", filename.c_str()); - return false; - } -} - -bool Image::saveImageToPNG(const std::string& filePath, bool isToRGB) -{ -#if CC_USE_WIC - return encodeWithWIC(filePath, isToRGB, GUID_ContainerFormatPng); -#elif CC_USE_PNG - bool ret = false; - do - { - FILE *fp; - png_structp png_ptr; - png_infop info_ptr; - png_colorp palette; - png_bytep *row_pointers; - - fp = fopen(FileUtils::getInstance()->getSuitableFOpen(filePath).c_str(), "wb"); - CC_BREAK_IF(nullptr == fp); - - png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); - - if (nullptr == png_ptr) - { - fclose(fp); - break; - } - - info_ptr = png_create_info_struct(png_ptr); - if (nullptr == info_ptr) - { - fclose(fp); - png_destroy_write_struct(&png_ptr, nullptr); - break; - } -#if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA && CC_TARGET_PLATFORM != CC_PLATFORM_NACL) - if (setjmp(png_jmpbuf(png_ptr))) - { - fclose(fp); - png_destroy_write_struct(&png_ptr, &info_ptr); - break; - } -#endif - png_init_io(png_ptr, fp); - - if (!isToRGB && hasAlpha()) - { - png_set_IHDR(png_ptr, info_ptr, _width, _height, 8, PNG_COLOR_TYPE_RGB_ALPHA, - PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); - } - else - { - png_set_IHDR(png_ptr, info_ptr, _width, _height, 8, PNG_COLOR_TYPE_RGB, - PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); - } - - palette = (png_colorp)png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH * sizeof (png_color)); - png_set_PLTE(png_ptr, info_ptr, palette, PNG_MAX_PALETTE_LENGTH); - - png_write_info(png_ptr, info_ptr); - - png_set_packing(png_ptr); - - row_pointers = (png_bytep *)malloc(_height * sizeof(png_bytep)); - if(row_pointers == nullptr) - { - fclose(fp); - png_destroy_write_struct(&png_ptr, &info_ptr); - break; - } - - if (!hasAlpha()) - { - for (int i = 0; i < (int)_height; i++) - { - row_pointers[i] = (png_bytep)_data + i * _width * 3; - } - - png_write_image(png_ptr, row_pointers); - - free(row_pointers); - row_pointers = nullptr; - } - else - { - if (isToRGB) - { - unsigned char *tempData = static_cast(malloc(_width * _height * 3 * sizeof(unsigned char))); - if (nullptr == tempData) - { - fclose(fp); - png_destroy_write_struct(&png_ptr, &info_ptr); - - free(row_pointers); - row_pointers = nullptr; - break; - } - - for (int i = 0; i < _height; ++i) - { - for (int j = 0; j < _width; ++j) - { - tempData[(i * _width + j) * 3] = _data[(i * _width + j) * 4]; - tempData[(i * _width + j) * 3 + 1] = _data[(i * _width + j) * 4 + 1]; - tempData[(i * _width + j) * 3 + 2] = _data[(i * _width + j) * 4 + 2]; - } - } - - for (int i = 0; i < (int)_height; i++) - { - row_pointers[i] = (png_bytep)tempData + i * _width * 3; - } - - png_write_image(png_ptr, row_pointers); - - free(row_pointers); - row_pointers = nullptr; - - if (tempData != nullptr) - { - free(tempData); - } - } - else - { - for (int i = 0; i < (int)_height; i++) - { - row_pointers[i] = (png_bytep)_data + i * _width * 4; - } - - png_write_image(png_ptr, row_pointers); - - free(row_pointers); - row_pointers = nullptr; - } - } - - png_write_end(png_ptr, info_ptr); - - png_free(png_ptr, palette); - palette = nullptr; - - png_destroy_write_struct(&png_ptr, &info_ptr); - - fclose(fp); - - ret = true; - } while (0); - return ret; -#else - CCLOG("png is not enabled, please enable it in ccConfig.h"); - return false; -#endif // CC_USE_PNG -} - -bool Image::saveImageToJPG(const std::string& filePath) -{ -#if CC_USE_WIC - return encodeWithWIC(filePath, false, GUID_ContainerFormatJpeg); -#elif CC_USE_JPEG - bool ret = false; - do - { - struct jpeg_compress_struct cinfo; - struct jpeg_error_mgr jerr; - FILE * outfile; /* target file */ - JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */ - int row_stride; /* physical row width in image buffer */ - - cinfo.err = jpeg_std_error(&jerr); - /* Now we can initialize the JPEG compression object. */ - jpeg_create_compress(&cinfo); - - CC_BREAK_IF((outfile = fopen(FileUtils::getInstance()->getSuitableFOpen(filePath).c_str(), "wb")) == nullptr); - - jpeg_stdio_dest(&cinfo, outfile); - - cinfo.image_width = _width; /* image width and height, in pixels */ - cinfo.image_height = _height; - cinfo.input_components = 3; /* # of color components per pixel */ - cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ - - jpeg_set_defaults(&cinfo); - jpeg_set_quality(&cinfo, 90, TRUE); - - jpeg_start_compress(&cinfo, TRUE); - - row_stride = _width * 3; /* JSAMPLEs per row in image_buffer */ - - if (hasAlpha()) - { - unsigned char *tempData = static_cast(malloc(_width * _height * 3 * sizeof(unsigned char))); - if (nullptr == tempData) - { - jpeg_finish_compress(&cinfo); - jpeg_destroy_compress(&cinfo); - fclose(outfile); - break; - } - - for (int i = 0; i < _height; ++i) - { - for (int j = 0; j < _width; ++j) - - { - tempData[(i * _width + j) * 3] = _data[(i * _width + j) * 4]; - tempData[(i * _width + j) * 3 + 1] = _data[(i * _width + j) * 4 + 1]; - tempData[(i * _width + j) * 3 + 2] = _data[(i * _width + j) * 4 + 2]; - } - } - - while (cinfo.next_scanline < cinfo.image_height) - { - row_pointer[0] = & tempData[cinfo.next_scanline * row_stride]; - (void) jpeg_write_scanlines(&cinfo, row_pointer, 1); - } - - if (tempData != nullptr) - { - free(tempData); - } - } - else - { - while (cinfo.next_scanline < cinfo.image_height) { - row_pointer[0] = & _data[cinfo.next_scanline * row_stride]; - (void) jpeg_write_scanlines(&cinfo, row_pointer, 1); - } - } - - jpeg_finish_compress(&cinfo); - fclose(outfile); - jpeg_destroy_compress(&cinfo); - - ret = true; - } while (0); - return ret; -#else - CCLOG("jpeg is not enabled, please enable it in ccConfig.h"); - return false; -#endif // CC_USE_JPEG -} - -#endif // (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) - namespace { /* @@ -1830,18 +1049,823 @@ bool Image::initWithTiffData(const unsigned char * data, ssize_t dataLen) #endif //CC_USE_TIFF } -void Image::premultipliedAlpha() -{ - CCASSERT(_renderFormat == Texture2D::PixelFormat::RGBA8888, "The pixel format should be RGBA8888!"); - unsigned int* fourBytes = (unsigned int*)_data; - for(int i = 0; i < _width * _height; i++) +namespace +{ + bool testFormatForPvr2TCSupport(PVR2TexturePixelFormat format) { - unsigned char* p = _data + i * 4; - fourBytes[i] = CC_RGB_PREMULTIPLY_ALPHA(p[0], p[1], p[2], p[3]); + return true; } - _hasPremultipliedAlpha = true; + bool testFormatForPvr3TCSupport(PVR3TexturePixelFormat format) + { + switch (format) { + case PVR3TexturePixelFormat::BGRA8888: + return Configuration::getInstance()->supportsBGRA8888(); + + case PVR3TexturePixelFormat::PVRTC2BPP_RGB: + case PVR3TexturePixelFormat::PVRTC2BPP_RGBA: + case PVR3TexturePixelFormat::PVRTC4BPP_RGB: + case PVR3TexturePixelFormat::PVRTC4BPP_RGBA: + case PVR3TexturePixelFormat::ETC1: + case PVR3TexturePixelFormat::RGBA8888: + case PVR3TexturePixelFormat::RGBA4444: + case PVR3TexturePixelFormat::RGBA5551: + case PVR3TexturePixelFormat::RGB565: + case PVR3TexturePixelFormat::RGB888: + case PVR3TexturePixelFormat::A8: + case PVR3TexturePixelFormat::L8: + case PVR3TexturePixelFormat::LA88: + return true; + + default: + return false; + } + } +} + +bool Image::initWithPVRv2Data(const unsigned char * data, ssize_t dataLen) +{ + int dataLength = 0, dataOffset = 0, dataSize = 0; + int blockSize = 0, widthBlocks = 0, heightBlocks = 0; + int width = 0, height = 0; + + //Cast first sizeof(PVRTexHeader) bytes of data stream as PVRTexHeader + const PVRv2TexHeader *header = static_cast(static_cast(data)); + + //Make sure that tag is in correct formatting + if (memcmp(&header->pvrTag, gPVRTexIdentifier, strlen(gPVRTexIdentifier)) != 0) + { + return false; + } + + Configuration *configuration = Configuration::getInstance(); + + //can not detect the premultiplied alpha from pvr file, use _PVRHaveAlphaPremultiplied instead. + _hasPremultipliedAlpha = _PVRHaveAlphaPremultiplied; + + unsigned int flags = CC_SWAP_INT32_LITTLE_TO_HOST(header->flags); + PVR2TexturePixelFormat formatFlags = static_cast(flags & PVR_TEXTURE_FLAG_TYPE_MASK); + bool flipped = (flags & (unsigned int)PVR2TextureFlag::VerticalFlip) ? true : false; + if (flipped) + { + CCLOG("cocos2d: WARNING: Image is flipped. Regenerate it using PVRTexTool"); + } + + if (! configuration->supportsNPOT() && + (static_cast(header->width) != ccNextPOT(header->width) + || static_cast(header->height) != ccNextPOT(header->height))) + { + CCLOG("cocos2d: ERROR: Loading an NPOT texture (%dx%d) but is not supported on this device", header->width, header->height); + return false; + } + + if (!testFormatForPvr2TCSupport(formatFlags)) + { + CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags); + return false; + } + + if (v2_pixel_formathash.find(formatFlags) == v2_pixel_formathash.end()) + { + CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags); + return false; + } + + auto it = Texture2D::getPixelFormatInfoMap().find(getDevicePixelFormat(v2_pixel_formathash.at(formatFlags))); + + if (it == Texture2D::getPixelFormatInfoMap().end()) + { + CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags); + return false; + } + + _renderFormat = it->first; + int bpp = it->second.bpp; + + //Reset num of mipmaps + _numberOfMipmaps = 0; + + //Get size of mipmap + _width = width = CC_SWAP_INT32_LITTLE_TO_HOST(header->width); + _height = height = CC_SWAP_INT32_LITTLE_TO_HOST(header->height); + + //Get ptr to where data starts.. + dataLength = CC_SWAP_INT32_LITTLE_TO_HOST(header->dataLength); + + //Move by size of header + _dataLen = dataLen - sizeof(PVRv2TexHeader); + _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); + memcpy(_data, (unsigned char*)data + sizeof(PVRv2TexHeader), _dataLen); + + // Calculate the data size for each texture level and respect the minimum number of blocks + while (dataOffset < dataLength) + { + switch (formatFlags) { + case PVR2TexturePixelFormat::PVRTC2BPP_RGBA: + if (!Configuration::getInstance()->supportsPVRTC()) + { + CCLOG("cocos2d: Hardware PVR decoder not present. Using software decoder"); + _unpack = true; + _mipmaps[_numberOfMipmaps].len = width*height*4; + _mipmaps[_numberOfMipmaps].address = new (std::nothrow) unsigned char[width*height*4]; + PVRTDecompressPVRTC(_data+dataOffset,width,height,_mipmaps[_numberOfMipmaps].address, true); + bpp = 2; + } + blockSize = 8 * 4; // Pixel by pixel block size for 2bpp + widthBlocks = width / 8; + heightBlocks = height / 4; + break; + case PVR2TexturePixelFormat::PVRTC4BPP_RGBA: + if (!Configuration::getInstance()->supportsPVRTC()) + { + CCLOG("cocos2d: Hardware PVR decoder not present. Using software decoder"); + _unpack = true; + _mipmaps[_numberOfMipmaps].len = width*height*4; + _mipmaps[_numberOfMipmaps].address = new (std::nothrow) unsigned char[width*height*4]; + PVRTDecompressPVRTC(_data+dataOffset,width,height,_mipmaps[_numberOfMipmaps].address, false); + bpp = 4; + } + blockSize = 4 * 4; // Pixel by pixel block size for 4bpp + widthBlocks = width / 4; + heightBlocks = height / 4; + break; + case PVR2TexturePixelFormat::BGRA8888: + if (Configuration::getInstance()->supportsBGRA8888() == false) + { + CCLOG("cocos2d: Image. BGRA8888 not supported on this device"); + return false; + } + default: + blockSize = 1; + widthBlocks = width; + heightBlocks = height; + break; + } + + // Clamp to minimum number of blocks + if (widthBlocks < 2) + { + widthBlocks = 2; + } + if (heightBlocks < 2) + { + heightBlocks = 2; + } + + dataSize = widthBlocks * heightBlocks * ((blockSize * bpp) / 8); + int packetLength = (dataLength - dataOffset); + packetLength = packetLength > dataSize ? dataSize : packetLength; + + //Make record to the mipmaps array and increment counter + if(!_unpack) + { + _mipmaps[_numberOfMipmaps].address = _data + dataOffset; + _mipmaps[_numberOfMipmaps].len = packetLength; + } + _numberOfMipmaps++; + + dataOffset += packetLength; + + //Update width and height to the next lower power of two + width = MAX(width >> 1, 1); + height = MAX(height >> 1, 1); + } + + if(_unpack) + { + _data = _mipmaps[0].address; + _dataLen = _mipmaps[0].len; + } + + return true; +} + +bool Image::initWithPVRv3Data(const unsigned char * data, ssize_t dataLen) +{ + if (static_cast(dataLen) < sizeof(PVRv3TexHeader)) + { + return false; + } + + const PVRv3TexHeader *header = static_cast(static_cast(data)); + + // validate version + if (CC_SWAP_INT32_BIG_TO_HOST(header->version) != 0x50565203) + { + CCLOG("cocos2d: WARNING: pvr file version mismatch"); + return false; + } + + // parse pixel format + PVR3TexturePixelFormat pixelFormat = static_cast(header->pixelFormat); + + if (!testFormatForPvr3TCSupport(pixelFormat)) + { + CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant", + static_cast(pixelFormat)); + return false; + } + + + if (v3_pixel_formathash.find(pixelFormat) == v3_pixel_formathash.end()) + { + CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant", + static_cast(pixelFormat)); + return false; + } + + auto it = Texture2D::getPixelFormatInfoMap().find(getDevicePixelFormat(v3_pixel_formathash.at(pixelFormat))); + + if (it == Texture2D::getPixelFormatInfoMap().end()) + { + CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant", + static_cast(pixelFormat)); + return false; + } + + _renderFormat = it->first; + int bpp = it->second.bpp; + + // flags + int flags = CC_SWAP_INT32_LITTLE_TO_HOST(header->flags); + + // PVRv3 specifies premultiply alpha in a flag -- should always respect this in PVRv3 files + if (flags & (unsigned int)PVR3TextureFlag::PremultipliedAlpha) + { + _hasPremultipliedAlpha = true; + } + else + { + _hasPremultipliedAlpha = false; + } + + // sizing + int width = CC_SWAP_INT32_LITTLE_TO_HOST(header->width); + int height = CC_SWAP_INT32_LITTLE_TO_HOST(header->height); + _width = width; + _height = height; + int dataOffset = 0, dataSize = 0; + int blockSize = 0, widthBlocks = 0, heightBlocks = 0; + + _dataLen = dataLen - (sizeof(PVRv3TexHeader) + header->metadataLength); + _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); + memcpy(_data, static_cast(data) + sizeof(PVRv3TexHeader) + header->metadataLength, _dataLen); + + _numberOfMipmaps = header->numberOfMipmaps; + CCASSERT(_numberOfMipmaps < MIPMAP_MAX, "Image: Maximum number of mimpaps reached. Increase the CC_MIPMAP_MAX value"); + + for (int i = 0; i < _numberOfMipmaps; i++) + { + switch ((PVR3TexturePixelFormat)pixelFormat) + { + case PVR3TexturePixelFormat::PVRTC2BPP_RGB : + case PVR3TexturePixelFormat::PVRTC2BPP_RGBA : + if (!Configuration::getInstance()->supportsPVRTC()) + { + CCLOG("cocos2d: Hardware PVR decoder not present. Using software decoder"); + _unpack = true; + _mipmaps[i].len = width*height*4; + _mipmaps[i].address = new (std::nothrow) unsigned char[width*height*4]; + PVRTDecompressPVRTC(_data+dataOffset,width,height,_mipmaps[i].address, true); + bpp = 2; + } + blockSize = 8 * 4; // Pixel by pixel block size for 2bpp + widthBlocks = width / 8; + heightBlocks = height / 4; + break; + case PVR3TexturePixelFormat::PVRTC4BPP_RGB : + case PVR3TexturePixelFormat::PVRTC4BPP_RGBA : + if (!Configuration::getInstance()->supportsPVRTC()) + { + CCLOG("cocos2d: Hardware PVR decoder not present. Using software decoder"); + _unpack = true; + _mipmaps[i].len = width*height*4; + _mipmaps[i].address = new (std::nothrow) unsigned char[width*height*4]; + PVRTDecompressPVRTC(_data+dataOffset,width,height,_mipmaps[i].address, false); + bpp = 4; + } + blockSize = 4 * 4; // Pixel by pixel block size for 4bpp + widthBlocks = width / 4; + heightBlocks = height / 4; + break; + case PVR3TexturePixelFormat::ETC1: + if (!Configuration::getInstance()->supportsETC()) + { + CCLOG("cocos2d: Hardware ETC1 decoder not present. Using software decoder"); + int bytePerPixel = 3; + unsigned int stride = width * bytePerPixel; + _unpack = true; + _mipmaps[i].len = width*height*bytePerPixel; + _mipmaps[i].address = new (std::nothrow) unsigned char[width*height*bytePerPixel]; + if (etc1_decode_image(static_cast(_data+dataOffset), static_cast(_mipmaps[i].address), width, height, bytePerPixel, stride) != 0) + { + return false; + } + } + blockSize = 4 * 4; // Pixel by pixel block size for 4bpp + widthBlocks = width / 4; + heightBlocks = height / 4; + break; + case PVR3TexturePixelFormat::BGRA8888: + if (! Configuration::getInstance()->supportsBGRA8888()) + { + CCLOG("cocos2d: Image. BGRA8888 not supported on this device"); + return false; + } + default: + blockSize = 1; + widthBlocks = width; + heightBlocks = height; + break; + } + + // Clamp to minimum number of blocks + if (widthBlocks < 2) + { + widthBlocks = 2; + } + if (heightBlocks < 2) + { + heightBlocks = 2; + } + + dataSize = widthBlocks * heightBlocks * ((blockSize * bpp) / 8); + auto packetLength = _dataLen - dataOffset; + packetLength = packetLength > dataSize ? dataSize : packetLength; + + if(!_unpack) + { + _mipmaps[i].address = _data + dataOffset; + _mipmaps[i].len = static_cast(packetLength); + } + + dataOffset += packetLength; + CCASSERT(dataOffset <= _dataLen, "Image: Invalid length"); + + + width = MAX(width >> 1, 1); + height = MAX(height >> 1, 1); + } + + if (_unpack) + { + _data = _mipmaps[0].address; + _dataLen = _mipmaps[0].len; + } + + return true; +} + +bool Image::initWithETCData(const unsigned char * data, ssize_t dataLen) +{ + const etc1_byte* header = static_cast(data); + + //check the data + if (! etc1_pkm_is_valid(header)) + { + return false; + } + + _width = etc1_pkm_get_width(header); + _height = etc1_pkm_get_height(header); + + if (0 == _width || 0 == _height) + { + return false; + } + + if (Configuration::getInstance()->supportsETC()) + { + //old opengl version has no define for GL_ETC1_RGB8_OES, add macro to make compiler happy. +#ifdef GL_ETC1_RGB8_OES + _renderFormat = Texture2D::PixelFormat::ETC; + _dataLen = dataLen - ETC_PKM_HEADER_SIZE; + _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); + memcpy(_data, static_cast(data) + ETC_PKM_HEADER_SIZE, _dataLen); + return true; +#endif + } + else + { + CCLOG("cocos2d: Hardware ETC1 decoder not present. Using software decoder"); + + //if it is not gles or device do not support ETC, decode texture by software + int bytePerPixel = 3; + unsigned int stride = _width * bytePerPixel; + _renderFormat = Texture2D::PixelFormat::RGB888; + + _dataLen = _width * _height * bytePerPixel; + _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); + + if (etc1_decode_image(static_cast(data) + ETC_PKM_HEADER_SIZE, static_cast(_data), _width, _height, bytePerPixel, stride) != 0) + { + _dataLen = 0; + if (_data != nullptr) + { + free(_data); + } + return false; + } + + return true; + } + return false; +} + +bool Image::initWithTGAData(tImageTGA* tgaData) +{ + bool ret = false; + + do + { + CC_BREAK_IF(tgaData == nullptr); + + // tgaLoadBuffer only support type 2, 3, 10 + if (2 == tgaData->type || 10 == tgaData->type) + { + // true color + // unsupported RGB555 + if (tgaData->pixelDepth == 16) + { + _renderFormat = Texture2D::PixelFormat::RGB5A1; + } + else if(tgaData->pixelDepth == 24) + { + _renderFormat = Texture2D::PixelFormat::RGB888; + } + else if(tgaData->pixelDepth == 32) + { + _renderFormat = Texture2D::PixelFormat::RGBA8888; + } + else + { + CCLOG("Image WARNING: unsupported true color tga data pixel format. FILE: %s", _filePath.c_str()); + break; + } + } + else if(3 == tgaData->type) + { + // gray + if (8 == tgaData->pixelDepth) + { + _renderFormat = Texture2D::PixelFormat::I8; + } + else + { + // actually this won't happen, if it happens, maybe the image file is not a tga + CCLOG("Image WARNING: unsupported gray tga data pixel format. FILE: %s", _filePath.c_str()); + break; + } + } + + _width = tgaData->width; + _height = tgaData->height; + _data = tgaData->imageData; + _dataLen = _width * _height * tgaData->pixelDepth / 8; + _fileType = Format::TGA; + + _hasPremultipliedAlpha = false; + ret = true; + + }while(false); + + if (ret) + { + if (FileUtils::getInstance()->getFileExtension(_filePath) != ".tga") + { + CCLOG("Image WARNING: the image file suffix is not tga, but parsed as a tga image file. FILE: %s", _filePath.c_str()); + } + } + else + { + if (tgaData && tgaData->imageData != nullptr) + { + free(tgaData->imageData); + _data = nullptr; + } + } + + return ret; +} + +bool Image::initWithPVRData(const unsigned char * data, ssize_t dataLen) +{ + return initWithPVRv2Data(data, dataLen) || initWithPVRv3Data(data, dataLen); +} + +bool Image::initWithRawData(const unsigned char * data, ssize_t dataLen, int width, int height, int bitsPerComponent, bool preMulti) +{ + bool ret = false; + do + { + CC_BREAK_IF(0 == width || 0 == height); + + _height = height; + _width = width; + _hasPremultipliedAlpha = preMulti; + _renderFormat = Texture2D::PixelFormat::RGBA8888; + + // only RGBA8888 supported + int bytesPerComponent = 4; + _dataLen = height * width * bytesPerComponent; + _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); + CC_BREAK_IF(! _data); + memcpy(_data, data, _dataLen); + + ret = true; + } while (0); + + return ret; +} + + +#if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) +bool Image::saveToFile(const std::string& filename, bool isToRGB) +{ + //only support for Texture2D::PixelFormat::RGB888 or Texture2D::PixelFormat::RGBA8888 uncompressed data + if (isCompressed() || (_renderFormat != Texture2D::PixelFormat::RGB888 && _renderFormat != Texture2D::PixelFormat::RGBA8888)) + { + CCLOG("cocos2d: Image: saveToFile is only support for Texture2D::PixelFormat::RGB888 or Texture2D::PixelFormat::RGBA8888 uncompressed data for now"); + return false; + } + + std::string fileExtension = FileUtils::getInstance()->getFileExtension(filename); + + if (fileExtension == ".png") + { + return saveImageToPNG(filename, isToRGB); + } + else if (fileExtension == ".jpg") + { + return saveImageToJPG(filename); + } + else + { + CCLOG("cocos2d: Image: saveToFile no support file extension(only .png or .jpg) for file: %s", filename.c_str()); + return false; + } +} +#endif // (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) + +bool Image::saveImageToPNG(const std::string& filePath, bool isToRGB) +{ +#if CC_USE_WIC + return encodeWithWIC(filePath, isToRGB, GUID_ContainerFormatPng); +#elif CC_USE_PNG + bool ret = false; + do + { + FILE *fp; + png_structp png_ptr; + png_infop info_ptr; + png_colorp palette; + png_bytep *row_pointers; + + fp = fopen(FileUtils::getInstance()->getSuitableFOpen(filePath).c_str(), "wb"); + CC_BREAK_IF(nullptr == fp); + + png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); + + if (nullptr == png_ptr) + { + fclose(fp); + break; + } + + info_ptr = png_create_info_struct(png_ptr); + if (nullptr == info_ptr) + { + fclose(fp); + png_destroy_write_struct(&png_ptr, nullptr); + break; + } +#if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA && CC_TARGET_PLATFORM != CC_PLATFORM_NACL) + if (setjmp(png_jmpbuf(png_ptr))) + { + fclose(fp); + png_destroy_write_struct(&png_ptr, &info_ptr); + break; + } +#endif + png_init_io(png_ptr, fp); + + if (!isToRGB && hasAlpha()) + { + png_set_IHDR(png_ptr, info_ptr, _width, _height, 8, PNG_COLOR_TYPE_RGB_ALPHA, + PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); + } + else + { + png_set_IHDR(png_ptr, info_ptr, _width, _height, 8, PNG_COLOR_TYPE_RGB, + PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); + } + + palette = (png_colorp)png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH * sizeof (png_color)); + png_set_PLTE(png_ptr, info_ptr, palette, PNG_MAX_PALETTE_LENGTH); + + png_write_info(png_ptr, info_ptr); + + png_set_packing(png_ptr); + + row_pointers = (png_bytep *)malloc(_height * sizeof(png_bytep)); + if(row_pointers == nullptr) + { + fclose(fp); + png_destroy_write_struct(&png_ptr, &info_ptr); + break; + } + + if (!hasAlpha()) + { + for (int i = 0; i < (int)_height; i++) + { + row_pointers[i] = (png_bytep)_data + i * _width * 3; + } + + png_write_image(png_ptr, row_pointers); + + free(row_pointers); + row_pointers = nullptr; + } + else + { + if (isToRGB) + { + unsigned char *tempData = static_cast(malloc(_width * _height * 3 * sizeof(unsigned char))); + if (nullptr == tempData) + { + fclose(fp); + png_destroy_write_struct(&png_ptr, &info_ptr); + + free(row_pointers); + row_pointers = nullptr; + break; + } + + for (int i = 0; i < _height; ++i) + { + for (int j = 0; j < _width; ++j) + { + tempData[(i * _width + j) * 3] = _data[(i * _width + j) * 4]; + tempData[(i * _width + j) * 3 + 1] = _data[(i * _width + j) * 4 + 1]; + tempData[(i * _width + j) * 3 + 2] = _data[(i * _width + j) * 4 + 2]; + } + } + + for (int i = 0; i < (int)_height; i++) + { + row_pointers[i] = (png_bytep)tempData + i * _width * 3; + } + + png_write_image(png_ptr, row_pointers); + + free(row_pointers); + row_pointers = nullptr; + + if (tempData != nullptr) + { + free(tempData); + } + } + else + { + for (int i = 0; i < (int)_height; i++) + { + row_pointers[i] = (png_bytep)_data + i * _width * 4; + } + + png_write_image(png_ptr, row_pointers); + + free(row_pointers); + row_pointers = nullptr; + } + } + + png_write_end(png_ptr, info_ptr); + + png_free(png_ptr, palette); + palette = nullptr; + + png_destroy_write_struct(&png_ptr, &info_ptr); + + fclose(fp); + + ret = true; + } while (0); + return ret; +#else + CCLOG("png is not enabled, please enable it in ccConfig.h"); + return false; +#endif // CC_USE_PNG +} + +bool Image::saveImageToJPG(const std::string& filePath) +{ +#if CC_USE_WIC + return encodeWithWIC(filePath, false, GUID_ContainerFormatJpeg); +#elif CC_USE_JPEG + bool ret = false; + do + { + struct jpeg_compress_struct cinfo; + struct jpeg_error_mgr jerr; + FILE * outfile; /* target file */ + JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */ + int row_stride; /* physical row width in image buffer */ + + cinfo.err = jpeg_std_error(&jerr); + /* Now we can initialize the JPEG compression object. */ + jpeg_create_compress(&cinfo); + + CC_BREAK_IF((outfile = fopen(FileUtils::getInstance()->getSuitableFOpen(filePath).c_str(), "wb")) == nullptr); + + jpeg_stdio_dest(&cinfo, outfile); + + cinfo.image_width = _width; /* image width and height, in pixels */ + cinfo.image_height = _height; + cinfo.input_components = 3; /* # of color components per pixel */ + cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ + + jpeg_set_defaults(&cinfo); + jpeg_set_quality(&cinfo, 90, TRUE); + + jpeg_start_compress(&cinfo, TRUE); + + row_stride = _width * 3; /* JSAMPLEs per row in image_buffer */ + + if (hasAlpha()) + { + unsigned char *tempData = static_cast(malloc(_width * _height * 3 * sizeof(unsigned char))); + if (nullptr == tempData) + { + jpeg_finish_compress(&cinfo); + jpeg_destroy_compress(&cinfo); + fclose(outfile); + break; + } + + for (int i = 0; i < _height; ++i) + { + for (int j = 0; j < _width; ++j) + + { + tempData[(i * _width + j) * 3] = _data[(i * _width + j) * 4]; + tempData[(i * _width + j) * 3 + 1] = _data[(i * _width + j) * 4 + 1]; + tempData[(i * _width + j) * 3 + 2] = _data[(i * _width + j) * 4 + 2]; + } + } + + while (cinfo.next_scanline < cinfo.image_height) + { + row_pointer[0] = & tempData[cinfo.next_scanline * row_stride]; + (void) jpeg_write_scanlines(&cinfo, row_pointer, 1); + } + + if (tempData != nullptr) + { + free(tempData); + } + } + else + { + while (cinfo.next_scanline < cinfo.image_height) { + row_pointer[0] = & _data[cinfo.next_scanline * row_stride]; + (void) jpeg_write_scanlines(&cinfo, row_pointer, 1); + } + } + + jpeg_finish_compress(&cinfo); + fclose(outfile); + jpeg_destroy_compress(&cinfo); + + ret = true; + } while (0); + return ret; +#else + CCLOG("jpeg is not enabled, please enable it in ccConfig.h"); + return false; +#endif // CC_USE_JPEG +} + +void Image::premultipliedAlpha() +{ + if (PNG_PREMULTIPLIED_ALPHA_ENABLED && _renderFormat == Texture2D::PixelFormat::RGBA8888) + { + unsigned int* fourBytes = (unsigned int*)_data; + for(int i = 0; i < _width * _height; i++) + { + unsigned char* p = _data + i * 4; + fourBytes[i] = CC_RGB_PREMULTIPLY_ALPHA(p[0], p[1], p[2], p[3]); + } + + _hasPremultipliedAlpha = true; + } + else + { + _hasPremultipliedAlpha = false; + return; + } } diff --git a/native/cocos/platform/CCImage.h b/native/cocos/platform/CCImage.h index 7517cfc2ae..78b011b21c 100644 --- a/native/cocos/platform/CCImage.h +++ b/native/cocos/platform/CCImage.h @@ -96,6 +96,21 @@ public: UNKNOWN }; + /** + * Enables or disables premultiplied alpha for PNG files. + * + * @param enabled (default: true) + */ + static void setPNGPremultipliedAlphaEnabled(bool enabled) { PNG_PREMULTIPLIED_ALPHA_ENABLED = enabled; } + + /** treats (or not) PVR files as if they have alpha premultiplied. + Since it is impossible to know at runtime if the PVR images have the alpha channel premultiplied, it is + possible load them as if they have (or not) the alpha channel premultiplied. + + By default it is disabled. + */ + static void setPVRImagesHavePremultipliedAlpha(bool haveAlphaPremultiplied); + /** @brief Load the image from the specified path. @param path the absolute file path. @@ -138,21 +153,6 @@ public: */ bool saveToFile(const std::string &filename, bool isToRGB = true); - /** - * Enables or disables premultiplied alpha for PNG files. - * - * @param enabled (default: true) - */ - static void setPNGPremultipliedAlphaEnabled(bool enabled) { PNG_PREMULTIPLIED_ALPHA_ENABLED = enabled; } - - /** treats (or not) PVR files as if they have alpha premultiplied. - Since it is impossible to know at runtime if the PVR images have the alpha channel premultiplied, it is - possible load them as if they have (or not) the alpha channel premultiplied. - - By default it is disabled. - */ - static void setPVRImagesHavePremultipliedAlpha(bool haveAlphaPremultiplied); - protected: bool initWithJpgData(const unsigned char * data, ssize_t dataLen); bool initWithPngData(const unsigned char * data, ssize_t dataLen); @@ -176,9 +176,10 @@ protected: It's same as define but it respects namespaces */ static const int MIPMAP_MAX = 16; - + /** + @brief Determine whether we premultiply alpha for png files. + */ static bool PNG_PREMULTIPLIED_ALPHA_ENABLED; - unsigned char *_data; ssize_t _dataLen; int _width; @@ -221,4 +222,3 @@ NS_CC_END /// @endcond #endif // __CC_IMAGE_H__ - diff --git a/native/cocos/platform/CCPlatformConfig.h b/native/cocos/platform/CCPlatformConfig.h index 53b65eb0bf..efb03745b4 100644 --- a/native/cocos/platform/CCPlatformConfig.h +++ b/native/cocos/platform/CCPlatformConfig.h @@ -56,15 +56,10 @@ THE SOFTWARE. // Determine target platform by compile environment macro. #define CC_TARGET_PLATFORM CC_PLATFORM_UNKNOWN -// android -#if defined(ANDROID) - #undef CC_TARGET_PLATFORM - #define CC_TARGET_PLATFORM CC_PLATFORM_ANDROID // Apple: Mac and iOS -#elif defined(__APPLE__) +#if defined(__APPLE__) && !defined(ANDROID) // exclude android for binding generator. #include - //// TARGET_OS_IPHONE inlcudes TARGET_OS_IOS TARGET_OS_TV and TARGET_OS_WATCH. see TargetConditionals.h - #if TARGET_OS_IPHONE + #if TARGET_OS_IPHONE // TARGET_OS_IPHONE includes TARGET_OS_IOS TARGET_OS_TV and TARGET_OS_WATCH. see TargetConditionals.h #undef CC_TARGET_PLATFORM #define CC_TARGET_PLATFORM CC_PLATFORM_IOS #elif TARGET_OS_MAC @@ -73,6 +68,12 @@ THE SOFTWARE. #endif #endif +// android +#if defined(ANDROID) + #undef CC_TARGET_PLATFORM + #define CC_TARGET_PLATFORM CC_PLATFORM_ANDROID +#endif + // win32 #if defined(_WIN32) && defined(_WINDOWS) #undef CC_TARGET_PLATFORM @@ -150,4 +151,3 @@ THE SOFTWARE. /// @endcond #endif // __BASE_CC_PLATFORM_CONFIG_H__ - diff --git a/native/cocos/platform/CCPlatformDefine.h b/native/cocos/platform/CCPlatformDefine.h index c588984c15..27b6a02c5a 100644 --- a/native/cocos/platform/CCPlatformDefine.h +++ b/native/cocos/platform/CCPlatformDefine.h @@ -45,4 +45,3 @@ THE SOFTWARE. /// @endcond #endif /* __PLATFORM_CCPLATFORMDEFINE_H__*/ - diff --git a/native/cocos/platform/CCPlatformMacros.h b/native/cocos/platform/CCPlatformMacros.h index fbd72ae695..deded5b818 100644 --- a/native/cocos/platform/CCPlatformMacros.h +++ b/native/cocos/platform/CCPlatformMacros.h @@ -107,11 +107,11 @@ static __TYPE__* create() \ */ #define CC_PROPERTY_READONLY(varType, varName, funName)\ protected: varType varName;\ -public: virtual varType get##funName() const; +public: virtual varType get##funName(void) const; #define CC_PROPERTY_READONLY_PASS_BY_REF(varType, varName, funName)\ protected: varType varName;\ -public: virtual const varType& get##funName() const; +public: virtual const varType& get##funName(void) const; /** @def CC_PROPERTY * It is used to declare a protected variable. @@ -127,12 +127,12 @@ public: virtual const varType& get##funName() const; */ #define CC_PROPERTY(varType, varName, funName)\ protected: varType varName;\ -public: virtual varType get##funName();\ +public: virtual varType get##funName(void) const;\ public: virtual void set##funName(varType var); #define CC_PROPERTY_PASS_BY_REF(varType, varName, funName)\ protected: varType varName;\ -public: virtual const varType& get##funName() const;\ +public: virtual const varType& get##funName(void) const;\ public: virtual void set##funName(const varType& var); /** @def CC_SYNTHESIZE_READONLY @@ -147,11 +147,11 @@ public: virtual void set##funName(const varType& var); */ #define CC_SYNTHESIZE_READONLY(varType, varName, funName)\ protected: varType varName;\ -public: virtual varType get##funName() const { return varName; } +public: virtual varType get##funName(void) const { return varName; } #define CC_SYNTHESIZE_READONLY_PASS_BY_REF(varType, varName, funName)\ protected: varType varName;\ -public: virtual const varType& get##funName() const { return varName; } +public: virtual const varType& get##funName(void) const { return varName; } /** @def CC_SYNTHESIZE * It is used to declare a protected variable. @@ -167,17 +167,17 @@ public: virtual const varType& get##funName() const { return varName; } */ #define CC_SYNTHESIZE(varType, varName, funName)\ protected: varType varName;\ -public: virtual varType get##funName() const { return varName; }\ +public: virtual varType get##funName(void) const { return varName; }\ public: virtual void set##funName(varType var){ varName = var; } #define CC_SYNTHESIZE_PASS_BY_REF(varType, varName, funName)\ protected: varType varName;\ -public: virtual const varType& get##funName() const { return varName; }\ +public: virtual const varType& get##funName(void) const { return varName; }\ public: virtual void set##funName(const varType& var){ varName = var; } #define CC_SYNTHESIZE_RETAIN(varType, varName, funName) \ private: varType varName; \ -public: virtual varType get##funName() const { return varName; } \ +public: virtual varType get##funName(void) const { return varName; } \ public: virtual void set##funName(varType var) \ { \ if (varName != var) \ @@ -327,4 +327,3 @@ public: virtual void set##funName(varType var) \ #endif #endif // __CC_PLATFORM_MACROS_H__ - diff --git a/native/cocos/platform/CCSAXParser.cpp b/native/cocos/platform/CCSAXParser.cpp index 424e2b9d1c..de7c1dbe98 100644 --- a/native/cocos/platform/CCSAXParser.cpp +++ b/native/cocos/platform/CCSAXParser.cpp @@ -92,7 +92,7 @@ SAXParser::SAXParser() _delegator = nullptr; } -SAXParser::~SAXParser() +SAXParser::~SAXParser(void) { } diff --git a/native/cocos/platform/CCSAXParser.h b/native/cocos/platform/CCSAXParser.h index 3689aa440c..e388b80b1b 100644 --- a/native/cocos/platform/CCSAXParser.h +++ b/native/cocos/platform/CCSAXParser.h @@ -73,7 +73,7 @@ public: * @js NA * @lua NA */ - ~SAXParser(); + ~SAXParser(void); /** * @js NA * @lua NA @@ -118,4 +118,3 @@ NS_CC_END /// @endcond #endif //__CCSAXPARSER_H__ - diff --git a/native/cocos/platform/CCStdC.h b/native/cocos/platform/CCStdC.h index 7434ed5526..c6a7ae176e 100644 --- a/native/cocos/platform/CCStdC.h +++ b/native/cocos/platform/CCStdC.h @@ -43,4 +43,3 @@ THE SOFTWARE. #endif #endif /* __PLATFORM_CCSTDC_H__*/ - diff --git a/native/cocos/platform/android/Android.mk b/native/cocos/platform/android/Android.mk index ceca429a99..9bc626935c 100644 --- a/native/cocos/platform/android/Android.mk +++ b/native/cocos/platform/android/Android.mk @@ -20,8 +20,6 @@ jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp \ jni/JniHelper.cpp \ jni/TouchesJni.cpp -LOCAL_WHOLE_STATIC_LIBRARIES := cpufeatures - LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) LOCAL_C_INCLUDES := $(LOCAL_PATH) \ diff --git a/native/cocos/platform/android/CCApplication-android.cpp b/native/cocos/platform/android/CCApplication-android.cpp index 3db056c262..b785dad723 100644 --- a/native/cocos/platform/android/CCApplication-android.cpp +++ b/native/cocos/platform/android/CCApplication-android.cpp @@ -27,15 +27,14 @@ THE SOFTWARE. #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID #include "platform/android/jni/JniHelper.h" -#include "CCApplication.h" +#include "platform/CCApplication.h" #include "base/CCDirector.h" #include #include #include #define LOG_TAG "CCApplication_android Debug" -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) -#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) +#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) // FIXME: 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. @@ -45,7 +44,7 @@ extern "C" size_t __ctype_get_mb_cur_max(void) { } #endif -#define HELPER_JAVA_CLASS "org/cocos2dx/lib/Cocos2dxHelper" +static const std::string helperClassName = "org/cocos2dx/lib/Cocos2dxHelper"; NS_CC_BEGIN @@ -60,6 +59,7 @@ Application::Application() Application::~Application() { + CCAssert(this == sm_pSharedApplication, ""); sm_pSharedApplication = nullptr; } @@ -99,7 +99,7 @@ void Application::destroyInstance() const char * Application::getCurrentLanguageCode() { static char code[3]={0}; - std::string language = JniHelper::callStaticStringMethod(HELPER_JAVA_CLASS, "getCurrentLanguage"); + std::string language = JniHelper::callStaticStringMethod(helperClassName, "getCurrentLanguage"); strncpy(code, language.c_str(), 2); code[2]='\0'; return code; @@ -107,7 +107,7 @@ const char * Application::getCurrentLanguageCode() LanguageType Application::getCurrentLanguage() { - std::string languageName = JniHelper::callStaticStringMethod(HELPER_JAVA_CLASS, "getCurrentLanguage"); + std::string languageName = JniHelper::callStaticStringMethod(helperClassName, "getCurrentLanguage"); const char* pLanguageName = languageName.c_str(); LanguageType ret = LanguageType::ENGLISH; @@ -195,9 +195,14 @@ Application::Platform Application::getTargetPlatform() return Platform::OS_ANDROID; } +std::string Application::getVersion() +{ + return JniHelper::callStaticStringMethod(helperClassName, "getVersion"); +} + bool Application::openURL(const std::string &url) { - return JniHelper::callStaticBooleanMethod(HELPER_JAVA_CLASS, "openURL", url); + return JniHelper::callStaticBooleanMethod(helperClassName, "openURL", url); } void Application::applicationScreenSizeChanged(int newWidth, int newHeight) { @@ -207,4 +212,3 @@ void Application::applicationScreenSizeChanged(int newWidth, int newHeight) { NS_CC_END #endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID - diff --git a/native/cocos/platform/android/CCApplication-android.h b/native/cocos/platform/android/CCApplication-android.h index d5680aced6..ef080397e0 100644 --- a/native/cocos/platform/android/CCApplication-android.h +++ b/native/cocos/platform/android/CCApplication-android.h @@ -51,7 +51,7 @@ public: @brief Callback by Director to limit FPS. @param interval The time, expressed in seconds, between current frame and next. */ - void setAnimationInterval(float interval); + void setAnimationInterval(float interval) override; /** @brief Run the message loop. @@ -70,25 +70,30 @@ public: @brief Get current language config @return Current language config */ - virtual LanguageType getCurrentLanguage(); + virtual LanguageType getCurrentLanguage() override; /** @brief Get current language iso 639-1 code @return Current language iso 639-1 code */ - virtual const char * getCurrentLanguageCode(); + virtual const char * getCurrentLanguageCode() override; /** @brief Get target platform */ - virtual Platform getTargetPlatform(); + virtual Platform getTargetPlatform() override; + + /** + @brief Get application version. + */ + virtual std::string getVersion() override; /** @brief Open url in default browser @param String with url to open. @return true if the resource located by the URL was successfully opened; otherwise false. */ - virtual bool openURL(const std::string &url); + virtual bool openURL(const std::string &url) override; /** @brief This function will be called when the application screen size is changed. @@ -106,4 +111,3 @@ NS_CC_END #endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID #endif // __CC_APPLICATION_ANDROID_H__ - diff --git a/native/cocos/platform/android/CCDevice-android.cpp b/native/cocos/platform/android/CCDevice-android.cpp index c19a92f4b6..b40636e186 100644 --- a/native/cocos/platform/android/CCDevice-android.cpp +++ b/native/cocos/platform/android/CCDevice-android.cpp @@ -31,12 +31,10 @@ THE SOFTWARE. #include #include #include "base/ccTypes.h" -#include "base/ccUTF8.h" #include "platform/android/jni/JniHelper.h" #include "platform/CCFileUtils.h" -#define helperClassName "org/cocos2dx/lib/Cocos2dxHelper" -#define LOGD(...) __android_log_print(ANDROID_LOG_ERROR,"",__VA_ARGS__) +static const std::string helperClassName = "org/cocos2dx/lib/Cocos2dxHelper"; NS_CC_BEGIN @@ -82,34 +80,32 @@ public: { } - bool getBitmapFromJavaShadowStroke( const std::string& text, + bool getBitmapFromJavaShadowStroke( const char *text, int nWidth, int nHeight, Device::TextAlign eAlignMask, const FontDefinition& textDefinition ) { - JniMethodInfo methodInfo; - if (! JniHelper::getStaticMethodInfo(methodInfo, "org/cocos2dx/lib/Cocos2dxBitmap", "createTextBitmapShadowStroke", - "(Ljava/lang/String;Ljava/lang/String;IIIIIIIIZIIIIFZI)Z")) - { - CCLOG("%s %d: error to get methodInfo", __FILE__, __LINE__); - return false; - } + JniMethodInfo methodInfo; + if (! JniHelper::getStaticMethodInfo(methodInfo, "org/cocos2dx/lib/Cocos2dxBitmap", "createTextBitmapShadowStroke", + "([BLjava/lang/String;IIIIIIIIZFFFFZIIIIFZI)Z")) + { + CCLOG("%s %d: error to get methodInfo", __FILE__, __LINE__); + return false; + } // Do a full lookup for the font path using FileUtils in case the given font name is a relative path to a font file asset, // or the path has been mapped to a different location in the app package: - std::string fullPathOrFontName = textDefinition._fontName; - if(FileUtils::getInstance()->isFileExist(fullPathOrFontName)) - { - fullPathOrFontName = FileUtils::getInstance()->fullPathForFilename(textDefinition._fontName); - // If the path name returned includes the 'assets' dir then that needs to be removed, because the android.content.Context - // requires this portion of the path to be omitted for assets inside the app package. - if (fullPathOrFontName.find("assets/") == 0) - { - fullPathOrFontName = fullPathOrFontName.substr(strlen("assets/")); // Chop out the 'assets/' portion of the path. - } - } - + std::string fullPathOrFontName = textDefinition._fontName; + if(FileUtils::getInstance()->isFileExist(fullPathOrFontName)) { + fullPathOrFontName = FileUtils::getInstance()->fullPathForFilename(textDefinition._fontName); + // If the path name returned includes the 'assets' dir then that needs to be removed, because the android.content.Context + // requires this portion of the path to be omitted for assets inside the app package. + if (fullPathOrFontName.find("assets/") == 0) + { + fullPathOrFontName = fullPathOrFontName.substr(strlen("assets/")); // Chop out the 'assets/' portion of the path. + } + } /**create bitmap * this method call Cococs2dx.createBitmap()(java code) to create the bitmap, the java code @@ -117,28 +113,29 @@ public: * and data. * use this approach to decrease the jni call number */ - auto jstrText = JniHelper::newStringUTFJNI(methodInfo.env, text); + int count = strlen(text); + jbyteArray strArray = methodInfo.env->NewByteArray(count); + methodInfo.env->SetByteArrayRegion(strArray, 0, count, reinterpret_cast(text)); jstring jstrFont = methodInfo.env->NewStringUTF(fullPathOrFontName.c_str()); - bool ret = true; - if(!methodInfo.env->CallStaticBooleanMethod(methodInfo.classID, methodInfo.methodID, jstrText, - jstrFont, textDefinition._fontSize, - textDefinition._fontFillColor.r, textDefinition._fontFillColor.g, - textDefinition._fontFillColor.b, textDefinition._fontAlpha, - eAlignMask, nWidth, nHeight, - textDefinition._stroke._strokeEnabled, - textDefinition._stroke._strokeColor.r, textDefinition._stroke._strokeColor.g, - textDefinition._stroke._strokeColor.b, textDefinition._stroke._strokeAlpha, - textDefinition._stroke._strokeSize, + + if(!methodInfo.env->CallStaticBooleanMethod(methodInfo.classID, methodInfo.methodID, strArray, + jstrFont, textDefinition._fontSize, textDefinition._fontFillColor.r, textDefinition._fontFillColor.g, + textDefinition._fontFillColor.b, textDefinition._fontAlpha, + eAlignMask, nWidth, nHeight, + textDefinition._shadow._shadowEnabled, textDefinition._shadow._shadowOffset.width, -textDefinition._shadow._shadowOffset.height, + textDefinition._shadow._shadowBlur, textDefinition._shadow._shadowOpacity, + textDefinition._stroke._strokeEnabled, textDefinition._stroke._strokeColor.r, textDefinition._stroke._strokeColor.g, + textDefinition._stroke._strokeColor.b, textDefinition._stroke._strokeAlpha, textDefinition._stroke._strokeSize, textDefinition._enableWrap, textDefinition._overflow)) { - ret = false; + return false; } - methodInfo.env->DeleteLocalRef(jstrText); + methodInfo.env->DeleteLocalRef(strArray); methodInfo.env->DeleteLocalRef(jstrFont); methodInfo.env->DeleteLocalRef(methodInfo.classID); - return ret; + return true; } public: @@ -153,7 +150,7 @@ static BitmapDC& sharedBitmapDC() return s_BmpDC; } -Data Device::getTextureDataForText(const std::string& text, const FontDefinition& textDefinition, TextAlign align, int &width, int &height, bool& hasPremultipliedAlpha) +Data Device::getTextureDataForText(const char * text, const FontDefinition& textDefinition, TextAlign align, int &width, int &height, bool& hasPremultipliedAlpha) { Data ret; do @@ -204,4 +201,3 @@ extern "C" env->GetByteArrayRegion(pixels, 0, size, (jbyte*)bitmapDC._data); } }; - diff --git a/native/cocos/platform/android/CCFileUtils-android.cpp b/native/cocos/platform/android/CCFileUtils-android.cpp index 60e98c5b21..69a926602c 100644 --- a/native/cocos/platform/android/CCFileUtils-android.cpp +++ b/native/cocos/platform/android/CCFileUtils-android.cpp @@ -26,22 +26,28 @@ THE SOFTWARE. #include "platform/CCPlatformConfig.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID -#include "CCFileUtils-android.h" +#include "platform/android/CCFileUtils-android.h" #include "platform/CCCommon.h" #include "platform/android/jni/JniHelper.h" +#include "platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h" #include "android/asset_manager.h" #include "android/asset_manager_jni.h" +#include "base/ZipUtils.h" #include #include -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, "cocos2d-x FileUtils-android" ,__VA_ARGS__) -#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, "cocos2d-x FileUtils-android", __VA_ARGS__) +#define LOG_TAG "CCFileUtils-android.cpp" +#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) -//using namespace std; +#define ASSETS_FOLDER_NAME "assets/" +#define ASSETS_FOLDER_NAME_LENGTH 7 + +using namespace std; NS_CC_BEGIN AAssetManager* FileUtilsAndroid::assetmanager = nullptr; +ZipFile* FileUtilsAndroid::obbfile = nullptr; void FileUtilsAndroid::setassetmanager(AAssetManager* a) { if (nullptr == a) { @@ -56,8 +62,8 @@ FileUtils* FileUtils::getInstance() { if (s_sharedFileUtils == nullptr) { - s_sharedFileUtils = new (std::nothrow) FileUtilsAndroid(); - if(!s_sharedFileUtils->init()) + s_sharedFileUtils = new FileUtilsAndroid(); + if (!s_sharedFileUtils->init()) { delete s_sharedFileUtils; s_sharedFileUtils = nullptr; @@ -73,11 +79,22 @@ FileUtilsAndroid::FileUtilsAndroid() FileUtilsAndroid::~FileUtilsAndroid() { + if (obbfile) + { + delete obbfile; + obbfile = nullptr; + } } bool FileUtilsAndroid::init() { - _defaultResRootPath = "assets/"; + _defaultResRootPath = ASSETS_FOLDER_NAME; + + std::string assetsPath(getApkPath()); + if (assetsPath.find("/obb/") != std::string::npos) + { + obbfile = new ZipFile(assetsPath); + } return FileUtils::init(); } @@ -149,9 +166,14 @@ bool FileUtilsAndroid::isFileExistInternal(const std::string& strFilePath) const const char* s = strFilePath.c_str(); // Found "assets/" at the beginning of the path and we don't want it - if (strFilePath.find(_defaultResRootPath) == 0) s += strlen("assets/"); - - if (FileUtilsAndroid::assetmanager) { + if (strFilePath.find(_defaultResRootPath) == 0) s += _defaultResRootPath.length(); + + if (obbfile && obbfile->fileExists(s)) + { + bFound = true; + } + else if (FileUtilsAndroid::assetmanager) + { AAsset* aa = AAssetManager_open(FileUtilsAndroid::assetmanager, s, AASSET_MODE_UNKNOWN); if (aa) { @@ -165,7 +187,7 @@ bool FileUtilsAndroid::isFileExistInternal(const std::string& strFilePath) const else { FILE *fp = fopen(strFilePath.c_str(), "r"); - if(fp) + if (fp) { bFound = true; fclose(fp); @@ -182,10 +204,7 @@ bool FileUtilsAndroid::isDirectoryExistInternal(const std::string& dirPath) cons } const char* s = dirPath.c_str(); - bool startWithAssets = (dirPath.find("assets/") == 0); - int lenOfAssets = 7; - - std::string tmpStr; + // find absolute path in flash memory if (s[0] == '/') { @@ -196,23 +215,26 @@ bool FileUtilsAndroid::isDirectoryExistInternal(const std::string& dirPath) cons return S_ISDIR(st.st_mode); } } - - // find it in apk's assets dir - // Found "assets/" at the beginning of the path and we don't want it - CCLOG("find in apk dirPath(%s)", s); - if (startWithAssets) + else { - s += lenOfAssets; - } - if (FileUtilsAndroid::assetmanager) - { - AAssetDir* aa = AAssetManager_openDir(FileUtilsAndroid::assetmanager, s); - if (aa && AAssetDir_getNextFileName(aa)) + // find it in apk's assets dir + // Found "assets/" at the beginning of the path and we don't want it + CCLOG("find in apk dirPath(%s)", s); + if (dirPath.find(ASSETS_FOLDER_NAME) == 0) { - AAssetDir_close(aa); - return true; + s += ASSETS_FOLDER_NAME_LENGTH; + } + if (FileUtilsAndroid::assetmanager) + { + AAssetDir* aa = AAssetManager_openDir(FileUtilsAndroid::assetmanager, s); + if (aa && AAssetDir_getNextFileName(aa)) + { + AAssetDir_close(aa); + return true; + } } } + return false; } @@ -229,229 +251,64 @@ bool FileUtilsAndroid::isAbsolutePath(const std::string& strPath) const return false; } -Data FileUtilsAndroid::getData(const std::string& filename, bool forString) +FileUtils::Status FileUtilsAndroid::getContents(const std::string& filename, ResizableBuffer* buffer) { + static const std::string apkprefix("assets/"); if (filename.empty()) + return FileUtils::Status::NotExists; + + string fullPath = fullPathForFilename(filename); + + if (fullPath[0] == '/') + return FileUtils::getContents(fullPath, buffer); + + string relativePath = string(); + size_t position = fullPath.find(apkprefix); + if (0 == position) { + // "assets/" is at the beginning of the path and we don't want it + relativePath += fullPath.substr(apkprefix.size()); + } else { + relativePath = fullPath; + } + + if (obbfile) { - return Data::Null; + if (obbfile->getFileData(relativePath, buffer)) + return FileUtils::Status::OK; } - std::string fullPath = fullPathForFilename(filename); - if(fullPath.empty()) - { - LOGD("Get data from file(%s) failed!", filename.c_str()); - return Data::Null; + if (nullptr == assetmanager) { + LOGD("... FileUtilsAndroid::assetmanager is nullptr"); + return FileUtils::Status::NotInitialized; } - unsigned char* data = nullptr; - ssize_t size = 0; - - if (fullPath[0] != '/') - { - if (nullptr == FileUtilsAndroid::assetmanager) { - LOGD("FileUtilsAndroid::getData error:assetmanager is nullptr"); - return Data::Null; - } - - std::string relativePath = std::string(); - - size_t position = fullPath.find("assets/"); - if (0 == position) { - // "assets/" is at the beginning of the path and we don't want it - relativePath += fullPath.substr(strlen("assets/")); - } else { - relativePath += fullPath; - } - CCLOGINFO("relative path = %s", relativePath.c_str()); - - // read asset data - AAsset* asset = AAssetManager_open(FileUtilsAndroid::assetmanager, - relativePath.c_str(), - AASSET_MODE_UNKNOWN); - if (nullptr == asset) { - LOGD("asset is nullptr,%s", filename.c_str()); - return Data::Null; - } - - off_t fileSize = AAsset_getLength(asset); - - if (forString) - { - data = (unsigned char*) malloc(fileSize + 1); - if (data) - data[fileSize] = '\0'; - } - else - { - data = (unsigned char*) malloc(fileSize); - } - if (data) - { - int bytesread = AAsset_read(asset, (void*)data, fileSize); - size = bytesread; - } - - AAsset_close(asset); - } - else - { - do - { - // read rrom other path than user set it - //CCLOG("GETTING FILE ABSOLUTE DATA: %s", filename); - const char* mode = nullptr; - if (forString) - mode = "rt"; - else - mode = "rb"; - - FILE *fp = fopen(fullPath.c_str(), mode); - CC_BREAK_IF(!fp); - - long fileSize; - fseek(fp,0,SEEK_END); - fileSize = ftell(fp); - fseek(fp,0,SEEK_SET); - if (forString) - { - data = (unsigned char*) malloc(fileSize + 1); - if (data) - data[fileSize] = '\0'; - } - else - { - data = (unsigned char*) malloc(fileSize); - } - - if (data) - { - fileSize = fread(data,sizeof(unsigned char), fileSize,fp); - } - - fclose(fp); - - size = fileSize; - } while (0); + AAsset* asset = AAssetManager_open(assetmanager, relativePath.data(), AASSET_MODE_UNKNOWN); + if (nullptr == asset) { + LOGD("asset is nullptr"); + return FileUtils::Status::OpenFailed; } - Data ret; - if (data == nullptr || size == 0) - { - LOGD("Get data from file(%s) failed!", filename.c_str()); - } - else - { - ret.fastSet(data, size); + auto size = AAsset_getLength(asset); + buffer->resize(size); + + int readsize = AAsset_read(asset, buffer->buffer(), size); + AAsset_close(asset); + + if (readsize < size) { + if (readsize >= 0) + buffer->resize(readsize); + return FileUtils::Status::ReadFailed; } - return ret; + return FileUtils::Status::OK; } -std::string FileUtilsAndroid::getStringFromFile(const std::string& filename) -{ - Data data = getData(filename, true); - if (data.isNull()) - return ""; - - std::string ret((const char*)data.getBytes()); - return ret; -} - -Data FileUtilsAndroid::getDataFromFile(const std::string& filename) -{ - return getData(filename, false); -} - -unsigned char* FileUtilsAndroid::getFileData(const std::string& filename, const char* mode, ssize_t * size) -{ - unsigned char * data = 0; - - if ( filename.empty() || (! mode) ) - { - return 0; - } - - std::string fullPath = fullPathForFilename(filename); - if (fullPath[0] != '/') - { - std::string relativePath = std::string(); - - size_t position = fullPath.find("assets/"); - if (0 == position) { - // "assets/" is at the beginning of the path and we don't want it - relativePath += fullPath.substr(strlen("assets/")); - } else { - relativePath += fullPath; - } - LOGD("relative path = %s", relativePath.c_str()); - - if (nullptr == FileUtilsAndroid::assetmanager) { - LOGD("... FileUtilsAndroid::assetmanager is nullptr"); - return nullptr; - } - - // read asset data - AAsset* asset = - AAssetManager_open(FileUtilsAndroid::assetmanager, - relativePath.c_str(), - AASSET_MODE_UNKNOWN); - if (nullptr == asset) { - LOGD("asset is nullptr"); - return nullptr; - } - - off_t fileSize = AAsset_getLength(asset); - - data = (unsigned char*) malloc(fileSize); - - int bytesread = AAsset_read(asset, (void*)data, fileSize); - if (size) - { - *size = bytesread; - } - - AAsset_close(asset); - } - else - { - do - { - // read rrom other path than user set it - //CCLOG("GETTING FILE ABSOLUTE DATA: %s", filename); - FILE *fp = fopen(fullPath.c_str(), mode); - CC_BREAK_IF(!fp); - - long fileSize; - fseek(fp,0,SEEK_END); - fileSize = ftell(fp); - fseek(fp,0,SEEK_SET); - data = (unsigned char*) malloc(fileSize); - fileSize = fread(data,sizeof(unsigned char), fileSize,fp); - fclose(fp); - - if (size) - { - *size = fileSize; - } - } while (0); - } - - if (! data) - { - std::string msg = "Get data from file("; - msg.append(filename).append(") failed!"); - CCLOG("%s", msg.c_str()); - } - - return data; -} - -std::string FileUtilsAndroid::getWritablePath() const +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 tmp = JniHelper::callStaticStringMethod("org/cocos2dx/lib/Cocos2dxHelper", "getCocos2dxWritablePath"); + string dir(""); + string tmp = JniHelper::callStaticStringMethod("org/cocos2dx/lib/Cocos2dxHelper", "getCocos2dxWritablePath"); if (tmp.length() > 0) { @@ -468,4 +325,3 @@ std::string FileUtilsAndroid::getWritablePath() const NS_CC_END #endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID - diff --git a/native/cocos/platform/android/CCFileUtils-android.h b/native/cocos/platform/android/CCFileUtils-android.h index eb7294b0df..023efb5af9 100644 --- a/native/cocos/platform/android/CCFileUtils-android.h +++ b/native/cocos/platform/android/CCFileUtils-android.h @@ -1,6 +1,6 @@ /**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2016 Chukong Technologies Inc. +Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -38,6 +38,8 @@ Copyright (c) 2013-2016 Chukong Technologies Inc. NS_CC_BEGIN +class ZipFile; + /** * @addtogroup platform * @{ @@ -57,25 +59,14 @@ public: static void setassetmanager(AAssetManager* a); static AAssetManager* getAssetManager() { return assetmanager; } + static ZipFile* getObbFile() { return obbfile; } /* override functions */ - virtual bool init() override; + bool init() override; virtual std::string getNewFilename(const std::string &filename) const override; - /** @deprecated Please use FileUtils::getDataFromFile or FileUtils::getStringFromFile instead. */ - CC_DEPRECATED_ATTRIBUTE virtual unsigned char* getFileData(const std::string& filename, const char* mode, ssize_t * size) override; - - /** - * Gets string from a file. - */ - virtual std::string getStringFromFile(const std::string& filename) override; - - /** - * Creates binary data from a file. - * @return A data object. - */ - virtual Data getDataFromFile(const std::string& filename) override; + virtual 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; @@ -83,9 +74,9 @@ public: private: virtual bool isFileExistInternal(const std::string& strFilePath) const override; virtual bool isDirectoryExistInternal(const std::string& dirPath) const override; - Data getData(const std::string& filename, bool forString); static AAssetManager* assetmanager; + static ZipFile* obbfile; }; // end of platform group @@ -96,4 +87,3 @@ NS_CC_END #endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID #endif // __CC_FILEUTILS_ANDROID_H__ - diff --git a/native/cocos/platform/android/CCGLViewImpl-android.cpp b/native/cocos/platform/android/CCGLViewImpl-android.cpp index 6e662305d0..8248f72f9d 100644 --- a/native/cocos/platform/android/CCGLViewImpl-android.cpp +++ b/native/cocos/platform/android/CCGLViewImpl-android.cpp @@ -26,7 +26,7 @@ THE SOFTWARE. #include "platform/CCPlatformConfig.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID -#include "CCGLViewImpl-android.h" +#include "platform/android/CCGLViewImpl-android.h" #include "base/CCDirector.h" #include "base/ccMacros.h" #include "platform/android/jni/JniHelper.h" @@ -129,4 +129,3 @@ void GLViewImpl::setIMEKeyboardState(bool bOpen) NS_CC_END #endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID - diff --git a/native/cocos/platform/android/CCPlatformDefine-android.h b/native/cocos/platform/android/CCPlatformDefine-android.h index 788024b602..aa1531b297 100644 --- a/native/cocos/platform/android/CCPlatformDefine-android.h +++ b/native/cocos/platform/android/CCPlatformDefine-android.h @@ -29,7 +29,7 @@ THE SOFTWARE. #include "platform/CCPlatformConfig.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID -#include "android/log.h" +#include #define CC_DLL @@ -65,4 +65,3 @@ THE SOFTWARE. #endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID #endif /* __CCPLATFORMDEFINE_H__*/ - diff --git a/native/cocos/platform/android/java/libs/com.android.vending.expansion.zipfile.jar b/native/cocos/platform/android/java/libs/com.android.vending.expansion.zipfile.jar new file mode 100644 index 0000000000000000000000000000000000000000..bbdeb8a5ee323b89dd2cf420a348080a5a7761a6 GIT binary patch literal 12370 zcmbWd1#leck}WK@m@Q^zX0%wcn3P4kpHw`Kp;S5#Z-jorR2mJ-$y_|6#l~$ z8U*RLspdR7mey}`^WQuA@BJU9vO;oF;$q4w46@=kvSXt%()0||2-5U46JwLLN=$RC zn|n@UBB+jZk}?yLsvzN@jDJP@-!0((!@|(c#L3>$ykKsfUB1owKFA-M{gr_#b_}EFH`&ZA|}x0sa3!Gy&$e0BJ-J z5JVyn5U&3B1!FPw3<)Go_-o^FvIrq zXFhQdGBo*%I7eCoL|m}&$IH4+5|sV;f&9bT&Bn_F_rq#!`xU0%)2}&8Bo^L#f0y}HRT_WpmNOKaj~;PM2@sRbXZj0x$L?U~_NX6UaOL46CwR;b48H#S zReo^gk;hk1`IE<%U~~9a-b~fD&K$Fixl4L*%x&rLw?+h?PaE@B{NOiNzU;4ET}W4? z1=G$}y)g){5Q6iUtdJi%%$|A(A2~aiRuBHikBs;qY(aA2aUwbPN%6f{} zUt_+rKStr`aa?wK^mj409S`n-1qS{~9Yt>Rm>VmF%EDn|KTLasEI(S0T|~g6(n=L( zNe5=gXa>{=hS~6-PRi`o4u=gTB&JH5-HVlhH#fCYJ5i;sj7G%*hF8@}e*(rR>F&0@ zzH{P_lSP05sV{A#5fMdSAisCxZYy6&(#TQd_49c;nj7nLC{qov_MctNk(nM_JvdxU zefzS4jjx!{g%^G&!71_LHJDp%=yb8N+-Ozc#mT`|<7(jIlAUz{oz{pjDLTTofs0E> zOq=KK;P9}2*k$nX%V46yiv~Nor#0_w@diSX6Yyy+r!1xCGetmfT(IeoSV6H>s!M!+ ziRnx)W`cl;a&Q~pk31KI!#pNP>Y&jS3X2k}4qhHU3Wu|Br7j1XMq{##U^3ed#ZAOU zTTGAV8nim|8v_<&1o^@Tji>5I0@u>--8Lkd%LJ2@pLN0b``?BG4DK}7JuZg2CSrZu zXt)jcESa6NR8IkP=ac*K{ec0^TMb@rcd{DPrILmxJ%Oeu*riy&B>9T0_RfjR}i5b`fp@XSkvrFB0{kk05I=XMG@lRy+GG?%9nH?+Y5~D0Xhs?03`z5n( z>UC7LH!)vE)M9us$(V7lf{lc=`hAvJ}MPt#Gog0s*Y0T_S2Oo zb4+D8Y2@0CR=+BUGud4Qd21lsc-4dhHERCaoih9rM9#Atm%=WhIs<*v?U+PW<8=kb z;+od=sD+t*67C(IzN&LKdC`{6@*4W&-q#Sv?ILFVc%X#=0M3)PVzr4my_TiD&U;!a zxz~JW!M4^V`E1ZhW(m8elrULG^O#@+CEirh(4F=x1R`abWsf0dxf-Z!Sf| zuu48>RtzDY3`Y3Lid%cqVq$q;AAhP+1E)ut&#IYza}V|^#EslIK76Ip`(gP*PcSP? zOrluDMw4DV)OUZjW=1qdx&7hmffflK%FF`?A6?x-=a}@#GlE*kXJmXb_LFy=tM&lr zW`_&e_@wZcVj#|(RET*Zt9;RuXdBiB8ly&R$FNVgT9-ip;gCa?ldEx&2;M4=F~_Q_ z-+0#y4O*g6T*Hxl6{_4lDpWPEspJ00#dKf(R5>u6Q#Hw9Geq6&odmIc7dm{>3aHxx`H*(hdHS+(X{}rUbCZOpoBi zxt1aBIasu04jwBnk+sHZVd0G7t|ZLY;8}w!G4+rJ=Hly8i5qzY214=cTptKW`V5t9 z8e94dNjU|Jfv~R6fQ;?eFZ(Ghn3~D~EHV6ho(q)9`^KFVa56B4GVyRS%?b=gA_X)G z)P~kIQwb5KD74ACB{X8iN<%De#M++c{D}OnO9|2@j<$&|P4#1Kpt4CRPQ`TW(;8%2O$~ueqLT>u4@6`Ck_N@}Jy_N{b2S<5ehkOoGz6x$IdbwWy=h3Ipp@ zu7?n=vv5|-llI`nlQ6rDMJ1LUt3o|$LRVyhPtmuXMx3n9j8j}YgAY-${Ya~O2)T3Y1&UC*D+`;W-_~O?k@b*{K zF?6v?!4WQWv33Sq9-Vdn(oK%UpC)~GVQX0%^iSjZ6f#?&stXlmWRFgqOa$cSp1oJOx|t87i=;Q zy2O*d7N=(NzoZX*EqDUjk5McTt!6Eb?t!AEA|AFR$SJ&01~Gz6oV$Vn>>M1E-S9>O zC}TGQp-(&KKmA=+(OAU2Z}Tj!6NtsIg>2haR?gyo`cZBOOsX zfF7J>zHHsE&hH>S6*;0*P6q`+8)Hv;!RzSECts5c$4$=I!=+z!DDBt`^vxFlkYVN4@zqXGy=mJl^WfbDSbni+tdA!_cy$M0YaWXd@b)` z_8~$xn9YzvHoUCv^(NRdFWfSXXkGTu$O%!~Do+`Gdczo#&CM)cMPwbCY3#29Lse!P z>P8XM$s@;tcn=jYk=&s$WOw4Uw=QmFjIWq(Ltr7sEN`h0mSoUGS=8oXd5`I=|zMhAk>AbvI)y)$F%Hbp%h z+C?rR9=(*-o(bgq}M0Cx%V$Pcp` zV|_}xfgsn$pVIhQNN0UVIabsQNB#COe@BjOBhVqn4QV+zdb>J0e$7kaBVjtPx%ExR zUqLYP6HmZi(&!6O&q0oLa&k&1$U7?w;Era(sFVaSV`2Zxtvkvqw7a z^m|Ci+aw3&yJrH&EZ{&y$vXB<8-`3;0w9`Ddt?ik)8-i|2()lM=LHNWuy))`>VOo~r zHGULTqw7oHW*UZE(z*M9^N)Rcd&FoBw6AUP52=4_r2}m2Y;{a#+<}`V6VA;0iAwk* z5)Q^($v?sf1ZJ_^yhX11P3TVEY%pGuJheq)_QmLbMbk@Q(u;%kBR{#cmfGTUV%19$ z@eo@NP~Wp9xfXC7e(5JAM5)C4EPIZrD;G)}BN@m?6Lp=yHq1IhG8sE~v-=PLafaL+ z0m>S3{-J0_K`5V#Qq85;fBNXS&m$;*=V{ic%wcy%1vpDYehaG7Ec3HKiyg@Bl6pwNA+{Lvn;&C)zHp4N%LPcHsDVJL_K# z4x1RK*m)`-N%D5Q44w`>A{eUz@-Q^Gy%?9Zu%379+-+8O!lJy}s~xi#IVvox9d%VB@ONQ&R5^udGcvuxH-{^f;nfPl4k=2244N(ty6CHKK@aj z|5>2+)4d`)K!Si^!hwJY{$CWR(qeyA&C0G04)#tif7Yo0HE9K9b*y(p&sF4#P$~;} zr7Bf0XvLE}sIL*BpQ9v$#Jd~r<8-#HnmE^2rzFo-7COvYPPqVXTe)_&nBS?DlL6Hc z6{{|Vqvsip^G7nAww=x*BnB=#bWQ{xPZJLx2QMGac79I>gS;U3n>R#m24tbhj#}Lo z$OPP1#xmWspkx6S1K8Yxr3O0PqR8w{{GrZHw>@NlTtgLz&7F{Ep~}`P_jL; z&)*2TAe*_!@nt?4487+DNY}{IroiNi+1Y=`?(@>98K!EYL&oCcb@I#iKTY}K`J$3Gk z*_NeTnuWHw04>dS=qYacL4s}%aTkw%t2}f;rV*^vuWA9I(ePksE$^w z$@f6(dn~*$%DYGr1-0+80JYDGPx;33bb0kJg!GdT4JuTpcGQ*OZZ1?qB@RFHz)F=1 zjntNLrBO71huPfLOG(_lUo;a~)uO8lRocSZ!f8{Ci|HB7zmJ#BdT^QNEAtd@2+Q@W zw$VFSj4#Gth}CtXukMhhh?gECtSi{+pZ7sXg<&~RfjjA-=JBP z)_RH8vIjFvp<{cY&e@wp1f5JP@qOd89y_Yg?#K-{rsofi{d}QJ9RSO*{^`1DvN>Oj zR`3V!V-ChrIKaY~aH|Z~_0nlh(}slC!5ZFv?5D(F5bPAQ5^vZNtna{bL`KVL4L?)wxi+)~4 z>PCp>klgTAai#}ch|F^QMoP%P-X|3O%EIh{7y{ysPFm|A(T=Bz@PfVi85>y_^oqjVlBs1_-s7|=; zc1E!;=}u|Xt618L`j&y;JLw5+tki_>j_|Ke>YvH{j*@P(=yx)Q`JK$g|JTV}%hEx~ z)Y;zE$=Fo$(#PD22BG{mTx4ud@uB|kt?1dUhs zl!c)3;4uuO1{6z3r&|@fnMk;a>W3%N<#rI#-Ubx58M3tjOfxwihKbK^aS>IhYn3T_ zpb3w#608wv#V}SPGevju1+!DykHlfxV|I2!4VbGoec^IiEQK5N;E|pTD>KyIXxkKQ z8mgxoaYH$CRRPO_xz*}A{$D3z9U<>R_LiBj7$5=Y`SW!?}y?Pwp;*1a9yryjdB{a{Y{2+Pm7U}K#AU3 zx!jjZC!7=?>;Qt567)(|rE&MrLG7pBVsypyJxKwOiBpcWBynYvbth z7VWTg4h9hWE+?6>T76Y`7#a;+vUYBB+$V;VPzr*&u~mqJTe7*y<1qw1ho)uh+v;EH zZqTL;ul`nSkgZG=*=UZCE69q-pGPrlRFOq=27Uy@IO+}{Kyo@tciZ~pZX%vvCuK{l z#8r{o=8xOTX>g9YG+CI)%u@rkG+cYcB;IamOPVQ|ZhC}D+jZSOvno(0GaVsUVi|~Ai zUTJHeUQCHEk5#9+LqWy(1*nv}0<%WuAJGjw)JhiDr3q_rrGDuv;H8-igZ0f5c2~0~ zk~Tee+mfwlePV+}YRk7amRCfx4lu{*Sh}}-G`_MNs*bjV$W+h?l zBfw@OmG1c7p3pZ^afxx?%D7+8)ull0{(u<&%hCPQ@XgN`2E^E2qWtkoW;!C=7leA< zs|IX{9eh>|X7GYu*1(pj5&J1Dt7m3e-;rYAA= z?1uHrr|Bx`Z}Bwoslu}Y`Vsa}^vcjl?&b0x6-d2Y<1tV|j5n=08HSjB>b(%ni!g5p z*Y?+N+ZfW0=}a4jN$$nYF&s#i{9(0CG19C0`x-HupjRHdB+NfRj(G6QEPd)MHvM_0 zc}I)v@V0n*J```i`1F~ShMHaxL^p?;PDcoEPM}BEIuMWz-zi~iXNl-g8wBtOZ%CZ_ z2&zl(xu@#4bW@oIjS!ENPI8v82jFNQeG-9e7S!y?~y7NO9JGewPIf`M8L8}{m<$k9m$H;k=jR_tg{eN{P% zwYZtlnmH)ou179Tvt?WN3jTk-3b4?~2YHY|Ks<>-KzRROUj={7p5S~E<`V@E(uc=P zt|8;3%!bH7KcS?yh2~yEhXx}Paghztf?=eL`4E%dgtDSRqi;-V)fd#0NPeylpG?xi z`r=dH(BgV>?zZOE*y_4w+j`=rUt{aqT2K2T=uYs2O7Xg?_UL$!={(7Q;e6gsXz%yh zGb-vr?7t>=p&cq05BV`9#mr+`^x>og1E3)<)E~aIrhE$)_z4V=ga5EC+Tf8YQWm}w zM0^Is2iz)Rzh%BRMhXxVOBKMu1H0lR^O0)T7+Jw6|sde{V>Rxkg7dY z!RX#i+VcYP0*z>!jS2#bxE}E+Upz|stxz6yKnuIg1mrD>lCPimM80&wBe>bQ%oy?P zZBo2C)dp(sx)+{WeGZ39_%-{uvk7NvnH0$AblK0+-q&3lIg6Dl?o4*d?lQC2s{Pt&?55{l=MP1T7&Do3!NT55C^F+B#vm4fg(g0DzXXL zGlhbt$(xGet7v3GHoi#WG#z24h1xR$H(_u82kP-FOvxO)hljc>RzLcAgYE z)SIxR{6C@L2B>`?0}k&dZocF}P>=XKX@-r7FdSRm;K0$4WVzoJj!=x$>^bh`I=aDRv?DxcI>UNH0NkUy1q1;PM(CWyhkRrG8`RCBKW6~E@CHkn{U z0$5FW;OL9l@T||&wJ9RcLx?{65UC@y;XzL~@h4%0=MgSJfk<-FNf!sYxbmbxEH5u| zLb%%cHtQAJ>W~#AKnJz<^ctWr;_ZG3A(i6pM!_Ac8APG$)=}-2b1j^UV$<#l6!%aW ztuKmN+9Zk9Ai()bVW^QAC3du>qbtc;c+4Eesm#Tyd;Q6@TyA4Ck&AqiOWnmQ1@ZV6 z3%~9rk*9Kdo`+vf{_vKRXH12;VZqfac9E%q>6WFk{)PwO{Y1lCx#$UQKlfzy4nMo+ zZ=-wE7FIFu$!b5%J><(1!c|t=ZSA_dpa%HFl{1H0L2F&v1&!)HO9^h|Eh8#+XPG`svVXRmWNE_y>D`6oBF zV%~}*FrrIQq!cm=F$DW63{z5L0qxjco`YvPB$qK|$r=iLB%^QTcrO-?G&>NxkLB`x zg;?7s7H?d6Ho7>Eeb6>+4zyi5676T7+&V-Kc>Cj|jB$H%b0k$vJ8&bHeVmeS`@5U; z6D;qKUb#EqOt&KP(Q#UiUp+gt54=U^+Fv25W-#GjP-&Ev1q4y`&YnrGn}Nx~Vvln& zCF1m_-ve=6-s6^-gn$W)A1r{*u?OH2EziZ?r_(n1gSXdg08(~oS!niFkfFU~i!ReK z8h7!KT9#l6)Jo;G2nD&HJ2PR68as2} z+{G^`3%9?x=mKY#Gn|2NbRv^H$RL;R&B?!*#wk{~6;?cti*|M>0%tXMpxJi*5qE&M zx4Vs&(Q}NZNn%Ev8hL>~zWc()2CPw{pqXgNd0w_`rEc;NB9Ws7=2 zK6jxP>5Npw`d-%rL0CxC76Ds1s(*3|uh!J;;MBnq?G^Pr&)JcvHw(7t{No#LgaStQ z_Zv0K*aOTRoyfM~j}LAON>L@Cdw3iE?mW{D+PRqS4~M?|C`Ab;K&Ro{FxxY-TTh&h zwD5BjaiZk2gmDYm8Qo?VTVv=`))aB{>Kc}wJ;BF-!s(p-T}&g#I=jdkTFdSbfMXzO z+a8SUz-btau=Wyyw#5mkh2G1h@(mF2T0%tUX$agdkgGF7^JPT-`T z^u5NtbCeJGPkS~d>KVe=Of!jBFc>L3DH!w&`i1I}om|aB!|G_^i_wkDQltIoltH=3 zV#=)=hplsM)bMQ<1TTMPYg(cB0-ZRSz8ZS_1Gy!j(@Xf?uG-| zunMpT_i2Uc0KWuKJUV~7VChx|e{X~7z`f+Bc+~6C$I83F96W3tgz$&COqRX${np7M z{{CisyJj6g2+}qQaq;Oj8wSIl5Nl_$GHo;D63HH}D~9S(ag2bqTfa9n8EQbuX@nh* zRvr}gr_UZ4Ph&%zoW8yytIo+xMWqA0eX*SDA{y^tjWgPmZL;qdYGg-+0LYFi2#p~dv^b96Th!ptvPaz4 z1wzsl#hMry{HXgK6|aPhC|PWp7qjpF^km5Gl4?BSXh)DGrnoA;VP;dKUkfQmlRKm) zOD~@Mo|C>lk)~*0@xpaVP{*@}7J-_7GCL$Y`uV#*b_ES&Wy?uV&m>B>HUjCPHPhCX zQy^E?4r|Rq4mAi+ul4k$W*~ z_6&MAtz8%OE`!|)Kf;)8>Co@Emy{C#6mbzwJ^QlP`Gs;T0hVR6A(_Y#_O3^h*Wj5$ z^x-p>A{bC}(e$WOIon@W?6q}@JRKBDt*_gaTLLmIO>U^jLBlP8!kTS_u88DKn#p$s zJ-sC(4zWZDwi>m9*0eN15-*kMH7a9B;8ba&Q;ckt4^mFQdpsr{oPqy)wv z4Zh7Uy6gpV_pLVWWb~Yos|e~G{owHN#kWbW_f__JR>$rgUT0U(qQ`iz{5#)<01a9- zcA6K~Np4SbxQP~LBcD*b{7l_lKrKPuP0I}gJ$Bmq3YgkKqbAVWHzR{yZ+8&B_8f@* z$Ud;~~6l5u2^3=3TWI(2d!}wjkmsmVNg~y-M`l zqw`*fL-+dcPpQ*=v`V0I<`Va)IrStdOBD7sVNo!%>Ucq6i5pRc{mw(E*8E|mis>7b z{uVh;Rebf^oRpQ$hD&6cT1Ni<-FQWkFvU#dOd!TWbe_;qI-DyRh991u3|p6C`v`N#TiH)3Fqcaj7t@(LF&4M z$vnGExsykqj!tYDE0;b&TEtPKEL%y&7UHVyx$tfiE#PGm^*@Yd?+bBkn~5ruLOXTtxqT& z(OLVrkI)-KmDjSb3>#w?S7)!p8##%W04?^7azO8cMU+pa8}Y?7!_G@R$i+Oz6}VR1 zgJt8D-x;W%f_E^IMdfAh^21~HJ%(W6+mEa%zhO>`iyPJw|JQJ912o zA2_U)YEkD`oGJ5G$=&{fLW3oy`wDtVp-0!6@U2P z=2?wjW;v_}U%MrJ|Mm`33v+qI=#beag0=;0JmMdt+3E#-#(XBP0Q25@^6y`_dUV2n z!*y%gnkIO5ceqb^E*JmEVc8X=&XJ?DfcMF0TOELV^rLwbRFDP*LkIuY66W81iQfwu z;{)_XU z3zPr$0RD%^U*h9`$MuI$`OozS7dYs@k}dyh?mvXfeNgZsUCgM)x{)BSPw{{egu B#+m>C literal 0 HcmV?d00001 diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java index 171d659e11..a1738677ac 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java @@ -39,7 +39,7 @@ public class Cocos2dxAccelerometer implements SensorEventListener { // Constants // =========================================================== - private static final String TAG = "Cocos2dxAccelerometer"; + private static final String TAG = Cocos2dxAccelerometer.class.getSimpleName(); // =========================================================== // Fields @@ -48,72 +48,101 @@ public class Cocos2dxAccelerometer implements SensorEventListener { private final Context mContext; private final SensorManager mSensorManager; private final Sensor mAccelerometer; + private final Sensor mCompass; private final int mNaturalOrientation; + final float[] accelerometerValues = new float[3]; + final float[] compassFieldValues = new float[3]; + static final float ALPHA = 0.25f; // if ALPHA = 1 OR 0, no filter applies. // =========================================================== // Constructors // =========================================================== public Cocos2dxAccelerometer(final Context context) { - mContext = context; + this.mContext = context; - mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE); - mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); + this.mSensorManager = (SensorManager) this.mContext.getSystemService(Context.SENSOR_SERVICE); + this.mAccelerometer = this.mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); + this.mCompass = this.mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); - final Display display = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); - mNaturalOrientation = display.getOrientation(); + final Display display = ((WindowManager) this.mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); + this.mNaturalOrientation = display.getOrientation(); } - public void enable() { - mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_GAME); + // =========================================================== + // Getter & Setter + // =========================================================== + + public void enableCompass() { + this.mSensorManager.registerListener(this, this.mCompass, SensorManager.SENSOR_DELAY_GAME); + } + + public void enableAccel() { + this.mSensorManager.registerListener(this, this.mAccelerometer, SensorManager.SENSOR_DELAY_GAME); } public void setInterval(float interval) { // Honeycomb version is 11 if(android.os.Build.VERSION.SDK_INT < 11) { - mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_GAME); + this.mSensorManager.registerListener(this, this.mAccelerometer, SensorManager.SENSOR_DELAY_GAME); } else { //convert seconds to microseconds - mSensorManager.registerListener(this, mAccelerometer, (int)(interval*100000)); + this.mSensorManager.registerListener(this, this.mAccelerometer, (int)(interval*100000)); } } public void disable() { - mSensorManager.unregisterListener(this); + this.mSensorManager.unregisterListener(this); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== - @Override public void onSensorChanged(final SensorEvent sensorEvent) { - if (sensorEvent.sensor.getType() != Sensor.TYPE_ACCELEROMETER) { - return; + if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { + + float x = sensorEvent.values[0]; + float y = sensorEvent.values[1]; + final float z = sensorEvent.values[2]; + + // needed by VR code + this.accelerometerValues[0] = x; + this.accelerometerValues[1] = y; + this.accelerometerValues[2] = z; + + /* + * Because the axes are not swapped when the device's screen orientation + * changes. So we should swap it here. In tablets such as Motorola Xoom, + * the default orientation is landscape, so should consider this. + */ + final int orientation = this.mContext.getResources().getConfiguration().orientation; + + if ((orientation == Configuration.ORIENTATION_LANDSCAPE) && (this.mNaturalOrientation != Surface.ROTATION_0)) { + final float tmp = x; + x = -y; + y = tmp; + } else if ((orientation == Configuration.ORIENTATION_PORTRAIT) && (this.mNaturalOrientation != Surface.ROTATION_0)) { + final float tmp = x; + x = y; + y = -tmp; + } + + + Cocos2dxGLSurfaceView.queueAccelerometer(x,y,z,sensorEvent.timestamp); + + /* + if(BuildConfig.DEBUG) { + Log.d(TAG, "x = " + sensorEvent.values[0] + " y = " + sensorEvent.values[1] + " z = " + pSensorEvent.values[2]); + } + */ } - - float x = sensorEvent.values[0]; - float y = sensorEvent.values[1]; - final float z = sensorEvent.values[2]; - - /* - * Because the axes are not swapped when the device's screen orientation - * changes. So we should swap it here. In tablets such as Motorola Xoom, - * the default orientation is landscape, so should consider this. - */ - final int orientation = mContext.getResources().getConfiguration().orientation; - - if ((orientation == Configuration.ORIENTATION_LANDSCAPE) && (mNaturalOrientation != Surface.ROTATION_0)) { - final float tmp = x; - x = -y; - y = tmp; - } else if ((orientation == Configuration.ORIENTATION_PORTRAIT) && (mNaturalOrientation != Surface.ROTATION_0)) { - final float tmp = x; - x = y; - y = -tmp; + else if (sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) { + // needed by VR code + this.compassFieldValues[0] = sensorEvent.values[0]; + this.compassFieldValues[1] = sensorEvent.values[1]; + this.compassFieldValues[2] = sensorEvent.values[2]; } - - Cocos2dxGLSurfaceView.queueAccelerometer(x,y,z,sensorEvent.timestamp); } @Override @@ -126,5 +155,8 @@ public class Cocos2dxAccelerometer implements SensorEventListener { // =========================================================== public static native void onSensorChanged(final float x, final float y, final float z, final long timestamp); -} + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java index 05d97985e8..d6132fb836 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java @@ -34,33 +34,42 @@ import android.media.AudioManager; import android.opengl.GLSurfaceView; import android.os.Build; import android.os.Bundle; +import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager.OnActivityResultListener; +import android.util.AttributeSet; import android.util.Log; import android.view.ViewGroup; import android.view.View; import android.view.Window; import android.view.WindowManager; +import android.widget.FrameLayout; + +import org.cocos2dx.lib.Cocos2dxHelper.Cocos2dxHelperListener; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLDisplay; -public abstract class Cocos2dxActivity extends Activity { - private final static String TAG = "Cocos2dxActivity"; +public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelperListener { + // =========================================================== + // Constants + // =========================================================== + + private final static String TAG = Cocos2dxActivity.class.getSimpleName(); // =========================================================== // Fields // =========================================================== - static ResizeLayout ROOT_LAYOUT = null; - + private Cocos2dxGLSurfaceView mGLSurfaceView = null; private int[] mGLContextAttrs = null; - private Cocos2dxHandler mHandler = null; - static Cocos2dxActivity COCOS_ACTIVITY = null; + private Cocos2dxHandler mHandler = null; + private static Cocos2dxActivity sContext = null; private Cocos2dxVideoHelper mVideoHelper = null; + private Cocos2dxWebViewHelper mWebViewHelper = null; private Cocos2dxEditBoxHelper mEditBoxHelper = null; - private boolean isHasFocus = true; + private boolean hasFocus = false; public Cocos2dxGLSurfaceView getGLSurfaceView(){ return mGLSurfaceView; @@ -68,10 +77,14 @@ public abstract class Cocos2dxActivity extends Activity { public class Cocos2dxEGLConfigChooser implements GLSurfaceView.EGLConfigChooser { - protected int[] configAttributes; - public Cocos2dxEGLConfigChooser(int[] attributes) + protected int[] configAttribs; + public Cocos2dxEGLConfigChooser(int redSize, int greenSize, int blueSize, int alphaSize, int depthSize, int stencilSize) { - configAttributes = attributes; + configAttribs = new int[] {redSize, greenSize, blueSize, alphaSize, depthSize, stencilSize}; + } + public Cocos2dxEGLConfigChooser(int[] attribs) + { + configAttribs = attribs; } private int findConfigAttrib(EGL10 egl, EGLDisplay display, @@ -151,15 +164,15 @@ public abstract class Cocos2dxActivity extends Activity { } @Override - public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) + public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) { int[] EGLattribs = { - EGL10.EGL_RED_SIZE, configAttributes[0], - EGL10.EGL_GREEN_SIZE, configAttributes[1], - EGL10.EGL_BLUE_SIZE, configAttributes[2], - EGL10.EGL_ALPHA_SIZE, configAttributes[3], - EGL10.EGL_DEPTH_SIZE, configAttributes[4], - EGL10.EGL_STENCIL_SIZE,configAttributes[5], + EGL10.EGL_RED_SIZE, configAttribs[0], + EGL10.EGL_GREEN_SIZE, configAttribs[1], + EGL10.EGL_BLUE_SIZE, configAttribs[2], + EGL10.EGL_ALPHA_SIZE, configAttribs[3], + EGL10.EGL_DEPTH_SIZE, configAttribs[4], + EGL10.EGL_STENCIL_SIZE,configAttribs[5], EGL10.EGL_RENDERABLE_TYPE, 4, //EGL_OPENGL_ES2_BIT EGL10.EGL_NONE }; @@ -188,7 +201,7 @@ public abstract class Cocos2dxActivity extends Activity { cfgVals[i] = new ConfigValue(egl, display, configs[i]); } - ConfigValue e = new ConfigValue(configAttributes); + ConfigValue e = new ConfigValue(configAttribs); // bin search int lo = 0; int hi = num; @@ -215,7 +228,7 @@ public abstract class Cocos2dxActivity extends Activity { } public static Context getContext() { - return COCOS_ACTIVITY; + return sContext; } public void setKeepScreenOn(boolean value) { @@ -251,30 +264,37 @@ public abstract class Cocos2dxActivity extends Activity { onLoadNativeLibraries(); - COCOS_ACTIVITY = this; - mHandler = new Cocos2dxHandler(this); - + sContext = this; + this.mHandler = new Cocos2dxHandler(this); + Cocos2dxHelper.init(this); - - mGLContextAttrs = getGLContextAttrs(); - init(); + + this.mGLContextAttrs = getGLContextAttrs(); + this.init(); if (mVideoHelper == null) { - mVideoHelper = new Cocos2dxVideoHelper(); + mVideoHelper = new Cocos2dxVideoHelper(this, mFrameLayout); + } + + if(mWebViewHelper == null){ + mWebViewHelper = new Cocos2dxWebViewHelper(mFrameLayout); } if(mEditBoxHelper == null){ - mEditBoxHelper = new Cocos2dxEditBoxHelper(); + mEditBoxHelper = new Cocos2dxEditBoxHelper(mFrameLayout); } - Cocos2dxWebViewHelper.init(); - Window window = getWindow(); + Window window = this.getWindow(); window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); this.setVolumeControlStream(AudioManager.STREAM_MUSIC); } //native method,call GLViewImpl::getGLContextAttrs() to get the OpenGL ES context attributions private static native int[] getGLContextAttrs(); + + // =========================================================== + // Getter & Setter + // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces @@ -282,23 +302,23 @@ public abstract class Cocos2dxActivity extends Activity { @Override protected void onResume() { - Log.d(TAG, "onResume()"); - this.hideVirtualButton(); + Log.d(TAG, "onResume()"); super.onResume(); - resumeIfHasFocus(); + this.hideVirtualButton(); + resumeIfHasFocus(); } @Override - public void onWindowFocusChanged(boolean isHasFocus) { - Log.d(TAG, "onWindowFocusChanged() hasFocus=" + isHasFocus); - super.onWindowFocusChanged(isHasFocus); - - COCOS_ACTIVITY.isHasFocus = isHasFocus; + public void onWindowFocusChanged(boolean hasFocus) { + Log.d(TAG, "onWindowFocusChanged() hasFocus=" + hasFocus); + super.onWindowFocusChanged(hasFocus); + + this.hasFocus = hasFocus; resumeIfHasFocus(); } private void resumeIfHasFocus() { - if(isHasFocus) { + if(hasFocus) { this.hideVirtualButton(); Cocos2dxHelper.onResume(); mGLSurfaceView.onResume(); @@ -316,24 +336,19 @@ public abstract class Cocos2dxActivity extends Activity { @Override protected void onDestroy() { super.onDestroy(); - - Cocos2dxEditBoxHelper.reset(); - Cocos2dxHelper.reset(); - Cocos2dxWebViewHelper.reset(); - - COCOS_ACTIVITY = null; - ROOT_LAYOUT = null; } - public void showDialog(final String title, final String message) { - Message msg = Message.obtain(); + @Override + public void showDialog(final String pTitle, final String pMessage) { + Message msg = new Message(); msg.what = Cocos2dxHandler.HANDLER_SHOW_DIALOG; - msg.obj = new Cocos2dxHandler.DialogMessage(title, message); - mHandler.sendMessageDelayed(msg, 0); + msg.obj = new Cocos2dxHandler.DialogMessage(pTitle, pMessage); + this.mHandler.sendMessage(msg); } - - public void runOnGLThread(final Runnable runnable) { - mGLSurfaceView.queueEvent(runnable); + + @Override + public void runOnGLThread(final Runnable pRunnable) { + this.mGLSurfaceView.queueEvent(pRunnable); } @Override @@ -346,36 +361,47 @@ public abstract class Cocos2dxActivity extends Activity { super.onActivityResult(requestCode, resultCode, data); } + + protected ResizeLayout mFrameLayout = null; + // =========================================================== + // Methods + // =========================================================== public void init() { + + // FrameLayout ViewGroup.LayoutParams framelayout_params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); - ROOT_LAYOUT = null; - ROOT_LAYOUT = new ResizeLayout(this); + mFrameLayout = new ResizeLayout(this); - ROOT_LAYOUT.setLayoutParams(framelayout_params); + mFrameLayout.setLayoutParams(framelayout_params); // Cocos2dxEditText layout - ViewGroup.LayoutParams editTextLayoutParams = + ViewGroup.LayoutParams edittext_layout_params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); - Cocos2dxEditBox editText = new Cocos2dxEditBox(this); - editText.setLayoutParams(editTextLayoutParams); - ROOT_LAYOUT.addView(editText); + Cocos2dxEditBox edittext = new Cocos2dxEditBox(this); + edittext.setLayoutParams(edittext_layout_params); + + + mFrameLayout.addView(edittext); // Cocos2dxGLSurfaceView - mGLSurfaceView = this.onCreateView(); - ROOT_LAYOUT.addView(mGLSurfaceView); + this.mGLSurfaceView = this.onCreateView(); + + // ...add to FrameLayout + mFrameLayout.addView(this.mGLSurfaceView); // Switch to supported OpenGL (ARGB888) mode on emulator if (isAndroidEmulator()) this.mGLSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0); - mGLSurfaceView.setCocos2dxRenderer(new Cocos2dxRenderer()); - mGLSurfaceView.setCocos2dxEditText(editText); + this.mGLSurfaceView.setCocos2dxRenderer(new Cocos2dxRenderer()); + this.mGLSurfaceView.setCocos2dxEditText(edittext); - setContentView(ROOT_LAYOUT); + // Set framelayout as the content view + setContentView(mFrameLayout); } public Cocos2dxGLSurfaceView onCreateView() { @@ -383,7 +409,7 @@ public abstract class Cocos2dxActivity extends Activity { //this line is need on some device if we specify an alpha bits if(this.mGLContextAttrs[3] > 0) glSurfaceView.getHolder().setFormat(PixelFormat.TRANSLUCENT); - Cocos2dxEGLConfigChooser chooser = new Cocos2dxEGLConfigChooser(mGLContextAttrs); + Cocos2dxEGLConfigChooser chooser = new Cocos2dxEGLConfigChooser(this.mGLContextAttrs); glSurfaceView.setEGLConfigChooser(chooser); return glSurfaceView; @@ -403,7 +429,7 @@ public abstract class Cocos2dxActivity extends Activity { } } - private static boolean isAndroidEmulator() { + private final static boolean isAndroidEmulator() { String model = Build.MODEL; Log.d(TAG, "model=" + model); String product = Build.PRODUCT; @@ -415,5 +441,8 @@ public abstract class Cocos2dxActivity extends Activity { Log.d(TAG, "isEmulator=" + isEmulator); return isEmulator; } -} + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java index bf43de4c6d..e9f40a4ccd 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java @@ -24,11 +24,14 @@ THE SOFTWARE. ****************************************************************************/ package org.cocos2dx.lib; +import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; +import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; +import android.text.BoringLayout; import android.text.Layout; import android.text.StaticLayout; import android.text.TextPaint; @@ -51,6 +54,24 @@ public final class Cocos2dxBitmap { private static final int VERTICAL_ALIGN_BOTTOM = 2; private static final int VERTICAL_ALIGN_CENTER = 3; + // =========================================================== + // Fields + // =========================================================== + + private static Context sContext; + + // =========================================================== + // Getter & Setter + // =========================================================== + + public static void setContext(final Context context) { + Cocos2dxBitmap.sContext = context; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + // =========================================================== // Methods // =========================================================== @@ -121,10 +142,17 @@ public final class Cocos2dxBitmap { return paint.getTypeface(); } - public static boolean createTextBitmapShadowStroke(final String string, final String fontName, int fontSize, + public static boolean createTextBitmapShadowStroke(byte[] bytes, final String fontName, int fontSize, int fontTintR, int fontTintG, int fontTintB, int fontTintA, int alignment, int width, int height, - boolean stroke, int strokeR, int strokeG, int strokeB, int strokeA, float strokeSize, boolean enableWrap, int overflow) { + boolean shadow, float shadowDX, float shadowDY, float shadowBlur, float shadowOpacity, + boolean stroke, int strokeR, int strokeG, int strokeB, int strokeA, float strokeSize, boolean enableWrap, int overflow) { + String string; + if (bytes == null || bytes.length == 0) { + return false; + } else { + string = new String(bytes); + } Layout.Alignment hAlignment = Layout.Alignment.ALIGN_NORMAL; int horizontalAlignment = alignment & 0x0F; @@ -233,7 +261,7 @@ public final class Cocos2dxBitmap { if (fontName.endsWith(".ttf")) { try { final Typeface typeFace = Cocos2dxTypefaces.get( - Cocos2dxActivity.COCOS_ACTIVITY, fontName); + Cocos2dxBitmap.sContext, fontName); paint.setTypeface(typeFace); } catch (final Exception e) { Log.e("Cocos2dxBitmap", "error to create ttf type face: " @@ -308,4 +336,3 @@ public final class Cocos2dxBitmap { TextUtils.TruncateAt.END).toString(); } } - diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBox.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBox.java index d7888f59cf..6690b607f9 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBox.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBox.java @@ -132,42 +132,6 @@ public class Cocos2dxEditBox extends EditText { this.setLayoutParams(layoutParams); } - public void setInputTextAlignment(int hAlign, int vAlign) { - int gravity; - - switch (hAlign) { - case 0: - gravity = Gravity.LEFT; - break; - case 1: - gravity = Gravity.CENTER_HORIZONTAL; - break; - case 2: - gravity = Gravity.RIGHT; - break; - default: - gravity = Gravity.LEFT; - break; - } - - switch (vAlign) { - case 0: - gravity = gravity | Gravity.TOP; - break; - case 1: - gravity = gravity | Gravity.CENTER_VERTICAL; - break; - case 2: - gravity = gravity | Gravity.BOTTOM; - break; - default: - gravity = gravity | Gravity.CENTER_VERTICAL; - break; - } - - this.setGravity(gravity); - } - public float getOpenGLViewScaleX() { return mScaleX; } @@ -211,11 +175,10 @@ public class Cocos2dxEditBox extends EditText { } public void setInputMode(int inputMode){ - this.setInputTextAlignment(0, 1); + switch (inputMode) { case kEditBoxInputModeAny: this.mInputModeConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE; - this.setInputTextAlignment(0, 0); break; case kEditBoxInputModeEmailAddr: this.mInputModeConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS; @@ -248,8 +211,9 @@ public class Cocos2dxEditBox extends EditText { public boolean onKeyDown(final int pKeyCode, final KeyEvent pKeyEvent) { switch (pKeyCode) { case KeyEvent.KEYCODE_BACK: + Cocos2dxActivity activity = (Cocos2dxActivity)this.getContext(); //To prevent program from going to background - Cocos2dxActivity.COCOS_ACTIVITY.getGLSurfaceView().requestFocus(); + activity.getGLSurfaceView().requestFocus(); return true; default: return super.onKeyDown(pKeyCode, pKeyEvent); @@ -291,4 +255,3 @@ public class Cocos2dxEditBox extends EditText { this.setInputType(this.mInputFlagConstraints | this.mInputModeConstraints); } } - diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxHelper.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxHelper.java index 57057147ac..3d11abd6e6 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxHelper.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxHelper.java @@ -29,7 +29,6 @@ import android.content.res.Resources; import android.graphics.Color; import android.graphics.Typeface; import android.os.Looper; -import android.renderscript.Type; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; @@ -45,18 +44,12 @@ import android.widget.FrameLayout; import android.widget.TextView; public class Cocos2dxEditBoxHelper { - private static final String TAG = "Cocos2dxEditBoxHelper"; + private static final String TAG = Cocos2dxEditBoxHelper.class.getSimpleName(); + private static Cocos2dxActivity mCocos2dxActivity; + private static ResizeLayout mFrameLayout; - private static SparseArray sEditBoxArray = null; - private static int sViewTag = 0; - - static void reset() { - if (sEditBoxArray != null) { - sEditBoxArray.clear(); - sEditBoxArray = null; - sViewTag = 0; - } - } + private static SparseArray mEditBoxArray; + private static int mViewTag = 0; //Call native methods private static native void editBoxEditingDidBegin(int index); @@ -74,17 +67,16 @@ public class Cocos2dxEditBoxHelper { editBoxEditingDidEnd(index, text); } - private static native void editBoxEditingReturn(int index); - public static void __editBoxEditingReturn(int index) { - editBoxEditingReturn(index); - } - public Cocos2dxEditBoxHelper() { - sEditBoxArray = new SparseArray(); + public Cocos2dxEditBoxHelper(ResizeLayout layout) { + Cocos2dxEditBoxHelper.mFrameLayout = layout; + + Cocos2dxEditBoxHelper.mCocos2dxActivity = (Cocos2dxActivity) Cocos2dxActivity.getContext(); + Cocos2dxEditBoxHelper.mEditBoxArray = new SparseArray(); } public static int convertToSP(float point){ - Resources r = Cocos2dxActivity.COCOS_ACTIVITY.getResources(); + Resources r = mCocos2dxActivity.getResources(); int convertedValue = (int)TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, point, r.getDisplayMetrics()); @@ -94,11 +86,11 @@ public class Cocos2dxEditBoxHelper { } public static int createEditBox(final int left, final int top, final int width, final int height, final float scaleX) { - final int index = sViewTag; - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + final int index = mViewTag; + mCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - final Cocos2dxEditBox editBox = new Cocos2dxEditBox(Cocos2dxActivity.COCOS_ACTIVITY); + final Cocos2dxEditBox editBox = new Cocos2dxEditBox(mCocos2dxActivity); editBox.setFocusable(true); editBox.setFocusableInTouchMode(true); editBox.setInputFlag(5); //kEditBoxInputFlagLowercaseAllCharacters @@ -110,7 +102,7 @@ public class Cocos2dxEditBoxHelper { editBox.setTextColor(Color.WHITE); editBox.setSingleLine(); editBox.setOpenGLViewScaleX(scaleX); - Resources r = Cocos2dxActivity.COCOS_ACTIVITY.getResources(); + Resources r = mCocos2dxActivity.getResources(); float density = r.getDisplayMetrics().density; int paddingBottom = (int)(height * 0.33f / density); paddingBottom = convertToSP(paddingBottom - 5 * scaleX / density); @@ -131,32 +123,33 @@ public class Cocos2dxEditBoxHelper { lParams.height = height; lParams.gravity = Gravity.TOP | Gravity.LEFT; - Cocos2dxActivity.ROOT_LAYOUT.addView(editBox, lParams); + mFrameLayout.addView(editBox, lParams); - editBox.setTag(false); editBox.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override - public void onTextChanged(final CharSequence s, int start, int before, int count) { + public void onTextChanged(CharSequence s, int start, int before, int count) { + //The optimization can't be turn on due to unknown keyboard hide in some custom keyboard +// mFrameLayout.setEnableForceDoLayout(false); + // Note that we must to copy a string to prevent string content is modified + // on UI thread while 's.toString' is invoked at the same time. + final String text = new String(s.toString()); + mCocos2dxActivity.runOnGLThread(new Runnable() { + @Override + public void run() { + Cocos2dxEditBoxHelper.__editBoxEditingChanged(index, text); + } + }); } - //http://stackoverflow.com/questions/21713246/addtextchangedlistener-and-ontextchanged-are-always-called-when-android-fragment @Override - public void afterTextChanged(final Editable s) { - if(!s.toString().equals("") && (Boolean)editBox.getTag()) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(new Runnable() { - @Override - public void run() { - Cocos2dxEditBoxHelper.__editBoxEditingChanged(index, s.toString()); - } - }); - } - } + public void afterTextChanged(Editable s) { + } }); @@ -164,27 +157,30 @@ public class Cocos2dxEditBoxHelper { @Override public void onFocusChange(View v, boolean hasFocus) { - editBox.setTag(true); if (hasFocus) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(new Runnable() { + mCocos2dxActivity.runOnGLThread(new Runnable() { @Override public void run() { Cocos2dxEditBoxHelper.__editBoxEditingDidBegin(index); } }); editBox.setSelection(editBox.getText().length()); - Cocos2dxActivity.ROOT_LAYOUT.setEnableForceDoLayout(true); - Cocos2dxActivity.COCOS_ACTIVITY.getGLSurfaceView().setSoftKeyboardShown(true); + mFrameLayout.setEnableForceDoLayout(true); + mCocos2dxActivity.getGLSurfaceView().setSoftKeyboardShown(true); Log.d(TAG, "edit box get focus"); } else { editBox.setVisibility(View.GONE); - Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(new Runnable() { + // Note that we must to copy a string to prevent string content is modified + // on UI thread while 's.toString' is invoked at the same time. + final String text = new String(editBox.getText().toString()); + mCocos2dxActivity.runOnGLThread(new Runnable() { @Override public void run() { - Cocos2dxEditBoxHelper.__editBoxEditingDidEnd(index, editBox.getText().toString()); + Cocos2dxEditBoxHelper.__editBoxEditingDidEnd(index, text); } }); - Cocos2dxActivity.ROOT_LAYOUT.setEnableForceDoLayout(false); + mCocos2dxActivity.hideVirtualButton(); + mFrameLayout.setEnableForceDoLayout(false); Log.d(TAG, "edit box lose focus"); } } @@ -195,14 +191,10 @@ public class Cocos2dxEditBoxHelper { // If the event is a key-down event on the "enter" button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { - //if editbox doesn't support multiline, just hide the keyboard if ((editBox.getInputType() & InputType.TYPE_TEXT_FLAG_MULTI_LINE) != InputType.TYPE_TEXT_FLAG_MULTI_LINE) { - Cocos2dxEditBoxHelper.runEditBoxEditingReturnInGLThread(index); Cocos2dxEditBoxHelper.closeKeyboardOnUiThread(index); return true; - } else { - Cocos2dxEditBoxHelper.runEditBoxEditingReturnInGLThread(index); } } return false; @@ -220,57 +212,54 @@ public class Cocos2dxEditBoxHelper { } }); - sEditBoxArray.put(index, editBox); - } - }); - return sViewTag++; - } - - private static void runEditBoxEditingReturnInGLThread(final int index) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(new Runnable() { - @Override - public void run() { - Cocos2dxEditBoxHelper.__editBoxEditingReturn(index); + mEditBoxArray.put(index, editBox); } }); + return mViewTag++; } public static void removeEditBox(final int index) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + mCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxEditBox editBox = sEditBoxArray.get(index); + Cocos2dxEditBox editBox = mEditBoxArray.get(index); if (editBox != null) { - sEditBoxArray.remove(index); - Cocos2dxActivity.ROOT_LAYOUT.removeView(editBox); + mEditBoxArray.remove(index); + mFrameLayout.removeView(editBox); + Log.e(TAG, "remove EditBox"); } } }); } public static void setFont(final int index, final String fontName, final float fontSize){ - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + mCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxEditBox editBox = sEditBoxArray.get(index); + Cocos2dxEditBox editBox = mEditBoxArray.get(index); if (editBox != null) { Typeface tf; if (!fontName.isEmpty()) { if (fontName.endsWith(".ttf")) { try { - tf = Cocos2dxTypefaces.get(Cocos2dxActivity.COCOS_ACTIVITY.getContext(), fontName); + tf = Cocos2dxTypefaces.get(mCocos2dxActivity.getContext(), fontName); } catch (final Exception e) { - Log.e("Cocos2dxEditBoxHelper", "error to create ttf type face: " + fontName); - tf = Typeface.create(fontName, Typeface.NORMAL); + Log.e("Cocos2dxEditBoxHelper", "error to create ttf type face: " + + fontName); + // The file may not find, use system font. + tf = Typeface.create(fontName, Typeface.NORMAL); } + } else { + tf = Typeface.create(fontName, Typeface.NORMAL); } - tf = Typeface.create(fontName, Typeface.NORMAL); + }else{ tf = Typeface.DEFAULT; } - //TODO: The font size is not the same across all the anroid devices... + // TODO: The font size is not the same across all the android devices... if (fontSize >= 0){ - float density = Cocos2dxActivity.COCOS_ACTIVITY.getResources().getDisplayMetrics().density; + float density = mCocos2dxActivity.getResources().getDisplayMetrics().density; +// Log.e("XXX", "density is " + density); editBox.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize / density ); } @@ -281,10 +270,10 @@ public class Cocos2dxEditBoxHelper { } public static void setFontColor(final int index, final int red, final int green, final int blue, final int alpha){ - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + mCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxEditBox editBox = sEditBoxArray.get(index); + Cocos2dxEditBox editBox = mEditBoxArray.get(index); if (editBox != null) { editBox.setTextColor(Color.argb(alpha, red, green, blue)); } @@ -293,10 +282,10 @@ public class Cocos2dxEditBoxHelper { } public static void setPlaceHolderText(final int index, final String text){ - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + mCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxEditBox editBox = sEditBoxArray.get(index); + Cocos2dxEditBox editBox = mEditBoxArray.get(index); if (editBox != null) { editBox.setHint(text); } @@ -305,10 +294,10 @@ public class Cocos2dxEditBoxHelper { } public static void setPlaceHolderTextColor(final int index, final int red, final int green, final int blue, final int alpha){ - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + mCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxEditBox editBox = sEditBoxArray.get(index); + Cocos2dxEditBox editBox = mEditBoxArray.get(index); if (editBox != null) { editBox.setHintTextColor(Color.argb(alpha, red, green, blue)); } @@ -317,10 +306,10 @@ public class Cocos2dxEditBoxHelper { } public static void setMaxLength(final int index, final int maxLength) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + mCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxEditBox editBox = sEditBoxArray.get(index); + Cocos2dxEditBox editBox = mEditBoxArray.get(index); if (editBox != null) { editBox.setMaxLength(maxLength); } @@ -329,10 +318,10 @@ public class Cocos2dxEditBoxHelper { } public static void setVisible(final int index, final boolean visible) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + mCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxEditBox editBox = sEditBoxArray.get(index); + Cocos2dxEditBox editBox = mEditBoxArray.get(index); if (editBox != null) { editBox.setVisibility(visible ? View.VISIBLE : View.GONE); } @@ -342,10 +331,10 @@ public class Cocos2dxEditBoxHelper { public static void setText(final int index, final String text){ - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + mCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxEditBox editBox = sEditBoxArray.get(index); + Cocos2dxEditBox editBox = mEditBoxArray.get(index); if (editBox != null) { editBox.setText(text); } @@ -354,10 +343,10 @@ public class Cocos2dxEditBoxHelper { } public static void setReturnType(final int index, final int returnType) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + mCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxEditBox editBox = sEditBoxArray.get(index); + Cocos2dxEditBox editBox = mEditBoxArray.get(index); if (editBox != null) { editBox.setReturnType(returnType); } @@ -366,10 +355,10 @@ public class Cocos2dxEditBoxHelper { } public static void setInputMode(final int index, final int inputMode) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + mCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxEditBox editBox = sEditBoxArray.get(index); + Cocos2dxEditBox editBox = mEditBoxArray.get(index); if (editBox != null) { editBox.setInputMode(inputMode); } @@ -378,10 +367,10 @@ public class Cocos2dxEditBoxHelper { } public static void setInputFlag(final int index, final int inputFlag) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + mCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxEditBox editBox = sEditBoxArray.get(index); + Cocos2dxEditBox editBox = mEditBoxArray.get(index); if (editBox != null) { editBox.setInputFlag(inputFlag); } @@ -391,10 +380,10 @@ public class Cocos2dxEditBoxHelper { public static void setEditBoxViewRect(final int index, final int left, final int top, final int maxWidth, final int maxHeight) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + mCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxEditBox editBox = sEditBoxArray.get(index); + Cocos2dxEditBox editBox = mEditBoxArray.get(index); if (editBox != null) { editBox.setEditBoxViewRect(left, top, maxWidth, maxHeight); } @@ -402,20 +391,14 @@ public class Cocos2dxEditBoxHelper { }); } - public static void openKeyboard(final int index) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { - @Override - public void run() { - openKeyboardOnUiThread(index); - } - }); - } - public static void closeKeyboard(final int index) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + + public static void openKeyboard(final int index) { + + mCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - closeKeyboardOnUiThread(index); + openKeyboardOnUiThread(index); } }); } @@ -426,12 +409,12 @@ public class Cocos2dxEditBoxHelper { return; } - final InputMethodManager imm = (InputMethodManager) Cocos2dxActivity.COCOS_ACTIVITY.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); - Cocos2dxEditBox editBox = sEditBoxArray.get(index); + final InputMethodManager imm = (InputMethodManager) mCocos2dxActivity.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + Cocos2dxEditBox editBox = mEditBoxArray.get(index); if (null != editBox) { editBox.requestFocus(); imm.showSoftInput(editBox, 0); - Cocos2dxActivity.COCOS_ACTIVITY.getGLSurfaceView().setSoftKeyboardShown(true); + mCocos2dxActivity.getGLSurfaceView().setSoftKeyboardShown(true); } } @@ -440,14 +423,25 @@ public class Cocos2dxEditBoxHelper { Log.e(TAG, "closeKeyboardOnUiThread doesn't run on UI thread!"); return; } - - final InputMethodManager imm = (InputMethodManager) Cocos2dxActivity.COCOS_ACTIVITY.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); - Cocos2dxEditBox editBox = sEditBoxArray.get(index); + + final InputMethodManager imm = (InputMethodManager) mCocos2dxActivity.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + Cocos2dxEditBox editBox = mEditBoxArray.get(index); if (null != editBox) { imm.hideSoftInputFromWindow(editBox.getWindowToken(), 0); - Cocos2dxActivity.COCOS_ACTIVITY.getGLSurfaceView().setSoftKeyboardShown(false); - Cocos2dxActivity.COCOS_ACTIVITY.getGLSurfaceView().requestFocus(); + mCocos2dxActivity.getGLSurfaceView().setSoftKeyboardShown(false); + mCocos2dxActivity.getGLSurfaceView().requestFocus(); + // can take effect after GLSurfaceView has focus + mCocos2dxActivity.hideVirtualButton(); } } -} + // Note that closeKeyboard will be invoked on GL thread + public static void closeKeyboard(final int index) { + mCocos2dxActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + closeKeyboardOnUiThread(index); + } + }); + } +} diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java index bce69d6ffc..f6eec17ebe 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java @@ -41,7 +41,7 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { // Constants // =========================================================== - private static final String TAG = "Cocos2dxGLSurfaceView"; + private static final String TAG = Cocos2dxGLSurfaceView.class.getSimpleName(); private final static int HANDLER_OPEN_IME_KEYBOARD = 2; private final static int HANDLER_CLOSE_IME_KEYBOARD = 3; @@ -49,87 +49,96 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { // =========================================================== // Fields // =========================================================== - private static IMEHandler sIMEHandler; - private static Cocos2dxGLSurfaceView sGLSurfaceView; - private static Cocos2dxTextInputWrapper sTextInputWrapper; - private Cocos2dxRenderer mCocosRenderer; - private Cocos2dxEditBox mCocosEditText; - private boolean mSoftKeyboardShown = false; + // TODO Static handler -> Potential leak! + private static Handler sHandler; + + private static Cocos2dxGLSurfaceView mCocos2dxGLSurfaceView; + private static Cocos2dxTextInputWraper sCocos2dxTextInputWraper; + + private Cocos2dxRenderer mCocos2dxRenderer; + private Cocos2dxEditBox mCocos2dxEditText; public boolean isSoftKeyboardShown() { return mSoftKeyboardShown; } public void setSoftKeyboardShown(boolean softKeyboardShown) { - mSoftKeyboardShown = softKeyboardShown; + this.mSoftKeyboardShown = softKeyboardShown; } + private boolean mSoftKeyboardShown = false; + + // =========================================================== // Constructors // =========================================================== public Cocos2dxGLSurfaceView(final Context context) { super(context); - initView(); + + this.initView(); } public Cocos2dxGLSurfaceView(final Context context, final AttributeSet attrs) { super(context, attrs); - initView(); - } - - static class IMEHandler extends Handler { - @Override - public void handleMessage(Message msg) { - switch (msg.what) { - case HANDLER_OPEN_IME_KEYBOARD: - if (null != sGLSurfaceView.mCocosEditText && sGLSurfaceView.mCocosEditText.requestFocus()) { - sGLSurfaceView.mCocosEditText.removeTextChangedListener(Cocos2dxGLSurfaceView.sTextInputWrapper); - sGLSurfaceView.mCocosEditText.setText(""); - final String text = (String) msg.obj; - sGLSurfaceView.mCocosEditText.append(text); - Cocos2dxGLSurfaceView.sTextInputWrapper.setOriginText(text); - sGLSurfaceView.mCocosEditText.addTextChangedListener(Cocos2dxGLSurfaceView.sTextInputWrapper); - - InputMethodManager imm = (InputMethodManager) Cocos2dxActivity.COCOS_ACTIVITY.getSystemService(Context.INPUT_METHOD_SERVICE); - imm.showSoftInput(sGLSurfaceView.mCocosEditText, 0); - Log.d(TAG, "showSoftInput"); - } - break; - - case HANDLER_CLOSE_IME_KEYBOARD: - if (null != sGLSurfaceView.mCocosEditText) { - sGLSurfaceView.mCocosEditText.removeTextChangedListener(Cocos2dxGLSurfaceView.sTextInputWrapper); - InputMethodManager imm = (InputMethodManager) Cocos2dxActivity.COCOS_ACTIVITY.getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow(sGLSurfaceView.mCocosEditText.getWindowToken(), 0); - sGLSurfaceView.requestFocus(); - Log.d(TAG, "HideSoftInput"); - } - break; - } - } + + this.initView(); } protected void initView() { - setEGLContextClientVersion(2); - setFocusableInTouchMode(true); + this.setEGLContextClientVersion(2); + this.setFocusableInTouchMode(true); - sGLSurfaceView = this; - sTextInputWrapper = new Cocos2dxTextInputWrapper(this); - sIMEHandler = new IMEHandler(); + Cocos2dxGLSurfaceView.mCocos2dxGLSurfaceView = this; + Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper = new Cocos2dxTextInputWraper(this); + + Cocos2dxGLSurfaceView.sHandler = new Handler() { + @Override + public void handleMessage(final Message msg) { + switch (msg.what) { + case HANDLER_OPEN_IME_KEYBOARD: + if (null != Cocos2dxGLSurfaceView.this.mCocos2dxEditText && Cocos2dxGLSurfaceView.this.mCocos2dxEditText.requestFocus()) { + Cocos2dxGLSurfaceView.this.mCocos2dxEditText.removeTextChangedListener(Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper); + Cocos2dxGLSurfaceView.this.mCocos2dxEditText.setText(""); + final String text = (String) msg.obj; + Cocos2dxGLSurfaceView.this.mCocos2dxEditText.append(text); + Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper.setOriginText(text); + Cocos2dxGLSurfaceView.this.mCocos2dxEditText.addTextChangedListener(Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper); + final InputMethodManager imm = (InputMethodManager) Cocos2dxGLSurfaceView.mCocos2dxGLSurfaceView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + imm.showSoftInput(Cocos2dxGLSurfaceView.this.mCocos2dxEditText, 0); + Log.d("GLSurfaceView", "showSoftInput"); + } + break; + + case HANDLER_CLOSE_IME_KEYBOARD: + if (null != Cocos2dxGLSurfaceView.this.mCocos2dxEditText) { + Cocos2dxGLSurfaceView.this.mCocos2dxEditText.removeTextChangedListener(Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper); + final InputMethodManager imm = (InputMethodManager) Cocos2dxGLSurfaceView.mCocos2dxGLSurfaceView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + imm.hideSoftInputFromWindow(Cocos2dxGLSurfaceView.this.mCocos2dxEditText.getWindowToken(), 0); + Cocos2dxGLSurfaceView.this.requestFocus(); + // can take effect after GLSurfaceView has focus + ((Cocos2dxActivity)Cocos2dxGLSurfaceView.mCocos2dxGLSurfaceView.getContext()).hideVirtualButton(); + Log.d("GLSurfaceView", "HideSoftInput"); + } + break; + } + } + }; } // =========================================================== // Getter & Setter // =========================================================== - public static Cocos2dxGLSurfaceView getInstance() { - return sGLSurfaceView; - } - public static void queueAccelerometer(final float x, final float y, final float z, final long timestamp) { - sGLSurfaceView.queueEvent(new Runnable() { - @Override + + public static Cocos2dxGLSurfaceView getInstance() { + return mCocos2dxGLSurfaceView; + } + + public static void queueAccelerometer(final float x, final float y, final float z, final long timestamp) { + mCocos2dxGLSurfaceView.queueEvent(new Runnable() { + @Override public void run() { Cocos2dxAccelerometer.onSensorChanged(x, y, z, timestamp); } @@ -137,27 +146,23 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { } public void setCocos2dxRenderer(final Cocos2dxRenderer renderer) { - mCocosRenderer = renderer; - setRenderer(mCocosRenderer); - } - - public Cocos2dxRenderer getCocos2dxRenderer() { - return mCocosRenderer; + this.mCocos2dxRenderer = renderer; + this.setRenderer(this.mCocos2dxRenderer); } private String getContentText() { - return mCocosRenderer.getContentText(); + return this.mCocos2dxRenderer.getContentText(); } public Cocos2dxEditBox getCocos2dxEditText() { - return mCocosEditText; + return this.mCocos2dxEditText; } - public void setCocos2dxEditText(final Cocos2dxEditBox cocos2dxEditText) { - mCocosEditText = cocos2dxEditText; - if (null != mCocosEditText && null != sTextInputWrapper) { - mCocosEditText.setOnEditorActionListener(sTextInputWrapper); - requestFocus(); + public void setCocos2dxEditText(final Cocos2dxEditBox pCocos2dxEditText) { + this.mCocos2dxEditText = pCocos2dxEditText; + if (null != this.mCocos2dxEditText && null != Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper) { + this.mCocos2dxEditText.setOnEditorActionListener(Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper); + this.requestFocus(); } } @@ -168,24 +173,24 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { @Override public void onResume() { super.onResume(); - setRenderMode(RENDERMODE_CONTINUOUSLY); - queueEvent(new Runnable() { + this.setRenderMode(RENDERMODE_CONTINUOUSLY); + this.queueEvent(new Runnable() { @Override public void run() { - sGLSurfaceView.mCocosRenderer.handleOnResume(); + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleOnResume(); } }); } @Override public void onPause() { - queueEvent(new Runnable() { + this.queueEvent(new Runnable() { @Override public void run() { - sGLSurfaceView.mCocosRenderer.handleOnPause(); + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleOnPause(); } }); - setRenderMode(RENDERMODE_WHEN_DIRTY); + this.setRenderMode(RENDERMODE_WHEN_DIRTY); //super.onPause(); } @@ -198,11 +203,10 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { final float[] ys = new float[pointerNumber]; if (mSoftKeyboardShown){ - InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); - View view = ((Activity)getContext()).getCurrentFocus(); - if (view != null) - imm.hideSoftInputFromWindow(view.getWindowToken(),0); - requestFocus(); + InputMethodManager imm = (InputMethodManager)this.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + View view = ((Activity)this.getContext()).getCurrentFocus(); + imm.hideSoftInputFromWindow(view.getWindowToken(),0); + this.requestFocus(); mSoftKeyboardShown = false; } @@ -222,7 +226,7 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { this.queueEvent(new Runnable() { @Override public void run() { - sGLSurfaceView.mCocosRenderer.handleActionDown(idPointerDown, xPointerDown, yPointerDown); + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionDown(idPointerDown, xPointerDown, yPointerDown); } }); break; @@ -236,7 +240,7 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { this.queueEvent(new Runnable() { @Override public void run() { - sGLSurfaceView.mCocosRenderer.handleActionDown(idDown, xDown, yDown); + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionDown(idDown, xDown, yDown); } }); break; @@ -245,7 +249,7 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { this.queueEvent(new Runnable() { @Override public void run() { - sGLSurfaceView.mCocosRenderer.handleActionMove(ids, xs, ys); + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionMove(ids, xs, ys); } }); break; @@ -259,7 +263,7 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { this.queueEvent(new Runnable() { @Override public void run() { - sGLSurfaceView.mCocosRenderer.handleActionUp(idPointerUp, xPointerUp, yPointerUp); + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionUp(idPointerUp, xPointerUp, yPointerUp); } }); break; @@ -273,7 +277,7 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { this.queueEvent(new Runnable() { @Override public void run() { - sGLSurfaceView.mCocosRenderer.handleActionUp(idUp, xUp, yUp); + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionUp(idUp, xUp, yUp); } }); break; @@ -282,12 +286,17 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { this.queueEvent(new Runnable() { @Override public void run() { - sGLSurfaceView.mCocosRenderer.handleActionCancel(ids, xs, ys); + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionCancel(ids, xs, ys); } }); break; } + /* + if (BuildConfig.DEBUG) { + Cocos2dxGLSurfaceView.dumpMotionEvent(pMotionEvent); + } + */ return true; } @@ -297,8 +306,8 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { */ @Override protected void onSizeChanged(final int pNewSurfaceWidth, final int pNewSurfaceHeight, final int pOldSurfaceWidth, final int pOldSurfaceHeight) { - if(!isInEditMode()) { - mCocosRenderer.setScreenWidthAndHeight(pNewSurfaceWidth, pNewSurfaceHeight); + if(!this.isInEditMode()) { + this.mCocos2dxRenderer.setScreenWidthAndHeight(pNewSurfaceWidth, pNewSurfaceHeight); } } @@ -306,7 +315,7 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { public boolean onKeyDown(final int pKeyCode, final KeyEvent pKeyEvent) { switch (pKeyCode) { case KeyEvent.KEYCODE_BACK: - Cocos2dxVideoHelper.sVideoHandler.sendEmptyMessage(Cocos2dxVideoHelper.KeyEventBack); + Cocos2dxVideoHelper.mVideoHandler.sendEmptyMessage(Cocos2dxVideoHelper.KeyEventBack); case KeyEvent.KEYCODE_MENU: case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_DPAD_RIGHT: @@ -318,7 +327,7 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { this.queueEvent(new Runnable() { @Override public void run() { - sGLSurfaceView.mCocosRenderer.handleKeyDown(pKeyCode); + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleKeyDown(pKeyCode); } }); return true; @@ -342,7 +351,7 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { this.queueEvent(new Runnable() { @Override public void run() { - sGLSurfaceView.mCocosRenderer.handleKeyUp(keyCode); + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleKeyUp(keyCode); } }); return true; @@ -351,28 +360,32 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { } } + // =========================================================== + // Methods + // =========================================================== + // =========================================================== // Inner and Anonymous Classes // =========================================================== public static void openIMEKeyboard() { - Message msg = Message.obtain(); - msg.what = HANDLER_OPEN_IME_KEYBOARD; - msg.obj = sGLSurfaceView.getContentText(); - sIMEHandler.sendMessage(msg); + final Message msg = new Message(); + msg.what = Cocos2dxGLSurfaceView.HANDLER_OPEN_IME_KEYBOARD; + msg.obj = Cocos2dxGLSurfaceView.mCocos2dxGLSurfaceView.getContentText(); + Cocos2dxGLSurfaceView.sHandler.sendMessage(msg); } public static void closeIMEKeyboard() { - Message msg = Message.obtain(); - msg.what = HANDLER_CLOSE_IME_KEYBOARD; - sIMEHandler.sendMessage(msg); + final Message msg = new Message(); + msg.what = Cocos2dxGLSurfaceView.HANDLER_CLOSE_IME_KEYBOARD; + Cocos2dxGLSurfaceView.sHandler.sendMessage(msg); } - public void insertText(final String text) { + public void insertText(final String pText) { this.queueEvent(new Runnable() { @Override public void run() { - sGLSurfaceView.mCocosRenderer.handleInsertText(text); + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleInsertText(pText); } }); } @@ -381,9 +394,32 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { this.queueEvent(new Runnable() { @Override public void run() { - sGLSurfaceView.mCocosRenderer.handleDeleteBackward(); + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleDeleteBackward(); } }); } -} + private static void dumpMotionEvent(final MotionEvent event) { + final String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE", "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" }; + final StringBuilder sb = new StringBuilder(); + final int action = event.getAction(); + final int actionCode = action & MotionEvent.ACTION_MASK; + sb.append("event ACTION_").append(names[actionCode]); + if (actionCode == MotionEvent.ACTION_POINTER_DOWN || actionCode == MotionEvent.ACTION_POINTER_UP) { + sb.append("(pid ").append(action >> MotionEvent.ACTION_POINTER_INDEX_SHIFT); + sb.append(")"); + } + sb.append("["); + for (int i = 0; i < event.getPointerCount(); i++) { + sb.append("#").append(i); + sb.append("(pid ").append(event.getPointerId(i)); + sb.append(")=").append((int) event.getX(i)); + sb.append(",").append((int) event.getY(i)); + if (i + 1 < event.getPointerCount()) { + sb.append(";"); + } + } + sb.append("]"); + Log.d(Cocos2dxGLSurfaceView.TAG, sb.toString()); + } +} diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHandler.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHandler.java index 8d823a6ab2..2de5e16d47 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHandler.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHandler.java @@ -25,7 +25,6 @@ THE SOFTWARE. package org.cocos2dx.lib; -import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Handler; @@ -42,15 +41,23 @@ public class Cocos2dxHandler extends Handler { // =========================================================== // Fields // =========================================================== - private WeakReference mActivityReference; - + private WeakReference mActivity; + // =========================================================== // Constructors // =========================================================== - public Cocos2dxHandler(Activity activity) { - mActivityReference = new WeakReference(activity); + public Cocos2dxHandler(Cocos2dxActivity activity) { + this.mActivity = new WeakReference(activity); } + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + // =========================================================== // Methods // =========================================================== @@ -64,12 +71,12 @@ public class Cocos2dxHandler extends Handler { } private void showDialog(Message msg) { - Activity theActivity = mActivityReference.get(); + Cocos2dxActivity theActivity = this.mActivity.get(); DialogMessage dialogMessage = (DialogMessage)msg.obj; new AlertDialog.Builder(theActivity) - .setTitle(dialogMessage.mTitle) - .setMessage(dialogMessage.mMessage) - .setPositiveButton("Ok", + .setTitle(dialogMessage.title) + .setMessage(dialogMessage.message) + .setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override @@ -85,13 +92,12 @@ public class Cocos2dxHandler extends Handler { // =========================================================== public static class DialogMessage { - public String mTitle; - public String mMessage; - + public String title; + public String message; + public DialogMessage(String title, String message) { - mTitle = title; - mMessage = message; + this.title = title; + this.message = message; } } } - diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java index 64bf796f2b..9144879cc5 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java @@ -1,6 +1,6 @@ /**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2016 Chukong Technologies Inc. +Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -24,87 +24,223 @@ THE SOFTWARE. ****************************************************************************/ package org.cocos2dx.lib; +import android.content.pm.PackageManager; +import android.media.AudioManager; import android.app.Activity; +import android.content.ComponentName; import android.content.Context; import android.content.Intent; +import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager.NameNotFoundException; +import android.content.res.AssetFileDescriptor; import android.content.res.AssetManager; import android.net.Uri; import android.os.Build; +import android.os.Environment; +import android.os.IBinder; +import android.os.ParcelFileDescriptor; import android.os.Vibrator; import android.preference.PreferenceManager.OnActivityResultListener; import android.util.DisplayMetrics; +import android.util.Log; import android.view.Display; import android.view.WindowManager; +import android.hardware.SensorManager; +import com.android.vending.expansion.zipfile.APKExpansionSupport; +import com.android.vending.expansion.zipfile.ZipResourceFile; + +import com.enhance.gameservice.IGameTuningService; + +import java.io.IOException; +import java.io.File; import java.io.UnsupportedEncodingException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.util.LinkedHashSet; import java.util.Locale; import java.util.Map; import java.util.Set; + public class Cocos2dxHelper { + // =========================================================== + // Constants + // =========================================================== private static final String PREFS_NAME = "Cocos2dxPrefsFile"; private static final int RUNNABLES_PER_FRAME = 5; + private static final String TAG = Cocos2dxHelper.class.getSimpleName(); // =========================================================== // Fields // =========================================================== - private static Cocos2dxMusic sCocosMusic; - private static Cocos2dxSound sCocosSound; + private static Cocos2dxMusic sCocos2dMusic; + private static Cocos2dxSound sCocos2dSound; private static AssetManager sAssetManager; - private static Cocos2dxAccelerometer sAccelerometer; + private static Cocos2dxAccelerometer sCocos2dxAccelerometer; private static boolean sAccelerometerEnabled; + private static boolean sCompassEnabled; private static boolean sActivityVisible; private static String sPackageName; private static String sFileDirectory; - + private static Activity sActivity = null; + private static Cocos2dxHelperListener sCocos2dxHelperListener; private static Set onActivityResultListeners = new LinkedHashSet(); private static Vibrator sVibrateService = null; + //Enhance API modification begin + private static IGameTuningService mGameServiceBinder = null; + private static final int BOOST_TIME = 7; + //Enhance API modification end + + // The absolute path to the OBB if it exists, else the absolute path to the APK. + private static String sAssetsPath = ""; + + // The OBB file + private static ZipResourceFile sOBBFile = null; + + // =========================================================== + // Constructors + // =========================================================== public static void runOnGLThread(final Runnable r) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(r); + ((Cocos2dxActivity)sActivity).runOnGLThread(r); } private static boolean sInited = false; public static void init(final Activity activity) { + sActivity = activity; + Cocos2dxHelper.sCocos2dxHelperListener = (Cocos2dxHelperListener)activity; if (!sInited) { + + PackageManager pm = activity.getPackageManager(); + boolean isSupportLowLatency = pm.hasSystemFeature(PackageManager.FEATURE_AUDIO_LOW_LATENCY); + + Log.d(TAG, "isSupportLowLatency:" + isSupportLowLatency); + + int sampleRate = 44100; + int bufferSizeInFrames = 192; + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { + AudioManager am = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE); + String strSampleRate = am.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE); + String strBufferSizeInFrames = am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER); + + sampleRate = Integer.parseInt(strSampleRate); + bufferSizeInFrames = Integer.parseInt(strBufferSizeInFrames); + + Log.d(TAG, "sampleRate: " + sampleRate + ", framesPerBuffer: " + bufferSizeInFrames); + } else { + Log.d(TAG, "android version is lower than " + Build.VERSION_CODES.JELLY_BEAN_MR1); + } + + nativeSetAudioDeviceInfo(isSupportLowLatency, sampleRate, bufferSizeInFrames); + final ApplicationInfo applicationInfo = activity.getApplicationInfo(); + + Cocos2dxHelper.sPackageName = applicationInfo.packageName; + Cocos2dxHelper.sFileDirectory = activity.getFilesDir().getAbsolutePath(); + + Cocos2dxHelper.nativeSetApkPath(Cocos2dxHelper.getAssetsPath()); + + Cocos2dxHelper.sCocos2dxAccelerometer = new Cocos2dxAccelerometer(activity); + Cocos2dxHelper.sCocos2dMusic = new Cocos2dxMusic(activity); + Cocos2dxHelper.sCocos2dSound = new Cocos2dxSound(activity); + Cocos2dxHelper.sAssetManager = activity.getAssets(); + Cocos2dxHelper.nativeSetContext((Context)activity, Cocos2dxHelper.sAssetManager); + + Cocos2dxBitmap.setContext(activity); - sPackageName = applicationInfo.packageName; - sFileDirectory = activity.getFilesDir().getAbsolutePath(); - - nativeSetApkPath(applicationInfo.sourceDir); - - sAccelerometer = new Cocos2dxAccelerometer(activity); - sCocosMusic = new Cocos2dxMusic(activity); - sCocosSound = new Cocos2dxSound(activity); - sAssetManager = activity.getAssets(); - nativeSetContext(activity.getClass().getClassLoader(), sAssetManager); - sVibrateService = (Vibrator)activity.getSystemService(Context.VIBRATOR_SERVICE); + Cocos2dxHelper.sVibrateService = (Vibrator)activity.getSystemService(Context.VIBRATOR_SERVICE); sInited = true; + + //Enhance API modification begin + Intent serviceIntent = new Intent(IGameTuningService.class.getName()); + serviceIntent.setPackage("com.enhance.gameservice"); + boolean suc = activity.getApplicationContext().bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE); + //Enhance API modification end + + int versionCode = 1; + try { + versionCode = Cocos2dxActivity.getContext().getPackageManager().getPackageInfo(Cocos2dxHelper.getCocos2dxPackageName(), 0).versionCode; + } catch (NameNotFoundException e) { + e.printStackTrace(); + } + try { + Cocos2dxHelper.sOBBFile = APKExpansionSupport.getAPKExpansionZipFile(Cocos2dxActivity.getContext(), versionCode, 0); + } catch (IOException e) { + e.printStackTrace(); + } } } - - public static Activity getActivity() { - return Cocos2dxActivity.COCOS_ACTIVITY; + + // This function returns the absolute path to the OBB if it exists, + // else it returns the absolute path to the APK. + public static String getAssetsPath() + { + if (Cocos2dxHelper.sAssetsPath == "") { + int versionCode = 1; + try { + versionCode = Cocos2dxHelper.sActivity.getPackageManager().getPackageInfo(Cocos2dxHelper.sPackageName, 0).versionCode; + } catch (NameNotFoundException e) { + e.printStackTrace(); + } + String pathToOBB = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/obb/" + Cocos2dxHelper.sPackageName + "/main." + versionCode + "." + Cocos2dxHelper.sPackageName + ".obb"; + File obbFile = new File(pathToOBB); + if (obbFile.exists()) + Cocos2dxHelper.sAssetsPath = pathToOBB; + else + Cocos2dxHelper.sAssetsPath = Cocos2dxHelper.sActivity.getApplicationInfo().sourceDir; + } + + return Cocos2dxHelper.sAssetsPath; } + + public static ZipResourceFile getObbFile() + { + return Cocos2dxHelper.sOBBFile; + } + + //Enhance API modification begin + private static ServiceConnection connection = new ServiceConnection() { + public void onServiceConnected(ComponentName name, IBinder service) { + mGameServiceBinder = IGameTuningService.Stub.asInterface(service); + fastLoading(BOOST_TIME); + } + public void onServiceDisconnected(ComponentName name) { + sActivity.getApplicationContext().unbindService(connection); + } + }; + //Enhance API modification end + + public static Activity getActivity() { + return sActivity; + } + public static void addOnActivityResultListener(OnActivityResultListener listener) { onActivityResultListeners.add(listener); } - + public static Set getOnActivityResultListeners() { return onActivityResultListeners; } - + public static boolean isActivityVisible(){ return sActivityVisible; } + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + // =========================================================== // Methods // =========================================================== @@ -113,7 +249,9 @@ public class Cocos2dxHelper { private static native void nativeSetEditTextDialogResult(final byte[] pBytes); - private static native void nativeSetContext(final ClassLoader classLoader, final AssetManager pAssetManager); + private static native void nativeSetContext(final Context pContext, final AssetManager pAssetManager); + + private static native void nativeSetAudioDeviceInfo(boolean isSupportLowLatency, int deviceSampleRate, int audioBufferSizeInFames); public static String getCocos2dxPackageName() { return Cocos2dxHelper.sPackageName; @@ -125,205 +263,208 @@ public class Cocos2dxHelper { public static String getCurrentLanguage() { return Locale.getDefault().getLanguage(); } - + public static String getDeviceModel(){ return Build.MODEL; } - public static int getSDKVersion() { - return Build.VERSION.SDK_INT; - } - public static AssetManager getAssetManager() { return Cocos2dxHelper.sAssetManager; } public static void enableAccelerometer() { - if (sAccelerometer != null) { - sAccelerometerEnabled = true; - sAccelerometer.enable(); - } + Cocos2dxHelper.sAccelerometerEnabled = true; + Cocos2dxHelper.sCocos2dxAccelerometer.enableAccel(); + } + + public static void enableCompass() { + Cocos2dxHelper.sCompassEnabled = true; + Cocos2dxHelper.sCocos2dxAccelerometer.enableCompass(); } public static void setAccelerometerInterval(float interval) { - if (sAccelerometer != null) { - sAccelerometer.setInterval(interval); - } + Cocos2dxHelper.sCocos2dxAccelerometer.setInterval(interval); } public static void disableAccelerometer() { - if (sAccelerometer != null) { - sAccelerometerEnabled = false; - sAccelerometer.disable(); - } + Cocos2dxHelper.sAccelerometerEnabled = false; + Cocos2dxHelper.sCocos2dxAccelerometer.disable(); } public static void setKeepScreenOn(boolean value) { - Cocos2dxActivity.COCOS_ACTIVITY.setKeepScreenOn(value); + ((Cocos2dxActivity)sActivity).setKeepScreenOn(value); } public static void vibrate(float duration) { - if (sVibrateService != null) - sVibrateService.vibrate((long)(duration * 1000)); + sVibrateService.vibrate((long)(duration * 1000)); } - public static boolean openURL(String url) { + public static String getVersion() { + try { + String version = Cocos2dxActivity.getContext().getPackageManager().getPackageInfo(Cocos2dxActivity.getContext().getPackageName(), 0).versionName; + return version; + } catch(Exception e) { + return ""; + } + } + + public static boolean openURL(String url) { boolean ret = false; try { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); - Cocos2dxActivity.COCOS_ACTIVITY.startActivity(i); + sActivity.startActivity(i); ret = true; } catch (Exception e) { } return ret; } + + public static long[] getObbAssetFileDescriptor(final String path) { + long[] array = new long[3]; + if (Cocos2dxHelper.sOBBFile != null) { + AssetFileDescriptor descriptor = Cocos2dxHelper.sOBBFile.getAssetFileDescriptor(path); + if (descriptor != null) { + try { + ParcelFileDescriptor parcel = descriptor.getParcelFileDescriptor(); + Method method = parcel.getClass().getMethod("getFd", new Class[] {}); + array[0] = (Integer)method.invoke(parcel); + array[1] = descriptor.getStartOffset(); + array[2] = descriptor.getLength(); + } catch (NoSuchMethodException e) { + Log.e(Cocos2dxHelper.TAG, "Accessing file descriptor directly from the OBB is only supported from Android 3.1 (API level 12) and above."); + } catch (IllegalAccessException e) { + Log.e(Cocos2dxHelper.TAG, e.toString()); + } catch (InvocationTargetException e) { + Log.e(Cocos2dxHelper.TAG, e.toString()); + } + } + } + return array; + } public static void preloadBackgroundMusic(final String pPath) { - sCocosMusic.preloadBackgroundMusic(pPath); + Cocos2dxHelper.sCocos2dMusic.preloadBackgroundMusic(pPath); } public static void playBackgroundMusic(final String pPath, final boolean isLoop) { - sCocosMusic.playBackgroundMusic(pPath, isLoop); + Cocos2dxHelper.sCocos2dMusic.playBackgroundMusic(pPath, isLoop); } public static void resumeBackgroundMusic() { - sCocosMusic.resumeBackgroundMusic(); + Cocos2dxHelper.sCocos2dMusic.resumeBackgroundMusic(); } public static void pauseBackgroundMusic() { - sCocosMusic.pauseBackgroundMusic(); + Cocos2dxHelper.sCocos2dMusic.pauseBackgroundMusic(); } public static void stopBackgroundMusic() { - sCocosMusic.stopBackgroundMusic(); + Cocos2dxHelper.sCocos2dMusic.stopBackgroundMusic(); } public static void rewindBackgroundMusic() { - sCocosMusic.rewindBackgroundMusic(); + Cocos2dxHelper.sCocos2dMusic.rewindBackgroundMusic(); + } + + public static boolean willPlayBackgroundMusic() { + return Cocos2dxHelper.sCocos2dMusic.willPlayBackgroundMusic(); } public static boolean isBackgroundMusicPlaying() { - return sCocosMusic.isBackgroundMusicPlaying(); + return Cocos2dxHelper.sCocos2dMusic.isBackgroundMusicPlaying(); } public static float getBackgroundMusicVolume() { - return sCocosMusic.getBackgroundVolume(); + return Cocos2dxHelper.sCocos2dMusic.getBackgroundVolume(); } public static void setBackgroundMusicVolume(final float volume) { - sCocosMusic.setBackgroundVolume(volume); + Cocos2dxHelper.sCocos2dMusic.setBackgroundVolume(volume); } public static void preloadEffect(final String path) { - sCocosSound.preloadEffect(path); + Cocos2dxHelper.sCocos2dSound.preloadEffect(path); } public static int playEffect(final String path, final boolean isLoop, final float pitch, final float pan, final float gain) { - return sCocosSound.playEffect(path, isLoop, pitch, pan, gain); + return Cocos2dxHelper.sCocos2dSound.playEffect(path, isLoop, pitch, pan, gain); } public static void resumeEffect(final int soundId) { - sCocosSound.resumeEffect(soundId); + Cocos2dxHelper.sCocos2dSound.resumeEffect(soundId); } public static void pauseEffect(final int soundId) { - sCocosSound.pauseEffect(soundId); + Cocos2dxHelper.sCocos2dSound.pauseEffect(soundId); } public static void stopEffect(final int soundId) { - sCocosSound.stopEffect(soundId); + Cocos2dxHelper.sCocos2dSound.stopEffect(soundId); } public static float getEffectsVolume() { - return sCocosSound.getEffectsVolume(); + return Cocos2dxHelper.sCocos2dSound.getEffectsVolume(); } public static void setEffectsVolume(final float volume) { - sCocosSound.setEffectsVolume(volume); + Cocos2dxHelper.sCocos2dSound.setEffectsVolume(volume); } public static void unloadEffect(final String path) { - sCocosSound.unloadEffect(path); + Cocos2dxHelper.sCocos2dSound.unloadEffect(path); } public static void pauseAllEffects() { - sCocosSound.pauseAllEffects(); + Cocos2dxHelper.sCocos2dSound.pauseAllEffects(); } public static void resumeAllEffects() { - sCocosSound.resumeAllEffects(); + Cocos2dxHelper.sCocos2dSound.resumeAllEffects(); } public static void stopAllEffects() { - sCocosSound.stopAllEffects(); + Cocos2dxHelper.sCocos2dSound.stopAllEffects(); } - public static void destroyAudioEngine() { - if (sCocosMusic != null) - { - sCocosMusic.end(); - sCocosMusic = null; - } - if (sCocosSound != null) - { - sCocosSound.end(); - sCocosSound = null; - } - } - - public static void reset() { - destroyAudioEngine(); - onActivityResultListeners.clear(); - - if (sAccelerometer != null) { - disableAccelerometer(); - sAccelerometer = null; - } - - sVibrateService = null; + public static void end() { + Cocos2dxHelper.sCocos2dMusic.end(); + Cocos2dxHelper.sCocos2dSound.end(); } public static void onResume() { sActivityVisible = true; - if (sAccelerometerEnabled) { - sAccelerometer.enable(); + if (Cocos2dxHelper.sAccelerometerEnabled) { + Cocos2dxHelper.sCocos2dxAccelerometer.enableAccel(); + } + if (Cocos2dxHelper.sCompassEnabled) { + Cocos2dxHelper.sCocos2dxAccelerometer.enableCompass(); } } public static void onPause() { sActivityVisible = false; - if (sAccelerometerEnabled) { - sAccelerometer.disable(); + if (Cocos2dxHelper.sAccelerometerEnabled) { + Cocos2dxHelper.sCocos2dxAccelerometer.disable(); } } public static void onEnterBackground() { - if (sCocosSound != null) { - sCocosSound.onEnterBackground(); - } - - if (sCocosMusic != null) { - sCocosMusic.onEnterBackground(); - } + sCocos2dSound.onEnterBackground(); + sCocos2dMusic.onEnterBackground(); } - + public static void onEnterForeground() { - if (sCocosSound != null) { - sCocosSound.onEnterForeground(); - } - - if (sCocosMusic != null) { - sCocosMusic.onEnterForeground(); - } + sCocos2dSound.onEnterForeground(); + sCocos2dMusic.onEnterForeground(); } - + public static void terminateProcess() { android.os.Process.killProcess(android.os.Process.myPid()); } private static void showDialog(final String pTitle, final String pMessage) { - Cocos2dxActivity.COCOS_ACTIVITY.showDialog(pTitle, pMessage); + Cocos2dxHelper.sCocos2dxHelperListener.showDialog(pTitle, pMessage); } @@ -331,7 +472,7 @@ public class Cocos2dxHelper { try { final byte[] bytesUTF8 = pResult.getBytes("UTF8"); - Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(new Runnable() { + Cocos2dxHelper.sCocos2dxHelperListener.runOnGLThread(new Runnable() { @Override public void run() { Cocos2dxHelper.nativeSetEditTextDialogResult(bytesUTF8); @@ -344,10 +485,10 @@ public class Cocos2dxHelper { public static int getDPI() { - if (Cocos2dxActivity.COCOS_ACTIVITY != null) + if (sActivity != null) { DisplayMetrics metrics = new DisplayMetrics(); - WindowManager wm = Cocos2dxActivity.COCOS_ACTIVITY.getWindowManager(); + WindowManager wm = sActivity.getWindowManager(); if (wm != null) { Display d = wm.getDefaultDisplay(); @@ -360,13 +501,13 @@ public class Cocos2dxHelper { } return -1; } - + // =========================================================== // Functions for CCUserDefault // =========================================================== - + public static boolean getBoolForKey(String key, boolean defaultValue) { - SharedPreferences settings = Cocos2dxActivity.COCOS_ACTIVITY.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); + SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); try { return settings.getBoolean(key, defaultValue); } @@ -393,9 +534,9 @@ public class Cocos2dxHelper { return false; } - + public static int getIntegerForKey(String key, int defaultValue) { - SharedPreferences settings = Cocos2dxActivity.COCOS_ACTIVITY.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); + SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); try { return settings.getInt(key, defaultValue); } @@ -421,9 +562,9 @@ public class Cocos2dxHelper { return 0; } - + public static float getFloatForKey(String key, float defaultValue) { - SharedPreferences settings = Cocos2dxActivity.COCOS_ACTIVITY.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); + SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); try { return settings.getFloat(key, defaultValue); } @@ -449,62 +590,62 @@ public class Cocos2dxHelper { return 0.0f; } - + public static double getDoubleForKey(String key, double defaultValue) { // SharedPreferences doesn't support saving double value return getFloatForKey(key, (float) defaultValue); } - + public static String getStringForKey(String key, String defaultValue) { - SharedPreferences settings = Cocos2dxActivity.COCOS_ACTIVITY.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); + SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); try { return settings.getString(key, defaultValue); } catch (Exception ex) { ex.printStackTrace(); - + return settings.getAll().get(key).toString(); } } - + public static void setBoolForKey(String key, boolean value) { - SharedPreferences settings = Cocos2dxActivity.COCOS_ACTIVITY.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); + SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(key, value); editor.commit(); } - + public static void setIntegerForKey(String key, int value) { - SharedPreferences settings = Cocos2dxActivity.COCOS_ACTIVITY.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); + SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putInt(key, value); editor.commit(); } - + public static void setFloatForKey(String key, float value) { - SharedPreferences settings = Cocos2dxActivity.COCOS_ACTIVITY.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); + SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putFloat(key, value); editor.commit(); } - + public static void setDoubleForKey(String key, double value) { // SharedPreferences doesn't support recording double value - SharedPreferences settings = Cocos2dxActivity.COCOS_ACTIVITY.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); + SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putFloat(key, (float)value); editor.commit(); } - + public static void setStringForKey(String key, String value) { - SharedPreferences settings = Cocos2dxActivity.COCOS_ACTIVITY.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); + SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putString(key, value); editor.commit(); } - + public static void deleteValueForKey(String key) { - SharedPreferences settings = Cocos2dxActivity.COCOS_ACTIVITY.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); + SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.remove(key); editor.commit(); @@ -521,6 +662,84 @@ public class Cocos2dxHelper { return null; } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + public static interface Cocos2dxHelperListener { + public void showDialog(final String pTitle, final String pMessage); + + public void runOnGLThread(final Runnable pRunnable); + } + + //Enhance API modification begin + public static int setResolutionPercent(int per) { + try { + if (mGameServiceBinder != null) { + return mGameServiceBinder.setPreferredResolution(per); + } + return -1; + } catch (Exception e) { + e.printStackTrace(); + return -1; + } + } + + public static int setFPS(int fps) { + try { + if (mGameServiceBinder != null) { + return mGameServiceBinder.setFramePerSecond(fps); + } + return -1; + } catch (Exception e) { + e.printStackTrace(); + return -1; + } + } + + public static int fastLoading(int sec) { + try { + if (mGameServiceBinder != null) { + return mGameServiceBinder.boostUp(sec); + } + return -1; + } catch (Exception e) { + e.printStackTrace(); + return -1; + } + } + + public static int getTemperature() { + try { + if (mGameServiceBinder != null) { + return mGameServiceBinder.getAbstractTemperature(); + } + return -1; + } catch (Exception e) { + e.printStackTrace(); + return -1; + } + } + + public static int setLowPowerMode(boolean enable) { + try { + if (mGameServiceBinder != null) { + return mGameServiceBinder.setGamePowerSaving(enable); + } + return -1; + } catch (Exception e) { + e.printStackTrace(); + return -1; + } + } + + //Enhance API modification end + public static float[] getAccelValue() { + return Cocos2dxHelper.sCocos2dxAccelerometer.accelerometerValues; + } + + public static float[] getCompassValue() { + return Cocos2dxHelper.sCocos2dxAccelerometer.compassFieldValues; + } } - diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHttpURLConnection.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHttpURLConnection.java index 2a4d3c5b69..33bdac6759 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHttpURLConnection.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHttpURLConnection.java @@ -105,8 +105,8 @@ public class Cocos2dxHttpURLConnection caInput = new BufferedInputStream(new FileInputStream(sslFilename)); }else { String assetString = "assets/"; - String assetsFileName = sslFilename.substring(assetString.length()); - caInput = new BufferedInputStream(Cocos2dxActivity.COCOS_ACTIVITY.getAssets().open(assetsFileName)); + String assetsfilenameString = sslFilename.substring(assetString.length()); + caInput = new BufferedInputStream(Cocos2dxHelper.getActivity().getAssets().open(assetsfilenameString)); } CertificateFactory cf = CertificateFactory.getInstance("X.509"); @@ -275,15 +275,15 @@ public class Cocos2dxHttpURLConnection try { byte[] buffer = new byte[1024]; - int size = 0; - ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); + int size = 0; + ByteArrayOutputStream bytestream = new ByteArrayOutputStream(); while((size = in.read(buffer, 0 , 1024)) != -1) { - byteStream.write(buffer, 0, size); + bytestream.write(buffer, 0, size); } - byte retBuffer[] = byteStream.toByteArray(); - byteStream.close(); - return retBuffer; + byte retbuffer[] = bytestream.toByteArray(); + bytestream.close(); + return retbuffer; } catch (Exception e) { Log.e("URLConnection exception", e.toString()); } @@ -335,7 +335,7 @@ public class Cocos2dxHttpURLConnection public static String combinCookies(List list, String hostDomain) { StringBuilder sbCookies = new StringBuilder(); String domain = hostDomain; - String tailMatch = "FALSE"; + String tailmatch = "FALSE"; String path = "/"; String secure = "FALSE"; String key = null; @@ -371,7 +371,7 @@ public class Cocos2dxHttpURLConnection sbCookies.append(domain); sbCookies.append('\t'); - sbCookies.append(tailMatch); //access + sbCookies.append(tailmatch); //access sbCookies.append('\t'); sbCookies.append(path); //path sbCookies.append('\t'); @@ -390,16 +390,15 @@ public class Cocos2dxHttpURLConnection private static String str2Seconds(String strTime) { Calendar c = Calendar.getInstance(); - long millisSecond = 0; + long milliseconds = 0; try { c.setTime(new SimpleDateFormat("EEE, dd-MMM-yy hh:mm:ss zzz", Locale.US).parse(strTime)); - millisSecond = c.getTimeInMillis()/1000; + milliseconds = c.getTimeInMillis() / 1000; } catch (ParseException e) { Log.e("URLConnection exception", e.toString()); } - return Long.toString(millisSecond); + return Long.toString(milliseconds); } } - diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxLocalStorage.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxLocalStorage.java index b12c2cc962..1619ee9de7 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxLocalStorage.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxLocalStorage.java @@ -39,19 +39,23 @@ public class Cocos2dxLocalStorage { private static DBOpenHelper mDatabaseOpenHelper = null; private static SQLiteDatabase mDatabase = null; - + /** + * Constructor + * @param context The Context within which to work, used to create the DB + * @return + */ public static boolean init(String dbName, String tableName) { - if (Cocos2dxActivity.COCOS_ACTIVITY != null) { + if (Cocos2dxActivity.getContext() != null) { DATABASE_NAME = dbName; TABLE_NAME = tableName; - mDatabaseOpenHelper = new DBOpenHelper(Cocos2dxActivity.COCOS_ACTIVITY); + mDatabaseOpenHelper = new DBOpenHelper(Cocos2dxActivity.getContext()); mDatabase = mDatabaseOpenHelper.getWritableDatabase(); return true; } return false; } - - public static void destory() { + + public static void destroy() { if (mDatabase != null) { mDatabase.close(); } @@ -121,8 +125,10 @@ public class Cocos2dxLocalStorage { @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { - + Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + + newVersion + ", which will destroy all old data"); + //db.execSQL("DROP TABLE IF EXISTS " + VIRTUAL_TABLE); + //onCreate(db); } } } - diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxMusic.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxMusic.java index a11bbdca49..413c7e6b71 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxMusic.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxMusic.java @@ -27,13 +27,18 @@ package org.cocos2dx.lib; import android.content.Context; import android.content.res.AssetFileDescriptor; +import android.media.AudioManager; import android.media.MediaPlayer; import android.util.Log; import java.io.FileInputStream; public class Cocos2dxMusic { - private static final String TAG = "Cocos2dxMusic"; + // =========================================================== + // Constants + // =========================================================== + + private static final String TAG = Cocos2dxMusic.class.getSimpleName(); // =========================================================== // Fields @@ -53,19 +58,36 @@ public class Cocos2dxMusic { // =========================================================== public Cocos2dxMusic(final Context context) { - mContext = context; - initData(); + this.mContext = context; + + this.initData(); } + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + public void preloadBackgroundMusic(final String path) { if ((this.mCurrentPath == null) || (!this.mCurrentPath.equals(path))) { + // preload new background music + // release old resource and create a new one - if (mBackgroundMediaPlayer != null) { - mBackgroundMediaPlayer.release(); + if (this.mBackgroundMediaPlayer != null) { + this.mBackgroundMediaPlayer.release(); } - mBackgroundMediaPlayer = createMediaPlayer(path); - mCurrentPath = path; + this.mBackgroundMediaPlayer = this.createMediaPlayer(path); + + // record the path + this.mCurrentPath = path; } } @@ -112,7 +134,7 @@ public class Cocos2dxMusic { } public void stopBackgroundMusic() { - if (mBackgroundMediaPlayer != null) { + if (this.mBackgroundMediaPlayer != null) { mBackgroundMediaPlayer.release(); mBackgroundMediaPlayer = createMediaPlayer(mCurrentPath); @@ -125,48 +147,70 @@ public class Cocos2dxMusic { } public void pauseBackgroundMusic() { - if (mBackgroundMediaPlayer != null && mBackgroundMediaPlayer.isPlaying()) { - mBackgroundMediaPlayer.pause(); - mPaused = true; - mManualPaused = true; + try { + if (this.mBackgroundMediaPlayer != null && this.mBackgroundMediaPlayer.isPlaying()) { + this.mBackgroundMediaPlayer.pause(); + this.mPaused = true; + this.mManualPaused = true; + } + } catch (IllegalStateException e) { + Log.e(TAG, "pauseBackgroundMusic, IllegalStateException was triggered!"); } } public void resumeBackgroundMusic() { - if (mBackgroundMediaPlayer != null && this.mPaused) { - mBackgroundMediaPlayer.start(); - mPaused = false; - mManualPaused = false; + try { + if (this.mBackgroundMediaPlayer != null && this.mPaused) { + this.mBackgroundMediaPlayer.start(); + this.mPaused = false; + this.mManualPaused = false; + } + } catch (IllegalStateException e) { + Log.e(TAG, "resumeBackgroundMusic, IllegalStateException was triggered!"); } } public void rewindBackgroundMusic() { - if (mBackgroundMediaPlayer != null) { + if (this.mBackgroundMediaPlayer != null) { playBackgroundMusic(mCurrentPath, mIsLoop); } } + public boolean willPlayBackgroundMusic() { + // We will play our own background music, if there isn't already some + // music active from some other app (eg the user playing their own + // music). + AudioManager manager = + (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE); + return !manager.isMusicActive(); + } + public boolean isBackgroundMusicPlaying() { boolean ret = false; - - if (mBackgroundMediaPlayer != null) { - ret = mBackgroundMediaPlayer.isPlaying(); + try { + if (this.mBackgroundMediaPlayer == null) { + ret = false; + } else { + ret = this.mBackgroundMediaPlayer.isPlaying(); + } + } catch (IllegalStateException e) { + Log.e(TAG, "isBackgroundMusicPlaying, IllegalStateException was triggered!"); } return ret; } public void end() { - if (mBackgroundMediaPlayer != null) { - mBackgroundMediaPlayer.release(); + if (this.mBackgroundMediaPlayer != null) { + this.mBackgroundMediaPlayer.release(); } - initData(); + this.initData(); } public float getBackgroundVolume() { - if (mBackgroundMediaPlayer != null) { - return (mLeftVolume + mRightVolume) / 2; + if (this.mBackgroundMediaPlayer != null) { + return (this.mLeftVolume + this.mRightVolume) / 2; } else { return 0.0f; } @@ -181,36 +225,50 @@ public class Cocos2dxMusic { volume = 1.0f; } - mLeftVolume = mRightVolume = volume; - if (mBackgroundMediaPlayer != null) { - mBackgroundMediaPlayer.setVolume(mLeftVolume, mRightVolume); + this.mLeftVolume = this.mRightVolume = volume; + if (this.mBackgroundMediaPlayer != null) { + this.mBackgroundMediaPlayer.setVolume(this.mLeftVolume, this.mRightVolume); } } public void onEnterBackground(){ - if (mBackgroundMediaPlayer != null && mBackgroundMediaPlayer.isPlaying()) { - mBackgroundMediaPlayer.pause(); - mPaused = true; + try { + if (this.mBackgroundMediaPlayer != null && this.mBackgroundMediaPlayer.isPlaying()) { + this.mBackgroundMediaPlayer.pause(); + this.mPaused = true; + } + } catch (IllegalStateException e) { + Log.e(TAG, "onEnterBackground, IllegalStateException was triggered!"); } } public void onEnterForeground(){ - if(!mManualPaused){ - if (mBackgroundMediaPlayer != null && mPaused) { - mBackgroundMediaPlayer.start(); - mPaused = false; + try { + if (!this.mManualPaused) { + if (this.mBackgroundMediaPlayer != null && this.mPaused) { + this.mBackgroundMediaPlayer.start(); + this.mPaused = false; + } } + } catch (IllegalStateException e) { + Log.e(TAG, "onEnterForeground, IllegalStateException was triggered!"); } } private void initData() { - mLeftVolume = 0.5f; - mRightVolume = 0.5f; - mBackgroundMediaPlayer = null; - mPaused = false; - mCurrentPath = null; + this.mLeftVolume = 0.5f; + this.mRightVolume = 0.5f; + this.mBackgroundMediaPlayer = null; + this.mPaused = false; + this.mCurrentPath = null; } + /** + * create MediaPlayer for music + * + * @param path The path relative to assets + * @return + */ private MediaPlayer createMediaPlayer(final String path) { MediaPlayer mediaPlayer = new MediaPlayer(); @@ -220,8 +278,13 @@ public class Cocos2dxMusic { mediaPlayer.setDataSource(fis.getFD()); fis.close(); } else { - final AssetFileDescriptor assetFileDescritor = this.mContext.getAssets().openFd(path); - mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(), assetFileDescritor.getStartOffset(), assetFileDescritor.getLength()); + if (Cocos2dxHelper.getObbFile() != null) { + final AssetFileDescriptor assetFileDescriptor = Cocos2dxHelper.getObbFile().getAssetFileDescriptor(path); + mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength()); + } else { + final AssetFileDescriptor assetFileDescriptor = this.mContext.getAssets().openFd(path); + mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength()); + } } mediaPlayer.prepare(); @@ -234,5 +297,8 @@ public class Cocos2dxMusic { return mediaPlayer; } -} + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxRenderer.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxRenderer.java index 5fa4e98665..74bc41d310 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxRenderer.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxRenderer.java @@ -41,11 +41,15 @@ public class Cocos2dxRenderer implements GLSurfaceView.Renderer { // Fields // =========================================================== - private long mLastTickInNanoSeconds = 0; - private int mScreenWidth = 0; - private int mScreenHeight = 0; + private long mLastTickInNanoSeconds; + private int mScreenWidth; + private int mScreenHeight; private boolean mNativeInitCompleted = false; + // =========================================================== + // Constructors + // =========================================================== + // =========================================================== // Getter & Setter // =========================================================== @@ -55,8 +59,8 @@ public class Cocos2dxRenderer implements GLSurfaceView.Renderer { } public void setScreenWidthAndHeight(final int surfaceWidth, final int surfaceHeight) { - mScreenWidth = surfaceWidth; - mScreenHeight = surfaceHeight; + this.mScreenWidth = surfaceWidth; + this.mScreenHeight = surfaceHeight; } // =========================================================== @@ -65,8 +69,8 @@ public class Cocos2dxRenderer implements GLSurfaceView.Renderer { @Override public void onSurfaceCreated(final GL10 GL10, final EGLConfig EGLConfig) { - Cocos2dxRenderer.nativeInit(mScreenWidth, mScreenHeight); - mLastTickInNanoSeconds = System.nanoTime(); + Cocos2dxRenderer.nativeInit(this.mScreenWidth, this.mScreenHeight); + this.mLastTickInNanoSeconds = System.nanoTime(); mNativeInitCompleted = true; } @@ -96,7 +100,7 @@ public class Cocos2dxRenderer implements GLSurfaceView.Renderer { /* * Render time MUST be counted in, or the FPS will slower than appointed. */ - mLastTickInNanoSeconds = System.nanoTime(); + this.mLastTickInNanoSeconds = System.nanoTime(); Cocos2dxRenderer.nativeRender(); } } @@ -174,5 +178,8 @@ public class Cocos2dxRenderer implements GLSurfaceView.Renderer { public String getContentText() { return Cocos2dxRenderer.nativeGetContentText(); } -} + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java index 043d1a80a3..e81dbcaed7 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java @@ -28,6 +28,7 @@ import android.content.Context; import android.media.AudioManager; import android.media.SoundPool; import android.util.Log; +import android.content.res.AssetFileDescriptor; import java.util.ArrayList; import java.util.HashMap; @@ -69,38 +70,40 @@ public class Cocos2dxSound { private static final int SOUND_QUALITY = 5; private final static int INVALID_SOUND_ID = -1; + private final static int INVALID_STREAM_ID = -1; + // =========================================================== // Constructors // =========================================================== public Cocos2dxSound(final Context context) { - mContext = context; + this.mContext = context; - initData(); + this.initData(); } private void initData() { if (Cocos2dxHelper.getDeviceModel().contains("GT-I9100")) { - mSoundPool = new SoundPool(Cocos2dxSound.MAX_SIMULTANEOUS_STREAMS_I9100, AudioManager.STREAM_MUSIC, Cocos2dxSound.SOUND_QUALITY); + this.mSoundPool = new SoundPool(Cocos2dxSound.MAX_SIMULTANEOUS_STREAMS_I9100, AudioManager.STREAM_MUSIC, Cocos2dxSound.SOUND_QUALITY); } else { - mSoundPool = new SoundPool(Cocos2dxSound.MAX_SIMULTANEOUS_STREAMS_DEFAULT, AudioManager.STREAM_MUSIC, Cocos2dxSound.SOUND_QUALITY); + this.mSoundPool = new SoundPool(Cocos2dxSound.MAX_SIMULTANEOUS_STREAMS_DEFAULT, AudioManager.STREAM_MUSIC, Cocos2dxSound.SOUND_QUALITY); } + + this.mSoundPool.setOnLoadCompleteListener(new OnLoadCompletedListener()); - mSoundPool.setOnLoadCompleteListener(new OnLoadCompletedListener()); - - mLeftVolume = 0.5f; - mRightVolume = 0.5f; + this.mLeftVolume = 0.5f; + this.mRightVolume = 0.5f; } public int preloadEffect(final String path) { - Integer soundID = mPathSoundIDMap.get(path); + Integer soundID = this.mPathSoundIDMap.get(path); if (soundID == null) { - soundID = createSoundIDFromAsset(path); + soundID = this.createSoundIDFromAsset(path); // save value just in case if file is really loaded if (soundID != Cocos2dxSound.INVALID_SOUND_ID) { - mPathSoundIDMap.put(path, soundID); + this.mPathSoundIDMap.put(path, soundID); } } @@ -109,37 +112,36 @@ public class Cocos2dxSound { public void unloadEffect(final String path) { // stop effects - final ArrayList streamIDs = mPathStreamIDsMap.get(path); + final ArrayList streamIDs = this.mPathStreamIDsMap.get(path); if (streamIDs != null) { for (final Integer steamID : streamIDs) { - mSoundPool.stop(steamID); + this.mSoundPool.stop(steamID); } } - mPathStreamIDsMap.remove(path); + this.mPathStreamIDsMap.remove(path); // unload effect - final Integer soundID = mPathSoundIDMap.get(path); + final Integer soundID = this.mPathSoundIDMap.get(path); if(soundID != null){ - mSoundPool.unload(soundID); - mPathSoundIDMap.remove(path); + this.mSoundPool.unload(soundID); + this.mPathSoundIDMap.remove(path); } } - private static final int LOAD_TIME_OUT = 500; + private static int LOAD_TIME_OUT = 500; - public int playEffect(final String path, final boolean loop, float pitch, float pan, float gain) - { - int streamID; + public int playEffect(final String path, final boolean loop, float pitch, float pan, float gain){ + Integer soundID = this.mPathSoundIDMap.get(path); + int streamID = Cocos2dxSound.INVALID_STREAM_ID; - Integer soundID = mPathSoundIDMap.get(path); if (soundID != null) { // parameters; pan = -1 for left channel, 1 for right channel, 0 for both channels // play sound - streamID = doPlayEffect(path, soundID, loop, pitch, pan, gain); + streamID = this.doPlayEffect(path, soundID, loop, pitch, pan, gain); } else { // the effect is not prepared - soundID = preloadEffect(path); + soundID = this.preloadEffect(path); if (soundID == Cocos2dxSound.INVALID_SOUND_ID) { // can not preload effect return Cocos2dxSound.INVALID_SOUND_ID; @@ -164,32 +166,32 @@ public class Cocos2dxSound { } public void stopEffect(final int steamID) { - mSoundPool.stop(steamID); + this.mSoundPool.stop(steamID); // remove record - for (final String path : mPathStreamIDsMap.keySet()) { - if (mPathStreamIDsMap.get(path).contains(steamID)) { - mPathStreamIDsMap.get(path).remove(mPathStreamIDsMap.get(path).indexOf(steamID)); + for (final String pPath : this.mPathStreamIDsMap.keySet()) { + if (this.mPathStreamIDsMap.get(pPath).contains(steamID)) { + this.mPathStreamIDsMap.get(pPath).remove(this.mPathStreamIDsMap.get(pPath).indexOf(steamID)); break; } } } public void pauseEffect(final int steamID) { - mSoundPool.pause(steamID); + this.mSoundPool.pause(steamID); } public void resumeEffect(final int steamID) { - mSoundPool.resume(steamID); + this.mSoundPool.resume(steamID); } public void pauseAllEffects() { - if (!mPathStreamIDsMap.isEmpty()) { - final Iterator>> iter = mPathStreamIDsMap.entrySet().iterator(); + if (!this.mPathStreamIDsMap.isEmpty()) { + final Iterator>> iter = this.mPathStreamIDsMap.entrySet().iterator(); while (iter.hasNext()) { final Entry> entry = iter.next(); for (final int steamID : entry.getValue()) { - mSoundPool.pause(steamID); + this.mSoundPool.pause(steamID); } } } @@ -198,12 +200,12 @@ public class Cocos2dxSound { public void resumeAllEffects() { // can not only invoke SoundPool.autoResume() here, because // it only resumes all effects paused by pauseAllEffects() - if (!mPathStreamIDsMap.isEmpty()) { - final Iterator>> iter = mPathStreamIDsMap.entrySet().iterator(); + if (!this.mPathStreamIDsMap.isEmpty()) { + final Iterator>> iter = this.mPathStreamIDsMap.entrySet().iterator(); while (iter.hasNext()) { final Entry> entry = iter.next(); for (final int steamID : entry.getValue()) { - mSoundPool.resume(steamID); + this.mSoundPool.resume(steamID); } } } @@ -212,22 +214,22 @@ public class Cocos2dxSound { @SuppressWarnings("unchecked") public void stopAllEffects() { // stop effects - if (!mPathStreamIDsMap.isEmpty()) { - final Iterator iter = mPathStreamIDsMap.entrySet().iterator(); + if (!this.mPathStreamIDsMap.isEmpty()) { + final Iterator iter = this.mPathStreamIDsMap.entrySet().iterator(); while (iter.hasNext()) { final Map.Entry> entry = (Map.Entry>) iter.next(); for (final int steamID : entry.getValue()) { - mSoundPool.stop(steamID); + this.mSoundPool.stop(steamID); } } } // remove records - mPathStreamIDsMap.clear(); + this.mPathStreamIDsMap.clear(); } public float getEffectsVolume() { - return (mLeftVolume + mRightVolume) / 2; + return (this.mLeftVolume + this.mRightVolume) / 2; } public void setEffectsVolume(float volume) { @@ -239,40 +241,45 @@ public class Cocos2dxSound { volume = 1; } - mLeftVolume = mRightVolume = volume; + this.mLeftVolume = this.mRightVolume = volume; // change the volume of playing sounds - if (!mPathStreamIDsMap.isEmpty()) { - final Iterator>> iter = mPathStreamIDsMap.entrySet().iterator(); + if (!this.mPathStreamIDsMap.isEmpty()) { + final Iterator>> iter = this.mPathStreamIDsMap.entrySet().iterator(); while (iter.hasNext()) { final Entry> entry = iter.next(); for (final int steamID : entry.getValue()) { - mSoundPool.setVolume(steamID, mLeftVolume, mRightVolume); + this.mSoundPool.setVolume(steamID, this.mLeftVolume, this.mRightVolume); } } } } public void end() { - mSoundPool.release(); - mPathStreamIDsMap.clear(); - mPathSoundIDMap.clear(); - mPlayWhenLoadedEffects.clear(); + this.mSoundPool.release(); + this.mPathStreamIDsMap.clear(); + this.mPathSoundIDMap.clear(); + this.mPlayWhenLoadedEffects.clear(); - mLeftVolume = 0.5f; - mRightVolume = 0.5f; + this.mLeftVolume = 0.5f; + this.mRightVolume = 0.5f; - initData(); + this.initData(); } public int createSoundIDFromAsset(final String path) { - int soundID; + int soundID = Cocos2dxSound.INVALID_SOUND_ID; try { if (path.startsWith("/")) { - soundID = mSoundPool.load(path, 0); + soundID = this.mSoundPool.load(path, 0); } else { - soundID = mSoundPool.load(mContext.getAssets().openFd(path), 0); + if (Cocos2dxHelper.getObbFile() != null) { + final AssetFileDescriptor assetFileDescriptor = Cocos2dxHelper.getObbFile().getAssetFileDescriptor(path); + soundID = mSoundPool.load(assetFileDescriptor, 0); + } else { + soundID = this.mSoundPool.load(this.mContext.getAssets().openFd(path), 0); + } } } catch (final Exception e) { soundID = Cocos2dxSound.INVALID_SOUND_ID; @@ -292,18 +299,18 @@ public class Cocos2dxSound { } private int doPlayEffect(final String path, final int soundId, final boolean loop, float pitch, float pan, float gain) { - float leftVolume = mLeftVolume * gain * (1.0f - clamp(pan, 0.0f, 1.0f)); - float rightVolume = mRightVolume * gain * (1.0f - clamp(-pan, 0.0f, 1.0f)); - float soundRate = clamp(SOUND_RATE * pitch, 0.5f, 2.0f); + float leftVolume = this.mLeftVolume * gain * (1.0f - this.clamp(pan, 0.0f, 1.0f)); + float rightVolume = this.mRightVolume * gain * (1.0f - this.clamp(-pan, 0.0f, 1.0f)); + float soundRate = this.clamp(SOUND_RATE * pitch, 0.5f, 2.0f); // play sound - int streamID = mSoundPool.play(soundId, clamp(leftVolume, 0.0f, 1.0f), clamp(rightVolume, 0.0f, 1.0f), Cocos2dxSound.SOUND_PRIORITY, loop ? -1 : 0, soundRate); + int streamID = this.mSoundPool.play(soundId, this.clamp(leftVolume, 0.0f, 1.0f), this.clamp(rightVolume, 0.0f, 1.0f), Cocos2dxSound.SOUND_PRIORITY, loop ? -1 : 0, soundRate); // record stream id - ArrayList streamIDs = mPathStreamIDsMap.get(path); + ArrayList streamIDs = this.mPathStreamIDsMap.get(path); if (streamIDs == null) { streamIDs = new ArrayList(); - mPathStreamIDsMap.put(path, streamIDs); + this.mPathStreamIDsMap.put(path, streamIDs); } streamIDs.add(streamID); @@ -311,11 +318,11 @@ public class Cocos2dxSound { } public void onEnterBackground(){ - mSoundPool.autoPause(); + this.mSoundPool.autoPause(); } public void onEnterForeground(){ - mSoundPool.autoResume(); + this.mSoundPool.autoResume(); } // =========================================================== @@ -357,4 +364,3 @@ public class Cocos2dxSound { } } } - diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTextInputWrapper.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTextInputWrapper.java index 46ae4371c9..c1ddfc9f63 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTextInputWrapper.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTextInputWrapper.java @@ -26,6 +26,7 @@ package org.cocos2dx.lib; import android.content.Context; import android.text.Editable; import android.text.TextWatcher; +import android.util.Log; import android.view.KeyEvent; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; @@ -37,7 +38,7 @@ public class Cocos2dxTextInputWrapper implements TextWatcher, OnEditorActionList // Constants // =========================================================== - private static final String TAG = "Cocos2dxTextInputWrapper"; + private static final String TAG = Cocos2dxTextInputWrapper.class.getSimpleName(); // =========================================================== // Fields @@ -51,8 +52,8 @@ public class Cocos2dxTextInputWrapper implements TextWatcher, OnEditorActionList // Constructors // =========================================================== - public Cocos2dxTextInputWrapper(final Cocos2dxGLSurfaceView cocos2dxGLSurfaceView) { - mCocos2dxGLSurfaceView = cocos2dxGLSurfaceView; + public Cocos2dxTextInputWrapper(final Cocos2dxGLSurfaceView pCocos2dxGLSurfaceView) { + this.mCocos2dxGLSurfaceView = pCocos2dxGLSurfaceView; } // =========================================================== @@ -60,13 +61,13 @@ public class Cocos2dxTextInputWrapper implements TextWatcher, OnEditorActionList // =========================================================== private boolean isFullScreenEdit() { - final TextView textField = mCocos2dxGLSurfaceView.getCocos2dxEditText(); + final TextView textField = this.mCocos2dxGLSurfaceView.getCocos2dxEditText(); final InputMethodManager imm = (InputMethodManager) textField.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); return imm.isFullscreenMode(); } - public void setOriginText(final String originText) { - mOriginText = originText; + public void setOriginText(final String pOriginText) { + this.mOriginText = pOriginText; } // =========================================================== @@ -75,55 +76,54 @@ public class Cocos2dxTextInputWrapper implements TextWatcher, OnEditorActionList @Override public void afterTextChanged(final Editable s) { - if (isFullScreenEdit()) { + if (this.isFullScreenEdit()) { return; } - int old_i = 0; int new_i = 0; - while (old_i < mText.length() && new_i < s.length()) { - if (mText.charAt(old_i) != s.charAt(new_i)) { + while (old_i < this.mText.length() && new_i < s.length()) { + if (this.mText.charAt(old_i) != s.charAt(new_i)) { break; } old_i += 1; new_i += 1; } - for (; old_i < mText.length(); ++old_i) { - mCocos2dxGLSurfaceView.deleteBackward(); + for (; old_i < this.mText.length(); ++old_i) { + this.mCocos2dxGLSurfaceView.deleteBackward(); } int nModified = s.length() - new_i; if (nModified > 0) { final String insertText = s.subSequence(new_i, s.length()).toString(); - mCocos2dxGLSurfaceView.insertText(insertText); + this.mCocos2dxGLSurfaceView.insertText(insertText); } - mText = s.toString(); + this.mText = s.toString(); } @Override - public void beforeTextChanged(final CharSequence charSequence, final int start, final int count, final int after) { - mText = charSequence.toString(); + public void beforeTextChanged(final CharSequence pCharSequence, final int start, final int count, final int after) { + this.mText = pCharSequence.toString(); } @Override - public void onTextChanged(final CharSequence charSequence, final int start, final int before, final int count) { + public void onTextChanged(final CharSequence pCharSequence, final int start, final int before, final int count) { } @Override - public boolean onEditorAction(final TextView textView, final int actionID, final KeyEvent keyEvent) { - if (mCocos2dxGLSurfaceView.getCocos2dxEditText() == textView && this.isFullScreenEdit()) { + public boolean onEditorAction(final TextView pTextView, final int pActionID, final KeyEvent pKeyEvent) { + if (this.mCocos2dxGLSurfaceView.getCocos2dxEditText() == pTextView && this.isFullScreenEdit()) { // user press the action button, delete all old text and insert new text if (null != mOriginText) { - for (int i = mOriginText.length(); i > 0; i--) { + for (int i = this.mOriginText.length(); i > 0; i--) { this.mCocos2dxGLSurfaceView.deleteBackward(); } } - - String text = textView.getText().toString(); - + + String text = pTextView.getText().toString(); + if (text != null) { /* If user input nothing, translate "\n" to engine. */ if ( text.compareTo("") == 0) { @@ -139,13 +139,11 @@ public class Cocos2dxTextInputWrapper implements TextWatcher, OnEditorActionList mCocos2dxGLSurfaceView.insertText(""); } } - - if (actionID == EditorInfo.IME_ACTION_DONE) { - mCocos2dxGLSurfaceView.requestFocus(); + + if (pActionID == EditorInfo.IME_ACTION_DONE) { + this.mCocos2dxGLSurfaceView.requestFocus(); } - return false; } } - diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTypefaces.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTypefaces.java index b22e8a855c..3bca1a888e 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTypefaces.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTypefaces.java @@ -30,15 +30,35 @@ import android.graphics.Typeface; import java.util.HashMap; public class Cocos2dxTypefaces { + // =========================================================== + // Constants + // =========================================================== + + // =========================================================== + // Fields + // =========================================================== + private static final HashMap sTypefaceCache = new HashMap(); + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + // =========================================================== // Methods // =========================================================== public static synchronized Typeface get(final Context context, final String assetName) { if (!Cocos2dxTypefaces.sTypefaceCache.containsKey(assetName)) { - Typeface typeface; + Typeface typeface = null; if (assetName.startsWith("/")) { typeface = Typeface.createFromFile(assetName); @@ -52,5 +72,9 @@ public class Cocos2dxTypefaces { return Cocos2dxTypefaces.sTypefaceCache.get(assetName); } -} + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + +} diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoHelper.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoHelper.java index cacebbd246..a60b1ff157 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoHelper.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoHelper.java @@ -36,14 +36,19 @@ import org.cocos2dx.lib.Cocos2dxVideoView.OnVideoEventListener; import java.lang.ref.WeakReference; public class Cocos2dxVideoHelper { - static VideoHandler sVideoHandler = null; - private SparseArray mVideoViews = null; - - Cocos2dxVideoHelper() + private FrameLayout mLayout = null; + private Cocos2dxActivity mActivity = null; + private SparseArray sVideoViews = null; + static VideoHandler mVideoHandler = null; + + Cocos2dxVideoHelper(Cocos2dxActivity activity,FrameLayout layout) { - sVideoHandler = new VideoHandler(this); - mVideoViews = new SparseArray(); + mActivity = activity; + mLayout = layout; + + mVideoHandler = new VideoHandler(this); + sVideoViews = new SparseArray(); } private static int videoTag = 0; @@ -173,57 +178,57 @@ public class Cocos2dxVideoHelper { @Override public void onVideoEvent(int tag,int event) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(new VideoEventRunnable(tag, event)); + mActivity.runOnGLThread(new VideoEventRunnable(tag, event)); } }; public static int createVideoWidget() { - Message msg = Message.obtain(); + Message msg = new Message(); msg.what = VideoTaskCreate; msg.arg1 = videoTag; - sVideoHandler.sendMessageDelayed(msg, 0); - + mVideoHandler.sendMessage(msg); + return videoTag++; } private void _createVideoView(int index) { - Cocos2dxVideoView videoView = new Cocos2dxVideoView(Cocos2dxActivity.COCOS_ACTIVITY,index); - mVideoViews.put(index, videoView); + Cocos2dxVideoView videoView = new Cocos2dxVideoView(mActivity,index); + sVideoViews.put(index, videoView); FrameLayout.LayoutParams lParams = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT); - Cocos2dxActivity.ROOT_LAYOUT.addView(videoView, lParams); + mLayout.addView(videoView, lParams); videoView.setZOrderOnTop(true); videoView.setOnCompletionListener(videoEventListener); } public static void removeVideoWidget(int index){ - Message msg = Message.obtain(); + Message msg = new Message(); msg.what = VideoTaskRemove; msg.arg1 = index; - sVideoHandler.sendMessageDelayed(msg, 0); + mVideoHandler.sendMessage(msg); } private void _removeVideoView(int index) { - Cocos2dxVideoView view = mVideoViews.get(index); + Cocos2dxVideoView view = sVideoViews.get(index); if (view != null) { view.stopPlayback(); - mVideoViews.remove(index); - Cocos2dxActivity.ROOT_LAYOUT.removeView(view); + sVideoViews.remove(index); + mLayout.removeView(view); } } public static void setVideoUrl(int index, int videoSource, String videoUrl) { - Message msg = Message.obtain(); + Message msg = new Message(); msg.what = VideoTaskSetSource; msg.arg1 = index; msg.arg2 = videoSource; msg.obj = videoUrl; - sVideoHandler.sendMessageDelayed(msg, 0); + mVideoHandler.sendMessage(msg); } private void _setVideoURL(int index, int videoSource, String videoUrl) { - Cocos2dxVideoView videoView = mVideoViews.get(index); + Cocos2dxVideoView videoView = sVideoViews.get(index); if (videoView != null) { switch (videoSource) { case 0: @@ -239,22 +244,22 @@ public class Cocos2dxVideoHelper { } public static void setVideoRect(int index, int left, int top, int maxWidth, int maxHeight) { - Message msg = Message.obtain(); + Message msg = new Message(); msg.what = VideoTaskSetRect; msg.arg1 = index; msg.obj = new Rect(left, top, maxWidth, maxHeight); - sVideoHandler.sendMessageDelayed(msg, 0); + mVideoHandler.sendMessage(msg); } private void _setVideoRect(int index, int left, int top, int maxWidth, int maxHeight) { - Cocos2dxVideoView videoView = mVideoViews.get(index); + Cocos2dxVideoView videoView = sVideoViews.get(index); if (videoView != null) { videoView.setVideoRect(left,top,maxWidth,maxHeight); } } public static void setFullScreenEnabled(int index, boolean enabled, int width, int height) { - Message msg = Message.obtain(); + Message msg = new Message(); msg.what = VideoTaskFullScreen; msg.arg1 = index; if (enabled) { @@ -263,115 +268,115 @@ public class Cocos2dxVideoHelper { msg.arg2 = 0; } msg.obj = new Rect(0, 0, width, height); - sVideoHandler.sendMessageDelayed(msg, 0); + mVideoHandler.sendMessage(msg); } private void _setFullScreenEnabled(int index, boolean enabled, int width,int height) { - Cocos2dxVideoView videoView = mVideoViews.get(index); + Cocos2dxVideoView videoView = sVideoViews.get(index); if (videoView != null) { videoView.setFullScreenEnabled(enabled, width, height); } } private void onBackKeyEvent() { - int viewCount = mVideoViews.size(); + int viewCount = sVideoViews.size(); for (int i = 0; i < viewCount; i++) { - int key = mVideoViews.keyAt(i); - Cocos2dxVideoView videoView = mVideoViews.get(key); + int key = sVideoViews.keyAt(i); + Cocos2dxVideoView videoView = sVideoViews.get(key); if (videoView != null) { videoView.setFullScreenEnabled(false, 0, 0); - Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(new VideoEventRunnable(key, KeyEventBack)); + mActivity.runOnGLThread(new VideoEventRunnable(key, KeyEventBack)); } } } public static void startVideo(int index) { - Message msg = Message.obtain(); + Message msg = new Message(); msg.what = VideoTaskStart; msg.arg1 = index; - sVideoHandler.sendMessageDelayed(msg, 0); + mVideoHandler.sendMessage(msg); } private void _startVideo(int index) { - Cocos2dxVideoView videoView = mVideoViews.get(index); + Cocos2dxVideoView videoView = sVideoViews.get(index); if (videoView != null) { videoView.start(); } } public static void pauseVideo(int index) { - Message msg = Message.obtain(); + Message msg = new Message(); msg.what = VideoTaskPause; msg.arg1 = index; - sVideoHandler.sendMessageDelayed(msg, 0); + mVideoHandler.sendMessage(msg); } private void _pauseVideo(int index) { - Cocos2dxVideoView videoView = mVideoViews.get(index); + Cocos2dxVideoView videoView = sVideoViews.get(index); if (videoView != null) { videoView.pause(); } } public static void resumeVideo(int index) { - Message msg = Message.obtain(); + Message msg = new Message(); msg.what = VideoTaskResume; msg.arg1 = index; - sVideoHandler.sendMessageDelayed(msg, 0); + mVideoHandler.sendMessage(msg); } private void _resumeVideo(int index) { - Cocos2dxVideoView videoView = mVideoViews.get(index); + Cocos2dxVideoView videoView = sVideoViews.get(index); if (videoView != null) { videoView.resume(); } } public static void stopVideo(int index) { - Message msg = Message.obtain(); + Message msg = new Message(); msg.what = VideoTaskStop; msg.arg1 = index; - sVideoHandler.sendMessageDelayed(msg, 0); + mVideoHandler.sendMessage(msg); } private void _stopVideo(int index) { - Cocos2dxVideoView videoView = mVideoViews.get(index); + Cocos2dxVideoView videoView = sVideoViews.get(index); if (videoView != null) { videoView.stop(); } } public static void restartVideo(int index) { - Message msg = Message.obtain(); + Message msg = new Message(); msg.what = VideoTaskRestart; msg.arg1 = index; - sVideoHandler.sendMessageDelayed(msg, 0); + mVideoHandler.sendMessage(msg); } private void _restartVideo(int index) { - Cocos2dxVideoView videoView = mVideoViews.get(index); + Cocos2dxVideoView videoView = sVideoViews.get(index); if (videoView != null) { videoView.restart(); } } public static void seekVideoTo(int index,int msec) { - Message msg = Message.obtain(); + Message msg = new Message(); msg.what = VideoTaskSeek; msg.arg1 = index; msg.arg2 = msec; - sVideoHandler.sendMessageDelayed(msg, 0); + mVideoHandler.sendMessage(msg); } private void _seekVideoTo(int index,int msec) { - Cocos2dxVideoView videoView = mVideoViews.get(index); + Cocos2dxVideoView videoView = sVideoViews.get(index); if (videoView != null) { videoView.seekTo(msec); } } public static void setVideoVisible(int index, boolean visible) { - Message msg = Message.obtain(); + Message msg = new Message(); msg.what = VideoTaskSetVisible; msg.arg1 = index; if (visible) { @@ -379,12 +384,12 @@ public class Cocos2dxVideoHelper { } else { msg.arg2 = 0; } - - sVideoHandler.sendMessageDelayed(msg, 0); + + mVideoHandler.sendMessage(msg); } private void _setVideoVisible(int index, boolean visible) { - Cocos2dxVideoView videoView = mVideoViews.get(index); + Cocos2dxVideoView videoView = sVideoViews.get(index); if (videoView != null) { if (visible) { videoView.fixSize(); @@ -396,7 +401,7 @@ public class Cocos2dxVideoHelper { } public static void setVideoKeepRatioEnabled(int index, boolean enable) { - Message msg = Message.obtain(); + Message msg = new Message(); msg.what = VideoTaskKeepRatio; msg.arg1 = index; if (enable) { @@ -404,14 +409,13 @@ public class Cocos2dxVideoHelper { } else { msg.arg2 = 0; } - sVideoHandler.sendMessageDelayed(msg, 0); + mVideoHandler.sendMessage(msg); } private void _setVideoKeepRatio(int index, boolean enable) { - Cocos2dxVideoView videoView = mVideoViews.get(index); + Cocos2dxVideoView videoView = sVideoViews.get(index); if (videoView != null) { videoView.setKeepRatio(enable); } } } - diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java index f18fad1b47..27d1bff4bf 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java @@ -1,8 +1,23 @@ +/* + * Copyright (C) 2006 The Android Open Source Project + * Copyright (c) 2014 Chukong Technologies Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.cocos2dx.lib; -import android.app.Activity; import android.app.AlertDialog; -import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.AssetFileDescriptor; @@ -61,8 +76,8 @@ public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl // recording the seek position while preparing private int mSeekWhenPrepared; - protected Activity mActivity = null; - + protected Cocos2dxActivity mCocos2dxActivity = null; + protected int mViewLeft = 0; protected int mViewTop = 0; protected int mViewWidth = 0; @@ -78,12 +93,12 @@ public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl protected int mFullScreenHeight = 0; private int mViewTag = 0; - - public Cocos2dxVideoView(Context context,int tag) { - super(context); - + + public Cocos2dxVideoView(Cocos2dxActivity activity,int tag) { + super(activity); + mViewTag = tag; - mActivity = Cocos2dxActivity.COCOS_ACTIVITY; + mCocos2dxActivity = activity; initVideoView(); } @@ -257,7 +272,7 @@ public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl // TODO: these constants need to be published somewhere in the framework. Intent i = new Intent("com.android.music.musicservicecommand"); i.putExtra("command", "pause"); - mActivity.sendBroadcast(i); + mCocos2dxActivity.sendBroadcast(i); // we shouldn't clear the target state, because somebody might have // called start() previously @@ -280,10 +295,10 @@ public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl mDuration = -1; mCurrentBufferPercentage = 0; if (mIsAssetRouse) { - AssetFileDescriptor afd = mActivity.getAssets().openFd(mVideoFilePath); + AssetFileDescriptor afd = mCocos2dxActivity.getAssets().openFd(mVideoFilePath); mMediaPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength()); } else { - mMediaPlayer.setDataSource(mActivity, mVideoUri); + mMediaPlayer.setDataSource(mCocos2dxActivity, mVideoUri); } mMediaPlayer.prepareAsync(); @@ -297,6 +312,13 @@ public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl mCurrentState = STATE_ERROR; mTargetState = STATE_ERROR; mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0); + return; + } catch (IllegalArgumentException ex) { + Log.w(TAG, "Unable to open content: " + mVideoUri, ex); + mCurrentState = STATE_ERROR; + mTargetState = STATE_ERROR; + mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0); + return; } } @@ -441,7 +463,7 @@ public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl * longer have a window, don't bother showing the user an error. */ if (getWindowToken() != null) { - Resources r = mActivity.getResources(); + Resources r = mCocos2dxActivity.getResources(); int messageId; if (framework_err == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) { @@ -454,8 +476,8 @@ public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl int titleId = r.getIdentifier("VideoView_error_title", "string", "android"); int buttonStringId = r.getIdentifier("VideoView_error_button", "string", "android"); - - new AlertDialog.Builder(mActivity) + + new AlertDialog.Builder(mCocos2dxActivity) .setTitle(r.getString(titleId)) .setMessage(messageId) .setPositiveButton(r.getString(buttonStringId), @@ -688,4 +710,3 @@ public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl return mMediaPlayer.getAudioSessionId(); } } - diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebView.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebView.java index d8ee12c6a8..a592dd50f9 100755 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebView.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebView.java @@ -13,6 +13,26 @@ import java.lang.reflect.Method; import java.net.URI; import java.util.concurrent.CountDownLatch; +class ShouldStartLoadingWorker implements Runnable { + private CountDownLatch mLatch; + private boolean[] mResult; + private final int mViewTag; + private final String mUrlString; + + ShouldStartLoadingWorker(CountDownLatch latch, boolean[] result, int viewTag, String urlString) { + this.mLatch = latch; + this.mResult = result; + this.mViewTag = viewTag; + this.mUrlString = urlString; + } + + @Override + public void run() { + this.mResult[0] = Cocos2dxWebViewHelper._shouldStartLoading(mViewTag, mUrlString); + this.mLatch.countDown(); // notify that result is ready + } +} + public class Cocos2dxWebView extends WebView { private static final String TAG = Cocos2dxWebViewHelper.class.getSimpleName(); @@ -60,10 +80,11 @@ public class Cocos2dxWebView extends WebView { class Cocos2dxWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, final String urlString) { - Cocos2dxActivity activity = Cocos2dxActivity.COCOS_ACTIVITY; + Cocos2dxActivity activity = (Cocos2dxActivity)getContext(); + try { URI uri = URI.create(urlString); - if (uri.getScheme().equals(mJSScheme)) { + if (uri != null && uri.getScheme().equals(mJSScheme)) { activity.runOnGLThread(new Runnable() { @Override public void run() { @@ -95,8 +116,8 @@ public class Cocos2dxWebView extends WebView { @Override public void onPageFinished(WebView view, final String url) { super.onPageFinished(view, url); - - Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(new Runnable() { + Cocos2dxActivity activity = (Cocos2dxActivity)getContext(); + activity.runOnGLThread(new Runnable() { @Override public void run() { Cocos2dxWebViewHelper._didFinishLoading(mViewTag, url); @@ -107,8 +128,8 @@ public class Cocos2dxWebView extends WebView { @Override public void onReceivedError(WebView view, int errorCode, String description, final String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); - - Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(new Runnable() { + Cocos2dxActivity activity = (Cocos2dxActivity)getContext(); + activity.runOnGLThread(new Runnable() { @Override public void run() { Cocos2dxWebViewHelper._didFailLoading(mViewTag, failingUrl); @@ -127,25 +148,4 @@ public class Cocos2dxWebView extends WebView { layoutParams.gravity = Gravity.TOP | Gravity.LEFT; this.setLayoutParams(layoutParams); } - - class ShouldStartLoadingWorker implements Runnable { - private CountDownLatch mLatch; - private boolean[] mResult; - private final int mViewTag; - private final String mUrlString; - - ShouldStartLoadingWorker(CountDownLatch latch, boolean[] result, int viewTag, String urlString) { - this.mLatch = latch; - this.mResult = result; - this.mViewTag = viewTag; - this.mUrlString = urlString; - } - - @Override - public void run() { - this.mResult[0] = Cocos2dxWebViewHelper._shouldStartLoading(mViewTag, mUrlString); - this.mLatch.countDown(); // notify that result is ready - } - } } - diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java index b422bc6d65..012d4b62bb 100755 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java @@ -36,27 +36,20 @@ import java.util.concurrent.FutureTask; public class Cocos2dxWebViewHelper { - private static final String TAG = "Cocos2dxWebViewHelper"; + private static final String TAG = Cocos2dxWebViewHelper.class.getSimpleName(); + private static Handler sHandler; + private static Cocos2dxActivity sCocos2dxActivity; + private static FrameLayout sLayout; - private static Handler sHandler = null; - private static SparseArray sWebViews = null; + private static SparseArray webViews; private static int viewTag = 0; - static void init() - { - if (sWebViews == null) - { - sWebViews = new SparseArray(); - sHandler = new Handler(Looper.myLooper()); - } - } + public Cocos2dxWebViewHelper(FrameLayout layout) { + Cocos2dxWebViewHelper.sLayout = layout; + Cocos2dxWebViewHelper.sHandler = new Handler(Looper.myLooper()); - static void reset() - { - if (sWebViews != null) - sWebViews.clear(); - sWebViews = null; - sHandler = null; + Cocos2dxWebViewHelper.sCocos2dxActivity = (Cocos2dxActivity) Cocos2dxActivity.getContext(); + Cocos2dxWebViewHelper.webViews = new SparseArray(); } private static native boolean shouldStartLoading(int index, String message); @@ -85,39 +78,39 @@ public class Cocos2dxWebViewHelper { public static int createWebView() { final int index = viewTag; - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxWebView webView = new Cocos2dxWebView(Cocos2dxActivity.COCOS_ACTIVITY, index); + Cocos2dxWebView webView = new Cocos2dxWebView(sCocos2dxActivity, index); FrameLayout.LayoutParams lParams = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT); - Cocos2dxActivity.ROOT_LAYOUT.addView(webView, lParams); + sLayout.addView(webView, lParams); - sWebViews.put(index, webView); + webViews.put(index, webView); } }); return viewTag++; } public static void removeWebView(final int index) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxWebView webView = sWebViews.get(index); + Cocos2dxWebView webView = webViews.get(index); if (webView != null) { - sWebViews.remove(index); - Cocos2dxActivity.ROOT_LAYOUT.removeView(webView); + webViews.remove(index); + sLayout.removeView(webView); } } }); } public static void setVisible(final int index, final boolean visible) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxWebView webView = sWebViews.get(index); + Cocos2dxWebView webView = webViews.get(index); if (webView != null) { webView.setVisibility(visible ? View.VISIBLE : View.GONE); } @@ -126,10 +119,10 @@ public class Cocos2dxWebViewHelper { } public static void setWebViewRect(final int index, final int left, final int top, final int maxWidth, final int maxHeight) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxWebView webView = sWebViews.get(index); + Cocos2dxWebView webView = webViews.get(index); if (webView != null) { webView.setWebViewRect(left, top, maxWidth, maxHeight); } @@ -138,10 +131,10 @@ public class Cocos2dxWebViewHelper { } public static void setJavascriptInterfaceScheme(final int index, final String scheme) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxWebView webView = sWebViews.get(index); + Cocos2dxWebView webView = webViews.get(index); if (webView != null) { webView.setJavascriptInterfaceScheme(scheme); } @@ -150,10 +143,10 @@ public class Cocos2dxWebViewHelper { } public static void loadData(final int index, final String data, final String mimeType, final String encoding, final String baseURL) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxWebView webView = sWebViews.get(index); + Cocos2dxWebView webView = webViews.get(index); if (webView != null) { webView.loadDataWithBaseURL(baseURL, data, mimeType, encoding, null); } @@ -162,10 +155,10 @@ public class Cocos2dxWebViewHelper { } public static void loadHTMLString(final int index, final String data, final String baseUrl) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxWebView webView = sWebViews.get(index); + Cocos2dxWebView webView = webViews.get(index); if (webView != null) { webView.loadDataWithBaseURL(baseUrl, data, null, null, null); } @@ -174,10 +167,10 @@ public class Cocos2dxWebViewHelper { } public static void loadUrl(final int index, final String url) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxWebView webView = sWebViews.get(index); + Cocos2dxWebView webView = webViews.get(index); if (webView != null) { webView.loadUrl(url); } @@ -186,10 +179,10 @@ public class Cocos2dxWebViewHelper { } public static void loadFile(final int index, final String filePath) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxWebView webView = sWebViews.get(index); + Cocos2dxWebView webView = webViews.get(index); if (webView != null) { webView.loadUrl(filePath); } @@ -198,10 +191,10 @@ public class Cocos2dxWebViewHelper { } public static void stopLoading(final int index) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxWebView webView = sWebViews.get(index); + Cocos2dxWebView webView = webViews.get(index); if (webView != null) { webView.stopLoading(); } @@ -211,10 +204,10 @@ public class Cocos2dxWebViewHelper { } public static void reload(final int index) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxWebView webView = sWebViews.get(index); + Cocos2dxWebView webView = webViews.get(index); if (webView != null) { webView.reload(); } @@ -232,7 +225,7 @@ public class Cocos2dxWebViewHelper { Callable callable = new Callable() { @Override public Boolean call() throws Exception { - Cocos2dxWebView webView = sWebViews.get(index); + Cocos2dxWebView webView = webViews.get(index); return webView != null && webView.canGoBack(); } }; @@ -249,7 +242,7 @@ public class Cocos2dxWebViewHelper { Callable callable = new Callable() { @Override public Boolean call() throws Exception { - Cocos2dxWebView webView = sWebViews.get(index); + Cocos2dxWebView webView = webViews.get(index); return webView != null && webView.canGoForward(); } }; @@ -263,10 +256,10 @@ public class Cocos2dxWebViewHelper { } public static void goBack(final int index) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxWebView webView = sWebViews.get(index); + Cocos2dxWebView webView = webViews.get(index); if (webView != null) { webView.goBack(); } @@ -275,10 +268,10 @@ public class Cocos2dxWebViewHelper { } public static void goForward(final int index) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxWebView webView = sWebViews.get(index); + Cocos2dxWebView webView = webViews.get(index); if (webView != null) { webView.goForward(); } @@ -287,10 +280,10 @@ public class Cocos2dxWebViewHelper { } public static void evaluateJS(final int index, final String js) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxWebView webView = sWebViews.get(index); + Cocos2dxWebView webView = webViews.get(index); if (webView != null) { webView.loadUrl("javascript:" + js); } @@ -299,10 +292,10 @@ public class Cocos2dxWebViewHelper { } public static void setScalesPageToFit(final int index, final boolean scalesPageToFit) { - Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + sCocos2dxActivity.runOnUiThread(new Runnable() { @Override public void run() { - Cocos2dxWebView webView = sWebViews.get(index); + Cocos2dxWebView webView = webViews.get(index); if (webView != null) { webView.setScalesPageToFit(scalesPageToFit); } @@ -310,4 +303,3 @@ public class Cocos2dxWebViewHelper { }); } } - diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/ResizeLayout.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/ResizeLayout.java index ade8d96ac6..11815e6b0e 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/ResizeLayout.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/ResizeLayout.java @@ -26,20 +26,14 @@ package org.cocos2dx.lib; import android.content.Context; import android.os.Handler; -import android.os.Message; import android.util.AttributeSet; import android.widget.FrameLayout; -import java.lang.ref.WeakReference; - public class ResizeLayout extends FrameLayout { private boolean mEnableForceDoLayout = false; - private MyLayoutHandler myLayoutHandler = null; public ResizeLayout(Context context){ super(context); - - myLayoutHandler = new MyLayoutHandler(this); } public ResizeLayout(Context context, AttributeSet attrs) { @@ -50,29 +44,6 @@ public class ResizeLayout extends FrameLayout { mEnableForceDoLayout = flag; } - static class MyLayoutHandler extends Handler { - WeakReference mReference; - - MyLayoutHandler(ResizeLayout layout) - { - mReference = new WeakReference(layout); - } - - @Override - public void handleMessage(Message msg) { - switch (msg.what) { - case 1024: { - ResizeLayout layout = mReference.get(); - layout.requestLayout(); - layout.invalidate(); - break; - } - default: - break; - } - } - } - @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); @@ -81,8 +52,16 @@ public class ResizeLayout extends FrameLayout { * is paned. We refresh the layout in 24 frames per seconds. * When the editBox is lose focus or when user begin to type, the do layout is disabled. */ - myLayoutHandler.sendEmptyMessageDelayed(1024, 1000 / 24); + final Handler handler = new Handler(); + handler.postDelayed(new Runnable() { + @Override + public void run() { + //Do something after 100ms + requestLayout(); + invalidate(); + } + }, 1000 / 24); + } } } - diff --git a/native/cocos/platform/android/javaactivity-android.cpp b/native/cocos/platform/android/javaactivity-android.cpp index ecd9048550..9887d6dd69 100644 --- a/native/cocos/platform/android/javaactivity-android.cpp +++ b/native/cocos/platform/android/javaactivity-android.cpp @@ -25,8 +25,8 @@ THE SOFTWARE. #include "platform/CCPlatformConfig.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID -#include "CCApplication-android.h" -#include "CCGLViewImpl-android.h" +#include "platform/android/CCApplication-android.h" +#include "platform/android/CCGLViewImpl-android.h" #include "base/CCDirector.h" #include "base/CCEventCustom.h" #include "base/CCEventType.h" @@ -36,7 +36,9 @@ THE SOFTWARE. #include "renderer/ccGLStateCache.h" #include "2d/CCDrawingPrimitives.h" #include "platform/android/jni/JniHelper.h" +#include "network/CCDownloader-android.h" #include +#include #include #define LOG_TAG "main" @@ -49,11 +51,34 @@ using namespace cocos2d; extern "C" { +// ndk break compatibility, refer to https://github.com/cocos2d/cocos2d-x/issues/16267 for detail information +// should remove it when using NDK r13 since NDK r13 will add back bsd_signal() +#if __ANDROID_API__ > 19 +#include +#include + typedef __sighandler_t (*bsd_signal_func_t)(int, __sighandler_t); + bsd_signal_func_t bsd_signal_func = NULL; + + __sighandler_t bsd_signal(int s, __sighandler_t f) { + if (bsd_signal_func == NULL) { + // For now (up to Android 7.0) this is always available + bsd_signal_func = (bsd_signal_func_t) dlsym(RTLD_DEFAULT, "bsd_signal"); + + if (bsd_signal_func == NULL) { + __android_log_assert("", "bsd_signal_wrapper", "bsd_signal symbol not found!"); + } + } + + return bsd_signal_func(s, f); + } +#endif // __ANDROID_API__ > 19 + JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) { JniHelper::setJavaVM(vm); cocos_android_app_init(JniHelper::getEnv()); - return JNI_VERSION_1_6; + + return JNI_VERSION_1_4; } JNIEXPORT void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit(JNIEnv* env, jobject thiz, jint w, jint h) @@ -79,6 +104,7 @@ JNIEXPORT void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit(JNIEnv* env, jo director->getEventDispatcher()->dispatchEvent(&recreatedEvent); director->setGLDefaultValues(); } + cocos2d::network::_preloadJavaDownloaderClass(); } JNIEXPORT jintArray Java_org_cocos2dx_lib_Cocos2dxActivity_getGLContextAttrs(JNIEnv* env, jobject thiz) diff --git a/native/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxAccelerometer.cpp b/native/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxAccelerometer.cpp index d155a7f284..462add13e1 100644 --- a/native/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxAccelerometer.cpp +++ b/native/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxAccelerometer.cpp @@ -1,4 +1,4 @@ -#include "JniHelper.h" +#include "platform/android/jni/JniHelper.h" #include #include "base/CCDirector.h" #include "base/CCEventDispatcher.h" @@ -20,4 +20,3 @@ extern "C" { Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); } } - diff --git a/native/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp b/native/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp index f71ed6fd65..15a3fb746e 100644 --- a/native/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp +++ b/native/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp @@ -23,17 +23,22 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "JniHelper.h" +#include "platform/android/jni/JniHelper.h" +#include +#include "base/CCDirector.h" +#include "platform/CCApplication.h" +#include "platform/CCFileUtils.h" +#include "base/ccUTF8.h" -#define BITMAP_JAVA_CLASS "org/cocos2dx/lib/Cocos2dxBitmap" +static const std::string className = "org/cocos2dx/lib/Cocos2dxBitmap"; using namespace cocos2d; int getFontSizeAccordingHeightJni(int height) { - return JniHelper::callStaticIntMethod(BITMAP_JAVA_CLASS, "getFontSizeAccordingHeight", height); + return JniHelper::callStaticIntMethod(className, "getFontSizeAccordingHeight", height); } std::string getStringWithEllipsisJni(const char* text, float width, float fontSize) { - return JniHelper::callStaticStringMethod(BITMAP_JAVA_CLASS, "getStringWithEllipsis", text, width, fontSize); + return JniHelper::callStaticStringMethod(className, "getStringWithEllipsis", text, width, fontSize); } diff --git a/native/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp b/native/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp index b09c759700..d7f2f320cd 100644 --- a/native/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp +++ b/native/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp @@ -26,22 +26,24 @@ THE SOFTWARE. #include #include #include -#include "JniHelper.h" -#include "CCFileUtils-android.h" +#include "platform/android/jni/JniHelper.h" +#include "platform/android/CCFileUtils-android.h" #include "android/asset_manager_jni.h" -#include "base/CCString.h" -#include "Java_org_cocos2dx_lib_Cocos2dxHelper.h" +#include "platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h" #include "base/ccUTF8.h" #define LOG_TAG "Java_org_cocos2dx_lib_Cocos2dxHelper.cpp" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) -#define HELPER_JAVA_CLASS "org/cocos2dx/lib/Cocos2dxHelper" +static const std::string className = "org/cocos2dx/lib/Cocos2dxHelper"; static EditTextCallback s_editTextCallback = nullptr; static void* s_ctx = nullptr; +static int __deviceSampleRate = 44100; +static int __deviceAudioBufferSizeInFrames = 192; + using namespace cocos2d; using namespace std; @@ -53,11 +55,17 @@ extern "C" { g_apkPath = JniHelper::jstring2string(apkPath); } - JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetContext(JNIEnv* env, jobject thiz, jobject classLoader, jobject assetManager) { - JniHelper::setClassLoaderFrom(classLoader); + JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetContext(JNIEnv* env, jobject thiz, jobject context, jobject assetManager) { + JniHelper::setClassLoaderFrom(context); FileUtilsAndroid::setassetmanager(AAssetManager_fromJava(env, assetManager)); } + JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetAudioDeviceInfo(JNIEnv* env, jobject thiz, jboolean isSupportLowLatency, jint deviceSampleRate, jint deviceAudioBufferSizeInFrames) { + __deviceSampleRate = deviceSampleRate; + __deviceAudioBufferSizeInFrames = deviceAudioBufferSizeInFrames; + LOGD("nativeSetAudioDeviceInfo: sampleRate: %d, bufferSizeInFrames: %d", __deviceSampleRate, __deviceAudioBufferSizeInFrames); + } + JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetEditTextDialogResult(JNIEnv* env, jobject obj, jbyteArray text) { jsize size = env->GetArrayLength(text); @@ -84,14 +92,49 @@ const char * getApkPath() { } std::string getPackageNameJNI() { - return JniHelper::callStaticStringMethod(HELPER_JAVA_CLASS, "getCocos2dxPackageName"); + return JniHelper::callStaticStringMethod(className, "getCocos2dxPackageName"); +} + +int getObbAssetFileDescriptorJNI(const char* path, long* startOffset, long* size) { + JniMethodInfo methodInfo; + int fd = 0; + + if (JniHelper::getStaticMethodInfo(methodInfo, className.c_str(), "getObbAssetFileDescriptor", "(Ljava/lang/String;)[J")) { + jstring stringArg = methodInfo.env->NewStringUTF(path); + jlongArray newArray = (jlongArray)methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID, stringArg); + jsize theArrayLen = methodInfo.env->GetArrayLength(newArray); + + if (theArrayLen == 3) { + jboolean copy = JNI_FALSE; + jlong *array = methodInfo.env->GetLongArrayElements(newArray, ©); + fd = static_cast(array[0]); + *startOffset = array[1]; + *size = array[2]; + methodInfo.env->ReleaseLongArrayElements(newArray, array, 0); + } + + methodInfo.env->DeleteLocalRef(methodInfo.classID); + methodInfo.env->DeleteLocalRef(stringArg); + } + + return fd; +} + +int getDeviceSampleRate() +{ + return __deviceSampleRate; +} + +int getDeviceAudioBufferSizeInFrames() +{ + return __deviceAudioBufferSizeInFrames; } void conversionEncodingJNI(const char* src, int byteSize, const char* fromCharset, char* dst, const char* newCharset) { JniMethodInfo methodInfo; - if (JniHelper::getStaticMethodInfo(methodInfo, HELPER_JAVA_CLASS, "conversionEncoding", "([BLjava/lang/String;Ljava/lang/String;)[B")) { + if (JniHelper::getStaticMethodInfo(methodInfo, className.c_str(), "conversionEncoding", "([BLjava/lang/String;Ljava/lang/String;)[B")) { jbyteArray strArray = methodInfo.env->NewByteArray(byteSize); methodInfo.env->SetByteArrayRegion(strArray, 0, byteSize, reinterpret_cast(src)); @@ -108,4 +151,3 @@ void conversionEncodingJNI(const char* src, int byteSize, const char* fromCharse methodInfo.env->DeleteLocalRef(methodInfo.classID); } } - diff --git a/native/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h b/native/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h index 3bb2958d63..cca78e8a59 100644 --- a/native/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h +++ b/native/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h @@ -31,7 +31,10 @@ typedef void (*EditTextCallback)(const char* text, void* ctx); extern const char * getApkPath(); extern std::string getPackageNameJNI(); +extern int getObbAssetFileDescriptorJNI(const char* path, long* startOffset, long* size); extern void conversionEncodingJNI(const char* src, int byteSize, const char* fromCharset, char* dst, const char* newCharset); -#endif /* __Java_org_cocos2dx_lib_Cocos2dxHelper_H__ */ +extern int getDeviceSampleRate(); +extern int getDeviceAudioBufferSizeInFrames(); +#endif /* __Java_org_cocos2dx_lib_Cocos2dxHelper_H__ */ diff --git a/native/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp b/native/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp index 4982bb85af..39a06ae230 100644 --- a/native/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp +++ b/native/cocos/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp @@ -3,9 +3,9 @@ #include "base/CCEventType.h" #include "base/CCEventCustom.h" #include "base/CCEventDispatcher.h" -#include "../CCApplication.h" +#include "platform/CCApplication.h" #include "platform/CCFileUtils.h" -#include "JniHelper.h" +#include "platform/android/jni/JniHelper.h" #include #include "base/ccUTF8.h" @@ -27,15 +27,22 @@ extern "C" { } JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeOnResume() { + static bool firstTime = true; if (Director::getInstance()->getOpenGLView()) { - Application::getInstance()->applicationWillEnterForeground(); + // don't invoke at first to keep the same logic as iOS + // can refer to https://github.com/cocos2d/cocos2d-x/issues/14206 + if (!firstTime) + Application::getInstance()->applicationWillEnterForeground(); + cocos2d::EventCustom foregroundEvent(EVENT_COME_TO_FOREGROUND); cocos2d::Director::getInstance()->getEventDispatcher()->dispatchEvent(&foregroundEvent); + + firstTime = false; } } JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInsertText(JNIEnv* env, jobject thiz, jstring text) { - std::string strValue = JniHelper::getStringUTFCharsJNI(env, text); + std::string strValue = cocos2d::StringUtils::getStringUTFCharsJNI(env, text); const char* pszText = strValue.c_str(); cocos2d::IMEDispatcher::sharedDispatcher()->dispatchInsertText(pszText, strlen(pszText)); } @@ -47,11 +54,10 @@ extern "C" { JNIEXPORT jstring JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeGetContentText() { JNIEnv * env = 0; - if (JniHelper::getJavaVM()->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK || ! env) { + if (JniHelper::getJavaVM()->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK || ! env) { return 0; } std::string pszText = cocos2d::IMEDispatcher::sharedDispatcher()->getContentText(); - return JniHelper::newStringUTFJNI(env, pszText); + return cocos2d::StringUtils::newStringUTFJNI(env, pszText); } } - diff --git a/native/cocos/platform/android/jni/JniHelper.cpp b/native/cocos/platform/android/jni/JniHelper.cpp index 5497b9aed8..8d6d217b2e 100644 --- a/native/cocos/platform/android/jni/JniHelper.cpp +++ b/native/cocos/platform/android/jni/JniHelper.cpp @@ -22,7 +22,7 @@ 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 "JniHelper.h" +#include "platform/android/jni/JniHelper.h" #include #include #include @@ -35,7 +35,7 @@ THE SOFTWARE. static pthread_key_t g_key; -static jclass _getClassID(const char *className) { +jclass _getClassID(const char *className) { if (nullptr == className) { return nullptr; } @@ -58,7 +58,7 @@ static jclass _getClassID(const char *className) { return _clazz; } -static void _detachCurrentThread(void* a) { +void _detachCurrentThread(void* a) { cocos2d::JniHelper::getJavaVM()->DetachCurrentThread(); } @@ -67,6 +67,9 @@ namespace cocos2d { JavaVM* JniHelper::_psJavaVM = nullptr; jmethodID JniHelper::loadclassMethod_methodID = nullptr; jobject JniHelper::classloader = nullptr; + std::function JniHelper::classloaderCallback = nullptr; + + jobject JniHelper::_activity = nullptr; std::unordered_map> JniHelper::localRefs; JavaVM* JniHelper::getJavaVM() { @@ -86,8 +89,8 @@ namespace cocos2d { JNIEnv* JniHelper::cacheEnv(JavaVM* jvm) { JNIEnv* _env = nullptr; // get jni environment - jint ret = jvm->GetEnv((void**)&_env, JNI_VERSION_1_6); - + jint ret = jvm->GetEnv((void**)&_env, JNI_VERSION_1_4); + switch (ret) { case JNI_OK : // Success! @@ -97,12 +100,11 @@ namespace cocos2d { case JNI_EDETACHED : // Thread not attached if (jvm->AttachCurrentThread(&_env, nullptr) < 0) - { - LOGE("Failed to get the environment using AttachCurrentThread()"); - return nullptr; - } - else - { + { + LOGE("Failed to get the environment using AttachCurrentThread()"); + + return nullptr; + } else { // Success : Attached and obtained JNIEnv! pthread_setspecific(g_key, _env); return _env; @@ -110,7 +112,7 @@ namespace cocos2d { case JNI_EVERSION : // Cannot recover from this error - LOGE("JNI interface version 1.6 not supported"); + LOGE("JNI interface version 1.4 not supported"); default : LOGE("Failed to get the environment using GetEnv()"); return nullptr; @@ -123,8 +125,27 @@ namespace cocos2d { _env = JniHelper::cacheEnv(_psJavaVM); 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 = cocos2d::JniHelper::getEnv()->CallObjectMethod(activityinstance, + _getclassloaderMethod.methodID); + + if (nullptr == _c) { + return false; + } - bool JniHelper::setClassLoaderFrom(jobject clsLoader) { JniMethodInfo _m; if (!JniHelper::getMethodInfo_DefaultClassLoader(_m, "java/lang/ClassLoader", @@ -133,51 +154,16 @@ namespace cocos2d { return false; } - JniHelper::classloader = cocos2d::JniHelper::getEnv()->NewGlobalRef(clsLoader); + JniHelper::classloader = cocos2d::JniHelper::getEnv()->NewGlobalRef(_c); JniHelper::loadclassMethod_methodID = _m.methodID; + JniHelper::_activity = cocos2d::JniHelper::getEnv()->NewGlobalRef(activityinstance); + if (JniHelper::classloaderCallback != nullptr){ + JniHelper::classloaderCallback(); + } return true; } - std::string JniHelper::getStringUTFCharsJNI(JNIEnv* env, jstring srcjStr, bool* ret) - { - std::string utf8Str; - const unsigned short * unicodeChar = ( const unsigned short *)env->GetStringChars(srcjStr, nullptr); - size_t unicodeCharLength = env->GetStringLength(srcjStr); - const std::u16string unicodeStr((const char16_t *)unicodeChar, unicodeCharLength); - bool flag = cocos2d::StringUtils::UTF16ToUTF8(unicodeStr, utf8Str); - - if (ret) - { - *ret = flag; - } - - if (!flag) - { - utf8Str = ""; - } - env->ReleaseStringChars(srcjStr, unicodeChar); - return utf8Str; - } - - jstring JniHelper::newStringUTFJNI(JNIEnv* env, const std::string& utf8Str, bool* ret) - { - std::u16string utf16Str; - bool flag = cocos2d::StringUtils::UTF8ToUTF16(utf8Str, utf16Str); - - if (ret) - { - *ret = flag; - } - - if(!flag) - { - utf16Str.clear(); - } - jstring stringText = env->NewString((const jchar*)utf16Str.data(), utf16Str.length()); - return stringText; - } - bool JniHelper::getStaticMethodInfo(JniMethodInfo &methodinfo, const char *className, const char *methodName, @@ -196,14 +182,14 @@ namespace cocos2d { jclass classID = _getClassID(className); if (! classID) { - LOGE("getStaticMethodInfo: Failed to find class:%s::%s::%s", className, methodName, paramCode); + LOGE("Failed to find class %s", className); env->ExceptionClear(); return false; } jmethodID methodID = env->GetStaticMethodID(classID, methodName, paramCode); if (! methodID) { - LOGE("getStaticMethodInfo: Failed to find static method:%s::%s::%s", className, methodName, paramCode); + LOGE("Failed to find static method id of %s", methodName); env->ExceptionClear(); return false; } @@ -231,14 +217,14 @@ namespace cocos2d { jclass classID = env->FindClass(className); if (! classID) { - LOGE("getMethodInfo_DefaultClassLoader: Failed to find class %s", className); + LOGE("Failed to find class %s", className); env->ExceptionClear(); return false; } jmethodID methodID = env->GetMethodID(classID, methodName, paramCode); if (! methodID) { - LOGE("getMethodInfo_DefaultClassLoader: Failed to find method id of %s", methodName); + LOGE("Failed to find method id of %s", methodName); env->ExceptionClear(); return false; } @@ -267,14 +253,14 @@ namespace cocos2d { jclass classID = _getClassID(className); if (! classID) { - LOGE("getMethodInfo: Failed to find class:%s::%s::%s", className, methodName, paramCode); + LOGE("Failed to find class %s", className); env->ExceptionClear(); return false; } jmethodID methodID = env->GetMethodID(classID, methodName, paramCode); if (! methodID) { - LOGE("getMethodInfo: Failed to find method:%s::%s::%s", className, methodName, paramCode); + LOGE("Failed to find method id of %s", methodName); env->ExceptionClear(); return false; } @@ -296,13 +282,13 @@ namespace cocos2d { return ""; } - std::string strValue = JniHelper::getStringUTFCharsJNI(env, jstr); + std::string strValue = cocos2d::StringUtils::getStringUTFCharsJNI(env, jstr); return strValue; } jstring JniHelper::convert(cocos2d::JniMethodInfo& t, const char* x) { - jstring ret = JniHelper::newStringUTFJNI(t.env, x ? x : ""); + jstring ret = cocos2d::StringUtils::newStringUTFJNI(t.env, x ? x : ""); localRefs[t.env].push_back(ret); return ret; } @@ -312,7 +298,7 @@ namespace cocos2d { } void JniHelper::deleteLocalRefs(JNIEnv* env) { - if (env == nullptr) { + if (!env) { return; } @@ -322,5 +308,8 @@ namespace cocos2d { localRefs[env].clear(); } -} //namespace cocos2d + 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 cocos2d diff --git a/native/cocos/platform/android/jni/JniHelper.h b/native/cocos/platform/android/jni/JniHelper.h index 90b51d8ba0..ee23a24e93 100644 --- a/native/cocos/platform/android/jni/JniHelper.h +++ b/native/cocos/platform/android/jni/JniHelper.h @@ -29,7 +29,9 @@ THE SOFTWARE. #include #include #include +#include #include "platform/CCPlatformMacros.h" +#include "math/Vec3.h" NS_CC_BEGIN @@ -46,6 +48,7 @@ public: static void setJavaVM(JavaVM *javaVM); static JavaVM* getJavaVM(); static JNIEnv* getEnv(); + static jobject getActivity(); static bool setClassLoaderFrom(jobject activityInstance); static bool getStaticMethodInfo(JniMethodInfo &methodinfo, @@ -57,134 +60,166 @@ public: const char *methodName, const char *paramCode); - /** - * @brief convert jstring to utf8 std::string, same function with env->getStringUTFChars. - * because getStringUTFChars can not pass special emoticon - * @param env The JNI Env - * @param srcjStr The jstring which want to convert - * @param ret True if the conversion succeeds and the ret pointer isn't null - * @returns the result of utf8 string - */ - static std::string getStringUTFCharsJNI(JNIEnv* env, jstring srcjStr, bool* ret = nullptr); - - /** - * @brief create a jstring with utf8 std::string, same function with env->newStringUTF - * because newStringUTF can not convert special emoticon - * @param env The JNI Env - * @param srcjStr The std::string which want to convert - * @param ret True if the conversion succeeds and the ret pointer isn't null - * @returns the result of jstring,the jstring need to DeleteLocalRef(jstring); - */ - static jstring newStringUTFJNI(JNIEnv* env, const std::string& utf8Str, bool* ret = nullptr); - static std::string jstring2string(jstring str); static jmethodID loadclassMethod_methodID; static jobject classloader; + static std::function classloaderCallback; template - static void callStaticVoidMethod(const char* className, - const char* methodName, + static void callStaticVoidMethod(const std::string& className, + const std::string& methodName, Ts... xs) { - std::string methodSignature = "(" + getJNISignature(xs...) + ")V"; - cocos2d::JniMethodInfo t; - if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, methodSignature.c_str())) { + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")V"; + if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { t.env->CallStaticVoidMethod(t.classID, t.methodID, convert(t, xs)...); t.env->DeleteLocalRef(t.classID); deleteLocalRefs(t.env); + } else { + reportError(className, methodName, signature); } } template - static bool callStaticBooleanMethod(const char* className, - const char* methodName, + static bool callStaticBooleanMethod(const std::string& className, + const std::string& methodName, Ts... xs) { - std::string methodSignature = "(" + getJNISignature(xs...) + ")Z"; - jboolean jret = JNI_FALSE; cocos2d::JniMethodInfo t; - if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, methodSignature.c_str())) { + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")Z"; + if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { jret = t.env->CallStaticBooleanMethod(t.classID, t.methodID, convert(t, xs)...); t.env->DeleteLocalRef(t.classID); deleteLocalRefs(t.env); + } else { + reportError(className, methodName, signature); } - return (jret == JNI_TRUE); } template - static int callStaticIntMethod(const char* className, - const char* methodName, + static int callStaticIntMethod(const std::string& className, + const std::string& methodName, Ts... xs) { - std::string methodSignature = "(" + getJNISignature(xs...) + ")I"; - jint ret = 0; cocos2d::JniMethodInfo t; - if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, methodSignature.c_str())) { + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")I"; + if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { ret = t.env->CallStaticIntMethod(t.classID, t.methodID, convert(t, xs)...); t.env->DeleteLocalRef(t.classID); deleteLocalRefs(t.env); + } else { + reportError(className, methodName, signature); } - return ret; } template - static float callStaticFloatMethod(const char* className, - const char* methodName, + static float callStaticFloatMethod(const std::string& className, + const std::string& methodName, Ts... xs) { - std::string methodSignature = "(" + getJNISignature(xs...) + ")F"; - jfloat ret = 0.0; cocos2d::JniMethodInfo t; - if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, methodSignature.c_str())) { + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")F"; + if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { ret = t.env->CallStaticFloatMethod(t.classID, t.methodID, convert(t, xs)...); t.env->DeleteLocalRef(t.classID); deleteLocalRefs(t.env); + } else { + reportError(className, methodName, signature); } - return ret; } template - static double callStaticDoubleMethod(const char* className, - const char* methodName, - Ts... xs) { - std::string methodSignature = "(" + getJNISignature(xs...) + ")D"; + static float* callStaticFloatArrayMethod(const std::string& className, + const std::string& methodName, + Ts... xs) { + static float ret[32]; + cocos2d::JniMethodInfo t; + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")[F"; + if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { + jfloatArray array = (jfloatArray) t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(t, xs)...); + jsize len = t.env->GetArrayLength(array); + if (len <= 32) { + jfloat* elems = t.env->GetFloatArrayElements(array, 0); + if (elems) { + memcpy(ret, elems, sizeof(float) * len); + t.env->ReleaseFloatArrayElements(array, elems, 0); + }; + } + t.env->DeleteLocalRef(t.classID); + deleteLocalRefs(t.env); + return &ret[0]; + } else { + reportError(className, methodName, signature); + } + return nullptr; + } + template + static Vec3 callStaticVec3Method(const std::string& className, + const std::string& methodName, + Ts... xs) { + Vec3 ret; + cocos2d::JniMethodInfo t; + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")[F"; + if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { + jfloatArray array = (jfloatArray) t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(t, xs)...); + 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]; + t.env->ReleaseFloatArrayElements(array, elems, 0); + } + t.env->DeleteLocalRef(t.classID); + deleteLocalRefs(t.env); + } else { + reportError(className, methodName, signature); + } + return ret; + } + + template + static double callStaticDoubleMethod(const std::string& className, + const std::string& methodName, + Ts... xs) { jdouble ret = 0.0; cocos2d::JniMethodInfo t; - if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, methodSignature.c_str())) { + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")D"; + if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { ret = t.env->CallStaticDoubleMethod(t.classID, t.methodID, convert(t, xs)...); t.env->DeleteLocalRef(t.classID); deleteLocalRefs(t.env); + } else { + reportError(className, methodName, signature); } - return ret; } template - static std::string callStaticStringMethod(const char* className, - const char* methodName, + static std::string callStaticStringMethod(const std::string& className, + const std::string& methodName, Ts... xs) { - std::string methodSignature = "(" + getJNISignature(xs...) + ")Ljava/lang/String;"; - std::string ret; cocos2d::JniMethodInfo t; - if (cocos2d::JniHelper::getStaticMethodInfo(t, className, methodName, methodSignature.c_str())) { + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")Ljava/lang/String;"; + if (cocos2d::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { jstring jret = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(t, xs)...); ret = cocos2d::JniHelper::jstring2string(jret); t.env->DeleteLocalRef(t.classID); t.env->DeleteLocalRef(jret); deleteLocalRefs(t.env); + } else { + reportError(className, methodName, signature); } - return ret; } private: - static JNIEnv* cacheEnv(JavaVM* jvm); static bool getMethodInfo_DefaultClassLoader(JniMethodInfo &methodinfo, @@ -193,6 +228,8 @@ private: const char *paramCode); static JavaVM* _psJavaVM; + + static jobject _activity; static jstring convert(cocos2d::JniMethodInfo& t, const char* x); @@ -258,9 +295,10 @@ private: static std::string getJNISignature(T x, Ts... xs) { return getJNISignature(x) + getJNISignature(xs...); } + + static void reportError(const std::string& className, const std::string& methodName, const std::string& signature); }; NS_CC_END #endif // __ANDROID_JNI_HELPER_H__ - diff --git a/native/cocos/platform/apple/CCDevice-apple.mm b/native/cocos/platform/apple/CCDevice-apple.mm index 86aea30979..5f60a874ef 100644 --- a/native/cocos/platform/apple/CCDevice-apple.mm +++ b/native/cocos/platform/apple/CCDevice-apple.mm @@ -23,7 +23,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCDevice-apple.h" +#include "platform/apple/CCDevice-apple.h" namespace FontUtils { NSMutableParagraphStyle* _calculateParagraphStyle(bool enableWrap, int overflow) diff --git a/native/cocos/platform/apple/CCFileUtils-apple.h b/native/cocos/platform/apple/CCFileUtils-apple.h index d932fffdc5..d3c1a751e8 100644 --- a/native/cocos/platform/apple/CCFileUtils-apple.h +++ b/native/cocos/platform/apple/CCFileUtils-apple.h @@ -26,6 +26,7 @@ #ifndef __CC_FILEUTILS_APPLE_H__ #define __CC_FILEUTILS_APPLE_H__ +#include #include #include @@ -46,7 +47,6 @@ class CC_DLL FileUtilsApple : public FileUtils public: FileUtilsApple(); virtual ~FileUtilsApple(); - /* override functions */ virtual std::string getWritablePath() const override; virtual std::string getFullPathForDirectoryAndFilename(const std::string& directory, const std::string& filename) const override; @@ -56,18 +56,19 @@ public: virtual bool writeToFile(const ValueMap& dict, const std::string& fullPath) override; virtual ValueVector getValueVectorFromFile(const std::string& filename) override; +#if CC_FILEUTILS_APPLE_ENABLE_OBJC void setBundle(NSBundle* bundle); +#endif - virtual bool isDirectoryExistInternal(const std::string& dirPath) const override; + virtual bool createDirectory(const std::string& path) override; +private: virtual bool isFileExistInternal(const std::string& filePath) const override; virtual bool removeDirectory(const std::string& dirPath) override; -private: - bool isFileExistInternal(const std::string& filePath,bool& isDirectory) const; virtual void valueMapCompact(ValueMap& valueMap) override; virtual void valueVectorCompact(ValueVector& valueVector) override; - NSBundle* getBundle() const; - NSBundle* _bundle; + struct IMPL; + std::unique_ptr pimpl_; }; // end of platform group @@ -76,4 +77,3 @@ private: NS_CC_END #endif // __CC_FILEUTILS_APPLE_H__ - diff --git a/native/cocos/platform/apple/CCFileUtils-apple.mm b/native/cocos/platform/apple/CCFileUtils-apple.mm index bbeba0fedc..4ba7f0cbf2 100644 --- a/native/cocos/platform/apple/CCFileUtils-apple.mm +++ b/native/cocos/platform/apple/CCFileUtils-apple.mm @@ -25,7 +25,7 @@ THE SOFTWARE. ****************************************************************************/ #import -#include "CCFileUtils-apple.h" +#include "platform/apple/CCFileUtils-apple.h" #include @@ -33,22 +33,91 @@ THE SOFTWARE. #include #include "base/CCDirector.h" -#include "base/CCString.h" +#include "deprecated/CCDictionary.h" #include "platform/CCFileUtils.h" #include "platform/CCSAXParser.h" NS_CC_BEGIN -static void addValueToDict(id nsKey, id nsValue, ValueMap& dict); -static void addObjectToNSDict(const std::string& key, const Value& value, NSMutableDictionary *dict); +struct FileUtilsApple::IMPL { + IMPL(NSBundle* bundle):bundle_([NSBundle mainBundle]) {} + void setBundle(NSBundle* bundle) { + bundle_ = bundle; + } + NSBundle* getBundle() const { + return bundle_; + } +private: + NSBundle* bundle_; +}; -static void addItemToArray(id item, ValueVector& array) +static id convertCCValueToNSObject(const cocos2d::Value &value); +static cocos2d::Value convertNSObjectToCCValue(id object); + +static void addNSObjectToCCMap(id nsKey, id nsValue, ValueMap& dict); +static void addCCValueToNSDictionary(const std::string& key, const Value& value, NSMutableDictionary *dict); +static void addNSObjectToCCVector(id item, ValueVector& array); +static void addCCValueToNSArray(const Value& value, NSMutableArray *array); + +static id convertCCValueToNSObject(const cocos2d::Value &value) +{ + switch (value.getType()) + { + case Value::Type::NONE: + return [NSNull null]; + + case Value::Type::STRING: + return [NSString stringWithCString:value.asString().c_str() encoding:NSUTF8StringEncoding]; + + case Value::Type::BYTE: + return [NSNumber numberWithInt:value.asByte()]; + + case Value::Type::INTEGER: + return [NSNumber numberWithInt:value.asInt()]; + + case Value::Type::UNSIGNED: + return [NSNumber numberWithUnsignedInt:value.asUnsignedInt()]; + + case Value::Type::FLOAT: + return [NSNumber numberWithFloat:value.asFloat()]; + + case Value::Type::DOUBLE: + return [NSNumber numberWithDouble:value.asDouble()]; + + case Value::Type::BOOLEAN: + return [NSNumber numberWithBool:value.asBool()]; + + case Value::Type::VECTOR: { + NSMutableArray *array = [NSMutableArray array]; + const ValueVector &vector = value.asValueVector(); + for (const auto &e : vector) { + addCCValueToNSArray(e, array); + } + return array; + } + + case Value::Type::MAP: { + NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; + const ValueMap &map = value.asValueMap(); + for (auto iter = map.begin(); iter != map.end(); ++iter) { + addCCValueToNSDictionary(iter->first, iter->second, dictionary); + } + return dictionary; + } + + case Value::Type::INT_KEY_MAP: + break; + } + + return [NSNull null]; +} + +static cocos2d::Value convertNSObjectToCCValue(id item) { // add string value into array if ([item isKindOfClass:[NSString class]]) { - array.push_back(Value([item UTF8String])); - return; + return Value([item UTF8String]); } // add number value into array(such as int, float, bool and so on) @@ -60,20 +129,20 @@ static void addItemToArray(id item, ValueVector& array) if(num == (void*)kCFBooleanFalse || num == (void*)kCFBooleanTrue) { bool v = [num boolValue]; - array.push_back(Value(v)); + return Value(v); } else if(strcmp(numType, @encode(float)) == 0) { - array.push_back(Value([num floatValue])); + return Value([num floatValue]); } else if(strcmp(numType, @encode(double)) == 0) { - array.push_back(Value([num doubleValue])); + return Value([num doubleValue]); } - else{ - array.push_back(Value([num intValue])); + else + { + return Value([num intValue]); } - return; } @@ -84,11 +153,10 @@ static void addItemToArray(id item, ValueVector& array) for (id subKey in [item allKeys]) { id subValue = [item objectForKey:subKey]; - addValueToDict(subKey, subValue, dict); + addNSObjectToCCMap(subKey, subValue, dict); } - - array.push_back(Value(dict)); - return; + + return Value(dict); } // add array value into array @@ -97,237 +165,54 @@ static void addItemToArray(id item, ValueVector& array) ValueVector subArray; for (id subItem in item) { - addItemToArray(subItem, subArray); + addNSObjectToCCVector(subItem, subArray); } - array.push_back(Value(subArray)); - return; + return Value(subArray); } + + return Value::Null; } -static void addObjectToNSArray(const Value& value, NSMutableArray *array) +static void addNSObjectToCCVector(id item, ValueVector& array) { - // add string into array - if (value.getType() == Value::Type::STRING) - { - NSString *element = [NSString stringWithCString:value.asString().c_str() encoding:NSUTF8StringEncoding]; - [array addObject:element]; - return; - } - - //add float into array - if (value.getType() == Value::Type::FLOAT) { - NSNumber *number = [NSNumber numberWithFloat:value.asFloat()]; - [array addObject:number]; - } - - //add double into array - if (value.getType() == Value::Type::DOUBLE) { - NSNumber *number = [NSNumber numberWithDouble:value.asDouble()]; - [array addObject:number]; - } - - //add boolean into array - if (value.getType() == Value::Type::BOOLEAN) { - NSNumber *element = [NSNumber numberWithBool:value.asBool()]; - [array addObject:element]; - } - - if (value.getType() == Value::Type::INTEGER) { - NSNumber *element = [NSNumber numberWithInt:value.asInt()]; - [array addObject:element]; - } - - //todo: add date and data support - - // add array into array - if (value.getType() == Value::Type::VECTOR) - { - NSMutableArray *element = [NSMutableArray array]; - - ValueVector valueArray = value.asValueVector(); - - for (const auto &e : valueArray) - { - addObjectToNSArray(e, element); - } - - [array addObject:element]; - return; - } - - // add dictionary value into array - if (value.getType() == Value::Type::MAP) - { - NSMutableDictionary *element = [NSMutableDictionary dictionary]; - - auto valueDict = value.asValueMap(); - for (auto iter = valueDict.begin(); iter != valueDict.end(); ++iter) - { - addObjectToNSDict(iter->first, iter->second, element); - } - - [array addObject:element]; - } + array.push_back(convertNSObjectToCCValue(item)); } -static void addValueToDict(id nsKey, id nsValue, ValueMap& dict) +static void addCCValueToNSArray(const Value& value, NSMutableArray *array) +{ + [array addObject:convertCCValueToNSObject(value)]; +} + +static void addNSObjectToCCMap(id nsKey, id nsValue, ValueMap& dict) { // the key must be a string CCASSERT([nsKey isKindOfClass:[NSString class]], "The key should be a string!"); std::string key = [nsKey UTF8String]; - - // the value is a string - if ([nsValue isKindOfClass:[NSString class]]) - { - dict[key] = Value([nsValue UTF8String]); - return; - } - - // the value is a number - if ([nsValue isKindOfClass:[NSNumber class]]) - { - NSNumber* num = nsValue; - const char* numType = [num objCType]; - if(num == (void*)kCFBooleanFalse || num == (void*)kCFBooleanTrue) - { - bool v = [num boolValue]; - dict[key] = Value(v); - } - else if(strcmp(numType, @encode(float)) == 0) - { - dict[key] = Value([num floatValue]); - } - else if(strcmp(numType, @encode(double)) == 0) - { - dict[key] = Value([num doubleValue]); - } - else{ - dict[key] = Value([num intValue]); - } - return; - } - - - // the value is a new dictionary - if ([nsValue isKindOfClass:[NSDictionary class]]) - { - ValueMap subDict; - - for (id subKey in [nsValue allKeys]) - { - id subValue = [nsValue objectForKey:subKey]; - addValueToDict(subKey, subValue, subDict); - } - dict[key] = Value(subDict); - return; - } - - // the value is a array - if ([nsValue isKindOfClass:[NSArray class]]) - { - ValueVector valueArray; - - for (id item in nsValue) - { - addItemToArray(item, valueArray); - } - dict[key] = Value(valueArray); - return; - } - + dict[key] = convertNSObjectToCCValue(nsValue); } -static void addObjectToNSDict(const std::string& key, const Value& value, NSMutableDictionary *dict) +static void addCCValueToNSDictionary(const std::string& key, const Value& value, NSMutableDictionary *dict) { NSString *NSkey = [NSString stringWithCString:key.c_str() encoding:NSUTF8StringEncoding]; - - // the object is a Dictionary - if (value.getType() == Value::Type::MAP) - { - NSMutableDictionary *dictElement = [NSMutableDictionary dictionary]; - ValueMap subDict = value.asValueMap(); - for (auto iter = subDict.begin(); iter != subDict.end(); ++iter) - { - addObjectToNSDict(iter->first, iter->second, dictElement); - } - - [dict setObject:dictElement forKey:NSkey]; - return; - } - - //add float into dict - if (value.getType() == Value::Type::FLOAT) { - NSNumber *number = [NSNumber numberWithFloat:value.asFloat()]; - [dict setObject:number forKey:NSkey]; - } - - //add double into dict - if (value.getType() == Value::Type::DOUBLE) { - NSNumber *number = [NSNumber numberWithDouble:value.asDouble()]; - [dict setObject:number forKey:NSkey]; - } - - //add boolean into dict - if (value.getType() == Value::Type::BOOLEAN) { - NSNumber *element = [NSNumber numberWithBool:value.asBool()]; - [dict setObject:element forKey:NSkey]; - } - - //add integer into dict - if (value.getType() == Value::Type::INTEGER) { - NSNumber *element = [NSNumber numberWithInt:value.asInt()]; - [dict setObject:element forKey:NSkey]; - } - - // the object is a String - if (value.getType() == Value::Type::STRING) - { - NSString *strElement = [NSString stringWithCString:value.asString().c_str() encoding:NSUTF8StringEncoding]; - [dict setObject:strElement forKey:NSkey]; - return; - } - - // the object is a Array - if (value.getType() == Value::Type::VECTOR) - { - NSMutableArray *arrElement = [NSMutableArray array]; - - ValueVector array = value.asValueVector(); - - for(const auto& v : array) - { - addObjectToNSArray(v, arrElement); - } - - [dict setObject:arrElement forKey:NSkey]; - return; - } + [dict setObject:convertCCValueToNSObject(value) forKey:NSkey]; } -static NSFileManager* s_fileManager = nil; -FileUtilsApple::FileUtilsApple() { - _bundle = [NSBundle mainBundle]; - s_fileManager = [NSFileManager defaultManager]; +FileUtilsApple::FileUtilsApple() : pimpl_(new IMPL([NSBundle mainBundle])) { } -FileUtilsApple::~FileUtilsApple() -{ - _bundle = nil; - s_fileManager = nil; -} +FileUtilsApple::~FileUtilsApple() = default; +#if CC_FILEUTILS_APPLE_ENABLE_OBJC void FileUtilsApple::setBundle(NSBundle* bundle) { - _bundle = bundle; + pimpl_->setBundle(bundle); } - -NSBundle* FileUtilsApple::getBundle() const { - return _bundle; -} - +#endif #pragma mark - FileUtils +static NSFileManager* s_fileManager = [NSFileManager defaultManager]; + FileUtils* FileUtils::getInstance() { if (s_sharedFileUtils == nullptr) @@ -359,43 +244,46 @@ std::string FileUtilsApple::getWritablePath() const return strRet; } -bool FileUtilsApple::isDirectoryExistInternal(const std::string &dirPath) const -{ - bool isDirectory = false; - auto isExist = isFileExistInternal(dirPath, isDirectory); - return isExist && isDirectory; -} - -bool FileUtilsApple::isFileExistInternal(const std::string &filePath) const -{ - bool isDirectory = false; - auto isExist = isFileExistInternal(filePath, isDirectory); - return isExist && !isDirectory; -} - -bool FileUtilsApple::isFileExistInternal(const std::string& filePath, bool& isDirectory) const +bool FileUtilsApple::isFileExistInternal(const std::string& filePath) const { if (filePath.empty()) + { return false; - - isDirectory = false; - - NSString* path = nil; - if (filePath[0] != '/') - path = [[getBundle() resourcePath] stringByAppendingPathComponent: - [NSString stringWithUTF8String:filePath.c_str()]]; - else - path = [NSString stringWithUTF8String:filePath.c_str()]; - - BOOL isDir = NO; - // Search path is an absolute path. - if ([s_fileManager fileExistsAtPath:path isDirectory:&isDir]) { - if (isDir) - isDirectory = true; - return true; } - return false; + bool ret = false; + + if (filePath[0] != '/') + { + std::string path; + std::string file; + size_t pos = filePath.find_last_of("/"); + if (pos != std::string::npos) + { + file = filePath.substr(pos+1); + path = filePath.substr(0, pos+1); + } + else + { + file = filePath; + } + + NSString* fullpath = [pimpl_->getBundle() pathForResource:[NSString stringWithUTF8String:file.c_str()] + ofType:nil + inDirectory:[NSString stringWithUTF8String:path.c_str()]]; + if (fullpath != nil) { + ret = true; + } + } + else + { + // Search path is an absolute path. + if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:filePath.c_str()]]) { + ret = true; + } + } + + return ret; } static int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) @@ -411,9 +299,9 @@ static int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, str bool FileUtilsApple::removeDirectory(const std::string& path) { - if (!path.empty() && path[path.size() - 1] != '/') + if (path.empty()) { - CCLOGERROR("Fail to remove directory, path must termniate with '/': %s", path.c_str()); + CCLOGERROR("Fail to remove directory, path is empty!"); return false; } @@ -427,7 +315,7 @@ std::string FileUtilsApple::getFullPathForDirectoryAndFilename(const std::string { if (directory[0] != '/') { - NSString* fullpath = [getBundle() pathForResource:[NSString stringWithUTF8String:filename.c_str()] + NSString* fullpath = [pimpl_->getBundle() pathForResource:[NSString stringWithUTF8String:filename.c_str()] ofType:nil inDirectory:[NSString stringWithUTF8String:directory.c_str()]]; if (fullpath != nil) { @@ -465,7 +353,7 @@ ValueMap FileUtilsApple::getValueMapFromData(const char* filedata, int filesize) for (id key in [dict allKeys]) { id value = [dict objectForKey:key]; - addValueToDict(key, value, ret); + addNSObjectToCCMap(key, value, ret); } } return ret; @@ -479,13 +367,12 @@ bool FileUtilsApple::writeToFile(const ValueMap& dict, const std::string &fullPa bool FileUtils::writeValueMapToFile(const ValueMap& dict, const std::string& fullPath) { valueMapCompact(const_cast(dict)); - //CCLOG("iOS||Mac Dictionary %d write to file %s", dict->_ID, fullPath.c_str()); NSMutableDictionary *nsDict = [NSMutableDictionary dictionary]; for (auto iter = dict.begin(); iter != dict.end(); ++iter) { - addObjectToNSDict(iter->first, iter->second, nsDict); + addCCValueToNSDictionary(iter->first, iter->second, nsDict); } NSString *file = [NSString stringWithUTF8String:fullPath.c_str()]; @@ -493,41 +380,6 @@ bool FileUtils::writeValueMapToFile(const ValueMap& dict, const std::string& ful return [nsDict writeToFile:file atomically:YES]; } -bool FileUtils::writeValueVectorToFile(const ValueVector& vecData, const std::string& fullPath) -{ - NSString* path = [NSString stringWithUTF8String:fullPath.c_str()]; - NSMutableArray* array = [NSMutableArray array]; - - for (const auto &e : vecData) - { - addObjectToNSArray(e, array); - } - - [array writeToFile:path atomically:YES]; - - return true; -} -ValueVector FileUtilsApple::getValueVectorFromFile(const std::string& filename) -{ - // NSString* pPath = [NSString stringWithUTF8String:pFileName]; - // NSString* pathExtension= [pPath pathExtension]; - // pPath = [pPath stringByDeletingPathExtension]; - // pPath = [[NSBundle mainBundle] pathForResource:pPath ofType:pathExtension]; - // fixing cannot read data using Array::createWithContentsOfFile - std::string fullPath = fullPathForFilename(filename); - NSString* path = [NSString stringWithUTF8String:fullPath.c_str()]; - NSArray* array = [NSArray arrayWithContentsOfFile:path]; - - ValueVector ret; - - for (id value in array) - { - addItemToArray(value, ret); - } - - return ret; -} - void FileUtilsApple::valueMapCompact(ValueMap& valueMap) { auto itr = valueMap.begin(); @@ -580,5 +432,58 @@ void FileUtilsApple::valueVectorCompact(ValueVector& valueVector) } } -NS_CC_END +bool FileUtils::writeValueVectorToFile(const ValueVector& vecData, const std::string& fullPath) +{ + NSString* path = [NSString stringWithUTF8String:fullPath.c_str()]; + NSMutableArray* array = [NSMutableArray array]; + for (const auto &e : vecData) + { + addCCValueToNSArray(e, array); + } + + [array writeToFile:path atomically:YES]; + + return true; +} +ValueVector FileUtilsApple::getValueVectorFromFile(const std::string& filename) +{ + // NSString* pPath = [NSString stringWithUTF8String:pFileName]; + // NSString* pathExtension= [pPath pathExtension]; + // pPath = [pPath stringByDeletingPathExtension]; + // pPath = [[NSBundle mainBundle] pathForResource:pPath ofType:pathExtension]; + // fixing cannot read data using Array::createWithContentsOfFile + std::string fullPath = fullPathForFilename(filename); + NSString* path = [NSString stringWithUTF8String:fullPath.c_str()]; + NSArray* array = [NSArray arrayWithContentsOfFile:path]; + + ValueVector ret; + + for (id value in array) + { + addNSObjectToCCVector(value, ret); + } + + return ret; +} + +bool FileUtilsApple::createDirectory(const std::string& path) +{ + CCASSERT(!path.empty(), "Invalid path"); + + if (isDirectoryExist(path)) + return true; + + NSError* error; + + bool result = [s_fileManager createDirectoryAtPath:[NSString stringWithUTF8String:path.c_str()] withIntermediateDirectories:YES attributes:nil error:&error]; + + if(!result && error != nil) + { + CCLOGERROR("Fail to create directory \"%s\": %s", path.c_str(), [error.localizedDescription UTF8String]); + } + + return result; +} + +NS_CC_END diff --git a/native/cocos/platform/apple/CCLock-apple.cpp b/native/cocos/platform/apple/CCLock-apple.cpp index e28e5c7602..5d396aef55 100644 --- a/native/cocos/platform/apple/CCLock-apple.cpp +++ b/native/cocos/platform/apple/CCLock-apple.cpp @@ -23,28 +23,27 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCLock-apple.h" +#include "platform/apple/CCLock-apple.h" NS_CC_BEGIN -Lock::Lock() +Lock::Lock(void) { } -Lock::~Lock() +Lock::~Lock(void) { } -void Lock::lock() +void Lock::lock(void) { } -void Lock::unlock() +void Lock::unlock(void) { } NS_CC_END - diff --git a/native/cocos/platform/apple/CCLock-apple.h b/native/cocos/platform/apple/CCLock-apple.h index 8a6ea4af57..0bf3640f13 100644 --- a/native/cocos/platform/apple/CCLock-apple.h +++ b/native/cocos/platform/apple/CCLock-apple.h @@ -36,18 +36,17 @@ public: /** * @js ctor */ - Lock(); + Lock(void); /** * @js NA * @lua NA */ - ~Lock(); + ~Lock(void); - void lock(); - void unlock(); + void lock(void); + void unlock(void); }; NS_CC_END #endif // __PLATFORM_IPHONE_PLATFORM_CCLOCK_H__ - diff --git a/native/cocos/platform/apple/CCThread-apple.mm b/native/cocos/platform/apple/CCThread-apple.mm index db25e4ed40..04730f5d2a 100644 --- a/native/cocos/platform/apple/CCThread-apple.mm +++ b/native/cocos/platform/apple/CCThread-apple.mm @@ -41,4 +41,3 @@ void ThreadHelper::releaseAutoreleasePool(void *autoreleasePool) } NS_CC_END - diff --git a/native/cocos/platform/desktop/CCGLViewImpl-desktop.cpp b/native/cocos/platform/desktop/CCGLViewImpl-desktop.cpp index 2f91976cff..2ca6284ca2 100644 --- a/native/cocos/platform/desktop/CCGLViewImpl-desktop.cpp +++ b/native/cocos/platform/desktop/CCGLViewImpl-desktop.cpp @@ -23,8 +23,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCGLViewImpl-desktop.h" +#include "platform/desktop/CCGLViewImpl-desktop.h" +#include #include #include "platform/CCApplication.h" @@ -33,11 +34,9 @@ THE SOFTWARE. #include "base/CCEventDispatcher.h" #include "base/CCEventKeyboard.h" #include "base/CCEventMouse.h" -#include "base/CCEventCustom.h" #include "base/CCIMEDispatcher.h" #include "base/ccUtils.h" #include "base/ccUTF8.h" -#include "base/CCString.h" NS_CC_BEGIN @@ -264,7 +263,7 @@ static keyCodeItem g_keyCodeStructArray[] = { ////////////////////////////////////////////////////////////////////////// -GLViewImpl::GLViewImpl() +GLViewImpl::GLViewImpl(bool initglfw) : _captured(false) , _supportTouch(false) , _isInRetinaMonitor(false) @@ -284,9 +283,11 @@ GLViewImpl::GLViewImpl() } GLFWEventHandler::setGLViewImpl(this); - - glfwSetErrorCallback(GLFWEventHandler::onGLFWError); - glfwInit(); + if (initglfw) + { + glfwSetErrorCallback(GLFWEventHandler::onGLFWError); + glfwInit(); + } } GLViewImpl::~GLViewImpl() @@ -297,9 +298,14 @@ GLViewImpl::~GLViewImpl() } GLViewImpl* GLViewImpl::create(const std::string& viewName) +{ + return GLViewImpl::create(viewName, false); +} + +GLViewImpl* GLViewImpl::create(const std::string& viewName, bool resizable) { auto ret = new (std::nothrow) GLViewImpl; - if(ret && ret->initWithRect(viewName, Rect(0, 0, 960, 640), 1.0f, false)) { + if(ret && ret->initWithRect(viewName, Rect(0, 0, 960, 640), 1.0f, resizable)) { ret->autorelease(); return ret; } @@ -354,10 +360,10 @@ bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float fram glfwWindowHint(GLFW_DEPTH_BITS,_glContextAttrs.depthBits); glfwWindowHint(GLFW_STENCIL_BITS,_glContextAttrs.stencilBits); - int needWidth = rect.size.width * _frameZoomFactor; - int neeHeight = rect.size.height * _frameZoomFactor; + int neededWidth = rect.size.width * _frameZoomFactor; + int neededHeight = rect.size.height * _frameZoomFactor; - _mainWindow = glfwCreateWindow(needWidth, neeHeight, _viewName.c_str(), _monitor, nullptr); + _mainWindow = glfwCreateWindow(neededWidth, neededHeight, _viewName.c_str(), _monitor, nullptr); if (_mainWindow == nullptr) { @@ -384,11 +390,11 @@ bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float fram */ int realW = 0, realH = 0; glfwGetWindowSize(_mainWindow, &realW, &realH); - if (realW != needWidth) + if (realW != neededWidth) { rect.size.width = realW / _frameZoomFactor; } - if (realH != neeHeight) + if (realH != neededHeight) { rect.size.height = realH / _frameZoomFactor; } @@ -425,6 +431,9 @@ bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float fram // Enable point size by default. glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); +// // GLFW v3.2 no longer emits "onGLFWWindowSizeFunCallback" at creation time. Force default viewport: +// setViewPortInPoints(0, 0, neededWidth, neededHeight); +// return true; } @@ -527,7 +536,7 @@ void GLViewImpl::setFrameZoomFactor(float zoomFactor) { CCASSERT(zoomFactor > 0.0f, "zoomFactor must be larger than 0"); - if (fabs(_frameZoomFactor - zoomFactor) < FLT_EPSILON) + if (std::abs(_frameZoomFactor - zoomFactor) < FLT_EPSILON) { return; } @@ -586,10 +595,10 @@ void GLViewImpl::setFrameSize(float width, float height) void GLViewImpl::setViewPortInPoints(float x , float y , float w , float h) { - glViewport((float)(x * _scaleX * _retinaFactor * _frameZoomFactor + _viewPortRect.origin.x * _retinaFactor * _frameZoomFactor), - (float)(y * _scaleY * _retinaFactor * _frameZoomFactor + _viewPortRect.origin.y * _retinaFactor * _frameZoomFactor), - (float)(w * _scaleX * _retinaFactor * _frameZoomFactor), - (float)(h * _scaleY * _retinaFactor * _frameZoomFactor)); + glViewport vp((GLint)(x * _scaleX * _retinaFactor * _frameZoomFactor + _viewPortRect.origin.x * _retinaFactor * _frameZoomFactor), + (GLint)(y * _scaleY * _retinaFactor * _frameZoomFactor + _viewPortRect.origin.y * _retinaFactor * _frameZoomFactor), + (GLint)(w * _scaleX * _retinaFactor * _frameZoomFactor), + (GLint)(h * _scaleY * _retinaFactor * _frameZoomFactor)); } void GLViewImpl::setScissorInPoints(float x , float y , float w , float h) @@ -613,7 +622,14 @@ Rect GLViewImpl::getScissorRect() const void GLViewImpl::onGLFWError(int errorID, const char* errorDesc) { - _glfwError = StringUtils::format("GLFWError #%d Happen, %s", errorID, errorDesc); + if (_mainWindow) + { + _glfwError = StringUtils::format("GLFWError #%d Happen, %s", errorID, errorDesc); + } + else + { + _glfwError.append(StringUtils::format("GLFWError #%d Happen, %s\n", errorID, errorDesc)); + } CCLOGERROR("%s", _glfwError.c_str()); } @@ -650,14 +666,14 @@ void GLViewImpl::onGLFWMouseCallBack(GLFWwindow* window, int button, int action, EventMouse event(EventMouse::MouseEventType::MOUSE_DOWN); event.setCursorPosition(cursorX, cursorY); event.setMouseButton(button); - Director::DirectorInstance->getEventDispatcher()->dispatchEvent(&event); + Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); } else if(GLFW_RELEASE == action) { EventMouse event(EventMouse::MouseEventType::MOUSE_UP); event.setCursorPosition(cursorX, cursorY); event.setMouseButton(button); - Director::DirectorInstance->getEventDispatcher()->dispatchEvent(&event); + Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); } } @@ -703,7 +719,7 @@ void GLViewImpl::onGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y) event.setMouseButton(GLFW_MOUSE_BUTTON_MIDDLE); } event.setCursorPosition(cursorX, cursorY); - Director::DirectorInstance->getEventDispatcher()->dispatchEvent(&event); + Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); } void GLViewImpl::onGLFWMouseScrollCallback(GLFWwindow* window, double x, double y) @@ -714,7 +730,7 @@ void GLViewImpl::onGLFWMouseScrollCallback(GLFWwindow* window, double x, double float cursorY = (_viewPortRect.origin.y + _viewPortRect.size.height - _mouseY) / _scaleY; event.setScrollData((float)x, -(float)y); event.setCursorPosition(cursorX, cursorY); - Director::DirectorInstance->getEventDispatcher()->dispatchEvent(&event); + Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); } void GLViewImpl::onGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) @@ -722,13 +738,30 @@ void GLViewImpl::onGLFWKeyCallback(GLFWwindow *window, int key, int scancode, in if (GLFW_REPEAT != action) { EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action); - auto dispatcher = Director::DirectorInstance->getEventDispatcher(); + auto dispatcher = Director::getInstance()->getEventDispatcher(); dispatcher->dispatchEvent(&event); } - if (GLFW_RELEASE != action && g_keyCodeMap[key] == EventKeyboard::KeyCode::KEY_BACKSPACE) + if (GLFW_RELEASE != action) { - IMEDispatcher::sharedDispatcher()->dispatchDeleteBackward(); + switch (g_keyCodeMap[key]) + { + case EventKeyboard::KeyCode::KEY_BACKSPACE: + IMEDispatcher::sharedDispatcher()->dispatchDeleteBackward(); + break; + case EventKeyboard::KeyCode::KEY_HOME: + case EventKeyboard::KeyCode::KEY_KP_HOME: + case EventKeyboard::KeyCode::KEY_DELETE: + case EventKeyboard::KeyCode::KEY_KP_DELETE: + case EventKeyboard::KeyCode::KEY_END: + case EventKeyboard::KeyCode::KEY_LEFT_ARROW: + case EventKeyboard::KeyCode::KEY_RIGHT_ARROW: + case EventKeyboard::KeyCode::KEY_ESCAPE: + IMEDispatcher::sharedDispatcher()->dispatchControlKey(g_keyCodeMap[key]); + break; + default: + break; + } } } @@ -738,12 +771,28 @@ void GLViewImpl::onGLFWCharCallback(GLFWwindow *window, unsigned int character) std::string utf8String; StringUtils::UTF16ToUTF8( wcharString, utf8String ); - IMEDispatcher::sharedDispatcher()->dispatchInsertText( utf8String.c_str(), utf8String.size() ); + static std::set controlUnicode = { + "\xEF\x9C\x80", // up + "\xEF\x9C\x81", // down + "\xEF\x9C\x82", // left + "\xEF\x9C\x83", // right + "\xEF\x9C\xA8", // delete + "\xEF\x9C\xA9", // home + "\xEF\x9C\xAB", // end + "\xEF\x9C\xAC", // pageup + "\xEF\x9C\xAD", // pagedown + "\xEF\x9C\xB9" // clear + }; + // Check for send control key + if (controlUnicode.find(utf8String) == controlUnicode.end()) + { + IMEDispatcher::sharedDispatcher()->dispatchInsertText( utf8String.c_str(), utf8String.size() ); + } } void GLViewImpl::onGLFWWindowPosCallback(GLFWwindow *windows, int x, int y) { - Director::DirectorInstance->setViewport(); + Director::getInstance()->setViewport(); } void GLViewImpl::onGLFWframebuffersize(GLFWwindow* window, int w, int h) @@ -753,7 +802,7 @@ void GLViewImpl::onGLFWframebuffersize(GLFWwindow* window, int w, int h) float factorX = frameSizeW / w * _retinaFactor * _frameZoomFactor; float factorY = frameSizeH / h * _retinaFactor * _frameZoomFactor; - if (fabs(factorX - 0.5f) < FLT_EPSILON && fabs(factorY - 0.5f) < FLT_EPSILON ) + if (std::abs(factorX - 0.5f) < FLT_EPSILON && std::abs(factorY - 0.5f) < FLT_EPSILON) { _isInRetinaMonitor = true; if (_isRetinaEnabled) @@ -767,7 +816,7 @@ void GLViewImpl::onGLFWframebuffersize(GLFWwindow* window, int w, int h) glfwSetWindowSize(window, static_cast(frameSizeW * 0.5f * _retinaFactor * _frameZoomFactor) , static_cast(frameSizeH * 0.5f * _retinaFactor * _frameZoomFactor)); } - else if(fabs(factorX - 2.0f) < FLT_EPSILON && fabs(factorY - 2.0f) < FLT_EPSILON) + else if (std::abs(factorX - 2.0f) < FLT_EPSILON && std::abs(factorY - 2.0f) < FLT_EPSILON) { _isInRetinaMonitor = false; _retinaFactor = 1; @@ -787,10 +836,6 @@ void GLViewImpl::onGLFWWindowSizeFunCallback(GLFWwindow *window, int width, int setFrameSize(frameWidth, frameHeight); setDesignResolutionSize(baseDesignSize.width, baseDesignSize.height, baseResolutionPolicy); Director::getInstance()->setViewport(); - - EventCustom event("window-resize"); - auto dispatcher = Director::DirectorInstance->getEventDispatcher(); - dispatcher->dispatchEvent(&event); } } @@ -913,4 +958,3 @@ bool GLViewImpl::initGlew() } NS_CC_END // end of namespace cocos2d; - diff --git a/native/cocos/platform/desktop/CCGLViewImpl-desktop.h b/native/cocos/platform/desktop/CCGLViewImpl-desktop.h index 09afb87b61..7f917ef302 100644 --- a/native/cocos/platform/desktop/CCGLViewImpl-desktop.h +++ b/native/cocos/platform/desktop/CCGLViewImpl-desktop.h @@ -57,6 +57,7 @@ class CC_DLL GLViewImpl : public GLView { public: static GLViewImpl* create(const std::string& viewName); + static GLViewImpl* create(const std::string& viewName, bool resizable); static GLViewImpl* createWithRect(const std::string& viewName, const Rect& size, float frameZoomFactor = 1.0f, bool resizable = false); static GLViewImpl* createWithFullScreen(const std::string& viewName); static GLViewImpl* createWithFullScreen(const std::string& viewName, const GLFWvidmode &videoMode, GLFWmonitor *monitor); @@ -112,7 +113,7 @@ public: #endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) protected: - GLViewImpl(); + GLViewImpl(bool initglfw = true); virtual ~GLViewImpl(); bool initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable); @@ -160,4 +161,3 @@ private: NS_CC_END // end of namespace cocos2d #endif // end of __CC_EGLViewImpl_DESKTOP_H__ - diff --git a/native/cocos/platform/ios/CCApplication-ios.h b/native/cocos/platform/ios/CCApplication-ios.h index 3db3f86f3d..663962f9bb 100644 --- a/native/cocos/platform/ios/CCApplication-ios.h +++ b/native/cocos/platform/ios/CCApplication-ios.h @@ -66,31 +66,36 @@ public: @brief Callback by Director for limit FPS. @param interval The time, expressed in seconds, between current frame and next. */ - virtual void setAnimationInterval(float interval); + virtual void setAnimationInterval(float interval) override; /** @brief Get current language config @return Current language config */ - virtual LanguageType getCurrentLanguage(); - + virtual LanguageType getCurrentLanguage() override; + /** @brief Get current language iso 639-1 code @return Current language iso 639-1 code */ - virtual const char * getCurrentLanguageCode(); - + virtual const char * getCurrentLanguageCode() override; + /** @brief Get target platform */ - virtual Platform getTargetPlatform(); - + virtual Platform getTargetPlatform() override; + + /** + @brief Get application version. + */ + virtual std::string getVersion() override; + /** @brief Open url in default browser @param String with url to open. @return true if the resource located by the URL was successfully opened; otherwise false. */ - virtual bool openURL(const std::string &url); + virtual bool openURL(const std::string &url) override; /** @brief This function will be called when the application screen size is changed. @@ -108,4 +113,3 @@ NS_CC_END #endif // CC_PLATFORM_IOS #endif // end of __CC_APPLICATION_IOS_H__ - diff --git a/native/cocos/platform/ios/CCApplication-ios.mm b/native/cocos/platform/ios/CCApplication-ios.mm index a8066d7917..a6d5b8a3d3 100644 --- a/native/cocos/platform/ios/CCApplication-ios.mm +++ b/native/cocos/platform/ios/CCApplication-ios.mm @@ -30,7 +30,7 @@ #import #import "math/CCGeometry.h" -#import "CCDirectorCaller-ios.h" +#import "platform/ios/CCDirectorCaller-ios.h" NS_CC_BEGIN @@ -38,16 +38,14 @@ Application* Application::sm_pSharedApplication = nullptr; Application::Application() { - if (sm_pSharedApplication) { - log("func:%s:,error:sm_pSharedApplication should be nullptr", __FUNCTION__); - } + CC_ASSERT(! sm_pSharedApplication); sm_pSharedApplication = this; } Application::~Application() { CC_ASSERT(this == sm_pSharedApplication); - sm_pSharedApplication = nullptr; + sm_pSharedApplication = 0; } int Application::run() @@ -70,6 +68,7 @@ void Application::setAnimationInterval(float interval) Application* Application::getInstance() { + CC_ASSERT(sm_pSharedApplication); return sm_pSharedApplication; } @@ -143,6 +142,14 @@ Application::Platform Application::getTargetPlatform() } } +std::string Application::getVersion() { + NSString* version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]; + if (version) { + return [version UTF8String]; + } + return ""; +} + bool Application::openURL(const std::string &url) { NSString* msg = [NSString stringWithCString:url.c_str() encoding:NSUTF8StringEncoding]; @@ -157,4 +164,3 @@ void Application::applicationScreenSizeChanged(int newWidth, int newHeight) { NS_CC_END #endif // CC_PLATFORM_IOS - diff --git a/native/cocos/platform/ios/CCCommon-ios.mm b/native/cocos/platform/ios/CCCommon-ios.mm index 319b177a9a..7a32639038 100644 --- a/native/cocos/platform/ios/CCCommon-ios.mm +++ b/native/cocos/platform/ios/CCCommon-ios.mm @@ -40,6 +40,9 @@ NS_CC_BEGIN // ios no MessageBox, use log instead void MessageBox(const char * msg, const char * title) { + // only enable it on iOS. + // FIXME: Implement it for tvOS +#if !defined(CC_TARGET_OS_TVOS) NSString * tmpTitle = (title) ? [NSString stringWithUTF8String : title] : nil; NSString * tmpMsg = (msg) ? [NSString stringWithUTF8String : msg] : nil; UIAlertView * messageBox = [[UIAlertView alloc] initWithTitle: tmpTitle @@ -49,6 +52,7 @@ void MessageBox(const char * msg, const char * title) otherButtonTitles: nil]; [messageBox autorelease]; [messageBox show]; +#endif } void LuaLog(const char * format) @@ -59,4 +63,3 @@ void LuaLog(const char * format) NS_CC_END #endif // CC_PLATFORM_IOS - diff --git a/native/cocos/platform/ios/CCDevice-ios.mm b/native/cocos/platform/ios/CCDevice-ios.mm index 8fcc76512c..95fe6b2a28 100644 --- a/native/cocos/platform/ios/CCDevice-ios.mm +++ b/native/cocos/platform/ios/CCDevice-ios.mm @@ -27,7 +27,7 @@ #include "platform/CCPlatformConfig.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS -#include "CCDevice.h" +#include "platform/CCDevice.h" #include "base/ccTypes.h" #include "platform/apple/CCDevice-apple.h" #include "base/CCEventDispatcher.h" @@ -36,7 +36,9 @@ #import // Accelerometer +#if !defined(CC_TARGET_OS_TVOS) #import +#endif #import #import // Vibrate @@ -154,6 +156,7 @@ static CGSize _calculateShrinkedSizeForString(NSAttributedString **str, id font, #define SENSOR_DELAY_GAME 0.02 +#if !defined(CC_TARGET_OS_TVOS) @interface CCAccelerometerDispatcher : NSObject { cocos2d::Acceleration *_acceleration; @@ -246,15 +249,16 @@ static CCAccelerometerDispatcher* s_pAccelerometerDispatcher; case UIInterfaceOrientationPortrait: break; default: - NSAssert(false, @"unknow orientation"); + NSAssert(false, @"unknown orientation"); } cocos2d::EventAcceleration event(*_acceleration); - auto dispatcher = cocos2d::Director::DirectorInstance->getEventDispatcher(); + auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher(); dispatcher->dispatchEvent(&event); } - @end +#endif // !defined(CC_TARGET_OS_TVOS) + // @@ -284,16 +288,18 @@ int Device::getDPI() } - - void Device::setAccelerometerEnabled(bool isEnabled) { +#if !defined(CC_TARGET_OS_TVOS) [[CCAccelerometerDispatcher sharedAccelerometerDispatcher] setAccelerometerEnabled:isEnabled]; +#endif } void Device::setAccelerometerInterval(float interval) { +#if !defined(CC_TARGET_OS_TVOS) [[CCAccelerometerDispatcher sharedAccelerometerDispatcher] setAccelerometerInterval:interval]; +#endif } typedef struct @@ -381,6 +387,8 @@ static bool _initWithString(const char * text, cocos2d::Device::TextAlign align, CC_BREAK_IF(! font); NSString * str = [NSString stringWithUTF8String:text]; + CC_BREAK_IF(!str); + CGSize dimensions; dimensions.width = info->width; dimensions.height = info->height; @@ -396,7 +404,7 @@ static bool _initWithString(const char * text, cocos2d::Device::TextAlign align, blue:info->tintColorB alpha:info->tintColorA]; - //adjust text rect acoording to overflow + // adjust text rect according to overflow NSMutableDictionary* tokenAttributesDict = [NSMutableDictionary dictionaryWithObjectsAndKeys: foregroundColor,NSForegroundColorAttributeName, font, NSFontAttributeName, @@ -530,7 +538,7 @@ static bool _initWithString(const char * text, cocos2d::Device::TextAlign align, } -Data Device::getTextureDataForText(const std::string& text, const FontDefinition& textDefinition, TextAlign align, int &width, int &height, bool& hasPremultipliedAlpha) +Data Device::getTextureDataForText(const char * text, const FontDefinition& textDefinition, TextAlign align, int &width, int &height, bool& hasPremultipliedAlpha) { Data ret; @@ -554,7 +562,7 @@ Data Device::getTextureDataForText(const std::string& text, const FontDefinition info.tintColorB = textDefinition._fontFillColor.b / 255.0f; info.tintColorA = textDefinition._fontAlpha / 255.0f; - if (! _initWithString(text.c_str(), align, textDefinition._fontName.c_str(), textDefinition._fontSize, &info, textDefinition._enableWrap, textDefinition._overflow)) + if (! _initWithString(text, align, textDefinition._fontName.c_str(), textDefinition._fontSize, &info, textDefinition._enableWrap, textDefinition._overflow)) { break; } @@ -573,7 +581,7 @@ void Device::setKeepScreenOn(bool value) } /*! - @brief Only works on iOS devices that support vibration (such as iPhone). Shoud only be used for important alerts. Use risks rejection in iTunes Store. + @brief Only works on iOS devices that support vibration (such as iPhone). Should only be used for important alerts. Use risks rejection in iTunes Store. @param duration ignored for iOS */ void Device::vibrate(float duration) diff --git a/native/cocos/platform/ios/CCDirectorCaller-ios.mm b/native/cocos/platform/ios/CCDirectorCaller-ios.mm index ac270e6ff7..0f877300f2 100644 --- a/native/cocos/platform/ios/CCDirectorCaller-ios.mm +++ b/native/cocos/platform/ios/CCDirectorCaller-ios.mm @@ -26,13 +26,13 @@ #include "platform/CCPlatformConfig.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS -#import "CCDirectorCaller-ios.h" +#import "platform/ios/CCDirectorCaller-ios.h" #import #import #import "base/CCDirector.h" -#import "CCEAGLView-ios.h" +#import "platform/ios/CCEAGLView-ios.h" static id s_sharedDirectorCaller; @@ -82,6 +82,13 @@ static id s_sharedDirectorCaller; return self; } +-(void) dealloc +{ + [[NSNotificationCenter defaultCenter] removeObserver:self]; + [displayLink release]; + [super dealloc]; +} + - (void)appDidBecomeActive { isAppActive = YES; @@ -92,13 +99,6 @@ static id s_sharedDirectorCaller; isAppActive = NO; } --(void) dealloc -{ - [[NSNotificationCenter defaultCenter] removeObserver:self]; - [displayLink release]; - [super dealloc]; -} - -(void) startMainLoop { // Director::setAnimationInterval() is called, we should invalidate it first @@ -129,7 +129,7 @@ static id s_sharedDirectorCaller; -(void) doCaller: (id) sender { - auto director = cocos2d::Director::DirectorInstance; + cocos2d::Director* director = cocos2d::Director::getInstance(); if (isAppActive && director) { //引擎是在下一帧才做结束的清理,而runtime版本在下一帧时EAGLView已经从superview移除 if (!director->isPurgeDirectorInNextLoop() && director->getOpenGLView()) { diff --git a/native/cocos/platform/ios/CCEAGLView-ios.h b/native/cocos/platform/ios/CCEAGLView-ios.h index 0c3feb61d6..b2fbaabc02 100644 --- a/native/cocos/platform/ios/CCEAGLView-ios.h +++ b/native/cocos/platform/ios/CCEAGLView-ios.h @@ -71,7 +71,7 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. #import #import -#import "CCESRenderer-ios.h" +#import "platform/ios/CCESRenderer-ios.h" //CLASS INTERFACE: @@ -157,4 +157,3 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. @end #endif // CC_PLATFORM_IOS - diff --git a/native/cocos/platform/ios/CCEAGLView-ios.mm b/native/cocos/platform/ios/CCEAGLView-ios.mm index c2e22bc7ce..ea5790e803 100644 --- a/native/cocos/platform/ios/CCEAGLView-ios.mm +++ b/native/cocos/platform/ios/CCEAGLView-ios.mm @@ -64,16 +64,17 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. #include "platform/CCPlatformConfig.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS -#import "CCEAGLView-ios.h" +#import "platform/ios/CCEAGLView-ios.h" #import #import "base/CCDirector.h" +#import "deprecated/CCSet.h" #import "base/CCTouch.h" #import "base/CCIMEDispatcher.h" -#import "CCGLViewImpl-ios.h" -#import "CCES2Renderer-ios.h" -#import "OpenGL_Internal-ios.h" +#import "platform/ios/CCGLViewImpl-ios.h" +#import "platform/ios/CCES2Renderer-ios.h" +#import "platform/ios/OpenGL_Internal-ios.h" //CLASS IMPLEMENTATIONS: @@ -257,9 +258,9 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. // Avoid flicker. Issue #350 //[director performSelectorOnMainThread:@selector(drawScene) withObject:nil waitUntilDone:YES]; - if ([NSThread isMainThread] && cocos2d::Director::DirectorInstance) + if ([NSThread isMainThread]) { - cocos2d::Director::DirectorInstance->drawScene(); + cocos2d::Director::getInstance()->drawScene(); } } @@ -378,20 +379,14 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. } } } - - if (cocos2d::Director::DirectorInstance) { - auto glView = cocos2d::Director::DirectorInstance->getOpenGLView(); - if (glView) { - glView->setIMEKeyboardState(false); - } - } } // Pass the touches to the superview #pragma mark CCEAGLView - Touch Delegate - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { - if (cocos2d::Director::DirectorInstance == nullptr) { + cocos2d::Director *director = cocos2d::Director::getInstance(); + if (director == nullptr) { return; } @@ -412,7 +407,7 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. ++i; } - auto glview = cocos2d::Director::DirectorInstance->getOpenGLView(); + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); glview->handleTouchesBegin(i, (intptr_t*)ids, xs, ys); } @@ -439,7 +434,7 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. ++i; } - auto glview = cocos2d::Director::DirectorInstance->getOpenGLView(); + auto glview = director->getOpenGLView(); glview->handleTouchesMove(i, (intptr_t*)ids, xs, ys, fs, ms); } @@ -457,7 +452,7 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. ++i; } - auto glview = cocos2d::Director::DirectorInstance->getOpenGLView(); + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); glview->handleTouchesEnd(i, (intptr_t*)ids, xs, ys); } @@ -475,7 +470,7 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. ++i; } - auto glview = cocos2d::Director::DirectorInstance->getOpenGLView(); + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); glview->handleTouchesCancel(i, (intptr_t*)ids, xs, ys); } @@ -728,7 +723,8 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. - (void)onUIKeyboardNotification:(NSNotification *)notif; { - if(cocos2d::Director::DirectorInstance == nullptr) + cocos2d::Director *director = cocos2d::Director::getInstance(); + if(director == nullptr) return; NSString * type = notif.name; @@ -743,8 +739,14 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. double aniDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; CGSize viewSize = self.frame.size; - CGFloat tmp; +#if defined(CC_TARGET_OS_TVOS) + // statusBarOrientation not defined on tvOS, and also, orientation makes + // no sense on tvOS + begin.origin.y = viewSize.height - begin.origin.y - begin.size.height; + end.origin.y = viewSize.height - end.origin.y - end.size.height; +#else + CGFloat tmp; switch (getFixedOrientation([[UIApplication sharedApplication] statusBarOrientation])) { case UIInterfaceOrientationPortrait: @@ -786,8 +788,9 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. default: break; } +#endif - auto glview = cocos2d::Director::DirectorInstance->getOpenGLView(); + auto glview = director->getOpenGLView(); float scaleX = glview->getScaleX(); float scaleY = glview->getScaleY(); @@ -804,7 +807,7 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. end.size.height -= offestY; } - // Convert to desigin coordinate + // Convert to design coordinate begin = CGRectApplyAffineTransform(begin, CGAffineTransformScale(CGAffineTransformIdentity, 1.0f/scaleX, 1.0f/scaleY)); end = CGRectApplyAffineTransform(end, CGAffineTransformScale(CGAffineTransformIdentity, 1.0f/scaleX, 1.0f/scaleY)); @@ -831,7 +834,14 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. //CGSize screenSize = self.window.screen.bounds.size; dispatcher->dispatchKeyboardDidShow(notiInfo); caretRect_ = end; - caretRect_.origin.y = viewSize.height - (caretRect_.origin.y + caretRect_.size.height + [UIFont smallSystemFontSize]); + +#if defined(CC_TARGET_OS_TVOS) + // smallSystemFontSize not available on TVOS + int fontSize = 12; +#else + int fontSize = [UIFont smallSystemFontSize]; +#endif + caretRect_.origin.y = viewSize.height - (caretRect_.origin.y + caretRect_.size.height + fontSize); caretRect_.size.height = 0; isKeyboardShown_ = YES; } @@ -847,6 +857,7 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. } } +#if !defined(CC_TARGET_OS_TVOS) UIInterfaceOrientation getFixedOrientation(UIInterfaceOrientation statusBarOrientation) { if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) @@ -855,6 +866,7 @@ UIInterfaceOrientation getFixedOrientation(UIInterfaceOrientation statusBarOrien } return statusBarOrientation; } +#endif -(void) doAnimationWhenKeyboardMoveWithDuration:(float)duration distance:(float)dis { @@ -867,11 +879,14 @@ UIInterfaceOrientation getFixedOrientation(UIInterfaceOrientation statusBarOrien if (dis < 0.0f) dis = 0.0f; - auto glview = cocos2d::Director::DirectorInstance->getOpenGLView(); + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); dis *= glview->getScaleY(); dis /= self.contentScaleFactor; +#if defined(CC_TARGET_OS_TVOS) + self.frame = CGRectMake(originalRect_.origin.x, originalRect_.origin.y - dis, originalRect_.size.width, originalRect_.size.height); +#else switch (getFixedOrientation([[UIApplication sharedApplication] statusBarOrientation])) { case UIInterfaceOrientationPortrait: @@ -893,7 +908,8 @@ UIInterfaceOrientation getFixedOrientation(UIInterfaceOrientation statusBarOrien default: break; } - +#endif + [UIView commitAnimations]; } @@ -909,4 +925,3 @@ UIInterfaceOrientation getFixedOrientation(UIInterfaceOrientation statusBarOrien @end #endif // CC_PLATFORM_IOS - diff --git a/native/cocos/platform/ios/CCES2Renderer-ios.h b/native/cocos/platform/ios/CCES2Renderer-ios.h index 527af7cae3..b984f32cec 100644 --- a/native/cocos/platform/ios/CCES2Renderer-ios.h +++ b/native/cocos/platform/ios/CCES2Renderer-ios.h @@ -31,12 +31,12 @@ #include "platform/CCPlatformConfig.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS -#import "CCESRenderer-ios.h" +#import "platform/ios/CCESRenderer-ios.h" #import #import -#import "CCPlatformMacros.h" +#import "platform/CCPlatformMacros.h" @interface CCES2Renderer : NSObject { @@ -83,4 +83,3 @@ #endif // CC_PLATFORM_IOS - diff --git a/native/cocos/platform/ios/CCES2Renderer-ios.m b/native/cocos/platform/ios/CCES2Renderer-ios.m index d9c6a4d1dc..a3788d3412 100644 --- a/native/cocos/platform/ios/CCES2Renderer-ios.m +++ b/native/cocos/platform/ios/CCES2Renderer-ios.m @@ -32,9 +32,9 @@ #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS -#import "CCES2Renderer-ios.h" +#import "platform/ios/CCES2Renderer-ios.h" #import "platform/CCPlatformMacros.h" -#import "OpenGL_Internal-ios.h" +#import "platform/ios/OpenGL_Internal-ios.h" #if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0 #define NSLog(...) do {} while (0) @@ -256,4 +256,3 @@ @end #endif // CC_PLATFORM_IOS - diff --git a/native/cocos/platform/ios/CCGLViewImpl-ios.mm b/native/cocos/platform/ios/CCGLViewImpl-ios.mm index da34c80782..74b49759f7 100644 --- a/native/cocos/platform/ios/CCGLViewImpl-ios.mm +++ b/native/cocos/platform/ios/CCGLViewImpl-ios.mm @@ -28,9 +28,10 @@ #import -#include "CCEAGLView-ios.h" -#include "CCDirectorCaller-ios.h" -#include "CCGLViewImpl-ios.h" +#include "platform/ios/CCEAGLView-ios.h" +#include "platform/ios/CCDirectorCaller-ios.h" +#include "platform/ios/CCGLViewImpl-ios.h" +#include "deprecated/CCSet.h" #include "base/CCTouch.h" NS_CC_BEGIN @@ -141,7 +142,10 @@ bool GLViewImpl::initWithRect(const std::string& viewName, const Rect& rect, flo multiSampling: NO numberOfSamples: 0]; + // Not available on tvOS +#if !defined(CC_TARGET_OS_TVOS) [eaglview setMultipleTouchEnabled:YES]; +#endif _screenSize.width = _designResolutionSize.width = [eaglview getWidth]; _screenSize.height = _designResolutionSize.height = [eaglview getHeight]; @@ -195,10 +199,11 @@ void GLViewImpl::end() { [CCDirectorCaller destroy]; - //runtime版本由宿主(eg:QQ浏览器)负责移除EAGLView - //CCEAGLView *eaglview = (CCEAGLView*) _eaglview; - //[eaglview removeFromSuperview]; + // destroy EAGLView + CCEAGLView *eaglview = (CCEAGLView*) _eaglview; + [eaglview removeFromSuperview]; + //[eaglview release]; release(); } @@ -225,4 +230,3 @@ void GLViewImpl::setIMEKeyboardState(bool open) NS_CC_END #endif // CC_PLATFOR_IOS - diff --git a/native/cocos/platform/mac/CCApplication-mac.h b/native/cocos/platform/mac/CCApplication-mac.h index da0b82a65f..b44b99754d 100644 --- a/native/cocos/platform/mac/CCApplication-mac.h +++ b/native/cocos/platform/mac/CCApplication-mac.h @@ -52,8 +52,8 @@ public: @brief Callback by Director for limit FPS. @param interval The time, which expressed in second in second, between current frame and next. */ - virtual void setAnimationInterval(float interval); - + virtual void setAnimationInterval(float interval) override; + /** @brief Get status bar rectangle in GLView window. */ @@ -77,30 +77,35 @@ public: @brief Get current language config @return Current language config */ - virtual LanguageType getCurrentLanguage(); - + virtual LanguageType getCurrentLanguage() override; + /** @brief Get current language iso 639-1 code @return Current language iso 639-1 code */ - virtual const char * getCurrentLanguageCode(); - + virtual const char * getCurrentLanguageCode() override; + /** @brief Get target platform */ - virtual Platform getTargetPlatform(); + virtual Platform getTargetPlatform() override; + + /** + @brief Get application version. + */ + virtual std::string getVersion() override; /** @brief Open url in default browser @param String with url to open. @return true if the resource located by the URL was successfully opened; otherwise false. */ - virtual bool openURL(const std::string &url); + virtual bool openURL(const std::string &url) override; void setStartupScriptFilename(const std::string& startupScriptFile); - - const std::string& getStartupScriptFilename(); - + + const std::string& getStartupScriptFilename(void); + protected: static Application * sm_pSharedApplication; @@ -114,4 +119,3 @@ NS_CC_END #endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC #endif // end of __CC_APPLICATION_MAC_H__; - diff --git a/native/cocos/platform/mac/CCApplication-mac.mm b/native/cocos/platform/mac/CCApplication-mac.mm index c3732e7975..88721429c9 100644 --- a/native/cocos/platform/mac/CCApplication-mac.mm +++ b/native/cocos/platform/mac/CCApplication-mac.mm @@ -46,7 +46,7 @@ static long getCurrentMillSecond() return lLastTime; } -Application* Application::sm_pSharedApplication = 0; +Application* Application::sm_pSharedApplication = nullptr; Application::Application() : _animationInterval(1.0f/60.0f*1000.0f) @@ -118,6 +118,14 @@ Application::Platform Application::getTargetPlatform() return Platform::OS_MAC; } +std::string Application::getVersion() { + NSString* version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]; + if (version) { + return [version UTF8String]; + } + return ""; +} + ///////////////////////////////////////////////////////////////////////////////////////////////// // static member function ////////////////////////////////////////////////////////////////////////////////////////////////// @@ -193,13 +201,31 @@ bool Application::openURL(const std::string &url) return [[NSWorkspace sharedWorkspace] openURL:nsUrl]; } +void Application::setResourceRootPath(const std::string& rootResDir) +{ + _resourceRootPath = rootResDir; + if (_resourceRootPath[_resourceRootPath.length() - 1] != '/') + { + _resourceRootPath += '/'; + } + FileUtils* pFileUtils = FileUtils::getInstance(); + std::vector searchPaths = pFileUtils->getSearchPaths(); + searchPaths.insert(searchPaths.begin(), _resourceRootPath); + pFileUtils->setSearchPaths(searchPaths); +} + +const std::string& Application::getResourceRootPath(void) +{ + return _resourceRootPath; +} + void Application::setStartupScriptFilename(const std::string& startupScriptFile) { _startupScriptFilename = startupScriptFile; std::replace(_startupScriptFilename.begin(), _startupScriptFilename.end(), '\\', '/'); } -const std::string& Application::getStartupScriptFilename() +const std::string& Application::getStartupScriptFilename(void) { return _startupScriptFilename; } @@ -207,4 +233,3 @@ const std::string& Application::getStartupScriptFilename() NS_CC_END #endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC - diff --git a/native/cocos/platform/mac/CCCommon-mac.mm b/native/cocos/platform/mac/CCCommon-mac.mm index 30d97333ae..d3dd36004e 100644 --- a/native/cocos/platform/mac/CCCommon-mac.mm +++ b/native/cocos/platform/mac/CCCommon-mac.mm @@ -53,7 +53,7 @@ void MessageBox(const char * msg, const char * title) [alert setInformativeText:tmpTitle]; [alert setAlertStyle:NSWarningAlertStyle]; - auto glview = Director::DirectorInstance->getOpenGLView(); + auto glview = Director::getInstance()->getOpenGLView(); id window = glview->getCocoaWindow(); [alert beginSheetModalForWindow:window modalDelegate:[window delegate] @@ -64,4 +64,3 @@ void MessageBox(const char * msg, const char * title) NS_CC_END #endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC - diff --git a/native/cocos/platform/mac/CCDevice-mac.mm b/native/cocos/platform/mac/CCDevice-mac.mm index 6ac18241eb..c57ffe7e0b 100644 --- a/native/cocos/platform/mac/CCDevice-mac.mm +++ b/native/cocos/platform/mac/CCDevice-mac.mm @@ -133,10 +133,16 @@ static NSSize _calculateRealSizeForString(NSAttributedString **str, id font, NSS NSMutableAttributedString *mutableString = [[*str mutableCopy] autorelease]; *str = __attributedStringWithFontSize(mutableString, fontSize); - CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( CGFLOAT_MAX, CGFLOAT_MAX) - options:NSStringDrawingUsesLineFragmentOrigin - context:nil].size; - +#ifdef __MAC_10_11 + #if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_11 + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size; + #else + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin].size; + #endif +#else + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin].size; +#endif + if(fitSize.width == 0 || fitSize.height == 0) continue; actualSize.size = fitSize; @@ -159,10 +165,16 @@ static NSSize _calculateRealSizeForString(NSAttributedString **str, id font, NSS NSMutableAttributedString *mutableString = [[*str mutableCopy] autorelease]; *str = __attributedStringWithFontSize(mutableString, fontSize); - - CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( constrainSize.width, CGFLOAT_MAX) - options:NSStringDrawingUsesLineFragmentOrigin - context:nil].size; + +#ifdef __MAC_10_11 + #if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_11 + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( constrainSize.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size; + #else + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( constrainSize.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin].size; + #endif +#else + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( constrainSize.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin].size; +#endif if(fitSize.width == 0 || fitSize.height == 0) continue; actualSize.size = fitSize; @@ -223,7 +235,6 @@ static CGFloat _calculateTextDrawStartHeight(cocos2d::Device::TextAlign align, C return startH; } - static bool _initWithString(const char * text, Device::TextAlign align, const char * fontName, int size, tImageInfo* info, const Color3B* fontColor, int fontAlpha, bool enableWrap, int overflow) { bool ret = false; @@ -233,6 +244,7 @@ static bool _initWithString(const char * text, Device::TextAlign align, const ch do { NSString * string = [NSString stringWithUTF8String:text]; + CC_BREAK_IF(!string); id font = _createSystemFont(fontName, size); CC_BREAK_IF(!font); @@ -326,22 +338,20 @@ static bool _initWithString(const char * text, Device::TextAlign align, const ch return ret; } -Data Device::getTextureDataForText(const std::string& text, const FontDefinition& textDefinition, TextAlign align, int &width, int &height, bool& hasPremultipliedAlpha) +Data Device::getTextureDataForText(const char * text, const FontDefinition& textDefinition, TextAlign align, int &width, int &height, bool& hasPremultipliedAlpha) { Data ret; do { tImageInfo info = {0}; info.width = textDefinition._dimensions.width; info.height = textDefinition._dimensions.height; - - if (! _initWithString(text.c_str(), align, textDefinition._fontName.c_str(), - textDefinition._fontSize, &info, &textDefinition._fontFillColor, - textDefinition._fontAlpha, textDefinition._enableWrap, textDefinition._overflow)) + + if (! _initWithString(text, align, textDefinition._fontName.c_str(), textDefinition._fontSize, &info, &textDefinition._fontFillColor, textDefinition._fontAlpha, textDefinition._enableWrap, textDefinition._overflow)) { break; } - height = info.height; - width = info.width; + height = (short)info.height; + width = (short)info.width; ret.fastSet(info.data,width * height * 4); hasPremultipliedAlpha = true; } while (0); @@ -362,4 +372,3 @@ void Device::vibrate(float duration) NS_CC_END #endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC - diff --git a/native/cocos/platform/win32/CCApplication-win32.cpp b/native/cocos/platform/win32/CCApplication-win32.cpp index 3db349d388..98adb6f5a2 100644 --- a/native/cocos/platform/win32/CCApplication-win32.cpp +++ b/native/cocos/platform/win32/CCApplication-win32.cpp @@ -31,6 +31,7 @@ THE SOFTWARE. #include #include "platform/CCFileUtils.h" #include +#include /** @brief This function change the PVRFrame show/hide setting in register. @param bEnable If true show the PVRFrame window, otherwise hide. @@ -40,7 +41,7 @@ static void PVRFrameEnableControlWindow(bool bEnable); NS_CC_BEGIN // sharedApplication pointer -Application * Application::sm_pSharedApplication = 0; +Application * Application::sm_pSharedApplication = nullptr; Application::Application() : _instance(nullptr) @@ -220,6 +221,47 @@ Application::Platform Application::getTargetPlatform() return Platform::OS_WINDOWS; } +std::string Application::getVersion() +{ + char verString[256] = { 0 }; + TCHAR szVersionFile[MAX_PATH]; + GetModuleFileName(NULL, szVersionFile, MAX_PATH); + DWORD verHandle = NULL; + UINT size = 0; + LPBYTE lpBuffer = NULL; + DWORD verSize = GetFileVersionInfoSize(szVersionFile, &verHandle); + + if (verSize != NULL) + { + LPSTR verData = new char[verSize]; + + if (GetFileVersionInfo(szVersionFile, verHandle, verSize, verData)) + { + if (VerQueryValue(verData, L"\\", (VOID FAR* FAR*)&lpBuffer, &size)) + { + if (size) + { + VS_FIXEDFILEINFO *verInfo = (VS_FIXEDFILEINFO *)lpBuffer; + if (verInfo->dwSignature == 0xfeef04bd) + { + + // Doesn't matter if you are on 32 bit or 64 bit, + // DWORD is always 32 bits, so first two revision numbers + // come from dwFileVersionMS, last two come from dwFileVersionLS + sprintf(verString, "%d.%d.%d.%d", (verInfo->dwFileVersionMS >> 16) & 0xffff, + (verInfo->dwFileVersionMS >> 0) & 0xffff, + (verInfo->dwFileVersionLS >> 16) & 0xffff, + (verInfo->dwFileVersionLS >> 0) & 0xffff + ); + } + } + } + } + delete[] verData; + } + return verString; +} + bool Application::openURL(const std::string &url) { WCHAR *temp = new WCHAR[url.size() + 1]; @@ -229,6 +271,25 @@ bool Application::openURL(const std::string &url) return (size_t)r>32; } +void Application::setResourceRootPath(const std::string& rootResDir) +{ + _resourceRootPath = rootResDir; + std::replace(_resourceRootPath.begin(), _resourceRootPath.end(), '\\', '/'); + if (_resourceRootPath[_resourceRootPath.length() - 1] != '/') + { + _resourceRootPath += '/'; + } + FileUtils* pFileUtils = FileUtils::getInstance(); + std::vector searchPaths = pFileUtils->getSearchPaths(); + searchPaths.insert(searchPaths.begin(), _resourceRootPath); + pFileUtils->setSearchPaths(searchPaths); +} + +const std::string& Application::getResourceRootPath(void) +{ + return _resourceRootPath; +} + void Application::setStartupScriptFilename(const std::string& startupScriptFile) { _startupScriptFilename = startupScriptFile; @@ -275,4 +336,3 @@ static void PVRFrameEnableControlWindow(bool bEnable) } #endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 - diff --git a/native/cocos/platform/win32/CCApplication-win32.h b/native/cocos/platform/win32/CCApplication-win32.h index 07040a65c2..c7b1bd9d81 100644 --- a/native/cocos/platform/win32/CCApplication-win32.h +++ b/native/cocos/platform/win32/CCApplication-win32.h @@ -73,6 +73,11 @@ public: @brief Get target platform */ virtual Platform getTargetPlatform(); + + /** + @brief Get application version + */ + virtual std::string getVersion() override; /** @brief Open url in default browser @@ -92,6 +97,7 @@ protected: HINSTANCE _instance; HACCEL _accelTable; LARGE_INTEGER _animationInterval; + std::string _resourceRootPath; std::string _startupScriptFilename; static Application * sm_pSharedApplication; @@ -102,4 +108,3 @@ NS_CC_END #endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 #endif // __CC_APPLICATION_WIN32_H__ - diff --git a/native/cocos/platform/win32/CCCommon-win32.cpp b/native/cocos/platform/win32/CCCommon-win32.cpp index 70d97f2655..098219abf7 100644 --- a/native/cocos/platform/win32/CCCommon-win32.cpp +++ b/native/cocos/platform/win32/CCCommon-win32.cpp @@ -28,6 +28,7 @@ THE SOFTWARE. #include "platform/CCCommon.h" #include "platform/CCStdC.h" +#include "platform/win32/CCUtils-win32.h" NS_CC_BEGIN @@ -35,30 +36,19 @@ NS_CC_BEGIN void MessageBox(const char * pszMsg, const char * pszTitle) { - MessageBoxA(nullptr, pszMsg, pszTitle, MB_OK); + std::wstring wsMsg = cocos2d::StringUtf8ToWideChar(pszMsg); + std::wstring wsTitle = cocos2d::StringUtf8ToWideChar(pszTitle); + MessageBoxW(nullptr, wsMsg.c_str(), wsTitle.c_str(), MB_OK); } void LuaLog(const char *pszMsg) { - int bufflen = MultiByteToWideChar(CP_UTF8, 0, pszMsg, -1, nullptr, 0); - WCHAR* widebuff = new WCHAR[bufflen + 1]; - memset(widebuff, 0, sizeof(WCHAR) * (bufflen + 1)); - MultiByteToWideChar(CP_UTF8, 0, pszMsg, -1, widebuff, bufflen); - - OutputDebugStringW(widebuff); + OutputDebugStringW(cocos2d::StringUtf8ToWideChar(pszMsg).c_str()); OutputDebugStringA("\n"); - bufflen = WideCharToMultiByte(CP_ACP, 0, widebuff, -1, nullptr, 0, nullptr, nullptr); - char* buff = new char[bufflen + 1]; - memset(buff, 0, sizeof(char) * (bufflen + 1)); - WideCharToMultiByte(CP_ACP, 0, widebuff, -1, buff, bufflen, nullptr, nullptr); - puts(buff); - - delete[] widebuff; - delete[] buff; + puts(UTF8StringToMultiByte(pszMsg).c_str()); } NS_CC_END #endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 - diff --git a/native/cocos/platform/win32/CCDevice-win32.cpp b/native/cocos/platform/win32/CCDevice-win32.cpp index 6b938365f3..9ce9d5ffb7 100644 --- a/native/cocos/platform/win32/CCDevice-win32.cpp +++ b/native/cocos/platform/win32/CCDevice-win32.cpp @@ -99,7 +99,7 @@ public: } - bool setFont(const char * pFontName = nullptr, int nSize = 0) + bool setFont(const char * pFontName = "", int nSize = 0) { bool bRet = false; do @@ -110,7 +110,7 @@ public: LOGFONTA tNewFont = {0}; LOGFONTA tOldFont = {0}; GetObjectA(hDefFont, sizeof(tNewFont), &tNewFont); - if (fontName.c_str()) + if (!fontName.empty()) { // create font from ttf file if (FileUtils::getInstance()->getFileExtension(fontName) == ".ttf") @@ -243,7 +243,7 @@ public: int drawText(const char * pszText, SIZE& tSize, Device::TextAlign eAlign) { int nRet = 0; - wchar_t * pwszBuffer = 0; + wchar_t * pwszBuffer = nullptr; wchar_t* fixedText = nullptr; do { @@ -431,7 +431,7 @@ static BitmapDC& sharedBitmapDC() return s_BmpDC; } -Data Device::getTextureDataForText(const std::string& text, const FontDefinition& textDefinition, TextAlign align, int &width, int &height, bool& hasPremultipliedAlpha) +Data Device::getTextureDataForText(const char * text, const FontDefinition& textDefinition, TextAlign align, int &width, int &height, bool& hasPremultipliedAlpha) { Data ret; do @@ -446,7 +446,7 @@ Data Device::getTextureDataForText(const std::string& text, const FontDefinition // draw text // does changing to SIZE here affects the font size by rounding from float? SIZE size = {(LONG) textDefinition._dimensions.width,(LONG) textDefinition._dimensions.height}; - CC_BREAK_IF(! dc.drawText(text.c_str(), size, align)); + CC_BREAK_IF(! dc.drawText(text, size, align)); int dataLen = size.cx * size.cy * 4; unsigned char* dataBuf = (unsigned char*)malloc(sizeof(unsigned char) * dataLen); @@ -504,4 +504,3 @@ void Device::vibrate(float duration) NS_CC_END #endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 - diff --git a/native/cocos/platform/win32/CCFileUtils-win32.cpp b/native/cocos/platform/win32/CCFileUtils-win32.cpp index c4c376ded1..72b8769ff2 100644 --- a/native/cocos/platform/win32/CCFileUtils-win32.cpp +++ b/native/cocos/platform/win32/CCFileUtils-win32.cpp @@ -26,11 +26,13 @@ THE SOFTWARE. #include "platform/CCPlatformConfig.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 -#include "CCFileUtils-win32.h" +#include "platform/win32/CCFileUtils-win32.h" +#include "platform/win32/CCUtils-win32.h" #include "platform/CCCommon.h" #include #include #include +#include using namespace std; @@ -57,81 +59,6 @@ static inline std::string convertPathFormatToUnixStyle(const std::string& path) return ret; } -static std::wstring StringUtf8ToWideChar(const std::string& strUtf8) -{ - std::wstring ret; - if (!strUtf8.empty()) - { - int nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, nullptr, 0); - if (nNum) - { - WCHAR* wideCharString = new WCHAR[nNum + 1]; - wideCharString[0] = 0; - - nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, wideCharString, nNum + 1); - - ret = wideCharString; - delete[] wideCharString; - } - else - { - CCLOG("Wrong convert to WideChar code:0x%x", GetLastError()); - } - } - return ret; -} - -static std::string StringWideCharToUtf8(const std::wstring& strWideChar) -{ - std::string ret; - if (!strWideChar.empty()) - { - int nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE); - if (nNum) - { - char* utf8String = new char[nNum + 1]; - utf8String[0] = 0; - - nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, utf8String, nNum + 1, nullptr, FALSE); - - ret = utf8String; - delete[] utf8String; - } - else - { - CCLOG("Wrong convert to Utf8 code:0x%x", GetLastError()); - } - } - - return ret; -} - -static std::string UTF8StringToMultiByte(const std::string& strUtf8) -{ - std::string ret; - if (!strUtf8.empty()) - { - std::wstring strWideChar = StringUtf8ToWideChar(strUtf8); - int nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE); - if (nNum) - { - char* ansiString = new char[nNum + 1]; - ansiString[0] = 0; - - nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, ansiString, nNum + 1, nullptr, FALSE); - - ret = ansiString; - delete[] ansiString; - } - else - { - CCLOG("Wrong convert to Ansi code:0x%x", GetLastError()); - } - } - - return ret; -} - static void _checkPath() { if (s_resourcePath.empty()) @@ -235,180 +162,44 @@ bool FileUtilsWin32::isAbsolutePath(const std::string& strPath) const return false; } -// Because windows is case insensitive, so we should check the file names. -static bool checkFileName(const std::string& fullPath, const std::string& filename) -{ - std::string tmpPath=convertPathFormatToUnixStyle(fullPath); - size_t len = tmpPath.length(); - size_t nl = filename.length(); - std::string realName; - while (tmpPath.length() >= len - nl && tmpPath.length()>2) - { - //CCLOG("%s", tmpPath.c_str()); - WIN32_FIND_DATAA data; - HANDLE h = FindFirstFileA(tmpPath.c_str(), &data); - FindClose(h); - if (h != INVALID_HANDLE_VALUE) - { - int fl = strlen(data.cFileName); - if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) - { - realName = "/" + realName; - } - realName = data.cFileName + realName; - if (0 != strcmp(&tmpPath.c_str()[tmpPath.length() - fl], data.cFileName)) - { - std::string msg = "File path error: \""; - msg.append(filename).append("\" the real name is: ").append(realName); - - CCLOG("%s", msg.c_str()); - return false; - } - } - else - { - break; - } - - do - { - tmpPath = tmpPath.substr(0, tmpPath.rfind("/")); - } while (tmpPath.back() == '.'); - } - return true; -} - -static Data getData(const std::string& filename, bool forString) +FileUtils::Status FileUtilsWin32::getContents(const std::string& filename, ResizableBuffer* buffer) { if (filename.empty()) + return FileUtils::Status::NotExists; + + // read the file from hardware + std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename); + + HANDLE fileHandle = ::CreateFile(StringUtf8ToWideChar(fullPath).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr); + if (fileHandle == INVALID_HANDLE_VALUE) + return FileUtils::Status::OpenFailed; + + DWORD hi; + auto size = ::GetFileSize(fileHandle, &hi); + if (hi > 0) + { + ::CloseHandle(fileHandle); + return FileUtils::Status::TooLarge; + } + // don't read file content if it is empty + if (size == 0) { - return Data::Null; - } - - unsigned char *buffer = nullptr; - - size_t size = 0; - do - { - // read the file from hardware - std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename); - - // check if the filename uses correct case characters - checkFileName(fullPath, filename); - - HANDLE fileHandle = ::CreateFile(StringUtf8ToWideChar(fullPath).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr); - CC_BREAK_IF(fileHandle == INVALID_HANDLE_VALUE); - - size = ::GetFileSize(fileHandle, nullptr); - - if (forString) - { - buffer = (unsigned char*) malloc(size + 1); - buffer[size] = '\0'; - } - else - { - buffer = (unsigned char*) malloc(size); - } - DWORD sizeRead = 0; - BOOL successed = FALSE; - successed = ::ReadFile(fileHandle, buffer, size, &sizeRead, nullptr); ::CloseHandle(fileHandle); - - if (!successed) - { - // should determine buffer value, or it will cause memory leak - if (buffer) - { - free(buffer); - buffer = nullptr; - } - } - } while (0); - - Data ret; - - if (buffer == nullptr || size == 0) - { - std::string msg = "Get data from file("; - // Gets error code. - DWORD errorCode = ::GetLastError(); - char errorCodeBuffer[20] = {0}; - snprintf(errorCodeBuffer, sizeof(errorCodeBuffer), "%d", errorCode); - - msg = msg + filename + ") failed, error code is " + errorCodeBuffer; - CCLOG("%s", msg.c_str()); - - if (buffer) - free(buffer); - } - else - { - ret.fastSet(buffer, size); - } - return ret; -} - -std::string FileUtilsWin32::getStringFromFile(const std::string& filename) -{ - Data data = getData(filename, true); - if (data.isNull()) - { - return ""; + return FileUtils::Status::OK; } - std::string ret((const char*)data.getBytes()); - return ret; -} + buffer->resize(size); + DWORD sizeRead = 0; + BOOL successed = ::ReadFile(fileHandle, buffer->buffer(), size, &sizeRead, nullptr); + ::CloseHandle(fileHandle); -Data FileUtilsWin32::getDataFromFile(const std::string& filename) -{ - return getData(filename, false); -} - -unsigned char* FileUtilsWin32::getFileData(const std::string& filename, const char* mode, ssize_t* size) -{ - unsigned char * pBuffer = nullptr; - *size = 0; - do - { - // read the file from hardware - std::string fullPath = fullPathForFilename(filename); - - // check if the filename uses correct case characters - checkFileName(fullPath, filename); - - HANDLE fileHandle = ::CreateFile(StringUtf8ToWideChar(fullPath).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr); - CC_BREAK_IF(fileHandle == INVALID_HANDLE_VALUE); - - *size = ::GetFileSize(fileHandle, nullptr); - - pBuffer = (unsigned char*) malloc(*size); - DWORD sizeRead = 0; - BOOL successed = FALSE; - successed = ::ReadFile(fileHandle, pBuffer, *size, &sizeRead, nullptr); - ::CloseHandle(fileHandle); - - if (!successed) - { - free(pBuffer); - pBuffer = nullptr; - } - } while (0); - - if (! pBuffer) - { - std::string msg = "Get data from file("; - // Gets error code. - DWORD errorCode = ::GetLastError(); - char errorCodeBuffer[20] = {0}; - snprintf(errorCodeBuffer, sizeof(errorCodeBuffer), "%d", errorCode); - - msg = msg + filename + ") failed, error code is " + errorCodeBuffer; - CCLOG("%s", msg.c_str()); + if (!successed) { + CCLOG("Get data from file(%s) failed, error code is %s", filename.data(), std::to_string(::GetLastError()).data()); + buffer->resize(sizeRead); + return FileUtils::Status::ReadFailed; } - return pBuffer; + return FileUtils::Status::OK; } std::string FileUtilsWin32::getPathForFilename(const std::string& filename, const std::string& resolutionDirectory, const std::string& searchPath) const @@ -636,4 +427,3 @@ bool FileUtilsWin32::removeDirectory(const std::string& dirPath) NS_CC_END #endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 - diff --git a/native/cocos/platform/win32/CCFileUtils-win32.h b/native/cocos/platform/win32/CCFileUtils-win32.h index e933a9cbbc..c84f11b914 100644 --- a/native/cocos/platform/win32/CCFileUtils-win32.h +++ b/native/cocos/platform/win32/CCFileUtils-win32.h @@ -107,27 +107,8 @@ protected: */ virtual bool removeDirectory(const std::string& dirPath) override; - /** - * Gets resource file data - * - * @param[in] filename The resource file name which contains the path. - * @param[in] mode The read mode of the file. - * @param[out] size If the file read operation succeeds, it will be the data size, otherwise 0. - * @return Upon success, a pointer to the data is returned, otherwise NULL. - * @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned. - */ - CC_DEPRECATED_ATTRIBUTE virtual unsigned char* getFileData(const std::string& filename, const char* mode, ssize_t * size) override; - /** - * Gets string from a file. - */ - virtual std::string getStringFromFile(const std::string& filename) override; - - /** - * Creates binary data from a file. - * @return A data object. - */ - virtual Data getDataFromFile(const std::string& filename) override; + virtual FileUtils::Status getContents(const std::string& filename, ResizableBuffer* buffer) override; /** * Gets full path for filename, resolution directory and search path. @@ -160,4 +141,3 @@ NS_CC_END #endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 #endif // __CC_FILEUTILS_WIN32_H__ - diff --git a/native/cocos/platform/win32/CCGL-win32.h b/native/cocos/platform/win32/CCGL-win32.h index b7942894a7..c064f1ab65 100644 --- a/native/cocos/platform/win32/CCGL-win32.h +++ b/native/cocos/platform/win32/CCGL-win32.h @@ -36,4 +36,3 @@ THE SOFTWARE. #endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 #endif // __CCGL_H__ - diff --git a/native/cocos/platform/win32/CCStdC-win32.h b/native/cocos/platform/win32/CCStdC-win32.h index 48e62188c0..5019be708e 100644 --- a/native/cocos/platform/win32/CCStdC-win32.h +++ b/native/cocos/platform/win32/CCStdC-win32.h @@ -89,7 +89,7 @@ typedef SSIZE_T ssize_t; #if _MSC_VER >= 1600 || defined(__MINGW32__) #include #else - #include "./compat/stdint.h" + #include "platform/win32/compat/stdint.h" #endif #define _WINSOCKAPI_ diff --git a/native/cocos/platform/win32/CCUtils-win32.cpp b/native/cocos/platform/win32/CCUtils-win32.cpp new file mode 100644 index 0000000000..9ee289f6d1 --- /dev/null +++ b/native/cocos/platform/win32/CCUtils-win32.cpp @@ -0,0 +1,108 @@ +/**************************************************************************** +Copyright (c) 2010-2012 cocos2d-x.org +Copyright (c) 2013-2016 Chukong Technologies Inc. + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ +#include "base/ccMacros.h" +#include "platform/CCPlatformMacros.h" +#include "platform/win32/CCUtils-win32.h" + +#include + +NS_CC_BEGIN + +std::wstring StringUtf8ToWideChar(const std::string& strUtf8) +{ + std::wstring ret; + if (!strUtf8.empty()) + { + int nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, nullptr, 0); + if (nNum) + { + WCHAR* wideCharString = new WCHAR[nNum + 1]; + wideCharString[0] = 0; + + nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, wideCharString, nNum + 1); + + ret = wideCharString; + delete[] wideCharString; + } + else + { + CCLOG("Wrong convert to WideChar code:0x%x", GetLastError()); + } + } + return ret; +} + +std::string StringWideCharToUtf8(const std::wstring& strWideChar) +{ + std::string ret; + if (!strWideChar.empty()) + { + int nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE); + if (nNum) + { + char* utf8String = new char[nNum + 1]; + utf8String[0] = 0; + + nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, utf8String, nNum + 1, nullptr, FALSE); + + ret = utf8String; + delete[] utf8String; + } + else + { + CCLOG("Wrong convert to Utf8 code:0x%x", GetLastError()); + } + } + + return ret; +} + +std::string UTF8StringToMultiByte(const std::string& strUtf8) +{ + std::string ret; + if (!strUtf8.empty()) + { + std::wstring strWideChar = StringUtf8ToWideChar(strUtf8); + int nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE); + if (nNum) + { + char* ansiString = new char[nNum + 1]; + ansiString[0] = 0; + + nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, ansiString, nNum + 1, nullptr, FALSE); + + ret = ansiString; + delete[] ansiString; + } + else + { + CCLOG("Wrong convert to Ansi code:0x%x", GetLastError()); + } + } + + return ret; +} + +NS_CC_END diff --git a/native/cocos/platform/win32/CCUtils-win32.h b/native/cocos/platform/win32/CCUtils-win32.h new file mode 100644 index 0000000000..995f4aa63d --- /dev/null +++ b/native/cocos/platform/win32/CCUtils-win32.h @@ -0,0 +1,41 @@ +/**************************************************************************** +Copyright (c) 2010-2012 cocos2d-x.org +Copyright (c) 2013-2016 Chukong Technologies Inc. + +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. +****************************************************************************/ + +#ifndef __CC_UTILS_WIN32_H__ +#define __CC_UTILS_WIN32_H__ + +#include "platform/CCPlatformMacros.h" + +#include + +NS_CC_BEGIN + +std::wstring CC_DLL StringUtf8ToWideChar(const std::string& strUtf8); +std::string CC_DLL StringWideCharToUtf8(const std::wstring& strWideChar); +std::string CC_DLL UTF8StringToMultiByte(const std::string& strUtf8); + +NS_CC_END + +#endif // __CC_UTILS_WIN32_H__ diff --git a/native/cocos/platform/win32/compat/stdint.h b/native/cocos/platform/win32/compat/stdint.h index 5922111e57..14276eba8b 100644 --- a/native/cocos/platform/win32/compat/stdint.h +++ b/native/cocos/platform/win32/compat/stdint.h @@ -32,7 +32,7 @@ #ifndef _MSC_STDINT_H_ // [ #define _MSC_STDINT_H_ -#include "CCPlatformConfig.h" +#include "platform/CCPlatformConfig.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 #ifndef _MSC_VER // [ @@ -249,4 +249,3 @@ typedef uint64_t uintmax_t; #endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 #endif // _MSC_STDINT_H_ ] - diff --git a/native/cocos/platform/win32/inet_pton_mingw.cpp b/native/cocos/platform/win32/inet_pton_mingw.cpp index ab5c345bd5..5c51fd3468 100644 --- a/native/cocos/platform/win32/inet_pton_mingw.cpp +++ b/native/cocos/platform/win32/inet_pton_mingw.cpp @@ -30,7 +30,7 @@ #define ERRNO ((int)GetLastError()) #define SET_ERRNO(x) (SetLastError((DWORD)(x))) -#include "inet_pton_mingw.h" +#include "platform/win32/inet_pton_mingw.h" #define ENABLE_IPV6 @@ -234,4 +234,3 @@ inet_pton6(const char *src, unsigned char *dst) #endif /* ENABLE_IPV6 */ #endif /* HAVE_INET_PTON */ -