diff --git a/cocos2dx/Android.mk b/cocos2dx/Android.mk index 54a2beb601..e2f98ff7d4 100644 --- a/cocos2dx/Android.mk +++ b/cocos2dx/Android.mk @@ -76,13 +76,14 @@ particle_nodes/CCParticleBatchNode.cpp \ particle_nodes/CCParticleSystemQuad.cpp \ platform/CCSAXParser.cpp \ platform/CCThread.cpp \ +platform/CCFileUtils.cpp \ platform/platform.cpp \ platform/CCEGLViewProtocol.cpp \ platform/android/CCEGLView.cpp \ platform/android/CCAccelerometer.cpp \ platform/android/CCApplication.cpp \ platform/android/CCCommon.cpp \ -platform/android/CCFileUtils.cpp \ +platform/android/CCFileUtilsAndroid.cpp \ platform/android/CCImage.cpp \ platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp \ platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp \ diff --git a/cocos2dx/cocoa/CCArray.cpp b/cocos2dx/cocoa/CCArray.cpp index 226b364d29..7da453e05b 100644 --- a/cocos2dx/cocoa/CCArray.cpp +++ b/cocos2dx/cocoa/CCArray.cpp @@ -24,6 +24,7 @@ THE SOFTWARE. ****************************************************************************/ #include "CCArray.h" +#include "platform/CCFileUtils.h" NS_CC_BEGIN @@ -131,11 +132,9 @@ CCArray* CCArray::createWithContentsOfFile(const char* pFileName) return pRet; } -extern CCArray* ccFileUtils_arrayWithContentsOfFileThreadSafe(const char* pFileName); - CCArray* CCArray::createWithContentsOfFileThreadSafe(const char* pFileName) { - return ccFileUtils_arrayWithContentsOfFileThreadSafe(pFileName); + return CCFileUtils::sharedFileUtils()->createCCArrayWithContentsOfFile(pFileName); } bool CCArray::init() diff --git a/cocos2dx/cocoa/CCDictionary.cpp b/cocos2dx/cocoa/CCDictionary.cpp index f5eedc9f72..a562425b95 100644 --- a/cocos2dx/cocoa/CCDictionary.cpp +++ b/cocos2dx/cocoa/CCDictionary.cpp @@ -25,6 +25,7 @@ #include "CCDictionary.h" #include "CCString.h" #include "CCInteger.h" +#include "platform/CCFileUtils.h" using namespace std; @@ -401,11 +402,9 @@ CCDictionary* CCDictionary::createWithDictionary(CCDictionary* srcDict) return pNewDict; } -extern CCDictionary* ccFileUtils_dictionaryWithContentsOfFileThreadSafe(const char *pFileName); - CCDictionary* CCDictionary::createWithContentsOfFileThreadSafe(const char *pFileName) { - return ccFileUtils_dictionaryWithContentsOfFileThreadSafe(pFileName); + return CCFileUtils::sharedFileUtils()->createCCDictionaryWithContentsOfFile(pFileName); } CCDictionary* CCDictionary::createWithContentsOfFile(const char *pFileName) diff --git a/cocos2dx/platform/CCFileUtilsCommon_cpp.h b/cocos2dx/platform/CCFileUtils.cpp similarity index 64% rename from cocos2dx/platform/CCFileUtilsCommon_cpp.h rename to cocos2dx/platform/CCFileUtils.cpp index 2473ad4990..927f5669f2 100644 --- a/cocos2dx/platform/CCFileUtilsCommon_cpp.h +++ b/cocos2dx/platform/CCFileUtils.cpp @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2010 cocos2d-x.org +Copyright (c) 2010-2013 cocos2d-x.org http://www.cocos2d-x.org @@ -21,21 +21,19 @@ 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_PLATFORM_FILEUTILS_CPP__ -#error "CCFileUtilsCommon_cpp.h can only be included for CCFileUtils.cpp in platform/win32(android,...)" -#endif /* __CC_PLATFORM_FILEUTILS_CPP__ */ #include "CCFileUtils.h" #include "CCDirector.h" #include "cocoa/CCDictionary.h" - -#if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS && CC_TARGET_PLATFORM != CC_PLATFORM_MAC) - #include "cocoa/CCString.h" #include "CCSAXParser.h" #include "support/zip_support/unzip.h" - #include + +using namespace std; + +#if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) && (CC_TARGET_PLATFORM != CC_PLATFORM_MAC) + #include #include #include @@ -318,16 +316,86 @@ public: } }; -CCDictionary* ccFileUtils_dictionaryWithContentsOfFileThreadSafe(const char *pFileName) +CCDictionary* CCFileUtils::createCCDictionaryWithContentsOfFile(const std::string& filename) { CCDictMaker tMaker; - return tMaker.dictionaryWithContentsOfFile(pFileName); + return tMaker.dictionaryWithContentsOfFile(filename.c_str()); } -CCArray* ccFileUtils_arrayWithContentsOfFileThreadSafe(const char* pFileName) +CCArray* CCFileUtils::createCCArrayWithContentsOfFile(const std::string& filename) { CCDictMaker tMaker; - return tMaker.arrayWithContentsOfFile(pFileName); + return tMaker.arrayWithContentsOfFile(filename.c_str()); +} + +#else +NS_CC_BEGIN + +/* The subclass CCFileUtilsIOS and CCFileUtilsMac should override these two method. */ +CCDictionary* CCFileUtils::createCCDictionaryWithContentsOfFile(const std::string& filename) {return NULL;} +CCArray* CCFileUtils::createCCArrayWithContentsOfFile(const std::string& filename) {return NULL;} + +#endif /* (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) && (CC_TARGET_PLATFORM != CC_PLATFORM_MAC) */ + + +CCFileUtils* CCFileUtils::s_sharedFileUtils = NULL; + +void CCFileUtils::purgeFileUtils() +{ + CC_SAFE_DELETE(s_sharedFileUtils); +} + +CCFileUtils::CCFileUtils() +: m_pFilenameLookupDict(NULL) +{ +} + +CCFileUtils::~CCFileUtils() +{ + CC_SAFE_RELEASE(m_pFilenameLookupDict); +} + +bool CCFileUtils::init() +{ + m_searchPathArray.push_back(m_strDefaultResRootPath); + m_searchResolutionsOrderArray.push_back(""); + return true; +} + +void CCFileUtils::purgeCachedEntries() +{ + m_fullPathCache.clear(); +} + +unsigned char* CCFileUtils::getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize) +{ + unsigned char * pBuffer = NULL; + CCAssert(pszFileName != NULL && pSize != NULL && pszMode != NULL, "Invalid parameters."); + *pSize = 0; + do + { + // read the file from hardware + std::string fullPath = fullPathForFilename(pszFileName); + FILE *fp = fopen(fullPath.c_str(), pszMode); + CC_BREAK_IF(!fp); + + fseek(fp,0,SEEK_END); + *pSize = ftell(fp); + fseek(fp,0,SEEK_SET); + pBuffer = new unsigned char[*pSize]; + *pSize = fread(pBuffer,sizeof(unsigned char), *pSize,fp); + fclose(fp); + } while (0); + + if (! pBuffer && isPopupNotify()) + { + std::string title = "Notification"; + std::string msg = "Get data from file("; + msg.append(pszFileName).append(") failed!"); + + CCMessageBox(msg.c_str(), title.c_str()); + } + return pBuffer; } unsigned char* CCFileUtils::getFileDataFromZip(const char* pszZipFilePath, const char* pszFileName, unsigned long * pSize) @@ -387,17 +455,103 @@ std::string CCFileUtils::getNewFilename(const char* pszFileName) return pszNewFileName; } +std::string CCFileUtils::getPathForFilename(const std::string& filename, const std::string& resolutionDirectory, const std::string& searchPath) +{ + std::string file = filename; + std::string file_path = ""; + size_t pos = filename.find_last_of("/"); + if (pos != std::string::npos) + { + file_path = filename.substr(0, pos+1); + file = filename.substr(pos+1); + } + + // searchPath + file_path + resourceDirectory + std::string path = searchPath; + path += file_path; + path += resolutionDirectory; + + path = getFullPathForDirectoryAndFilename(path, file); + + //CCLOG("getPathForFilename, fullPath = %s", path.c_str()); + return path; +} + + +std::string CCFileUtils::fullPathForFilename(const char* pszFileName) +{ + CCAssert(pszFileName != NULL, "CCFileUtils: Invalid path"); + + std::string strFileName = pszFileName; + if (isAbsolutePath(pszFileName)) + { + //CCLOG("Return absolute path( %s ) directly.", pszFileName); + return pszFileName; + } + + // Already Cached ? + std::map::iterator cacheIter = m_fullPathCache.find(pszFileName); + if (cacheIter != m_fullPathCache.end()) + { + //CCLOG("Return full path from cache: %s", cacheIter->second.c_str()); + return cacheIter->second; + } + + // Get the new file name. + std::string newFilename = getNewFilename(pszFileName); + + string fullpath = ""; + + for (std::vector::iterator searchPathsIter = m_searchPathArray.begin(); + searchPathsIter != m_searchPathArray.end(); ++searchPathsIter) { + for (std::vector::iterator resOrderIter = m_searchResolutionsOrderArray.begin(); + resOrderIter != m_searchResolutionsOrderArray.end(); ++resOrderIter) { + + //CCLOG("\n\nSEARCHING: %s, %s, %s", newFilename.c_str(), resOrderIter->c_str(), searchPathsIter->c_str()); + + fullpath = this->getPathForFilename(newFilename, *resOrderIter, *searchPathsIter); + + if (fullpath.length() > 0) + { + // Using the filename passed in as key. + m_fullPathCache.insert(std::pair(pszFileName, fullpath)); + //CCLOG("Returning path: %s", fullpath.c_str()); + return fullpath; + } + } + } + + // The file wasn't found, return the file name passed in. + return pszFileName; +} + +const char* CCFileUtils::fullPathFromRelativeFile(const char *pszFilename, const char *pszRelativeFile) +{ + std::string relativeFile = pszRelativeFile; + CCString *pRet = CCString::create(""); + pRet->m_sString = relativeFile.substr(0, relativeFile.rfind('/')+1); + pRet->m_sString += getNewFilename(pszFilename); + return pRet->getCString(); +} + void CCFileUtils::setSearchResolutionsOrder(const std::vector& searchResolutionsOrder) { bool bExistDefault = false; m_searchResolutionsOrderArray.clear(); for (std::vector::const_iterator iter = searchResolutionsOrder.begin(); iter != searchResolutionsOrder.end(); ++iter) { - if (!bExistDefault && (*iter) == "") + std::string resolutionDirectory = *iter; + if (!bExistDefault && resolutionDirectory == "") { bExistDefault = true; } - m_searchResolutionsOrderArray.push_back(*iter); + + if (resolutionDirectory.length() > 0 && resolutionDirectory[resolutionDirectory.length()-1] != '/') + { + resolutionDirectory += "/"; + } + + m_searchResolutionsOrderArray.push_back(resolutionDirectory); } if (!bExistDefault) { @@ -415,9 +569,36 @@ const std::vector& CCFileUtils::getSearchPaths() return m_searchPathArray; } -const char* CCFileUtils::getResourceDirectory() +void CCFileUtils::setSearchPaths(const std::vector& searchPaths) { - return m_obDirectory.c_str(); + bool bExistDefaultRootPath = false; + + m_searchPathArray.clear(); + for (std::vector::const_iterator iter = searchPaths.begin(); iter != searchPaths.end(); ++iter) + { + std::string strPrefix; + std::string path; + if (!isAbsolutePath(*iter)) + { // Not an absolute path + strPrefix = m_strDefaultResRootPath; + } + path = strPrefix+(*iter); + if (path.length() > 0 && path[path.length()-1] != '/') + { + path += "/"; + } + if (!bExistDefaultRootPath && path == m_strDefaultResRootPath) + { + bExistDefaultRootPath = true; + } + m_searchPathArray.push_back(path); + } + + if (!bExistDefaultRootPath) + { + //CCLOG("Default root path doesn't exist, adding it."); + m_searchPathArray.push_back(m_strDefaultResRootPath); + } } void CCFileUtils::setFilenameLookupDictionary(CCDictionary* pFilenameLookupDict) @@ -447,6 +628,20 @@ void CCFileUtils::loadFilenameLookupDictionaryFromFile(const char* filename) } } +std::string CCFileUtils::getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename) +{ + std::string ret = strDirectory+strFilename; + if (!isFileExist(ret)) { + ret = ""; + } + return ret; +} + +bool CCFileUtils::isAbsolutePath(const std::string& strPath) +{ + return strPath[0] == '/' ? true : false; +} + ////////////////////////////////////////////////////////////////////////// // Notification support when getFileData from invalid file path. ////////////////////////////////////////////////////////////////////////// @@ -464,4 +659,3 @@ bool CCFileUtils::isPopupNotify() NS_CC_END -#endif // (CC_TARGET_PLATFORM != CC_PLATFORM_IOS && CC_TARGET_PLATFORM != CC_PLATFORM_MAC) diff --git a/cocos2dx/platform/CCFileUtils.h b/cocos2dx/platform/CCFileUtils.h index bddeb189ed..5650686d9f 100644 --- a/cocos2dx/platform/CCFileUtils.h +++ b/cocos2dx/platform/CCFileUtils.h @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2010 cocos2d-x.org +Copyright (c) 2010-2013 cocos2d-x.org http://www.cocos2d-x.org @@ -21,11 +21,12 @@ 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_FILEUTILS_PLATFORM_H__ -#define __CC_FILEUTILS_PLATFORM_H__ +#ifndef __CC_FILEUTILS_H__ +#define __CC_FILEUTILS_H__ #include #include +#include #include "CCPlatformMacros.h" #include "ccTypes.h" #include "ccTypeInfo.h" @@ -42,6 +43,8 @@ class CCArray; //! @brief Helper class to handle file operations class CC_DLL CCFileUtils : public TypeInfo { + friend class CCArray; + friend class CCDictionary; public: /** * Returns an unique ID for this class. @@ -63,6 +66,11 @@ public: */ static void purgeFileUtils(); + /** + * The destructor of CCFileUtils. + */ + virtual ~CCFileUtils(); + /** * Purges the file searching cache. * @@ -71,36 +79,29 @@ public: * All the resources will be downloaded to the writable folder, before new js app launchs, * this method should be invoked to clean the file search cache. */ - void purgeCachedEntries(); + virtual void purgeCachedEntries(); /** - @brief Get resource file data - @param[in] pszFileName The resource file name which contains the path. - @param[in] pszMode The read mode of the file. - @param[out] pSize 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. - */ - unsigned char* getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize); - - /** - @brief Get resource file data from a zip file. - @param[in] pszFileName The resource file name which contains the relative path of the zip file. - @param[out] pSize 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. - */ - unsigned char* getFileDataFromZip(const char* pszZipFilePath, const char* pszFileName, unsigned long * pSize); - - /** - * @brief Generate the absolute path of the file. - * @param pszRelativePath The relative path of the file. - * @return The absolute path of the file. - * @warning We only add the ResourcePath before the relative path of the file. - * @deprecated Please use fullPathForFilename instead. + * Gets resource file data * + * @param[in] pszFileName The resource file name which contains the path. + * @param[in] pszMode The read mode of the file. + * @param[out] pSize 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 const char* fullPathFromRelativePath(const char *pszRelativePath); + virtual unsigned char* getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize); + + /** + * Gets resource file data from a zip file. + * + * @param[in] pszFileName The resource file name which contains the relative path of the zip file. + * @param[out] pSize 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. + */ + virtual unsigned char* getFileDataFromZip(const char* pszZipFilePath, const char* pszFileName, unsigned long * pSize); + /** Returns the fullpath for a given filename. @@ -147,12 +148,14 @@ public: @since v2.1 */ - std::string fullPathForFilename(const char* pszFileName); + virtual std::string fullPathForFilename(const char* pszFileName); /** * Loads the filenameLookup dictionary from the contents of a filename. * * @note The plist file name should follow the format below: + * + * @code * * * @@ -173,12 +176,12 @@ public: * * * - * + * @endcode * @param filename The plist file name. * @since v2.1 */ - void loadFilenameLookupDictionaryFromFile(const char* filename); + virtual void loadFilenameLookupDictionaryFromFile(const char* filename); /** * Sets the filenameLookup dictionary. @@ -186,7 +189,7 @@ public: * @param pFilenameLookupDict The dictionary for replacing filename. * @since v2.1 */ - void setFilenameLookupDictionary(CCDictionary* pFilenameLookupDict); + virtual void setFilenameLookupDictionary(CCDictionary* pFilenameLookupDict); /** * Gets full path from a file name and the path of the reletive file. @@ -197,34 +200,28 @@ public: * Return: /User/path1/path2/hello.pvr (If there a a key(hello.png)-value(hello.pvr) in FilenameLookup dictionary. ) * */ - const char* fullPathFromRelativeFile(const char *pszFilename, const char *pszRelativeFile); - - /** - @brief Set the resource directory; we will find resources relative to this directory. - @param pszDirectoryName Relative path to root. - @deprecated Please use setSearchPaths instead. - */ - CC_DEPRECATED_ATTRIBUTE void setResourceDirectory(const char *pszDirectoryName); + virtual const char* fullPathFromRelativeFile(const char *pszFilename, const char *pszRelativeFile); /** * Sets the array that contains the search order of the resources. * * @param searchResolutionsOrder The source array that contains the search order of the resources. - * @see getSearchResolutionsOrder(), fullPathForFilename(). + * @see getSearchResolutionsOrder(void), fullPathForFilename(const char*). * @since v2.1 */ - void setSearchResolutionsOrder(const std::vector& searchResolutionsOrder); + virtual void setSearchResolutionsOrder(const std::vector& searchResolutionsOrder); /** * Gets the array that contains the search order of the resources. * - * @see setSearchResolutionsOrder(), fullPathForFilename(). + * @see setSearchResolutionsOrder(const std::vector&), fullPathForFilename(const char*). * @since v2.1 */ - const std::vector& getSearchResolutionsOrder(); + virtual const std::vector& getSearchResolutionsOrder(); /** * Sets the array of search paths. + * * You can use this array to modify the search path of the resources. * If you want to use "themes" or search resources in the "cache", you can do it easily by adding new entries in this array. * @@ -236,62 +233,151 @@ public: * "resources-large" will be converted to "assets/resources-large" since it was a relative path. * * @param searchPaths The array contains search paths. - * @see fullPathForFilename() + * @see fullPathForFilename(const char*) * @since v2.1 */ - void setSearchPaths(const std::vector& searchPaths); + virtual void setSearchPaths(const std::vector& searchPaths); /** * Gets the array of search paths. * * @return The array of search paths. - * @see fullPathForFilename(). + * @see fullPathForFilename(const char*). */ - const std::vector& getSearchPaths(); + virtual const std::vector& getSearchPaths(); + + /** + * Gets the writeable path. + * @return The path that can be write/read a file in + */ + virtual std::string getWriteablePath() = 0; /** - * Gets the resource directory - * @deprecated Please use getSearchPaths() instead. + * Checks whether a file exists. + * + * @note If a relative path was passed in, it will be inserted a default root path at the beginning. + * @param strFilePath The path of the file, it could be a relative or absolute path. + * @return true if the file exists, otherwise it will return false. */ - CC_DEPRECATED_ATTRIBUTE const char* getResourceDirectory(); - + virtual bool isFileExist(const std::string& strFilePath) = 0; + /** - @brief Get the writeable path - @return The path that can write/read file - */ - std::string getWriteablePath(); - + * Checks whether the path is an absolute path. + * + * @note On Android, if the parameter passed in is relative to "assets/", this method will treat it as an absolute path. + * Also on Blackberry, path starts with "app/native/Resources/" is treated as an absolute path. + * + * @param strPath The path that needs to be checked. + * @return true if it's an absolute path, otherwise it will return false. + */ + virtual bool isAbsolutePath(const std::string& strPath); + + /** - @brief Set/Get whether pop-up a message box when the image load failed - */ - void setPopupNotify(bool bNotify); - bool isPopupNotify(); + * Sets/Gets whether to pop-up a message box when failed to load an image. + */ + virtual void setPopupNotify(bool bNotify); + virtual bool isPopupNotify(); protected: - CCFileUtils(void) - : m_pFilenameLookupDict(NULL) - { - } + /** + * The default constructor. + */ + CCFileUtils(); - bool init(); + /** + * Initializes the instance of CCFileUtils. It will set m_searchPathArray and m_searchResolutionsOrderArray to default values. + * + * @note When you are porting Cocos2d-x to a new platform, you may need to take care of this method. + * You could assign a default value to m_strDefaultResRootPath in the subclass of CCFileUtils(e.g. CCFileUtilsAndroid). Then invoke the CCFileUtils::init(). + * @return true if successed, otherwise it returns false. + * + */ + virtual bool init(); - std::string getNewFilename(const char* pszFileName); - std::string getPathForFilename(const std::string& filename, const std::string& resourceDirectory, const std::string& searchPath); + /** + * Gets the new filename from the filename lookup dictionary. + * @param pszFileName The original filename. + * @return The new filename after searching in the filename lookup dictionary. + * If the original filename wasn't in the dictionary, it will return the original filename. + */ + virtual std::string getNewFilename(const char* pszFileName); - std::string m_obDirectory; + /** + * Gets full path for filename, resolution directory and search path. + * + * @param filename The file name. + * @param resolutionDirectory The resolution directory. + * @param searchPath The search path. + * @return The full path of the file. It will return an empty string if the full path of the file doesn't exist. + */ + virtual std::string getPathForFilename(const std::string& filename, const std::string& resolutionDirectory, const std::string& searchPath); + + /** + * Gets full path for the directory and the filename. + * + * @note Only iOS and Mac need to override this method since they are using + * `[[NSBundle mainBundle] pathForResource: ofType: inDirectory:]` to make a full path. + * Other platforms will use the default implementation of this method. + * @param strDirectory The directory contains the file we are looking for. + * @param strFilename The name of the file. + * @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& strDirectory, const std::string& strFilename); + + /** + * Creates a dictionary by the contents of a file. + * @note This method is used internally. + */ + virtual CCDictionary* createCCDictionaryWithContentsOfFile(const std::string& filename); + + /** + * Creates an array by the contents of a file. + * @note This method is used internally. + */ + virtual CCArray* createCCArrayWithContentsOfFile(const std::string& filename); /** Dictionary used to lookup filenames based on a key. - It is used internally by the following methods: - - const char* fullPathForFilename(const char* )key; - - @since v2.1 + * It is used internally by the following methods: + * + * std::string fullPathForFilename(const char*); + * + * @since v2.1 */ CCDictionary* m_pFilenameLookupDict; + /** + * The vector contains resolution folders. + * The lower index of the element in this vector, the higher priority for this resolution directory. + */ std::vector m_searchResolutionsOrderArray; + + /** + * The vector contains search paths. + * The lower index of the element in this vector, the higher priority for this search path. + */ std::vector m_searchPathArray; + + /** + * The default root path of resources. + * If the default root path of resources needs to be changed, do it in the `init` method of CCFileUtils's subclass. + * For instance: + * On Android, the default root path of resources will be assigned with "assets/" in CCFileUtilsAndroid::init(). + * Similarly on Blackberry, we assign "app/native/Resources/" to this variable in CCFileUtilsBlackberry::init(). + */ std::string m_strDefaultResRootPath; + + /** + * The full path cache. When a file is found, it will be added into this cache. + * This variable is used for improving the performance of file search. + */ + std::map m_fullPathCache; + + /** + * The singleton pointer of CCFileUtils. + */ + static CCFileUtils* s_sharedFileUtils; + }; // end of platform group @@ -299,4 +385,4 @@ protected: NS_CC_END -#endif // __CC_FILEUTILS_PLATFORM_H__ +#endif // __CC_FILEUTILS_H__ diff --git a/cocos2dx/platform/android/CCFileUtils.cpp b/cocos2dx/platform/android/CCFileUtils.cpp deleted file mode 100644 index 0d26b2cacf..0000000000 --- a/cocos2dx/platform/android/CCFileUtils.cpp +++ /dev/null @@ -1,303 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#define __CC_PLATFORM_FILEUTILS_CPP__ -#include -#include "platform/CCFileUtilsCommon_cpp.h" -#include "support/zip_support/ZipUtils.h" -#include "platform/CCCommon.h" -#include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h" - -using namespace std; - -NS_CC_BEGIN - -static CCFileUtils* s_pFileUtils = NULL; -// record the zip on the resource path -static ZipFile *s_pZipFile = NULL; -// The full path cache, key: relative path, value: full path. -static std::map s_fullPathCache; - -CCFileUtils* CCFileUtils::sharedFileUtils() -{ - if (s_pFileUtils == NULL) - { - s_pFileUtils = new CCFileUtils(); - s_pFileUtils->init(); - std::string resourcePath = getApkPath(); - s_pZipFile = new ZipFile(resourcePath, "assets/"); - } - return s_pFileUtils; -} - -bool CCFileUtils::init() -{ - m_strDefaultResRootPath = "assets/"; - m_searchPathArray.push_back(m_strDefaultResRootPath); - m_searchResolutionsOrderArray.push_back(""); - - return true; -} - -void CCFileUtils::purgeFileUtils() -{ - if (s_pFileUtils != NULL) - { - s_pFileUtils->purgeCachedEntries(); - CC_SAFE_RELEASE(s_pFileUtils->m_pFilenameLookupDict); - } - - CC_SAFE_DELETE(s_pZipFile); - CC_SAFE_DELETE(s_pFileUtils); -} - -void CCFileUtils::purgeCachedEntries() -{ - s_fullPathCache.clear(); -} - -const char* CCFileUtils::fullPathFromRelativePath(const char *pszRelativePath) -{ - return CCString::create(fullPathForFilename(pszRelativePath))->getCString(); -} - -std::string CCFileUtils::fullPathForFilename(const char* pszFileName) -{ - CCAssert(pszFileName != NULL, "CCFileUtils: Invalid path"); - - // Return directly if it's an absolute path. - // On Android, there are two situations for full path. - // 1) Files in APK, e.g. assets/path/path/file.png - // 2) Files not in APK, e.g. /data/data/org.cocos2dx.hellocpp/cache/path/path/file.png, or /sdcard/path/path/file.png. - // So these two situations need to be checked on Android. - std::string strFileName = pszFileName; - if (pszFileName[0] == '/' || strFileName.find(m_strDefaultResRootPath) == 0) - { - //CCLOG("Return absolute path( %s ) directly.", pszFileName); - return pszFileName; - } - // Already Cached ? - std::map::iterator cacheIter = s_fullPathCache.find(pszFileName); - if (cacheIter != s_fullPathCache.end()) - { - //CCLOG("Return full path from cache: %s", cacheIter->second.c_str()); - return cacheIter->second; - } - - // Get the new file name. - std::string newFilename = getNewFilename(pszFileName); - - string fullpath = ""; - - bool bFound = false; - - for (std::vector::iterator searchPathsIter = m_searchPathArray.begin(); - searchPathsIter != m_searchPathArray.end(); ++searchPathsIter) { - for (std::vector::iterator resOrderIter = m_searchResolutionsOrderArray.begin(); - resOrderIter != m_searchResolutionsOrderArray.end(); ++resOrderIter) { - - //CCLOG("\n\nSEARCHING: %s, %s, %s", newFilename.c_str(), resOrderIter->c_str(), searchPathsIter->c_str()); - fullpath = this->getPathForFilename(newFilename, *resOrderIter, *searchPathsIter); - - // Check whether file exists in apk. - if (s_pZipFile->fileExists(fullpath)) - { - bFound = true; - } - else - { - FILE *fp = fopen(fullpath.c_str(), "r"); - if(fp) - { - bFound = true; - fclose(fp); - } - } - if (bFound) - { - // Using the filename passed in as key. - s_fullPathCache.insert(std::pair(pszFileName, fullpath)); - //CCLOG("Returning path: %s", fullpath.c_str()); - return fullpath; - } - } - } - - // The file wasn't found, return the file name passed in. - return pszFileName; -} - -const char* CCFileUtils::fullPathFromRelativeFile(const char *pszFilename, const char *pszRelativeFile) -{ - std::string relativeFile = pszRelativeFile; - CCString *pRet = CCString::create(""); - pRet->m_sString = relativeFile.substr(0, relativeFile.rfind('/')+1); - pRet->m_sString += getNewFilename(pszFilename); - return pRet->getCString(); -} - -std::string CCFileUtils::getPathForFilename(const std::string& filename, const std::string& resourceDirectory, const std::string& searchPath) -{ - std::string file = filename; - std::string file_path = ""; - size_t pos = filename.find_last_of("/"); - if (pos != std::string::npos) - { - file_path = filename.substr(0, pos+1); - file = filename.substr(pos+1); - } - - // searchPath + file_path + resourceDirectory - std::string path = searchPath; - if (path.size() > 0 && path[path.length()-1] != '/') - { - path += "/"; - } - path += file_path; - path += resourceDirectory; - - if (path.size() > 0 && path[path.length()-1] != '/') - { - path += "/"; - } - path += file; - - //CCLOG("getPathForFilename, fullPath = %s", path.c_str()); - return path; -} - -unsigned char* CCFileUtils::getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize) -{ - unsigned char * pData = 0; - - if ((! pszFileName) || (! pszMode) || 0 == strlen(pszFileName)) - { - return 0; - } - - if (pszFileName[0] != '/') - { - //CCLOG("GETTING FILE RELATIVE DATA: %s", pszFileName); - string fullPath = fullPathForFilename(pszFileName); - pData = s_pZipFile->getFileData(fullPath.c_str(), pSize); - } - else - { - do - { - // read rrom other path than user set it - //CCLOG("GETTING FILE ABSOLUTE DATA: %s", pszFileName); - FILE *fp = fopen(pszFileName, pszMode); - CC_BREAK_IF(!fp); - - unsigned long size; - fseek(fp,0,SEEK_END); - size = ftell(fp); - fseek(fp,0,SEEK_SET); - pData = new unsigned char[size]; - size = fread(pData,sizeof(unsigned char), size,fp); - fclose(fp); - - if (pSize) - { - *pSize = size; - } - } while (0); - } - - if (! pData && isPopupNotify()) - { - std::string title = "Notification"; - std::string msg = "Get data from file("; - msg.append(pszFileName).append(") failed!"); - CCMessageBox(msg.c_str(), title.c_str()); - } - - return pData; -} - -void CCFileUtils::setResourceDirectory(const char* pszResourceDirectory) -{ - if (pszResourceDirectory == NULL) return; - m_obDirectory = pszResourceDirectory; - std::vector searchPaths = this->getSearchPaths();; - searchPaths.insert(searchPaths.begin(), pszResourceDirectory); - this->setSearchPaths(searchPaths); -} - -void CCFileUtils::setSearchPaths(const std::vector& searchPaths) -{ - bool bExistDefaultRootPath = false; - - m_searchPathArray.clear(); - for (std::vector::const_iterator iter = searchPaths.begin(); iter != searchPaths.end(); ++iter) - { - std::string strPrefix; - std::string path; - if ((*iter)[0] != '/') - { // Not an absolute path - if (iter->find(m_strDefaultResRootPath) != 0) - { // The path contains no default resource root path, insert the root path. - strPrefix = m_strDefaultResRootPath; - } - } - path = strPrefix+(*iter); - if (path.length() > 0 && path[path.length()-1] != '/') - { - path += "/"; - } - if (!bExistDefaultRootPath && path == m_strDefaultResRootPath) - { - bExistDefaultRootPath = true; - } - m_searchPathArray.push_back(path); - } - - if (!bExistDefaultRootPath) - { - //CCLOG("Default root path doesn't exist, adding it."); - m_searchPathArray.push_back(m_strDefaultResRootPath); - } -} - -string CCFileUtils::getWriteablePath() -{ - // Fix for Nexus 10 (Android 4.2 multi-user environment) - // the path is retrieved through Java Context.getCacheDir() method - string dir(""); - const char *tmp = getCacheDirectoryJNI(); - - if (tmp) - { - dir.append(tmp).append("/"); - - return dir; - } - else - { - return ""; - } -} - -NS_CC_END diff --git a/cocos2dx/platform/android/CCFileUtilsAndroid.cpp b/cocos2dx/platform/android/CCFileUtilsAndroid.cpp new file mode 100644 index 0000000000..fec413c5e7 --- /dev/null +++ b/cocos2dx/platform/android/CCFileUtilsAndroid.cpp @@ -0,0 +1,176 @@ +/**************************************************************************** +Copyright (c) 2010 cocos2d-x.org + +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 "CCFileUtilsAndroid.h" +#include "support/zip_support/ZipUtils.h" +#include "platform/CCCommon.h" +#include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h" + +using namespace std; + +NS_CC_BEGIN + +// record the zip on the resource path +static ZipFile *s_pZipFile = NULL; + +CCFileUtils* CCFileUtils::sharedFileUtils() +{ + if (s_sharedFileUtils == NULL) + { + s_sharedFileUtils = new CCFileUtilsAndroid(); + s_sharedFileUtils->init(); + std::string resourcePath = getApkPath(); + s_pZipFile = new ZipFile(resourcePath, "assets/"); + } + return s_sharedFileUtils; +} + +CCFileUtilsAndroid::CCFileUtilsAndroid() +{ +} + +CCFileUtilsAndroid::~CCFileUtilsAndroid() +{ + CC_SAFE_DELETE(s_pZipFile); +} + +bool CCFileUtilsAndroid::init() +{ + m_strDefaultResRootPath = "assets/"; + return CCFileUtils::init(); +} + +bool CCFileUtilsAndroid::isFileExist(const std::string& strFilePath) +{ + bool bFound = false; + + // Check whether file exists in apk. + if (strFilePath[0] != '/') + { + std::string strPath = strFilePath; + if (strPath.find(m_strDefaultResRootPath) != 0) + {// Didn't find "assets/" at the beginning of the path, adding it. + strPath.insert(0, m_strDefaultResRootPath); + } + + if (s_pZipFile->fileExists(strPath)) + { + bFound = true; + } + } + else + { + FILE *fp = fopen(strFilePath.c_str(), "r"); + if(fp) + { + bFound = true; + fclose(fp); + } + } + return bFound; +} + +bool CCFileUtilsAndroid::isAbsolutePath(const std::string& strPath) +{ + // On Android, there are two situations for full path. + // 1) Files in APK, e.g. assets/path/path/file.png + // 2) Files not in APK, e.g. /data/data/org.cocos2dx.hellocpp/cache/path/path/file.png, or /sdcard/path/path/file.png. + // So these two situations need to be checked on Android. + if (strPath[0] == '/' || strPath.find(m_strDefaultResRootPath) == 0) + { + return true; + } + return false; +} + + +unsigned char* CCFileUtilsAndroid::getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize) +{ + unsigned char * pData = 0; + + if ((! pszFileName) || (! pszMode) || 0 == strlen(pszFileName)) + { + return 0; + } + + if (pszFileName[0] != '/') + { + //CCLOG("GETTING FILE RELATIVE DATA: %s", pszFileName); + string fullPath = fullPathForFilename(pszFileName); + pData = s_pZipFile->getFileData(fullPath.c_str(), pSize); + } + else + { + do + { + // read rrom other path than user set it + //CCLOG("GETTING FILE ABSOLUTE DATA: %s", pszFileName); + FILE *fp = fopen(pszFileName, pszMode); + CC_BREAK_IF(!fp); + + unsigned long size; + fseek(fp,0,SEEK_END); + size = ftell(fp); + fseek(fp,0,SEEK_SET); + pData = new unsigned char[size]; + size = fread(pData,sizeof(unsigned char), size,fp); + fclose(fp); + + if (pSize) + { + *pSize = size; + } + } while (0); + } + + if (! pData && isPopupNotify()) + { + std::string title = "Notification"; + std::string msg = "Get data from file("; + msg.append(pszFileName).append(") failed!"); + CCMessageBox(msg.c_str(), title.c_str()); + } + + return pData; +} + +string CCFileUtilsAndroid::getWriteablePath() +{ + // Fix for Nexus 10 (Android 4.2 multi-user environment) + // the path is retrieved through Java Context.getCacheDir() method + string dir(""); + const char *tmp = getCacheDirectoryJNI(); + + if (tmp) + { + dir.append(tmp).append("/"); + + return dir; + } + else + { + return ""; + } +} + +NS_CC_END diff --git a/cocos2dx/platform/android/CCFileUtilsAndroid.h b/cocos2dx/platform/android/CCFileUtilsAndroid.h new file mode 100644 index 0000000000..39faecd604 --- /dev/null +++ b/cocos2dx/platform/android/CCFileUtilsAndroid.h @@ -0,0 +1,63 @@ +/**************************************************************************** + Copyright (c) 2010 cocos2d-x.org + + 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_FILEUTILS_ANDROID_H__ +#define __CC_FILEUTILS_ANDROID_H__ + +#include "platform/CCFileUtils.h" +#include "platform/CCPlatformMacros.h" +#include "ccTypes.h" +#include "ccTypeInfo.h" +#include +#include + +NS_CC_BEGIN + +/** + * @addtogroup platform + * @{ + */ + +//! @brief Helper class to handle file operations +class CC_DLL CCFileUtilsAndroid : public CCFileUtils +{ + friend class CCFileUtils; + CCFileUtilsAndroid(); +public: + virtual ~CCFileUtilsAndroid(); + + /* override funtions */ + bool init(); + virtual unsigned char* getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize); + virtual std::string getWriteablePath(); + virtual bool isFileExist(const std::string& strFilePath); + virtual bool isAbsolutePath(const std::string& strPath); +}; + +// end of platform group +/// @} + +NS_CC_END + +#endif // __CC_FILEUTILS_ANDROID_H__ + diff --git a/cocos2dx/platform/blackberry/CCFileUtils.cpp b/cocos2dx/platform/blackberry/CCFileUtils.cpp deleted file mode 100644 index 89ee228eec..0000000000 --- a/cocos2dx/platform/blackberry/CCFileUtils.cpp +++ /dev/null @@ -1,263 +0,0 @@ -/**************************************************************************** -Copyright (c) 2012 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#define __CC_PLATFORM_FILEUTILS_CPP__ -#include "platform/CCFileUtilsCommon_cpp.h" -#include "CCApplication.h" -#include - -NS_CC_BEGIN; - -#define MAX_PATH 256 - -static CCFileUtils *s_pFileUtils = 0; -static std::map s_fullPathCache; - -CCFileUtils *CCFileUtils::sharedFileUtils() -{ - if (!s_pFileUtils) { - s_pFileUtils = new CCFileUtils(); - s_pFileUtils->init(); - } - - return s_pFileUtils; -} - -void CCFileUtils::purgeFileUtils() -{ - if (s_pFileUtils != NULL) - { - s_pFileUtils->purgeCachedEntries(); - CC_SAFE_RELEASE(s_pFileUtils->m_pFilenameLookupDict); - } - - CC_SAFE_DELETE(s_pFileUtils); -} - -bool CCFileUtils::init() -{ - m_strDefaultResRootPath = "app/native/Resources/"; - m_searchPathArray.push_back(m_strDefaultResRootPath); - m_searchResolutionsOrderArray.push_back(""); - - return true; -} - - -void CCFileUtils::purgeCachedEntries() -{ - s_fullPathCache.clear(); -} - -std::string CCFileUtils::getPathForFilename(const std::string& filename, const std::string& resourceDirectory, const std::string& searchPath) -{ - std::string file = filename; - std::string file_path = ""; - size_t pos = filename.find_last_of("/"); - if (pos != std::string::npos) - { - file_path = filename.substr(0, pos+1); - file = filename.substr(pos+1); - } - - // searchPath + file_path + resourceDirectory - std::string path = searchPath; - if (path.size() > 0 && path[path.length()-1] != '/') - { - path += "/"; - } - path += file_path; - path += resourceDirectory; - - if (path.size() > 0 && path[path.length()-1] != '/') - { - path += "/"; - } - path += file; - - return path; -} - -std::string CCFileUtils::fullPathForFilename(const char* pszFileName) -{ - CCAssert(pszFileName != NULL, "CCFileUtils: Invalid path"); - - // Return directly if it's absolute path. - std::string strFileName = pszFileName; - if (pszFileName[0] == '/' || strFileName.find(m_strDefaultResRootPath) == 0) - { - //CCLOG("Return absolute path( %s ) directly.", pszFileName); - return pszFileName; - } - - // Already Cached ? - std::map::iterator cacheIter = s_fullPathCache.find(pszFileName); - if (cacheIter != s_fullPathCache.end()) { - //CCLOG("Return full path from cache: %s", cacheIter->second.c_str()); - return cacheIter->second; - } - - // in Lookup Filename dictionary ? - std::string newFileName = getNewFilename(pszFileName); - - std::string fullpath; - - for (std::vector::iterator searchPathsIter = m_searchPathArray.begin(); - searchPathsIter != m_searchPathArray.end(); ++searchPathsIter) { - for (std::vector::iterator resOrderIter = m_searchResolutionsOrderArray.begin(); - resOrderIter != m_searchResolutionsOrderArray.end(); ++resOrderIter) { - - fullpath = this->getPathForFilename(newFileName, *resOrderIter, *searchPathsIter); - - // check if file or path exist - if (access(fullpath.c_str(), F_OK) != -1) - { - // Adding the full path to cache if the file was found. - s_fullPathCache.insert(std::pair(pszFileName, fullpath)); - //CCLOG("Returning path: %s", fullpath.c_str()); - return fullpath; - } - } - } - - // The file wasn't found, return the file name passed in. - return pszFileName; -} - -const char* CCFileUtils::fullPathFromRelativePath(const char *pszRelativePath) -{ - return CCString::create(fullPathForFilename(pszRelativePath))->getCString(); -} - - -const char *CCFileUtils::fullPathFromRelativeFile(const char *pszFilename, const char *pszRelativeFile) -{ - std::string relativeFile = pszRelativeFile; - CCString *pRet = CCString::create(""); - pRet->m_sString = relativeFile.substr(0, relativeFile.rfind('/')+1); - pRet->m_sString += getNewFilename(pszFilename); - return pRet->m_sString.c_str(); -} - -unsigned char* CCFileUtils::getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize) -{ - unsigned char *buffer = 0; - - if (!pszFileName || !pszMode) - { - return 0; - } - - std::string full_path = fullPathForFilename(pszFileName); - - do - { - // read from other path than user set it - FILE *fp = fopen(full_path.c_str(), pszMode); - CC_BREAK_IF(!fp); - - unsigned long size; - fseek(fp,0,SEEK_END); - size = ftell(fp); - fseek(fp,0,SEEK_SET); - buffer = new unsigned char[size]; - size = fread(buffer, sizeof(unsigned char), size, fp); - fclose(fp); - - if (pSize) - { - *pSize = size; - } - } while (0); - - if (!buffer && isPopupNotify()) - { - std::string title = "Notification"; - std::string msg = "Get data from file("; - msg.append(full_path.c_str()).append(") failed!"); - CCMessageBox(msg.c_str(), title.c_str()); - } - - return buffer; -} - -void CCFileUtils::setResourceDirectory(const char* pszResourceDirectory) -{ - if (pszResourceDirectory == NULL) return; - m_obDirectory = pszResourceDirectory; - std::vector searchPaths = this->getSearchPaths();; - searchPaths.insert(searchPaths.begin(), pszResourceDirectory); - this->setSearchPaths(searchPaths); -} - -void CCFileUtils::setSearchPaths(const std::vector& searchPaths) -{ - bool bExistDefaultRootPath = false; - - m_searchPathArray.clear(); - for (std::vector::const_iterator iter = searchPaths.begin(); iter != searchPaths.end(); ++iter) - { - std::string strPrefix; - std::string path; - if ((*iter)[0] != '/') - { // Not an absolute path - if (iter->find(m_strDefaultResRootPath) != 0) - { // The path contains no default resource root path, insert the root path. - strPrefix = m_strDefaultResRootPath; - } - } - path = strPrefix+(*iter); - if (path.length() > 0 && path[path.length()-1] != '/') - { - path += "/"; - } - if (!bExistDefaultRootPath && path == m_strDefaultResRootPath) - { - bExistDefaultRootPath = true; - } - m_searchPathArray.push_back(path); - } - - if (!bExistDefaultRootPath) - { - //CCLOG("Default root path doesn't exist, adding it."); - m_searchPathArray.push_back(m_strDefaultResRootPath); - } -} - -std::string CCFileUtils::getWriteablePath() -{ - // Let's write it in the current working directory's data folder - char cwd[FILENAME_MAX]; - - getcwd(cwd, FILENAME_MAX - 1); - cwd[FILENAME_MAX-1] = '\0'; - - std::string path = cwd; - path += "/data/"; - - return path; -} - -NS_CC_END; diff --git a/cocos2dx/platform/blackberry/CCFileUtilsBlackberry.cpp b/cocos2dx/platform/blackberry/CCFileUtilsBlackberry.cpp new file mode 100644 index 0000000000..e24b4b78e3 --- /dev/null +++ b/cocos2dx/platform/blackberry/CCFileUtilsBlackberry.cpp @@ -0,0 +1,68 @@ +#include "CCFileUtilsBlackberry.h" +#include "platform/CCCommon.h" +#include "ccMacros.h" +#include "CCApplication.h" +#include "cocoa/CCString.h" +#include + +using namespace std; + +NS_CC_BEGIN + +CCFileUtils* CCFileUtils::sharedFileUtils() +{ + if (s_sharedFileUtils == NULL) + { + s_sharedFileUtils = new CCFileUtilsBlackberry(); + s_sharedFileUtils->init(); + } + return s_sharedFileUtils; +} + +CCFileUtilsBlackberry::CCFileUtilsBlackberry() +{} + +bool CCFileUtilsBlackberry::init() +{ + m_strDefaultResRootPath = "app/native/Resources/"; + return CCFileUtils::init(); +} + +string CCFileUtilsBlackberry::getWriteablePath() +{ + // Let's write it in the current working directory's data folder + char cwd[FILENAME_MAX] = {0}; + + getcwd(cwd, FILENAME_MAX - 1); + cwd[FILENAME_MAX-1] = '\0'; + + std::string path = cwd; + path += "/data/"; + + return path; +} + +bool CCFileUtilsBlackberry::isAbsolutePath(const std::string& strPath) +{ + if (strPath[0] == '/' || strPath.find(m_strDefaultResRootPath) == 0) + { + return true; + } + return false; +} + +bool CCFileUtilsBlackberry::isFileExist(const std::string& strFilePath) +{ + std::string strPath = strFilePath; + if (strPath[0] != '/') + { // Not absolute path, add the default root path at the beginning. + if (strPath.find(m_strDefaultResRootPath) != 0) + {// Didn't find "assets/" at the beginning of the path, adding it. + strPath.insert(0, m_strDefaultResRootPath); + } + } + + return access(strPath.c_str(), F_OK) != -1 ? true : false; +} + +NS_CC_END diff --git a/cocos2dx/platform/blackberry/CCFileUtilsBlackberry.h b/cocos2dx/platform/blackberry/CCFileUtilsBlackberry.h new file mode 100644 index 0000000000..b760f27121 --- /dev/null +++ b/cocos2dx/platform/blackberry/CCFileUtilsBlackberry.h @@ -0,0 +1,60 @@ +/**************************************************************************** + Copyright (c) 2010-2013 cocos2d-x.org + + 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_FILEUTILS_BLACKBERRY_H__ +#define __CC_FILEUTILS_BLACKBERRY_H__ + +#include "platform/CCFileUtils.h" +#include "platform/CCPlatformMacros.h" +#include "ccTypes.h" +#include "ccTypeInfo.h" +#include +#include + +NS_CC_BEGIN + +/** + * @addtogroup platform + * @{ + */ + +//! @brief Helper class to handle file operations +class CC_DLL CCFileUtilsBlackberry : public CCFileUtils +{ + friend class CCFileUtils; + CCFileUtilsBlackberry(); +public: + /* override funtions */ + bool init(); + virtual std::string getWriteablePath(); + virtual bool isFileExist(const std::string& strFilePath); + virtual bool isAbsolutePath(const std::string& strPath); +}; + +// end of platform group +/// @} + +NS_CC_END + +#endif // __CC_FILEUTILS_BLACKBERRY_H__ + diff --git a/cocos2dx/platform/blackberry/CCImage.cpp b/cocos2dx/platform/blackberry/CCImage.cpp old mode 100644 new mode 100755 index 2c668a3dc9..ce7d662d09 --- a/cocos2dx/platform/blackberry/CCImage.cpp +++ b/cocos2dx/platform/blackberry/CCImage.cpp @@ -28,7 +28,7 @@ #include #include #include - +#include #include "platform/CCImage.h" #include "platform/CCFileUtils.h" #include "platform/CCCommon.h" @@ -408,7 +408,13 @@ bool CCImage::initWithString( CC_BREAK_IF(! pText); BitmapDC &dc = sharedBitmapDC(); - std::string fullFontName = CCFileUtils::sharedFileUtils()->fullPathForFilename(pFontName); + std::string fullFontName = pFontName; + std::string lowerCasePath = fullFontName; + std::transform(lowerCasePath.begin(), lowerCasePath.end(), lowerCasePath.begin(), ::tolower); + + if ( lowerCasePath.find(".ttf") != std::string::npos ) { + fullFontName = CCFileUtils::sharedFileUtils()->fullPathForFilename(pFontName); + } //CCLog("-----pText=%s and Font File is %s nWidth= %d,nHeight=%d",pText,fullFontName.c_str(),nWidth,nHeight); CC_BREAK_IF(! dc.getBitmap(pText, nWidth, nHeight, eAlignMask, fullFontName.c_str(), nSize)); diff --git a/cocos2dx/platform/ios/CCFileUtils.mm b/cocos2dx/platform/ios/CCFileUtils.mm deleted file mode 100644 index b6392b2a30..0000000000 --- a/cocos2dx/platform/ios/CCFileUtils.mm +++ /dev/null @@ -1,517 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2011 Zynga 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. -****************************************************************************/ -#import -#import - -#include -#include -#include -#include -#include -#include "cocoa/CCString.h" -#include "CCFileUtils.h" -#include "CCDirector.h" -#include "CCSAXParser.h" -#include "CCDictionary.h" -#include "support/zip_support/unzip.h" - -#define MAX_PATH 260 - -USING_NS_CC; - -static void static_addValueToCCDict(id key, id value, CCDictionary* pDict); -static void static_addItemToCCArray(id item, CCArray* pArray); - -static void static_addItemToCCArray(id item, CCArray *pArray) -{ - // add string value into array - if ([item isKindOfClass:[NSString class]]) { - CCString* pValue = new CCString([item UTF8String]); - - pArray->addObject(pValue); - pValue->release(); - return; - } - - // add number value into array(such as int, float, bool and so on) - if ([item isKindOfClass:[NSNumber class]]) { - NSString* pStr = [item stringValue]; - CCString* pValue = new CCString([pStr UTF8String]); - - pArray->addObject(pValue); - pValue->release(); - return; - } - - // add dictionary value into array - if ([item isKindOfClass:[NSDictionary class]]) { - CCDictionary* pDictItem = new CCDictionary(); - for (id subKey in [item allKeys]) { - id subValue = [item objectForKey:subKey]; - static_addValueToCCDict(subKey, subValue, pDictItem); - } - pArray->addObject(pDictItem); - pDictItem->release(); - return; - } - - // add array value into array - if ([item isKindOfClass:[NSArray class]]) { - CCArray *pArrayItem = new CCArray(); - pArrayItem->init(); - for (id subItem in item) { - static_addItemToCCArray(subItem, pArrayItem); - } - pArray->addObject(pArrayItem); - pArrayItem->release(); - return; - } -} - -static void static_addValueToCCDict(id key, id value, CCDictionary* pDict) -{ - // the key must be a string - CCAssert([key isKindOfClass:[NSString class]], "The key should be a string!"); - std::string pKey = [key UTF8String]; - - // the value is a new dictionary - if ([value isKindOfClass:[NSDictionary class]]) { - CCDictionary* pSubDict = new CCDictionary(); - for (id subKey in [value allKeys]) { - id subValue = [value objectForKey:subKey]; - static_addValueToCCDict(subKey, subValue, pSubDict); - } - pDict->setObject(pSubDict, pKey.c_str()); - pSubDict->release(); - return; - } - - // the value is a string - if ([value isKindOfClass:[NSString class]]) { - CCString* pValue = new CCString([value UTF8String]); - - pDict->setObject(pValue, pKey.c_str()); - pValue->release(); - return; - } - - // the value is a number - if ([value isKindOfClass:[NSNumber class]]) { - NSString* pStr = [value stringValue]; - CCString* pValue = new CCString([pStr UTF8String]); - - pDict->setObject(pValue, pKey.c_str()); - pValue->release(); - return; - } - - // the value is a array - if ([value isKindOfClass:[NSArray class]]) { - CCArray *pArray = new CCArray(); - pArray->init(); - for (id item in value) { - static_addItemToCCArray(item, pArray); - } - pDict->setObject(pArray, pKey.c_str()); - pArray->release(); - return; - } -} - -NS_CC_BEGIN - -static std::map s_fullPathCache; - -static CCFileUtils* s_pFileUtils = NULL; -static NSFileManager* s_fileManager = [NSFileManager defaultManager]; - -CCFileUtils* CCFileUtils::sharedFileUtils() -{ - if (s_pFileUtils == NULL) - { - s_pFileUtils = new CCFileUtils(); - s_pFileUtils->init(); - } - return s_pFileUtils; -} - -void CCFileUtils::purgeFileUtils() -{ - if (s_pFileUtils != NULL) - { - s_pFileUtils->purgeCachedEntries(); - CC_SAFE_RELEASE(s_pFileUtils->m_pFilenameLookupDict); - } - - CC_SAFE_DELETE(s_pFileUtils); -} - -void CCFileUtils::purgeCachedEntries() -{ - s_fullPathCache.clear(); -} - -bool CCFileUtils::init() -{ - m_strDefaultResRootPath = ""; - m_searchPathArray.push_back(m_strDefaultResRootPath); - m_searchResolutionsOrderArray.push_back(""); - - return true; -} - -void CCFileUtils::setSearchResolutionsOrder(const std::vector& searchResolutionsOrder) -{ - bool bExistDefault = false; - m_searchResolutionsOrderArray.clear(); - for (std::vector::const_iterator iter = searchResolutionsOrder.begin(); iter != searchResolutionsOrder.end(); ++iter) - { - if (!bExistDefault && (*iter) == "") - { - bExistDefault = true; - } - m_searchResolutionsOrderArray.push_back(*iter); - } - if (!bExistDefault) - { - m_searchResolutionsOrderArray.push_back(""); - } -} - -const std::vector& CCFileUtils::getSearchResolutionsOrder() -{ - return m_searchResolutionsOrderArray; -} - -void CCFileUtils::setSearchPaths(const std::vector& searchPaths) -{ - bool bExistDefault = false; - m_searchPathArray.clear(); - for (std::vector::const_iterator iter = searchPaths.begin(); iter != searchPaths.end(); ++iter) - { - if (!bExistDefault && (*iter) == "") - { - bExistDefault = true; - } - m_searchPathArray.push_back(*iter); - } - if (!bExistDefault) - { - m_searchPathArray.push_back(m_strDefaultResRootPath); - } -} - -const std::vector& CCFileUtils::getSearchPaths() -{ - return m_searchPathArray; -} - -void CCFileUtils::setResourceDirectory(const char *pszDirectoryName) -{ - m_obDirectory = pszDirectoryName; - if (m_obDirectory.size() > 0 && m_obDirectory[m_obDirectory.size() - 1] != '/') - { - m_obDirectory.append("/"); - } - m_searchPathArray.insert(m_searchPathArray.begin(), m_obDirectory); -} - -const char* CCFileUtils::getResourceDirectory() -{ - return m_obDirectory.c_str(); -} - -const char* CCFileUtils::fullPathFromRelativePath(const char *pszRelativePath) -{ - return CCString::create(fullPathForFilename(pszRelativePath))->getCString(); -} - -std::string CCFileUtils::getNewFilename(const char* pszFileName) -{ - const char* pszNewFileName = NULL; - // in Lookup Filename dictionary ? - CCString* fileNameFound = m_pFilenameLookupDict ? (CCString*)m_pFilenameLookupDict->objectForKey(pszFileName) : NULL; - if( NULL == fileNameFound || fileNameFound->length() == 0) { - pszNewFileName = pszFileName; - } - else { - pszNewFileName = fileNameFound->getCString(); - } - return pszNewFileName; -} - -std::string CCFileUtils::getPathForFilename(const std::string& filename, const std::string& resourceDirectory, const std::string& searchPath) -{ - std::string file = filename; - std::string file_path = ""; - size_t pos = filename.find_last_of("/"); - if (pos != std::string::npos) - { - file_path = filename.substr(0, pos+1); - file = filename.substr(pos+1); - } - - // searchPath + file_path + resourceDirectory - std::string path = searchPath; - if (path[path.length()-1] != '/') - { - path += "/"; - } - path += file_path; - path += resourceDirectory; - - if (searchPath[0] != '/') - { - NSString* fullpath = [[NSBundle mainBundle] pathForResource:[NSString stringWithUTF8String:file.c_str()] - ofType:nil - inDirectory:[NSString stringWithUTF8String:path.c_str()]]; - if (fullpath != nil) { - return [fullpath UTF8String]; - } - } - else - {// Search path is an absolute path. - std::string fullPath = path + file; - if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:fullPath.c_str()]]) { - return fullPath; - } - } - - // Return empty string when file wasn't found. - return ""; -} - -std::string CCFileUtils::fullPathForFilename(const char* pszFileName) -{ - CCAssert(pszFileName != NULL, "CCFileUtils: Invalid path"); - - NSString *relPath = [NSString stringWithUTF8String:pszFileName]; - - // Return directly if it's an absolute path. - if ([relPath isAbsolutePath]) { - return pszFileName; - } - - // Already Cached ? - std::map::iterator cacheIter = s_fullPathCache.find(pszFileName); - if (cacheIter != s_fullPathCache.end()) { - //CCLOG("Return full path from cache: %s", cacheIter->second.c_str()); - return cacheIter->second; - } - - std::string fullpath = ""; - - // in Lookup Filename dictionary ? - std::string newfilename = this->getNewFilename(pszFileName); - - for (std::vector::iterator searchPathsIter = m_searchPathArray.begin(); - searchPathsIter != m_searchPathArray.end(); ++searchPathsIter) { - for (std::vector::iterator resOrderIter = m_searchResolutionsOrderArray.begin(); - resOrderIter != m_searchResolutionsOrderArray.end(); ++resOrderIter) { - - fullpath = this->getPathForFilename(newfilename, *resOrderIter, *searchPathsIter); - - if (fullpath.length() > 0) - { - // Adding the full path to cache if the file was found. - s_fullPathCache.insert(std::pair(pszFileName, fullpath)); - return fullpath; - } - } - } - - // The file wasn't found, return the file name passed in. - return pszFileName; -} - -void CCFileUtils::loadFilenameLookupDictionaryFromFile(const char* filename) -{ - std::string pFullPath = this->fullPathForFilename(filename); - if (pFullPath.length() > 0) - { - CCDictionary* pDict = CCDictionary::createWithContentsOfFile(filename); - if (pDict) - { - CCDictionary* pMetadata = (CCDictionary*)pDict->objectForKey("metadata"); - int version = ((CCString*)pMetadata->objectForKey("version"))->intValue(); - if (version != 1) - { - CCLOG("cocos2d: ERROR: Invalid filenameLookup dictionary version: %ld. Filename: %s", (long)version, filename); - return; - } - - setFilenameLookupDictionary((CCDictionary*)pDict->objectForKey("filenames")); - } - } -} - -void CCFileUtils::setFilenameLookupDictionary(CCDictionary* pFilenameLookupDict) -{ - CC_SAFE_RELEASE(m_pFilenameLookupDict); - m_pFilenameLookupDict = pFilenameLookupDict; - CC_SAFE_RETAIN(m_pFilenameLookupDict); -} - -const char* CCFileUtils::fullPathFromRelativeFile(const char *pszFilename, const char *pszRelativeFile) -{ - std::string relativeFile = fullPathForFilename(pszRelativeFile); - CCString *pRet = CCString::create(""); - pRet->m_sString = relativeFile.substr(0, relativeFile.rfind('/')+1); - pRet->m_sString += getNewFilename(pszFilename); - return pRet->m_sString.c_str(); -} - -CCDictionary* ccFileUtils_dictionaryWithContentsOfFileThreadSafe(const char *pFileName) -{ - std::string fullPath = CCFileUtils::sharedFileUtils()->fullPathForFilename(pFileName); - NSString* pPath = [NSString stringWithUTF8String:fullPath.c_str()]; - NSDictionary* pDict = [NSDictionary dictionaryWithContentsOfFile:pPath]; - - CCDictionary* pRet = new CCDictionary(); - for (id key in [pDict allKeys]) { - id value = [pDict objectForKey:key]; - static_addValueToCCDict(key, value, pRet); - } - - return pRet; -} - -CCArray* ccFileUtils_arrayWithContentsOfFileThreadSafe(const char* pFileName) -{ -// NSString* pPath = [NSString stringWithUTF8String:pFileName]; -// NSString* pathExtension= [pPath pathExtension]; -// pPath = [pPath stringByDeletingPathExtension]; -// pPath = [[NSBundle mainBundle] pathForResource:pPath ofType:pathExtension]; -// fixing cannot read data using CCArray::createWithContentsOfFile - std::string fullPath = CCFileUtils::sharedFileUtils()->fullPathForFilename(pFileName); - NSString* pPath = [NSString stringWithUTF8String:fullPath.c_str()]; - NSArray* pArray = [NSArray arrayWithContentsOfFile:pPath]; - - CCArray* pRet = new CCArray(); - for (id value in pArray) { - static_addItemToCCArray(value, pRet); - } - - return pRet; -} - -unsigned char* CCFileUtils::getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize) -{ - unsigned char * pBuffer = NULL; - CCAssert(pszFileName != NULL && pSize != NULL && pszMode != NULL, "Invalid parameters."); - *pSize = 0; - do - { - // read the file from hardware - std::string fullPath = fullPathForFilename(pszFileName); - FILE *fp = fopen(fullPath.c_str(), pszMode); - CC_BREAK_IF(!fp); - - fseek(fp,0,SEEK_END); - *pSize = ftell(fp); - fseek(fp,0,SEEK_SET); - pBuffer = new unsigned char[*pSize]; - *pSize = fread(pBuffer,sizeof(unsigned char), *pSize,fp); - fclose(fp); - } while (0); - - if (! pBuffer && isPopupNotify()) - { - std::string title = "Notification"; - std::string msg = "Get data from file("; - msg.append(pszFileName).append(") failed!"); - - CCMessageBox(msg.c_str(), title.c_str()); - } - return pBuffer; -} - -// notification support when getFileData from a invalid file -static bool s_bPopupNotify = true; - -void CCFileUtils::setPopupNotify(bool bNotify) -{ - s_bPopupNotify = bNotify; -} - -bool CCFileUtils::isPopupNotify() -{ - return s_bPopupNotify; -} - -std::string CCFileUtils::getWriteablePath() -{ - // save to document folder - NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); - NSString *documentsDirectory = [paths objectAtIndex:0]; - std::string strRet = [documentsDirectory UTF8String]; - strRet.append("/"); - return strRet; -} - -unsigned char* CCFileUtils::getFileDataFromZip(const char* pszZipFilePath, const char* pszFileName, unsigned long * pSize) -{ - unsigned char * pBuffer = NULL; - unzFile pFile = NULL; - *pSize = 0; - - do - { - CC_BREAK_IF(!pszZipFilePath || !pszFileName); - CC_BREAK_IF(strlen(pszZipFilePath) == 0); - - pFile = unzOpen(pszZipFilePath); - CC_BREAK_IF(!pFile); - - int nRet = unzLocateFile(pFile, pszFileName, 1); - CC_BREAK_IF(UNZ_OK != nRet); - - char szFilePathA[260]; - unz_file_info FileInfo; - nRet = unzGetCurrentFileInfo(pFile, &FileInfo, szFilePathA, sizeof(szFilePathA), NULL, 0, NULL, 0); - CC_BREAK_IF(UNZ_OK != nRet); - - nRet = unzOpenCurrentFile(pFile); - CC_BREAK_IF(UNZ_OK != nRet); - - pBuffer = new unsigned char[FileInfo.uncompressed_size]; - int nSize = 0; - nSize = unzReadCurrentFile(pFile, pBuffer, FileInfo.uncompressed_size); - CCAssert(nSize == 0 || nSize == (int)FileInfo.uncompressed_size, "the file size is wrong"); - - *pSize = FileInfo.uncompressed_size; - unzCloseCurrentFile(pFile); - } while (0); - - if (pFile) - { - unzClose(pFile); - } - - return pBuffer; -} - -NS_CC_END - diff --git a/cocos2dx/platform/ios/CCFileUtilsIOS.h b/cocos2dx/platform/ios/CCFileUtilsIOS.h new file mode 100644 index 0000000000..7ba85e5d77 --- /dev/null +++ b/cocos2dx/platform/ios/CCFileUtilsIOS.h @@ -0,0 +1,61 @@ +/**************************************************************************** + Copyright (c) 2010 cocos2d-x.org + + 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_FILEUTILS_IOS_H__ +#define __CC_FILEUTILS_IOS_H__ + +#include "CCFileUtils.h" +#include +#include +#include "CCPlatformMacros.h" +#include "ccTypes.h" +#include "ccTypeInfo.h" + +NS_CC_BEGIN + +/** + * @addtogroup platform + * @{ + */ + +//! @brief Helper class to handle file operations +class CC_DLL CCFileUtilsIOS : public CCFileUtils +{ +public: + /* override funtions */ + virtual std::string getWriteablePath(); + virtual bool isFileExist(const std::string& strFilePath); + virtual bool isAbsolutePath(const std::string& strPath); + virtual std::string getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename); + + virtual CCDictionary* createCCDictionaryWithContentsOfFile(const std::string& filename); + virtual CCArray* createCCArrayWithContentsOfFile(const std::string& filename); +}; + +// end of platform group +/// @} + +NS_CC_END + +#endif // __CC_FILEUTILS_IOS_H__ + diff --git a/cocos2dx/platform/ios/CCFileUtilsIOS.mm b/cocos2dx/platform/ios/CCFileUtilsIOS.mm new file mode 100644 index 0000000000..79660d28d4 --- /dev/null +++ b/cocos2dx/platform/ios/CCFileUtilsIOS.mm @@ -0,0 +1,257 @@ +/**************************************************************************** +Copyright (c) 2010-2012 cocos2d-x.org +Copyright (c) 2011 Zynga 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. +****************************************************************************/ +#import +#import + +#include +#include +#include "cocoa/CCString.h" +#include "CCFileUtils.h" +#include "CCDirector.h" +#include "CCSAXParser.h" +#include "CCDictionary.h" +#include "support/zip_support/unzip.h" + +#include "CCFileUtilsIOS.h" + +NS_CC_BEGIN + +static void addValueToCCDict(id key, id value, CCDictionary* pDict); + +static void addItemToCCArray(id item, CCArray *pArray) +{ + // add string value into array + if ([item isKindOfClass:[NSString class]]) { + CCString* pValue = new CCString([item UTF8String]); + + pArray->addObject(pValue); + pValue->release(); + return; + } + + // add number value into array(such as int, float, bool and so on) + if ([item isKindOfClass:[NSNumber class]]) { + NSString* pStr = [item stringValue]; + CCString* pValue = new CCString([pStr UTF8String]); + + pArray->addObject(pValue); + pValue->release(); + return; + } + + // add dictionary value into array + if ([item isKindOfClass:[NSDictionary class]]) { + CCDictionary* pDictItem = new CCDictionary(); + for (id subKey in [item allKeys]) { + id subValue = [item objectForKey:subKey]; + addValueToCCDict(subKey, subValue, pDictItem); + } + pArray->addObject(pDictItem); + pDictItem->release(); + return; + } + + // add array value into array + if ([item isKindOfClass:[NSArray class]]) { + CCArray *pArrayItem = new CCArray(); + pArrayItem->init(); + for (id subItem in item) { + addItemToCCArray(subItem, pArrayItem); + } + pArray->addObject(pArrayItem); + pArrayItem->release(); + return; + } +} + +static void addValueToCCDict(id key, id value, CCDictionary* pDict) +{ + // the key must be a string + CCAssert([key isKindOfClass:[NSString class]], "The key should be a string!"); + std::string pKey = [key UTF8String]; + + // the value is a new dictionary + if ([value isKindOfClass:[NSDictionary class]]) { + CCDictionary* pSubDict = new CCDictionary(); + for (id subKey in [value allKeys]) { + id subValue = [value objectForKey:subKey]; + addValueToCCDict(subKey, subValue, pSubDict); + } + pDict->setObject(pSubDict, pKey.c_str()); + pSubDict->release(); + return; + } + + // the value is a string + if ([value isKindOfClass:[NSString class]]) { + CCString* pValue = new CCString([value UTF8String]); + + pDict->setObject(pValue, pKey.c_str()); + pValue->release(); + return; + } + + // the value is a number + if ([value isKindOfClass:[NSNumber class]]) { + NSString* pStr = [value stringValue]; + CCString* pValue = new CCString([pStr UTF8String]); + + pDict->setObject(pValue, pKey.c_str()); + pValue->release(); + return; + } + + // the value is a array + if ([value isKindOfClass:[NSArray class]]) { + CCArray *pArray = new CCArray(); + pArray->init(); + for (id item in value) { + addItemToCCArray(item, pArray); + } + pDict->setObject(pArray, pKey.c_str()); + pArray->release(); + return; + } +} + +CCFileUtils* CCFileUtils::sharedFileUtils() +{ + if (s_sharedFileUtils == NULL) + { + s_sharedFileUtils = new CCFileUtilsIOS(); + s_sharedFileUtils->init(); + } + return s_sharedFileUtils; +} + + +static NSFileManager* s_fileManager = [NSFileManager defaultManager]; + +std::string CCFileUtilsIOS::getWriteablePath() +{ + // save to document folder + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); + NSString *documentsDirectory = [paths objectAtIndex:0]; + std::string strRet = [documentsDirectory UTF8String]; + strRet.append("/"); + return strRet; +} + +bool CCFileUtilsIOS::isFileExist(const std::string& strFilePath) +{ + bool bRet = false; + + if (strFilePath[0] != '/') + { + std::string path = strFilePath; + std::string file; + size_t pos = path.find_last_of("/"); + if (pos != std::string::npos) + { + file = path.substr(pos+1); + path = path.substr(0, pos+1); + NSString* fullpath = [[NSBundle mainBundle] pathForResource:[NSString stringWithUTF8String:file.c_str()] + ofType:nil + inDirectory:[NSString stringWithUTF8String:path.c_str()]]; + if (fullpath != nil) { + bRet = true; + } + } + } + else + { + // Search path is an absolute path. + if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:strFilePath.c_str()]]) { + bRet = true; + } + } + + return bRet; +} + +std::string CCFileUtilsIOS::getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename) +{ + if (strDirectory[0] != '/') + { + NSString* fullpath = [[NSBundle mainBundle] pathForResource:[NSString stringWithUTF8String:strFilename.c_str()] + ofType:nil + inDirectory:[NSString stringWithUTF8String:strDirectory.c_str()]]; + if (fullpath != nil) { + return [fullpath UTF8String]; + } + } + else + { + std::string fullPath = strDirectory+strFilename; + // Search path is an absolute path. + if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:fullPath.c_str()]]) { + return fullPath; + } + } + return ""; +} + +bool CCFileUtilsIOS::isAbsolutePath(const std::string& strPath) +{ + NSString* path = [NSString stringWithUTF8String:strPath.c_str()]; + return [path isAbsolutePath] ? true : false; +} + +CCDictionary* CCFileUtilsIOS::createCCDictionaryWithContentsOfFile(const std::string& filename) +{ + std::string fullPath = CCFileUtils::sharedFileUtils()->fullPathForFilename(filename.c_str()); + NSString* pPath = [NSString stringWithUTF8String:fullPath.c_str()]; + NSDictionary* pDict = [NSDictionary dictionaryWithContentsOfFile:pPath]; + + CCDictionary* pRet = new CCDictionary(); + for (id key in [pDict allKeys]) { + id value = [pDict objectForKey:key]; + addValueToCCDict(key, value, pRet); + } + + return pRet; +} + +CCArray* CCFileUtilsIOS::createCCArrayWithContentsOfFile(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 CCArray::createWithContentsOfFile + std::string fullPath = CCFileUtils::sharedFileUtils()->fullPathForFilename(filename.c_str()); + NSString* pPath = [NSString stringWithUTF8String:fullPath.c_str()]; + NSArray* pArray = [NSArray arrayWithContentsOfFile:pPath]; + + CCArray* pRet = new CCArray(); + for (id value in pArray) { + addItemToCCArray(value, pRet); + } + + return pRet; +} + +NS_CC_END + diff --git a/cocos2dx/platform/linux/CCFileUtils.cpp b/cocos2dx/platform/linux/CCFileUtils.cpp deleted file mode 100644 index 38993a5009..0000000000 --- a/cocos2dx/platform/linux/CCFileUtils.cpp +++ /dev/null @@ -1,248 +0,0 @@ -/* - * CCFileUtils_Linux.cpp - * - * Created on: Aug 9, 2011 - * Author: laschweinski - */ -#include "platform/CCCommon.h" -#include "ccMacros.h" -#define __CC_PLATFORM_FILEUTILS_CPP__ -#include "platform/CCFileUtilsCommon_cpp.h" -#include "platform/CCFileUtils.h" -#include "CCApplication.h" -#include "cocoa/CCString.h" -#include -#include -#include -#include - -using namespace std; - -NS_CC_BEGIN - -static CCFileUtils* s_pFileUtils = NULL; -static std::map s_fullPathCache; - -CCFileUtils* CCFileUtils::sharedFileUtils() -{ - if (s_pFileUtils == NULL) - { - s_pFileUtils = new CCFileUtils(); - s_pFileUtils->init(); - } - return s_pFileUtils; -} - -bool CCFileUtils::init() -{ - // get application path - int length = 0; - char fullpath[256] = {0}; - length = readlink("/proc/self/exe", fullpath, sizeof(fullpath)); - fullpath[length] = '\0'; - - std::string resourcePath = fullpath; - resourcePath = resourcePath.substr(0, resourcePath.find_last_of("/")); - resourcePath += "/../../../Resources/"; - m_strDefaultResRootPath = resourcePath; - //CCLOG("DEFAULT RES PATH = %s", m_strDefaultResRootPath.c_str()); - m_searchPathArray.push_back(m_strDefaultResRootPath); - m_searchResolutionsOrderArray.push_back(""); - - return true; -} - -void CCFileUtils::purgeFileUtils() -{ - if (s_pFileUtils != NULL) - { - s_pFileUtils->purgeCachedEntries(); - CC_SAFE_RELEASE(s_pFileUtils->m_pFilenameLookupDict); - } - - CC_SAFE_DELETE(s_pFileUtils); -} - -void CCFileUtils::purgeCachedEntries() -{ - s_fullPathCache.clear(); -} - -std::string CCFileUtils::getPathForFilename(const std::string& filename, const std::string& resourceDirectory, const std::string& searchPath) -{ - std::string file = filename; - std::string file_path = ""; - size_t pos = filename.find_last_of("/"); - if (pos != std::string::npos) - { - file_path = filename.substr(0, pos+1); - file = filename.substr(pos+1); - } - - // searchPath + file_path + resourceDirectory - std::string path = searchPath; - if (path.size() > 0 && path[path.length()-1] != '/') - { - path += "/"; - } - path += file_path; - path += resourceDirectory; - - if (path.size() > 0 && path[path.length()-1] != '/') - { - path += "/"; - } - path += file; - - return path; -} - -std::string CCFileUtils::fullPathForFilename(const char* pszFileName) -{ - CCAssert(pszFileName != NULL, "CCFileUtils: Invalid path"); - - // Return directly if it's an absolute path. - if (pszFileName[0] == '/') - { - //CCLOG("return absolute path directly: %s ", pszFileName); - return pszFileName; - } - - // Already Cached ? - std::map::iterator cacheIter = s_fullPathCache.find(pszFileName); - if (cacheIter != s_fullPathCache.end()) { - //CCLOG("Return full path from cache: %s", cacheIter->second.c_str()); - return cacheIter->second; - } - - // in Lookup Filename dictionary ? - std::string newFileName = getNewFilename(pszFileName); - - std::string fullpath; - - for (std::vector::iterator searchPathsIter = m_searchPathArray.begin(); - searchPathsIter != m_searchPathArray.end(); ++searchPathsIter) { - for (std::vector::iterator resOrderIter = m_searchResolutionsOrderArray.begin(); - resOrderIter != m_searchResolutionsOrderArray.end(); ++resOrderIter) { - - //CCLOG("\n\nSEARCHING: %s, %s, %s", newFileName.c_str(), resOrderIter->c_str(), searchPathsIter->c_str()); - - fullpath = this->getPathForFilename(newFileName, *resOrderIter, *searchPathsIter); - - // check if file or path exist - struct stat sts; - if (stat(fullpath.c_str(), &sts) != -1) - { - // Adding the full path to cache if the file was found. - s_fullPathCache.insert(std::pair(pszFileName, fullpath)); - //CCLOG("Returning path: %s", fullpath.c_str()); - return fullpath; - } - } - } - - // The file wasn't found, return the file name passed in. - return pszFileName; -} - -const char* CCFileUtils::fullPathFromRelativePath(const char *pszRelativePath) -{ - return CCString::create(fullPathForFilename(pszRelativePath))->getCString(); -} - - -const char *CCFileUtils::fullPathFromRelativeFile(const char *pszFilename, const char *pszRelativeFile) -{ - std::string relativeFile = pszRelativeFile; - CCString *pRet = CCString::create(""); - pRet->m_sString = relativeFile.substr(0, relativeFile.rfind('/')+1); - pRet->m_sString += getNewFilename(pszFilename); - return pRet->m_sString.c_str(); -} - -unsigned char* CCFileUtils::getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize) -{ - unsigned char * pData = 0; - - if (!pszFileName || !pszMode) - { - return 0; - } - - do - { - std::string fullPath = fullPathForFilename(pszFileName); - // read rrom other path than user set it - FILE *fp = fopen(fullPath.c_str(), pszMode); - CC_BREAK_IF(!fp); - - fseek(fp,0,SEEK_END); - *pSize = ftell(fp); - fseek(fp,0,SEEK_SET); - pData = new unsigned char[*pSize]; - *pSize = fread(pData,sizeof(unsigned char), *pSize,fp); - fclose(fp); - }while (0); - - if (! pData && isPopupNotify()) - { - std::string title = "Notification"; - std::string msg = "Get data from file("; - msg.append(pszFileName).append(") failed!"); - CCMessageBox(msg.c_str(), title.c_str()); - } - return pData; - -} - -void CCFileUtils::setResourceDirectory(const char* pszResourceDirectory) -{ - if (pszResourceDirectory == NULL) return; - m_obDirectory = pszResourceDirectory; - std::vector searchPaths = this->getSearchPaths();; - searchPaths.insert(searchPaths.begin(), pszResourceDirectory); - this->setSearchPaths(searchPaths); -} - -void CCFileUtils::setSearchPaths(const std::vector& searchPaths) -{ - bool bExistDefaultRootPath = false; - - m_searchPathArray.clear(); - for (std::vector::const_iterator iter = searchPaths.begin(); iter != searchPaths.end(); ++iter) - { - std::string strPrefix; - std::string path; - if ((*iter)[0] != '/') - { // Not an absolute path - if (iter->find(m_strDefaultResRootPath) != 0) - { // The path contains no default resource root path, insert the root path. - strPrefix = m_strDefaultResRootPath; - } - } - path = strPrefix+(*iter); - if (path.length() > 0 && path[path.length()-1] != '/') - { - path += "/"; - } - if (!bExistDefaultRootPath && path == m_strDefaultResRootPath) - { - bExistDefaultRootPath = true; - } - m_searchPathArray.push_back(path); - } - - if (!bExistDefaultRootPath) - { - //CCLOG("Default root path doesn't exist, adding it."); - m_searchPathArray.push_back(m_strDefaultResRootPath); - } -} - -string CCFileUtils::getWriteablePath() -{ - //return current resource path - return m_strDefaultResRootPath; -} - -NS_CC_END diff --git a/cocos2dx/platform/linux/CCFileUtilsLinux.cpp b/cocos2dx/platform/linux/CCFileUtilsLinux.cpp new file mode 100644 index 0000000000..5a6c392034 --- /dev/null +++ b/cocos2dx/platform/linux/CCFileUtilsLinux.cpp @@ -0,0 +1,68 @@ +/* + * CCFileUtilsLinux.cpp + * + * Created on: Aug 9, 2011 + * Author: laschweinski + */ +#include "CCFileUtilsLinux.h" +#include "platform/CCCommon.h" +#include "ccMacros.h" +#include "CCApplication.h" +#include "cocoa/CCString.h" +#include +#include +#include +#include + +using namespace std; + +NS_CC_BEGIN + +CCFileUtils* CCFileUtils::sharedFileUtils() +{ + if (s_sharedFileUtils == NULL) + { + s_sharedFileUtils = new CCFileUtilsLinux(); + s_sharedFileUtils->init(); + } + return s_sharedFileUtils; +} + +CCFileUtilsLinux::CCFileUtilsLinux() +{} + +bool CCFileUtilsLinux::init() +{ + // get application path + int length = 0; + char fullpath[256] = {0}; + length = readlink("/proc/self/exe", fullpath, sizeof(fullpath)); + fullpath[length] = '\0'; + + std::string resourcePath = fullpath; + resourcePath = resourcePath.substr(0, resourcePath.find_last_of("/")); + resourcePath += "/../../../Resources/"; + m_strDefaultResRootPath = resourcePath; + + return CCFileUtils::init(); +} + +string CCFileUtilsLinux::getWriteablePath() +{ + //return current resource path + return m_strDefaultResRootPath; +} + +bool CCFileUtilsLinux::isFileExist(const std::string& strFilePath) +{ + std::string strPath = strFilePath; + if (!isAbsolutePath(strPath)) + { // Not absolute path, add the default root path at the beginning. + strPath.insert(0, m_strDefaultResRootPath); + } + + struct stat sts; + return (stat(strPath.c_str(), &sts) != -1) ? true : false; +} + +NS_CC_END diff --git a/cocos2dx/platform/linux/CCFileUtilsLinux.h b/cocos2dx/platform/linux/CCFileUtilsLinux.h new file mode 100644 index 0000000000..da83a087da --- /dev/null +++ b/cocos2dx/platform/linux/CCFileUtilsLinux.h @@ -0,0 +1,59 @@ +/**************************************************************************** + Copyright (c) 2010 cocos2d-x.org + + 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_FILEUTILS_LINUX_H__ +#define __CC_FILEUTILS_LINUX_H__ + +#include "platform/CCFileUtils.h" +#include "platform/CCPlatformMacros.h" +#include "ccTypes.h" +#include "ccTypeInfo.h" +#include +#include + +NS_CC_BEGIN + +/** + * @addtogroup platform + * @{ + */ + +//! @brief Helper class to handle file operations +class CC_DLL CCFileUtilsLinux : public CCFileUtils +{ + friend class CCFileUtils; + CCFileUtilsLinux(); +public: + /* override funtions */ + bool init(); + virtual std::string getWriteablePath(); + virtual bool isFileExist(const std::string& strFilePath); +}; + +// end of platform group +/// @} + +NS_CC_END + +#endif // __CC_FILEUTILS_LINUX_H__ + diff --git a/cocos2dx/platform/mac/CCFileUtils.mm b/cocos2dx/platform/mac/CCFileUtils.mm deleted file mode 100755 index 17d77bef78..0000000000 --- a/cocos2dx/platform/mac/CCFileUtils.mm +++ /dev/null @@ -1,517 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2011 cocos2d-x.org - Copyright (c) 2011 Zynga 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. - ****************************************************************************/ -#import - -#include -#include -#include -#include -#include -#include "CCString.h" -#include "CCFileUtils.h" -#include "CCDirector.h" -#include "CCApplication.h" -#include "CCSAXParser.h" -#include "CCDictionary.h" -#include "support/zip_support/unzip.h" - -#define MAX_PATH 260 - -USING_NS_CC; - -static void static_addValueToCCDict(id key, id value, CCDictionary* pDict); -static void static_addItemToCCArray(id item, CCArray* pArray); - -static void static_addItemToCCArray(id item, CCArray *pArray) -{ - // add string value into array - if ([item isKindOfClass:[NSString class]]) { - CCString* pValue = new CCString([item UTF8String]); - - pArray->addObject(pValue); - pValue->release(); - return; - } - - // add number value into array(such as int, float, bool and so on) - if ([item isKindOfClass:[NSNumber class]]) { - NSString* pStr = [item stringValue]; - CCString* pValue = new CCString([pStr UTF8String]); - - pArray->addObject(pValue); - pValue->release(); - return; - } - - // add dictionary value into array - if ([item isKindOfClass:[NSDictionary class]]) { - CCDictionary* pDictItem = new CCDictionary(); - for (id subKey in [item allKeys]) { - id subValue = [item objectForKey:subKey]; - static_addValueToCCDict(subKey, subValue, pDictItem); - } - pArray->addObject(pDictItem); - pDictItem->release(); - return; - } - - // add array value into array - if ([item isKindOfClass:[NSArray class]]) { - CCArray *pArrayItem = new CCArray(); - pArrayItem->init(); - for (id subItem in item) { - static_addItemToCCArray(subItem, pArrayItem); - } - pArray->addObject(pArrayItem); - pArrayItem->release(); - return; - } -} - -static void static_addValueToCCDict(id key, id value, CCDictionary* pDict) -{ - // the key must be a string - CCAssert([key isKindOfClass:[NSString class]], "The key should be a string!"); - std::string pKey = [key UTF8String]; - - // the value is a new dictionary - if ([value isKindOfClass:[NSDictionary class]]) { - CCDictionary* pSubDict = new CCDictionary(); - for (id subKey in [value allKeys]) { - id subValue = [value objectForKey:subKey]; - static_addValueToCCDict(subKey, subValue, pSubDict); - } - pDict->setObject(pSubDict, pKey.c_str()); - pSubDict->release(); - return; - } - - // the value is a string - if ([value isKindOfClass:[NSString class]]) { - CCString* pValue = new CCString([value UTF8String]); - - pDict->setObject(pValue, pKey.c_str()); - pValue->release(); - return; - } - - // the value is a number - if ([value isKindOfClass:[NSNumber class]]) { - NSString* pStr = [value stringValue]; - CCString* pValue = new CCString([pStr UTF8String]); - - pDict->setObject(pValue, pKey.c_str()); - pValue->release(); - return; - } - - // the value is a array - if ([value isKindOfClass:[NSArray class]]) { - CCArray *pArray = new CCArray(); - pArray->init(); - for (id item in value) { - static_addItemToCCArray(item, pArray); - } - pDict->setObject(pArray, pKey.c_str()); - pArray->release(); - return; - } -} - -NS_CC_BEGIN - -CCDictionary* ccFileUtils_dictionaryWithContentsOfFileThreadSafe(const char *pFileName); -CCArray* ccFileUtils_arrayWithContentsOfFileThreadSafe(const char* pFileName); - -static CCFileUtils* s_pFileUtils = NULL; -static NSFileManager* s_fileManager = [NSFileManager defaultManager]; -static std::map s_fullPathCache; - -CCFileUtils* CCFileUtils::sharedFileUtils() -{ - if (s_pFileUtils == NULL) - { - s_pFileUtils = new CCFileUtils(); - s_pFileUtils->init(); - } - return s_pFileUtils; -} - -void CCFileUtils::purgeFileUtils() -{ - if (s_pFileUtils != NULL) - { - s_pFileUtils->purgeCachedEntries(); - CC_SAFE_RELEASE(s_pFileUtils->m_pFilenameLookupDict); - } - - CC_SAFE_DELETE(s_pFileUtils); -} - -void CCFileUtils::purgeCachedEntries() -{ - s_fullPathCache.clear(); -} - -bool CCFileUtils::init() -{ - m_strDefaultResRootPath = ""; - m_searchPathArray.push_back(m_strDefaultResRootPath); - m_searchResolutionsOrderArray.push_back(""); - - return true; -} - -void CCFileUtils::setSearchResolutionsOrder(const std::vector& searchResolutionsOrder) -{ - bool bExistDefault = false; - m_searchResolutionsOrderArray.clear(); - for (std::vector::const_iterator iter = searchResolutionsOrder.begin(); iter != searchResolutionsOrder.end(); ++iter) - { - if (!bExistDefault && (*iter) == "") - { - bExistDefault = true; - } - m_searchResolutionsOrderArray.push_back(*iter); - } - if (!bExistDefault) - { - m_searchResolutionsOrderArray.push_back(""); - } -} - -const std::vector& CCFileUtils::getSearchResolutionsOrder() -{ - return m_searchResolutionsOrderArray; -} - -void CCFileUtils::setSearchPaths(const std::vector& searchPaths) -{ - bool bExistDefault = false; - m_searchPathArray.clear(); - for (std::vector::const_iterator iter = searchPaths.begin(); iter != searchPaths.end(); ++iter) - { - if (!bExistDefault && (*iter) == "") - { - bExistDefault = true; - } - m_searchPathArray.push_back(*iter); - } - if (!bExistDefault) - { - m_searchPathArray.push_back(m_strDefaultResRootPath); - } -} - -const std::vector& CCFileUtils::getSearchPaths() -{ - return m_searchPathArray; -} - -void CCFileUtils::setResourceDirectory(const char *pszDirectoryName) -{ - m_obDirectory = pszDirectoryName; - if (m_obDirectory.size() > 0 && m_obDirectory[m_obDirectory.size() - 1] != '/') - { - m_obDirectory.append("/"); - } - m_searchPathArray.insert(m_searchPathArray.begin(), m_obDirectory); -} - -const char* CCFileUtils::getResourceDirectory() -{ - return m_obDirectory.c_str(); -} - -const char* CCFileUtils::fullPathFromRelativePath(const char *pszRelativePath) -{ - return CCString::create(fullPathForFilename(pszRelativePath))->getCString(); -} - -std::string CCFileUtils::getNewFilename(const char* pszFileName) -{ - const char* pszNewFileName = NULL; - // in Lookup Filename dictionary ? - CCString* fileNameFound = m_pFilenameLookupDict ? (CCString*)m_pFilenameLookupDict->objectForKey(pszFileName) : NULL; - if( NULL == fileNameFound || fileNameFound->length() == 0) { - pszNewFileName = pszFileName; - } - else { - pszNewFileName = fileNameFound->getCString(); - } - return pszNewFileName; -} - -std::string CCFileUtils::getPathForFilename(const std::string& filename, const std::string& resourceDirectory, const std::string& searchPath) -{ - std::string file = filename; - std::string file_path = ""; - size_t pos = filename.find_last_of("/"); - if (pos != std::string::npos) - { - file_path = filename.substr(0, pos+1); - file = filename.substr(pos+1); - } - - // searchPath + file_path + resourceDirectory - std::string path = searchPath; - if (path[path.length()-1] != '/') - { - path += "/"; - } - path += file_path; - path += resourceDirectory; - - if (searchPath[0] != '/') - { - NSString* fullpath = [[NSBundle mainBundle] pathForResource:[NSString stringWithUTF8String:file.c_str()] - ofType:nil - inDirectory:[NSString stringWithUTF8String:path.c_str()]]; - if (fullpath != nil) { - return [fullpath UTF8String]; - } - } - else - {// Search path is an absolute path. - std::string fullPath = path + file; - if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:fullPath.c_str()]]) { - return fullPath; - } - } - - // Return empty string when file wasn't found. - return ""; -} - -std::string CCFileUtils::fullPathForFilename(const char* pszFileName) -{ - CCAssert(pszFileName != NULL, "CCFileUtils: Invalid path"); - - NSString *relPath = [NSString stringWithUTF8String:pszFileName]; - - // Return directly if it's an absolute path. - if ([relPath isAbsolutePath]) { - return pszFileName; - } - - // Already Cached ? - std::map::iterator cacheIter = s_fullPathCache.find(pszFileName); - if (cacheIter != s_fullPathCache.end()) { - //CCLOG("Return full path from cache: %s", cacheIter->second.c_str()); - return cacheIter->second; - } - - std::string fullpath = ""; - - // in Lookup Filename dictionary ? - std::string newfilename = this->getNewFilename(pszFileName); - - for (std::vector::iterator searchPathsIter = m_searchPathArray.begin(); - searchPathsIter != m_searchPathArray.end(); ++searchPathsIter) { - for (std::vector::iterator resOrderIter = m_searchResolutionsOrderArray.begin(); - resOrderIter != m_searchResolutionsOrderArray.end(); ++resOrderIter) { - - fullpath = this->getPathForFilename(newfilename, *resOrderIter, *searchPathsIter); - - if (fullpath.length() > 0) - { - // Adding the full path to cache if the file was found. - s_fullPathCache.insert(std::pair(pszFileName, fullpath)); - return fullpath; - } - } - } - - // The file wasn't found, return the file name passed in. - return pszFileName; -} - -void CCFileUtils::loadFilenameLookupDictionaryFromFile(const char* filename) -{ - std::string pFullPath = this->fullPathForFilename(filename); - if (pFullPath.length() > 0) - { - CCDictionary* pDict = CCDictionary::createWithContentsOfFile(filename); - if (pDict) - { - CCDictionary* pMetadata = (CCDictionary*)pDict->objectForKey("metadata"); - int version = ((CCString*)pMetadata->objectForKey("version"))->intValue(); - if (version != 1) - { - CCLOG("cocos2d: ERROR: Invalid filenameLookup dictionary version: %ld. Filename: %s", (long)version, filename); - return; - } - - setFilenameLookupDictionary((CCDictionary*)pDict->objectForKey("filenames")); - } - } -} - -void CCFileUtils::setFilenameLookupDictionary(CCDictionary* pFilenameLookupDict) -{ - CC_SAFE_RELEASE(m_pFilenameLookupDict); - m_pFilenameLookupDict = pFilenameLookupDict; - CC_SAFE_RETAIN(m_pFilenameLookupDict); -} - - -const char* CCFileUtils::fullPathFromRelativeFile(const char *pszFilename, const char *pszRelativeFile) -{ - std::string relativeFile = fullPathForFilename(pszRelativeFile); - CCString *pRet = CCString::create(""); - pRet->m_sString = relativeFile.substr(0, relativeFile.rfind('/')+1); - pRet->m_sString += getNewFilename(pszFilename); - return pRet->m_sString.c_str(); -} - -CCDictionary* ccFileUtils_dictionaryWithContentsOfFileThreadSafe(const char *pFileName) -{ - std::string fullPath = CCFileUtils::sharedFileUtils()->fullPathForFilename(pFileName); - NSString* pPath = [NSString stringWithUTF8String:fullPath.c_str()]; - NSDictionary* pDict = [NSDictionary dictionaryWithContentsOfFile:pPath]; - - CCDictionary* pRet = new CCDictionary(); - for (id key in [pDict allKeys]) { - id value = [pDict objectForKey:key]; - static_addValueToCCDict(key, value, pRet); - } - - return pRet; -} - -CCArray* ccFileUtils_arrayWithContentsOfFileThreadSafe(const char* pFileName) -{ - NSString* pPath = [NSString stringWithUTF8String:pFileName]; - NSString* pathExtension= [pPath pathExtension]; - pPath = [pPath stringByDeletingPathExtension]; - pPath = [[NSBundle mainBundle] pathForResource:pPath ofType:pathExtension]; - NSArray* pArray = [NSArray arrayWithContentsOfFile:pPath]; - - CCArray* pRet = new CCArray(); - for (id value in pArray) { - static_addItemToCCArray(value, pRet); - } - - return pRet; -} - -unsigned char* CCFileUtils::getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize) -{ - unsigned char * pBuffer = NULL; - CCAssert(pszFileName != NULL && pSize != NULL && pszMode != NULL, "Invaild parameters."); - *pSize = 0; - do - { - std::string fullPath = fullPathForFilename(pszFileName); - // read the file from hardware - FILE *fp = fopen(fullPath.c_str(), pszMode); - CC_BREAK_IF(!fp); - - fseek(fp,0,SEEK_END); - *pSize = ftell(fp); - fseek(fp,0,SEEK_SET); - pBuffer = new unsigned char[*pSize]; - *pSize = fread(pBuffer,sizeof(unsigned char), *pSize,fp); - fclose(fp); - } while (0); - - if (! pBuffer && isPopupNotify()) - { - std::string title = "Notification"; - std::string msg = "Get data from file("; - msg.append(pszFileName).append(") failed!"); - - CCMessageBox(msg.c_str(), title.c_str()); - } - return pBuffer; -} - -// notification support when getFileData from a invalid file -static bool s_bPopupNotify = true; - -void CCFileUtils::setPopupNotify(bool bNotify) -{ - s_bPopupNotify = bNotify; -} - -bool CCFileUtils::isPopupNotify() -{ - return s_bPopupNotify; -} - -std::string CCFileUtils::getWriteablePath() -{ - // save to document folder - NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); - NSString *documentsDirectory = [paths objectAtIndex:0]; - std::string strRet = [documentsDirectory UTF8String]; - strRet.append("/"); - return strRet; -} - -unsigned char* CCFileUtils::getFileDataFromZip(const char* pszZipFilePath, const char* pszFileName, unsigned long * pSize) -{ - unsigned char * pBuffer = NULL; - unzFile pFile = NULL; - *pSize = 0; - - do - { - CC_BREAK_IF(!pszZipFilePath || !pszFileName); - CC_BREAK_IF(strlen(pszZipFilePath) == 0); - - pFile = unzOpen(pszZipFilePath); - CC_BREAK_IF(!pFile); - - int nRet = unzLocateFile(pFile, pszFileName, 1); - CC_BREAK_IF(UNZ_OK != nRet); - - char szFilePathA[260]; - unz_file_info FileInfo; - nRet = unzGetCurrentFileInfo(pFile, &FileInfo, szFilePathA, sizeof(szFilePathA), NULL, 0, NULL, 0); - CC_BREAK_IF(UNZ_OK != nRet); - - nRet = unzOpenCurrentFile(pFile); - CC_BREAK_IF(UNZ_OK != nRet); - - pBuffer = new unsigned char[FileInfo.uncompressed_size]; - int nSize = 0; - nSize = unzReadCurrentFile(pFile, pBuffer, FileInfo.uncompressed_size); - CCAssert(nSize == 0 || nSize == (int)FileInfo.uncompressed_size, "the file size is wrong"); - - *pSize = FileInfo.uncompressed_size; - unzCloseCurrentFile(pFile); - } while (0); - - if (pFile) - { - unzClose(pFile); - } - - return pBuffer; -} - -NS_CC_END - diff --git a/cocos2dx/platform/mac/CCFileUtilsMac.h b/cocos2dx/platform/mac/CCFileUtilsMac.h new file mode 100644 index 0000000000..1b5e8252ec --- /dev/null +++ b/cocos2dx/platform/mac/CCFileUtilsMac.h @@ -0,0 +1,61 @@ +/**************************************************************************** + Copyright (c) 2010 cocos2d-x.org + + 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_FILEUTILSMAC_H__ +#define __CC_FILEUTILSMAC_H__ + +#include "CCFileUtils.h" +#include +#include +#include "CCPlatformMacros.h" +#include "ccTypes.h" +#include "ccTypeInfo.h" + +NS_CC_BEGIN +/** + * @addtogroup platform + * @{ + */ + +//! @brief Helper class to handle file operations +class CC_DLL CCFileUtilsMac : public CCFileUtils +{ +public: + /* override funtions */ + virtual std::string getWriteablePath(); + virtual bool isFileExist(const std::string& strFilePath); + virtual bool isAbsolutePath(const std::string& strPath); + virtual std::string getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename); + + virtual CCDictionary* createCCDictionaryWithContentsOfFile(const std::string& filename); + virtual CCArray* createCCArrayWithContentsOfFile(const std::string& filename); + +}; + +// end of platform group +/// @} + +NS_CC_END + +#endif // __CC_FILEUTILSMAC_H__ + diff --git a/cocos2dx/platform/mac/CCFileUtilsMac.mm b/cocos2dx/platform/mac/CCFileUtilsMac.mm new file mode 100644 index 0000000000..f57db512e3 --- /dev/null +++ b/cocos2dx/platform/mac/CCFileUtilsMac.mm @@ -0,0 +1,255 @@ +/**************************************************************************** +Copyright (c) 2010-2012 cocos2d-x.org +Copyright (c) 2011 Zynga 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 "CCFileUtilsMac.h" +#import +#include +#include +#include "cocoa/CCString.h" +#include "CCFileUtils.h" +#include "CCDirector.h" +#include "CCSAXParser.h" +#include "CCDictionary.h" +#include "support/zip_support/unzip.h" + +NS_CC_BEGIN + +static void addValueToCCDict(id key, id value, CCDictionary* pDict); + +static void addItemToCCArray(id item, CCArray *pArray) +{ + // add string value into array + if ([item isKindOfClass:[NSString class]]) { + CCString* pValue = new CCString([item UTF8String]); + + pArray->addObject(pValue); + pValue->release(); + return; + } + + // add number value into array(such as int, float, bool and so on) + if ([item isKindOfClass:[NSNumber class]]) { + NSString* pStr = [item stringValue]; + CCString* pValue = new CCString([pStr UTF8String]); + + pArray->addObject(pValue); + pValue->release(); + return; + } + + // add dictionary value into array + if ([item isKindOfClass:[NSDictionary class]]) { + CCDictionary* pDictItem = new CCDictionary(); + for (id subKey in [item allKeys]) { + id subValue = [item objectForKey:subKey]; + addValueToCCDict(subKey, subValue, pDictItem); + } + pArray->addObject(pDictItem); + pDictItem->release(); + return; + } + + // add array value into array + if ([item isKindOfClass:[NSArray class]]) { + CCArray *pArrayItem = new CCArray(); + pArrayItem->init(); + for (id subItem in item) { + addItemToCCArray(subItem, pArrayItem); + } + pArray->addObject(pArrayItem); + pArrayItem->release(); + return; + } +} + +static void addValueToCCDict(id key, id value, CCDictionary* pDict) +{ + // the key must be a string + CCAssert([key isKindOfClass:[NSString class]], "The key should be a string!"); + std::string pKey = [key UTF8String]; + + // the value is a new dictionary + if ([value isKindOfClass:[NSDictionary class]]) { + CCDictionary* pSubDict = new CCDictionary(); + for (id subKey in [value allKeys]) { + id subValue = [value objectForKey:subKey]; + addValueToCCDict(subKey, subValue, pSubDict); + } + pDict->setObject(pSubDict, pKey.c_str()); + pSubDict->release(); + return; + } + + // the value is a string + if ([value isKindOfClass:[NSString class]]) { + CCString* pValue = new CCString([value UTF8String]); + + pDict->setObject(pValue, pKey.c_str()); + pValue->release(); + return; + } + + // the value is a number + if ([value isKindOfClass:[NSNumber class]]) { + NSString* pStr = [value stringValue]; + CCString* pValue = new CCString([pStr UTF8String]); + + pDict->setObject(pValue, pKey.c_str()); + pValue->release(); + return; + } + + // the value is a array + if ([value isKindOfClass:[NSArray class]]) { + CCArray *pArray = new CCArray(); + pArray->init(); + for (id item in value) { + addItemToCCArray(item, pArray); + } + pDict->setObject(pArray, pKey.c_str()); + pArray->release(); + return; + } +} + +CCFileUtils* CCFileUtils::sharedFileUtils() +{ + if (s_sharedFileUtils == NULL) + { + s_sharedFileUtils = new CCFileUtilsMac(); + s_sharedFileUtils->init(); + } + return s_sharedFileUtils; +} + + +static NSFileManager* s_fileManager = [NSFileManager defaultManager]; + +std::string CCFileUtilsMac::getWriteablePath() +{ + // save to document folder + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); + NSString *documentsDirectory = [paths objectAtIndex:0]; + std::string strRet = [documentsDirectory UTF8String]; + strRet.append("/"); + return strRet; +} + +bool CCFileUtilsMac::isFileExist(const std::string& strFilePath) +{ + bool bRet = false; + + if (strFilePath[0] != '/') + { + std::string path = strFilePath; + std::string file; + size_t pos = path.find_last_of("/"); + if (pos != std::string::npos) + { + file = path.substr(pos+1); + path = path.substr(0, pos+1); + NSString* fullpath = [[NSBundle mainBundle] pathForResource:[NSString stringWithUTF8String:file.c_str()] + ofType:nil + inDirectory:[NSString stringWithUTF8String:path.c_str()]]; + if (fullpath != nil) { + bRet = true; + } + } + } + else + { + // Search path is an absolute path. + if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:strFilePath.c_str()]]) { + bRet = true; + } + } + + return bRet; +} + +std::string CCFileUtilsMac::getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename) +{ + if (strDirectory[0] != '/') + { + NSString* fullpath = [[NSBundle mainBundle] pathForResource:[NSString stringWithUTF8String:strFilename.c_str()] + ofType:nil + inDirectory:[NSString stringWithUTF8String:strDirectory.c_str()]]; + if (fullpath != nil) { + return [fullpath UTF8String]; + } + } + else + { + std::string fullPath = strDirectory+strFilename; + // Search path is an absolute path. + if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:fullPath.c_str()]]) { + return fullPath; + } + } + return ""; +} + +bool CCFileUtilsMac::isAbsolutePath(const std::string& strPath) +{ + NSString* path = [NSString stringWithUTF8String:strPath.c_str()]; + return [path isAbsolutePath] ? true : false; +} + +CCDictionary* CCFileUtilsMac::createCCDictionaryWithContentsOfFile(const std::string& filename) +{ + std::string fullPath = CCFileUtils::sharedFileUtils()->fullPathForFilename(filename.c_str()); + NSString* pPath = [NSString stringWithUTF8String:fullPath.c_str()]; + NSDictionary* pDict = [NSDictionary dictionaryWithContentsOfFile:pPath]; + + CCDictionary* pRet = new CCDictionary(); + for (id key in [pDict allKeys]) { + id value = [pDict objectForKey:key]; + addValueToCCDict(key, value, pRet); + } + + return pRet; +} + +CCArray* CCFileUtilsMac::createCCArrayWithContentsOfFile(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 CCArray::createWithContentsOfFile + std::string fullPath = CCFileUtils::sharedFileUtils()->fullPathForFilename(filename.c_str()); + NSString* pPath = [NSString stringWithUTF8String:fullPath.c_str()]; + NSArray* pArray = [NSArray arrayWithContentsOfFile:pPath]; + + CCArray* pRet = new CCArray(); + for (id value in pArray) { + addItemToCCArray(value, pRet); + } + + return pRet; +} + + +NS_CC_END + diff --git a/cocos2dx/platform/marmalade/CCFileUtils.cpp b/cocos2dx/platform/marmalade/CCFileUtils.cpp deleted file mode 100644 index c7459fb322..0000000000 --- a/cocos2dx/platform/marmalade/CCFileUtils.cpp +++ /dev/null @@ -1,248 +0,0 @@ -/**************************************************************************** - Copyright (c) 2011 cocos2d-x.org http://cocos2d-x.org - Copyright (c) 2011 Максим Аксенов - Copyright (c) 2011 Giovanni Zito, Francis Styck - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#define __CC_PLATFORM_FILEUTILS_CPP__ -#include "CCFileUtils.h" -#include "CCFileUtilsCommon_cpp.h" -#include "string.h" -#include "stack" -#include "CCString.h" - -#include "CCApplication.h" - -#include "IwDebug.h" // for CCLog - - -NS_CC_BEGIN; - - -static CCFileUtils* s_pFileUtils = NULL; -static std::map s_fullPathCache; - -CCFileUtils* CCFileUtils::sharedFileUtils() -{ - if (s_pFileUtils == NULL) - { - s_pFileUtils = new CCFileUtils(); - s_pFileUtils->init(); - } - return s_pFileUtils; -} - -bool CCFileUtils::init() -{ - m_strDefaultResRootPath = ""; - m_searchPathArray.push_back(m_strDefaultResRootPath); - m_searchResolutionsOrderArray.push_back(""); - - return true; -} - -void CCFileUtils::purgeFileUtils() -{ - if (s_pFileUtils != NULL) - { - s_pFileUtils->purgeCachedEntries(); - CC_SAFE_RELEASE(s_pFileUtils->m_pFilenameLookupDict); - } - - CC_SAFE_DELETE(s_pFileUtils); -} - -void CCFileUtils::purgeCachedEntries() -{ - s_fullPathCache.clear(); -} - -std::string CCFileUtils::getPathForFilename(const std::string& filename, const std::string& resourceDirectory, const std::string& searchPath) -{ - std::string file = filename; - std::string file_path = ""; - size_t pos = filename.find_last_of("/"); - if (pos != std::string::npos) - { - file_path = filename.substr(0, pos+1); - file = filename.substr(pos+1); - } - - // searchPath + file_path + resourceDirectory - std::string path = searchPath; - if (path.size() > 0 && path[path.length()-1] != '/') - { - path += "/"; - } - path += file_path; - path += resourceDirectory; - - if (path.size() > 0 && path[path.length()-1] != '/') - { - path += "/"; - } - path += file; - - return path; -} - -std::string CCFileUtils::fullPathForFilename(const char* pszFileName) -{ - // TODO HOW ARE WE SUPPOSED TO WRITE BACK TO THE "ignore" REFERENCE? - IwAssert(GAME, pszFileName); - - // Return directly if it's an absolute path. - if (pszFileName[0] == '/') - { - //CCLOG("Return absolute path( %s ) directly.", pszFileName); - return pszFileName; - } - - // Already Cached ? - std::map::iterator cacheIter = s_fullPathCache.find(pszFileName); - if (cacheIter != s_fullPathCache.end()) { - //CCLOG("Return full path from cache: %s", cacheIter->second.c_str()); - return cacheIter->second; - } - - std::string newFileName = getNewFilename(pszFileName); - std::string fullpath; - - for (std::vector::iterator searchPathsIter = m_searchPathArray.begin(); - searchPathsIter != m_searchPathArray.end(); ++searchPathsIter) { - for (std::vector::iterator resOrderIter = m_searchResolutionsOrderArray.begin(); - resOrderIter != m_searchResolutionsOrderArray.end(); ++resOrderIter) { - - //CCLOG("\n\nSEARCHING: %s, %s, %s", newFileName.c_str(), resOrderIter->c_str(), searchPathsIter->c_str()); - - fullpath = this->getPathForFilename(newFileName, *resOrderIter, *searchPathsIter); - - // check if file or path exist - if (s3eFileCheckExists(fullpath.c_str()) == S3E_TRUE) - { - // Adding the full path to cache if the file was found. - s_fullPathCache.insert(std::pair(pszFileName, fullpath)); - //CCLOG("Returning path: %s", fullpath.c_str()); - return fullpath; - } - } - } - - // The file wasn't found, return the file name passed in. - return pszFileName; -} - -const char* CCFileUtils::fullPathFromRelativePath(const char *pszRelativePath) -{ - return CCString::create(fullPathForFilename(pszRelativePath))->getCString(); -} - - -const char *CCFileUtils::fullPathFromRelativeFile(const char *pszFilename, const char *pszRelativeFile) -{ - std::string relativeFile = pszRelativeFile; - CCString *pRet = CCString::create(""); - pRet->m_sString = relativeFile.substr(0, relativeFile.rfind('/')+1); - pRet->m_sString += getNewFilename(pszFilename); - return pRet->m_sString.c_str(); -} - -unsigned char* CCFileUtils::getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize) -{ - IW_CALLSTACK("CCFileUtils::getFileData"); - - std::string fullPath = fullPathForFilename(pszFileName); - - s3eFile* pFile = s3eFileOpen(fullPath.c_str(), pszMode); - - if (! pFile && isPopupNotify()) - { - IwAssertMsg(GAME, pFile, ("Open file %s Failed. s3eFileError Code : %i", pszFileName, s3eFileGetError())); - } - if (! pFile) - { - *pSize = 0; - return 0; - } - int32 fileSize = s3eFileGetSize(pFile); - *pSize=fileSize; - - static int32* pDataToBeReadBinary; - - pDataToBeReadBinary = (int32*)s3eMallocBase(fileSize); - memset(pDataToBeReadBinary, 0, fileSize); - s3eFileRead(pDataToBeReadBinary, fileSize, 1, pFile); - s3eFileClose(pFile); - - return (unsigned char*)pDataToBeReadBinary; -} - -void CCFileUtils::setResourceDirectory(const char* pszResourceDirectory) -{ - if (pszResourceDirectory == NULL) return; - m_obDirectory = pszResourceDirectory; - std::vector searchPaths = this->getSearchPaths();; - searchPaths.insert(searchPaths.begin(), pszResourceDirectory); - this->setSearchPaths(searchPaths); -} - -void CCFileUtils::setSearchPaths(const std::vector& searchPaths) -{ - bool bExistDefaultRootPath = false; - - m_searchPathArray.clear(); - for (std::vector::const_iterator iter = searchPaths.begin(); iter != searchPaths.end(); ++iter) - { - std::string strPrefix; - std::string path; - if ((*iter)[0] != '/') - { // Not an absolute path - if (iter->find(m_strDefaultResRootPath) != 0) - { // The path contains no default resource root path, insert the root path. - strPrefix = m_strDefaultResRootPath; - } - } - path = strPrefix+(*iter); - if (path.length() > 0 && path[path.length()-1] != '/') - { - path += "/"; - } - if (!bExistDefaultRootPath && path == m_strDefaultResRootPath) - { - bExistDefaultRootPath = true; - } - m_searchPathArray.push_back(path); - } - - if (!bExistDefaultRootPath) - { - //CCLOG("Default root path doesn't exist, adding it."); - m_searchPathArray.push_back(m_strDefaultResRootPath); - } -} - -std::string CCFileUtils::getWriteablePath() -{ - return std::string("ram://"); -} - -NS_CC_END; - diff --git a/cocos2dx/platform/marmalade/CCFileUtilsMarmalade.cpp b/cocos2dx/platform/marmalade/CCFileUtilsMarmalade.cpp new file mode 100644 index 0000000000..b4e506e75b --- /dev/null +++ b/cocos2dx/platform/marmalade/CCFileUtilsMarmalade.cpp @@ -0,0 +1,75 @@ +#include "CCFileUtilsMarmalade.h" +#include "platform/CCCommon.h" +#include "ccMacros.h" +#include "CCApplication.h" +#include "cocoa/CCString.h" +#include "IwDebug.h" // for CCLog + +using namespace std; + +NS_CC_BEGIN + +CCFileUtils* CCFileUtils::sharedFileUtils() +{ + if (s_sharedFileUtils == NULL) + { + s_sharedFileUtils = new CCFileUtilsMarmalade(); + s_sharedFileUtils->init(); + } + return s_sharedFileUtils; +} + +CCFileUtilsMarmalade::CCFileUtilsMarmalade() +{} + + +string CCFileUtilsMarmalade::getWriteablePath() +{ + return std::string("ram://"); +} + +bool CCFileUtilsMarmalade::isFileExist(const std::string& strFilePath) +{ + return s3eFileCheckExists(strFilePath.c_str()) == S3E_TRUE ? true : false; +} + +unsigned char* CCFileUtilsMarmalade::getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize) +{ + IW_CALLSTACK("CCFileUtils::getFileData"); + + std::string fullPath = fullPathForFilename(pszFileName); + + s3eFile* pFile = s3eFileOpen(fullPath.c_str(), pszMode); + + if (! pFile && isPopupNotify()) + { + IwAssertMsg(GAME, pFile, ("Open file %s Failed. s3eFileError Code : %i", pszFileName, s3eFileGetError())); + } + if (! pFile) + { + *pSize = 0; + return 0; + } + int32 fileSize = s3eFileGetSize(pFile); + *pSize=fileSize; + + static int32* pDataToBeReadBinary; + + pDataToBeReadBinary = (int32*)s3eMallocBase(fileSize); + memset(pDataToBeReadBinary, 0, fileSize); + s3eFileRead(pDataToBeReadBinary, fileSize, 1, pFile); + s3eFileClose(pFile); + + return (unsigned char*)pDataToBeReadBinary; +} + +bool CCFileUtilsMarmalade::isAbsolutePath(const std::string& strPath) +{ + if (strPath[0] == '/' || strPath.find("ram://") == 0) + { + return true; + } + return false; +} + +NS_CC_END diff --git a/cocos2dx/platform/marmalade/CCFileUtilsMarmalade.h b/cocos2dx/platform/marmalade/CCFileUtilsMarmalade.h new file mode 100644 index 0000000000..3371797850 --- /dev/null +++ b/cocos2dx/platform/marmalade/CCFileUtilsMarmalade.h @@ -0,0 +1,60 @@ +/**************************************************************************** + Copyright (c) 2010 cocos2d-x.org + + 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_FILEUTILS_MARMALADE_H__ +#define __CC_FILEUTILS_MARMALADE_H__ + +#include "platform/CCFileUtils.h" +#include "platform/CCPlatformMacros.h" +#include "ccTypes.h" +#include "ccTypeInfo.h" +#include +#include + +NS_CC_BEGIN + +/** + * @addtogroup platform + * @{ + */ + +//! @brief Helper class to handle file operations +class CC_DLL CCFileUtilsMarmalade : public CCFileUtils +{ + friend class CCFileUtils; + CCFileUtilsMarmalade(); +public: + /* override funtions */ + virtual std::string getWriteablePath(); + virtual bool isFileExist(const std::string& strFilePath); + virtual bool isAbsolutePath(const std::string& strPath); + virtual unsigned char* getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize); +}; + +// end of platform group +/// @} + +NS_CC_END + +#endif // __CC_FILEUTILS_MARMALADE_H__ + diff --git a/cocos2dx/platform/marmalade/CCImage.cpp b/cocos2dx/platform/marmalade/CCImage.cpp index 05ec65c413..cdb1594c1d 100644 --- a/cocos2dx/platform/marmalade/CCImage.cpp +++ b/cocos2dx/platform/marmalade/CCImage.cpp @@ -24,7 +24,7 @@ #include #include #include - +#include #include "CCImage.h" #include "CCCommon.h" #include "CCStdC.h" @@ -863,7 +863,13 @@ bool CCImage::initWithString( BitmapDC &dc = sharedBitmapDC(); - std::string fullFontName = CCFileUtils::sharedFileUtils()->fullPathForFilename(pFontName); + std::string fullFontName = pFontName; + std::string lowerCasePath = fullFontName; + std::transform(lowerCasePath.begin(), lowerCasePath.end(), lowerCasePath.begin(), ::tolower); + + if ( lowerCasePath.find(".ttf") != std::string::npos ) { + fullFontName = CCFileUtils::sharedFileUtils()->fullPathForFilename(pFontName); + } CC_BREAK_IF(! dc.getBitmap(pText, nWidth, nHeight, eAlignMask, fullFontName.c_str(), nSize)); diff --git a/cocos2dx/platform/win32/CCFileUtils.cpp b/cocos2dx/platform/win32/CCFileUtils.cpp deleted file mode 100644 index ad8718daec..0000000000 --- a/cocos2dx/platform/win32/CCFileUtils.cpp +++ /dev/null @@ -1,299 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ -#define __CC_PLATFORM_FILEUTILS_CPP__ -#include "platform/CCFileUtilsCommon_cpp.h" -#include -#include "CCDirector.h" -#include "CCApplication.h" - -using namespace std; - -NS_CC_BEGIN - -// record the resource path -static char s_pszResourcePath[MAX_PATH] = {0}; -static std::map s_fullPathCache; - -static void _CheckPath() -{ - if (! s_pszResourcePath[0]) - { - WCHAR wszPath[MAX_PATH] = {0}; - int nNum = WideCharToMultiByte(CP_ACP, 0, wszPath, - GetCurrentDirectoryW(sizeof(wszPath), wszPath), - s_pszResourcePath, MAX_PATH, NULL, NULL); - s_pszResourcePath[nNum] = '\\'; - } -} - -static CCFileUtils* s_pFileUtils = NULL; - -CCFileUtils* CCFileUtils::sharedFileUtils() -{ - if (s_pFileUtils == NULL) - { - _CheckPath(); - s_pFileUtils = new CCFileUtils(); - s_pFileUtils->init(); - } - return s_pFileUtils; -} - -void CCFileUtils::purgeFileUtils() -{ - if (s_pFileUtils != NULL) - { - s_pFileUtils->purgeCachedEntries(); - CC_SAFE_RELEASE(s_pFileUtils->m_pFilenameLookupDict); - } - - CC_SAFE_DELETE(s_pFileUtils); -} - -void CCFileUtils::purgeCachedEntries() -{ - s_fullPathCache.clear(); -} - -bool CCFileUtils::init() -{ - m_strDefaultResRootPath = s_pszResourcePath; - m_searchPathArray.push_back(m_strDefaultResRootPath); - m_searchResolutionsOrderArray.push_back(""); - - return true; -} - -const char* CCFileUtils::fullPathFromRelativePath(const char *pszRelativePath) -{ - return CCString::create(fullPathForFilename(pszRelativePath))->getCString(); -} - -std::string CCFileUtils::getPathForFilename(const std::string& filename, const std::string& resourceDirectory, const std::string& searchPath) -{ - std::string file = filename; - std::string file_path = ""; - size_t pos = filename.find_last_of("/"); - if (pos != std::string::npos) - { - file_path = filename.substr(0, pos+1); - file = filename.substr(pos+1); - } - - // searchPath + file_path + resourceDirectory - std::string path = searchPath; - if (path.size() > 0 && path[path.length()-1] != '/') - { - path += "/"; - } - path += file_path; - path += resourceDirectory; - - if (path.size() > 0 && path[path.length()-1] != '/') - { - path += "/"; - } - path += file; - - return path; -} - -std::string CCFileUtils::fullPathForFilename(const char* pszFileName) -{ - CCAssert(pszFileName != NULL, "CCFileUtils: Invalid path"); - - // Return directly if it's an absolute path. - if (strlen(pszFileName) > 3 - && pszFileName[0] >= 'a' && pszFileName[0] <= 'z' - && pszFileName[0] >= 'A' && pszFileName[0] <= 'Z' - && (pszFileName[1] == ':') - && (pszFileName[2] == '\\' || pszFileName[2] == '/') - ) - { - //CCLOG("Probably invoking fullPathForFilename recursively, return the full path: %s", pszFileName); - return pszFileName; - } - - // Already Cached ? - std::map::iterator cacheIter = s_fullPathCache.find(pszFileName); - if (cacheIter != s_fullPathCache.end()) { - //CCLOG("Return full path from cache: %s", cacheIter->second.c_str()); - return cacheIter->second; - } - - std::string newFileName = getNewFilename(pszFileName); - std::string fullpath; - - for (std::vector::iterator searchPathsIter = m_searchPathArray.begin(); - searchPathsIter != m_searchPathArray.end(); ++searchPathsIter) { - for (std::vector::iterator resOrderIter = m_searchResolutionsOrderArray.begin(); - resOrderIter != m_searchResolutionsOrderArray.end(); ++resOrderIter) { - - fullpath = this->getPathForFilename(newFileName, *resOrderIter, *searchPathsIter); - - if (GetFileAttributesA(fullpath.c_str()) != -1) - { - // Adding the full path to cache if the file was found. - s_fullPathCache.insert(std::pair(pszFileName, fullpath)); - //CCLOG("Returning path: %s", fullpath.c_str()); - return fullpath; - } - } - } - - // The file wasn't found, return the file name passed in. - return pszFileName; -} - -const char *CCFileUtils::fullPathFromRelativeFile(const char *pszFilename, const char *pszRelativeFile) -{ - std::string relativeFile = pszRelativeFile; - CCString *pRet = CCString::create(""); - pRet->m_sString = relativeFile.substr(0, relativeFile.find_last_of("/\\") + 1); - pRet->m_sString += getNewFilename(pszFilename); - return pRet->m_sString.c_str(); -} - -unsigned char* CCFileUtils::getFileData(const char* pszFileName, const char* pszMode, unsigned long* pSize) -{ - unsigned char* pBuffer = NULL; - CCAssert(pszFileName != NULL && pSize != NULL && pszMode != NULL, "Invaild parameters."); - *pSize = 0; - do - { - std::string fullPath = fullPathForFilename(pszFileName); - // read the file from hardware - FILE *fp = fopen(fullPath.c_str(), pszMode); - CC_BREAK_IF(!fp); - - fseek(fp,0,SEEK_END); - *pSize = ftell(fp); - fseek(fp,0,SEEK_SET); - pBuffer = new unsigned char[*pSize]; - *pSize = fread(pBuffer,sizeof(unsigned char), *pSize,fp); - fclose(fp); - } while (0); - - if (! pBuffer && isPopupNotify()) - { - std::string title = "Notification"; - std::string msg = "Get data from file("; - msg.append(pszFileName).append(") failed!"); - - CCMessageBox(msg.c_str(), title.c_str()); - } - return pBuffer; -} - -void CCFileUtils::setResourceDirectory(const char* pszResourceDirectory) -{ - if (pszResourceDirectory == NULL) return; - m_obDirectory = pszResourceDirectory; - std::vector searchPaths = this->getSearchPaths();; - searchPaths.insert(searchPaths.begin(), pszResourceDirectory); - this->setSearchPaths(searchPaths); -} - -void CCFileUtils::setSearchPaths(const std::vector& searchPaths) -{ - bool bExistDefaultRootPath = false; - - m_searchPathArray.clear(); - for (std::vector::const_iterator iter = searchPaths.begin(); iter != searchPaths.end(); ++iter) - { - std::string strPrefix; - std::string path; - if (iter->length() > 1 && (*iter)[1] != ':') - { // Not an absolute path - if (iter->find(m_strDefaultResRootPath) != 0) - { // The path contains no default resource root path, insert the root path. - strPrefix = m_strDefaultResRootPath; - } - } - path = strPrefix+(*iter); - if (path.length() > 0 && path[path.length()-1] != '/' && path[path.length()-1] != '\\') - { - path += "/"; - } - if (!bExistDefaultRootPath && path == m_strDefaultResRootPath) - { - bExistDefaultRootPath = true; - } - m_searchPathArray.push_back(path); - } - - if (!bExistDefaultRootPath) - { - //CCLOG("Default root path doesn't exist, adding it."); - m_searchPathArray.push_back(m_strDefaultResRootPath); - } -} - -string CCFileUtils::getWriteablePath() -{ - // Get full path of executable, e.g. c:\Program Files (x86)\My Game Folder\MyGame.exe - char full_path[_MAX_PATH + 1]; - ::GetModuleFileNameA(NULL, full_path, _MAX_PATH + 1); - - // Debug app uses executable directory; Non-debug app uses local app data directory -#ifndef _DEBUG - // Get filename of executable only, e.g. MyGame.exe - char *base_name = strrchr(full_path, '\\'); - - if(base_name) - { - char app_data_path[_MAX_PATH + 1]; - - // Get local app data directory, e.g. C:\Documents and Settings\username\Local Settings\Application Data - if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, app_data_path))) - { - string ret((char*)app_data_path); - - // Adding executable filename, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame.exe - ret += base_name; - - // Remove ".exe" extension, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame - ret = ret.substr(0, ret.rfind(".")); - - ret += "\\"; - - // Create directory - if (SUCCEEDED(SHCreateDirectoryExA(NULL, ret.c_str(), NULL))) - { - return ret; - } - } - } -#endif // not defined _DEBUG - - // If fetching of local app data directory fails, use the executable one - string ret((char*)full_path); - - // remove xxx.exe - ret = ret.substr(0, ret.rfind("\\") + 1); - - return ret; -} - -NS_CC_END diff --git a/cocos2dx/platform/win32/CCFileUtilsWin32.cpp b/cocos2dx/platform/win32/CCFileUtilsWin32.cpp new file mode 100644 index 0000000000..9993fbb5de --- /dev/null +++ b/cocos2dx/platform/win32/CCFileUtilsWin32.cpp @@ -0,0 +1,134 @@ +/**************************************************************************** +Copyright (c) 2010 cocos2d-x.org + +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 "CCFileUtilsWin32.h" +#include "platform/CCCommon.h" +#include + +using namespace std; + +NS_CC_BEGIN + +static char s_pszResourcePath[MAX_PATH] = {0}; + +static void _checkPath() +{ + if (! s_pszResourcePath[0]) + { + WCHAR wszPath[MAX_PATH] = {0}; + int nNum = WideCharToMultiByte(CP_ACP, 0, wszPath, + GetCurrentDirectoryW(sizeof(wszPath), wszPath), + s_pszResourcePath, MAX_PATH, NULL, NULL); + s_pszResourcePath[nNum] = '\\'; + } +} + +CCFileUtils* CCFileUtils::sharedFileUtils() +{ + if (s_sharedFileUtils == NULL) + { + s_sharedFileUtils = new CCFileUtilsWin32(); + s_sharedFileUtils->init(); + } + return s_sharedFileUtils; +} + +CCFileUtilsWin32::CCFileUtilsWin32() +{ +} + +bool CCFileUtilsWin32::init() +{ + _checkPath(); + m_strDefaultResRootPath = s_pszResourcePath; + return CCFileUtils::init(); +} + +bool CCFileUtilsWin32::isFileExist(const std::string& strFilePath) +{ + std::string strPath = strFilePath; + if (!isAbsolutePath(strPath)) + { // Not absolute path, add the default root path at the beginning. + strPath.insert(0, m_strDefaultResRootPath); + } + return GetFileAttributesA(strPath.c_str()) != -1 ? true : false; +} + +bool CCFileUtilsWin32::isAbsolutePath(const std::string& strPath) +{ + if ( strPath.length() > 2 + && ( (strPath[0] >= 'a' && strPath[0] <= 'z') || (strPath[0] >= 'A' && strPath[0] <= 'Z') ) + && strPath[1] == ':') + { + return true; + } + return false; +} + +string CCFileUtilsWin32::getWriteablePath() +{ + // Get full path of executable, e.g. c:\Program Files (x86)\My Game Folder\MyGame.exe + char full_path[_MAX_PATH + 1]; + ::GetModuleFileNameA(NULL, full_path, _MAX_PATH + 1); + + // Debug app uses executable directory; Non-debug app uses local app data directory +#ifndef _DEBUG + // Get filename of executable only, e.g. MyGame.exe + char *base_name = strrchr(full_path, '\\'); + + if(base_name) + { + char app_data_path[_MAX_PATH + 1]; + + // Get local app data directory, e.g. C:\Documents and Settings\username\Local Settings\Application Data + if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, app_data_path))) + { + string ret((char*)app_data_path); + + // Adding executable filename, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame.exe + ret += base_name; + + // Remove ".exe" extension, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame + ret = ret.substr(0, ret.rfind(".")); + + ret += "\\"; + + // Create directory + if (SUCCEEDED(SHCreateDirectoryExA(NULL, ret.c_str(), NULL))) + { + return ret; + } + } + } +#endif // not defined _DEBUG + + // If fetching of local app data directory fails, use the executable one + string ret((char*)full_path); + + // remove xxx.exe + ret = ret.substr(0, ret.rfind("\\") + 1); + + return ret; +} + +NS_CC_END diff --git a/cocos2dx/platform/win32/CCFileUtilsWin32.h b/cocos2dx/platform/win32/CCFileUtilsWin32.h new file mode 100644 index 0000000000..e8946f4ef7 --- /dev/null +++ b/cocos2dx/platform/win32/CCFileUtilsWin32.h @@ -0,0 +1,60 @@ +/**************************************************************************** + Copyright (c) 2010 cocos2d-x.org + + 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_FILEUTILS_WIN32_H__ +#define __CC_FILEUTILS_WIN32_H__ + +#include "platform/CCFileUtils.h" +#include "platform/CCPlatformMacros.h" +#include "ccTypes.h" +#include "ccTypeInfo.h" +#include +#include + +NS_CC_BEGIN + +/** + * @addtogroup platform + * @{ + */ + +//! @brief Helper class to handle file operations +class CC_DLL CCFileUtilsWin32 : public CCFileUtils +{ + friend class CCFileUtils; + CCFileUtilsWin32(); +public: + /* override funtions */ + bool init(); + virtual std::string getWriteablePath(); + virtual bool isFileExist(const std::string& strFilePath); + virtual bool isAbsolutePath(const std::string& strPath); +}; + +// end of platform group +/// @} + +NS_CC_END + +#endif // __CC_FILEUTILS_WIN32_H__ + diff --git a/cocos2dx/proj.blackberry/.cproject b/cocos2dx/proj.blackberry/.cproject index 8390b0735d..33369afcae 100644 --- a/cocos2dx/proj.blackberry/.cproject +++ b/cocos2dx/proj.blackberry/.cproject @@ -92,7 +92,7 @@ - + @@ -190,7 +190,7 @@ - + @@ -293,7 +293,7 @@ - + @@ -357,7 +357,7 @@