CCFileUtils-android.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /****************************************************************************
  2. Copyright (c) 2010-2012 cocos2d-x.org
  3. Copyright (c) 2013-2017 Chukong Technologies Inc.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #include "platform/CCPlatformConfig.h"
  22. #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
  23. #include "platform/android/CCFileUtils-android.h"
  24. #include "platform/CCCommon.h"
  25. #include "platform/android/jni/JniHelper.h"
  26. #include "platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
  27. #include "android/asset_manager.h"
  28. #include "android/asset_manager_jni.h"
  29. #include "base/ZipUtils.h"
  30. #include "base/CCDirector.h"
  31. #include "base/CCEventDispatcher.h"
  32. #include "base/CCEventType.h"
  33. #include <stdlib.h>
  34. #include <sys/stat.h>
  35. #define LOG_TAG "CCFileUtils-android.cpp"
  36. #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
  37. #define ASSETS_FOLDER_NAME "assets/"
  38. #define ASSETS_FOLDER_NAME_LENGTH 7
  39. using namespace std;
  40. NS_CC_BEGIN
  41. AAssetManager* FileUtilsAndroid::assetmanager = nullptr;
  42. ZipFile* FileUtilsAndroid::obbfile = nullptr;
  43. void FileUtilsAndroid::setassetmanager(AAssetManager* a) {
  44. if (nullptr == a) {
  45. LOGD("setassetmanager : received unexpected nullptr parameter");
  46. return;
  47. }
  48. cocos2d::FileUtilsAndroid::assetmanager = a;
  49. }
  50. FileUtils* FileUtils::getInstance()
  51. {
  52. if (s_sharedFileUtils == nullptr)
  53. {
  54. s_sharedFileUtils = new FileUtilsAndroid();
  55. if (!s_sharedFileUtils->init())
  56. {
  57. delete s_sharedFileUtils;
  58. s_sharedFileUtils = nullptr;
  59. CCLOG("ERROR: Could not init CCFileUtilsAndroid");
  60. }
  61. }
  62. return s_sharedFileUtils;
  63. }
  64. FileUtilsAndroid::FileUtilsAndroid()
  65. {
  66. }
  67. FileUtilsAndroid::~FileUtilsAndroid()
  68. {
  69. if (obbfile)
  70. {
  71. delete obbfile;
  72. obbfile = nullptr;
  73. }
  74. }
  75. bool FileUtilsAndroid::init()
  76. {
  77. _defaultResRootPath = ASSETS_FOLDER_NAME;
  78. std::string assetsPath(getApkPath());
  79. if (assetsPath.find("/obb/") != std::string::npos)
  80. {
  81. obbfile = new ZipFile(assetsPath);
  82. }
  83. return FileUtils::init();
  84. }
  85. std::string FileUtilsAndroid::getNewFilename(const std::string &filename) const
  86. {
  87. std::string newFileName = FileUtils::getNewFilename(filename);
  88. // ../xxx do not fix this path
  89. auto pos = newFileName.find("../");
  90. if (pos == std::string::npos || pos == 0)
  91. {
  92. return newFileName;
  93. }
  94. std::vector<std::string> v(3);
  95. v.resize(0);
  96. auto change = false;
  97. size_t size = newFileName.size();
  98. size_t idx = 0;
  99. bool noexit = true;
  100. while (noexit)
  101. {
  102. pos = newFileName.find('/', idx);
  103. std::string tmp;
  104. if (pos == std::string::npos)
  105. {
  106. tmp = newFileName.substr(idx, size - idx);
  107. noexit = false;
  108. }else
  109. {
  110. tmp = newFileName.substr(idx, pos - idx + 1);
  111. }
  112. auto t = v.size();
  113. if (t > 0 && v[t-1].compare("../") != 0 &&
  114. (tmp.compare("../") == 0 || tmp.compare("..") == 0))
  115. {
  116. v.pop_back();
  117. change = true;
  118. }else
  119. {
  120. v.push_back(tmp);
  121. }
  122. idx = pos + 1;
  123. }
  124. if (change)
  125. {
  126. newFileName.clear();
  127. for (auto &s : v)
  128. {
  129. newFileName.append(s);
  130. }
  131. }
  132. return newFileName;
  133. }
  134. bool FileUtilsAndroid::isFileExistInternal(const std::string& strFilePath) const
  135. {
  136. if (strFilePath.empty())
  137. {
  138. return false;
  139. }
  140. bool bFound = false;
  141. // Check whether file exists in apk.
  142. if (strFilePath[0] != '/')
  143. {
  144. const char* s = strFilePath.c_str();
  145. // Found "assets/" at the beginning of the path and we don't want it
  146. if (strFilePath.find(_defaultResRootPath) == 0) s += _defaultResRootPath.length();
  147. if (obbfile && obbfile->fileExists(s))
  148. {
  149. bFound = true;
  150. }
  151. else if (FileUtilsAndroid::assetmanager)
  152. {
  153. AAsset* aa = AAssetManager_open(FileUtilsAndroid::assetmanager, s, AASSET_MODE_UNKNOWN);
  154. if (aa)
  155. {
  156. bFound = true;
  157. AAsset_close(aa);
  158. } else {
  159. // CCLOG("[AssetManager] ... in APK %s, found = false!", strFilePath.c_str());
  160. }
  161. }
  162. }
  163. else
  164. {
  165. FILE *fp = fopen(strFilePath.c_str(), "r");
  166. if (fp)
  167. {
  168. bFound = true;
  169. fclose(fp);
  170. }
  171. }
  172. return bFound;
  173. }
  174. bool FileUtilsAndroid::isDirectoryExistInternal(const std::string& dirPath) const
  175. {
  176. if (dirPath.empty())
  177. {
  178. return false;
  179. }
  180. const char* s = dirPath.c_str();
  181. // find absolute path in flash memory
  182. if (s[0] == '/')
  183. {
  184. CCLOG("find in flash memory dirPath(%s)", s);
  185. struct stat st;
  186. if (stat(s, &st) == 0)
  187. {
  188. return S_ISDIR(st.st_mode);
  189. }
  190. }
  191. else
  192. {
  193. // find it in apk's assets dir
  194. // Found "assets/" at the beginning of the path and we don't want it
  195. CCLOG("find in apk dirPath(%s)", s);
  196. if (dirPath.find(ASSETS_FOLDER_NAME) == 0)
  197. {
  198. s += ASSETS_FOLDER_NAME_LENGTH;
  199. }
  200. if (FileUtilsAndroid::assetmanager)
  201. {
  202. AAssetDir* aa = AAssetManager_openDir(FileUtilsAndroid::assetmanager, s);
  203. if (aa && AAssetDir_getNextFileName(aa))
  204. {
  205. AAssetDir_close(aa);
  206. return true;
  207. }
  208. }
  209. }
  210. return false;
  211. }
  212. bool FileUtilsAndroid::isAbsolutePath(const std::string& strPath) const
  213. {
  214. // On Android, there are two situations for full path.
  215. // 1) Files in APK, e.g. assets/path/path/file.png
  216. // 2) Files not in APK, e.g. /data/data/org.cocos2dx.hellocpp/cache/path/path/file.png, or /sdcard/path/path/file.png.
  217. // So these two situations need to be checked on Android.
  218. if (strPath[0] == '/' || strPath.find(_defaultResRootPath) == 0)
  219. {
  220. return true;
  221. }
  222. return false;
  223. }
  224. FileUtils::Status FileUtilsAndroid::getContents(const std::string& filename, ResizableBuffer* buffer)
  225. {
  226. Director::getInstance()->getEventDispatcher()->dispatchCustomEvent(EVENT_BEFORE_READ_FILE);
  227. static const std::string apkprefix("assets/");
  228. if (filename.empty())
  229. return FileUtils::Status::NotExists;
  230. string fullPath = fullPathForFilename(filename);
  231. if (fullPath[0] == '/')
  232. return FileUtils::getContents(fullPath, buffer);
  233. string relativePath = string();
  234. size_t position = fullPath.find(apkprefix);
  235. if (0 == position) {
  236. // "assets/" is at the beginning of the path and we don't want it
  237. relativePath += fullPath.substr(apkprefix.size());
  238. } else {
  239. relativePath = fullPath;
  240. }
  241. if (obbfile)
  242. {
  243. if (obbfile->getFileData(relativePath, buffer))
  244. return FileUtils::Status::OK;
  245. }
  246. if (nullptr == assetmanager) {
  247. LOGD("... FileUtilsAndroid::assetmanager is nullptr");
  248. return FileUtils::Status::NotInitialized;
  249. }
  250. AAsset* asset = AAssetManager_open(assetmanager, relativePath.data(), AASSET_MODE_UNKNOWN);
  251. if (nullptr == asset) {
  252. LOGD("asset is nullptr");
  253. return FileUtils::Status::OpenFailed;
  254. }
  255. auto size = AAsset_getLength(asset);
  256. buffer->resize(size);
  257. int readsize = AAsset_read(asset, buffer->buffer(), size);
  258. AAsset_close(asset);
  259. if (readsize < size) {
  260. if (readsize >= 0)
  261. buffer->resize(readsize);
  262. return FileUtils::Status::ReadFailed;
  263. }
  264. return FileUtils::Status::OK;
  265. }
  266. string FileUtilsAndroid::getWritablePath() const
  267. {
  268. // Fix for Nexus 10 (Android 4.2 multi-user environment)
  269. // the path is retrieved through Java Context.getCacheDir() method
  270. string dir("");
  271. string tmp = JniHelper::callStaticStringMethod("org/cocos2dx/lib/Cocos2dxHelper", "getCocos2dxWritablePath");
  272. if (tmp.length() > 0)
  273. {
  274. dir.append(tmp).append("/");
  275. return dir;
  276. }
  277. else
  278. {
  279. return "";
  280. }
  281. }
  282. NS_CC_END
  283. #endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID