Filesystem.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. /**
  2. * Copyright (c) 2006-2010 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include <common/config.h>
  21. #include <common/utf8.h>
  22. #include <common/b64.h>
  23. #include "Filesystem.h"
  24. namespace love
  25. {
  26. namespace filesystem
  27. {
  28. namespace physfs
  29. {
  30. Filesystem::Filesystem()
  31. : open_count(0), buffer(0), isInited(false)
  32. {
  33. }
  34. Filesystem::~Filesystem()
  35. {
  36. if(isInited)
  37. {
  38. isInited = false;
  39. PHYSFS_deinit();
  40. }
  41. }
  42. const char * Filesystem::getName() const
  43. {
  44. return "love.filesystem.physfs";
  45. }
  46. void Filesystem::init(const char * arg0)
  47. {
  48. if(!PHYSFS_init(arg0))
  49. throw Exception(PHYSFS_getLastError());
  50. isInited = true;
  51. }
  52. bool Filesystem::setIdentity( const char * ident )
  53. {
  54. if(!isInited)
  55. return false;
  56. // Store the save directory.
  57. save_identity = std::string(ident);
  58. // Generate the relative path to the game save folder.
  59. save_path_relative = std::string(LOVE_APPDATA_FOLDER LOVE_PATH_SEPARATOR) + save_identity;
  60. // Generate the full path to the game save folder.
  61. save_path_full = std::string(getAppdataDirectory()) + std::string(LOVE_PATH_SEPARATOR);
  62. save_path_full += save_path_relative;
  63. // We now have something like:
  64. // save_identity: game
  65. // save_path_relative: ./LOVE/game
  66. // save_path_full: C:\Documents and Settings\user\Application Data/LOVE/game
  67. // Try to add the save directory to the search path.
  68. // (No error on fail, it means that the path doesn't exist).
  69. PHYSFS_addToSearchPath(save_path_full.c_str(), 0);
  70. return true;
  71. }
  72. bool Filesystem::setSource(const char * source)
  73. {
  74. if(!isInited)
  75. return false;
  76. // Check whether directory is already set.
  77. if(!game_source.empty())
  78. return false;
  79. // Add the directory.
  80. if(!PHYSFS_addToSearchPath(source, 1))
  81. return false;
  82. // Save the game source.
  83. game_source = std::string(source);
  84. return true;
  85. }
  86. bool Filesystem::setupWriteDirectory()
  87. {
  88. if(!isInited)
  89. return false;
  90. // These must all be set.
  91. if(save_identity.empty() || save_path_full.empty() || save_path_relative.empty())
  92. return false;
  93. // Set the appdata folder as writable directory.
  94. // (We must create the save folder before mounting it).
  95. if(!PHYSFS_setWriteDir(getAppdataDirectory()))
  96. return false;
  97. // Create the save folder. (We're now "at" %APPDATA%).
  98. if(!mkdir(save_path_relative.c_str()))
  99. {
  100. PHYSFS_setWriteDir(0); // Clear the write directory in case of error.
  101. return false;
  102. }
  103. // Set the final write directory.
  104. if(!PHYSFS_setWriteDir(save_path_full.c_str()))
  105. return false;
  106. // Add the directory. (Will not be readded if already present).
  107. if(!PHYSFS_addToSearchPath(save_path_full.c_str(), 0))
  108. {
  109. PHYSFS_setWriteDir(0); // Clear the write directory in case of error.
  110. return false;
  111. }
  112. return true;
  113. }
  114. File * Filesystem::newFile(const char *filename)
  115. {
  116. return new File(filename);
  117. }
  118. FileData * Filesystem::newFileData(void * data, int size, const char * filename)
  119. {
  120. FileData * fd = new FileData(size, std::string(filename));
  121. // Copy the data into FileData.
  122. memcpy(fd->getData(), data, size);
  123. return fd;
  124. }
  125. FileData * Filesystem::newFileData(const char * b64, const char * filename)
  126. {
  127. int size = strlen(b64);
  128. int outsize = 0;
  129. char * dst = b64_decode(b64, size, outsize);
  130. FileData * fd = new FileData(outsize, std::string(filename));
  131. // Copy the data into FileData.
  132. memcpy(fd->getData(), dst, outsize);
  133. delete [] dst;
  134. return fd;
  135. }
  136. const char * Filesystem::getWorkingDirectory()
  137. {
  138. if(cwd.empty())
  139. {
  140. #ifdef LOVE_WINDOWS
  141. WCHAR w_cwd[LOVE_MAX_PATH];
  142. _wgetcwd(w_cwd, LOVE_MAX_PATH);
  143. cwd = to_utf8(w_cwd);
  144. replace_char(cwd, '\\', '/');
  145. #else
  146. char * cwd_char = new char[LOVE_MAX_PATH];
  147. getcwd(cwd_char, LOVE_MAX_PATH);
  148. cwd = cwd_char; // if getcwd fails, cwd_char (and thus cwd) will still be empty
  149. delete [] cwd_char;
  150. #endif
  151. }
  152. return cwd.c_str();
  153. }
  154. const char * Filesystem::getUserDirectory()
  155. {
  156. return PHYSFS_getUserDir();
  157. }
  158. const char * Filesystem::getAppdataDirectory()
  159. {
  160. #ifdef LOVE_WINDOWS
  161. if(appdata.empty())
  162. {
  163. wchar_t * w_appdata = _wgetenv(TEXT("APPDATA"));
  164. appdata = to_utf8(w_appdata);
  165. replace_char(appdata, '\\', '/');
  166. }
  167. return appdata.c_str();
  168. #elif defined(LOVE_MACOSX)
  169. if(appdata.empty())
  170. {
  171. std::string udir = getUserDirectory();
  172. udir.append("/Library/Application Support");
  173. appdata = udir;
  174. }
  175. return appdata.c_str();
  176. #elif defined(LOVE_LINUX)
  177. if(appdata.empty())
  178. {
  179. char * xdgdatahome = getenv("XDG_DATA_HOM");
  180. if (!xdgdatahome)
  181. appdata = getUserDirectory();
  182. else
  183. appdata = xdgdatahome;
  184. }
  185. return appdata.c_str();
  186. #else
  187. return getUserDirectory();
  188. #endif
  189. }
  190. const char * Filesystem::getSaveDirectory()
  191. {
  192. return save_path_full.c_str();
  193. }
  194. bool Filesystem::exists(const char * file)
  195. {
  196. if(PHYSFS_exists(file))
  197. return true;
  198. return false;
  199. }
  200. bool Filesystem::isDirectory(const char * file)
  201. {
  202. if(PHYSFS_isDirectory(file))
  203. return true;
  204. return false;
  205. }
  206. bool Filesystem::isFile(const char * file)
  207. {
  208. return exists(file) && !isDirectory(file);
  209. }
  210. bool Filesystem::mkdir(const char * file)
  211. {
  212. if(PHYSFS_getWriteDir() == 0 && !setupWriteDirectory())
  213. return false;
  214. if(!PHYSFS_mkdir(file))
  215. return false;
  216. return true;
  217. }
  218. bool Filesystem::remove(const char * file)
  219. {
  220. if(PHYSFS_getWriteDir() == 0 && !setupWriteDirectory())
  221. return false;
  222. if(!PHYSFS_delete(file))
  223. return false;
  224. return true;
  225. }
  226. int Filesystem::read(lua_State * L)
  227. {
  228. // The file to read from. The file must either be created
  229. // on-the-fly, or passed as a parameter.
  230. File * file;
  231. if(lua_isstring(L, 1))
  232. {
  233. // Create the file.
  234. file = newFile(lua_tostring(L, 1));
  235. }
  236. else
  237. return luaL_error(L, "Expected filename.");
  238. // Optionally, the caller can specify whether to read
  239. // the whole file, or just a part of it.
  240. int count = luaL_optint(L, 2, file->getSize());
  241. // Read the data.
  242. Data * data = file->read(count);
  243. // Error check.
  244. if(data == 0)
  245. return luaL_error(L, "File could not be read.");
  246. // Close and delete the file, if we created it.
  247. // (I.e. if the first parameter is a string).
  248. if(lua_isstring(L, 1))
  249. file->release();
  250. // Push the string.
  251. lua_pushlstring(L, (char*)data->getData(), data->getSize());
  252. // Push the size.
  253. lua_pushinteger(L, data->getSize());
  254. // Lua has a copy now, so we can free it.
  255. data->release();
  256. return 2;
  257. }
  258. int Filesystem::write(lua_State * L)
  259. {
  260. // The file to write to. The file must either be created
  261. // on-the-fly, or passed as a parameter.
  262. File * file;
  263. // We know for sure that we need a second parameter, so
  264. // let's check that first.
  265. if(lua_isnoneornil(L, 2))
  266. return luaL_error(L, "Second argument needed.");
  267. if(lua_isstring(L, 1))
  268. {
  269. // Create the file.
  270. file = newFile(lua_tostring(L, 1));
  271. }
  272. else
  273. return luaL_error(L, "Expected filename.");
  274. // Get the current mode of the file.
  275. File::Mode mode = file->getMode();
  276. if(mode == File::CLOSED)
  277. {
  278. // It should be possible to use append mode, but
  279. // normal File::Mode::Write is the default.
  280. int mode = luaL_optint(L, 4, File::WRITE);
  281. // Open the file.
  282. if(!file->open((File::Mode)mode))
  283. return luaL_error(L, "Could not open file.");
  284. }
  285. size_t length = 0;
  286. const char * input;
  287. if(lua_isstring(L, 2)) {
  288. input = lua_tolstring(L, 2, &length);
  289. } else if (luax_istype(L, 2, DATA_T)) {
  290. love::Data * data = luax_totype<love::Data>(L, 2, "Data", DATA_T);
  291. length = data->getSize();
  292. input = (char *)data->getData();
  293. } else {
  294. return luaL_error(L, "Expected string or data for argument #2.");
  295. }
  296. // Get how much we should write. Length of string default.
  297. length = luaL_optint(L, 3, length);
  298. // Write the data.
  299. bool success = file->write(input, length);
  300. // Close and delete the file, if we created
  301. // it in this function.
  302. if(lua_isstring(L, 1))
  303. {
  304. // Kill the file if "we" created it.
  305. file->close();
  306. file->release();
  307. }
  308. if(!success)
  309. return luaL_error(L, "Data could not be written.");
  310. lua_pushboolean(L, success);
  311. return 1;
  312. }
  313. int Filesystem::enumerate(lua_State * L)
  314. {
  315. int n = lua_gettop(L);
  316. if( n != 1 )
  317. return luaL_error(L, "Function requires a single parameter.");
  318. int type = lua_type(L, 1);
  319. if(type != LUA_TSTRING)
  320. return luaL_error(L, "Function requires parameter of type string.");
  321. const char * dir = lua_tostring(L, 1);
  322. char **rc = PHYSFS_enumerateFiles(dir);
  323. char **i;
  324. int index = 1;
  325. lua_newtable(L);
  326. for (i = rc; *i != 0; i++)
  327. {
  328. lua_pushinteger(L, index);
  329. lua_pushstring(L, *i);
  330. lua_settable(L, -3);
  331. index++;
  332. }
  333. PHYSFS_freeList(rc);
  334. return 1;
  335. }
  336. int Filesystem::lines(lua_State * L)
  337. {
  338. File * file;
  339. if(lua_isstring(L, 1))
  340. {
  341. file = newFile(lua_tostring(L, 1));
  342. if(!file->open(File::READ))
  343. return luaL_error(L, "Could not open file %s.\n", lua_tostring(L, 1));
  344. lua_pop(L, 1);
  345. luax_newtype(L, "File", FILESYSTEM_FILE_T, file, false);
  346. lua_pushboolean(L, 1); // 1 = autoclose.
  347. }
  348. else
  349. return luaL_error(L, "Expected filename.");
  350. // Reset the file position.
  351. if(!file->seek(0))
  352. return luaL_error(L, "File does not appear to be open.\n");
  353. lua_pushcclosure(L, lines_i, 2);
  354. return 1;
  355. }
  356. int Filesystem::lines_i(lua_State * L)
  357. {
  358. // We're using a 1k buffer.
  359. const static int bufsize = 8;
  360. static char buf[bufsize];
  361. File * file = luax_checktype<File>(L, lua_upvalueindex(1), "File", FILESYSTEM_FILE_T);
  362. int close = (int)lua_tointeger(L, lua_upvalueindex(2));
  363. // Find the next newline.
  364. // pos must be at the start of the line we're trying to find.
  365. int pos = file->tell();
  366. int newline = -1;
  367. int totalread = 0;
  368. while(!file->eof())
  369. {
  370. int current = file->tell();
  371. int read = file->read(buf, bufsize);
  372. totalread += read;
  373. if(read < 0)
  374. return luaL_error(L, "Readline failed!");
  375. for(int i = 0;i<read;i++)
  376. {
  377. if(buf[i] == '\n')
  378. {
  379. newline = current+i;
  380. break;
  381. }
  382. }
  383. if(newline > 0)
  384. break;
  385. }
  386. // Special case for the last "line".
  387. if(newline <= 0 && file->eof() && totalread > 0)
  388. newline = pos + totalread;
  389. // We've got a newline.
  390. if(newline > 0)
  391. {
  392. // Ok, we've got a line.
  393. int linesize = (newline-pos);
  394. // Allocate memory for the string.
  395. char * str = new char[linesize];
  396. // Read it.
  397. file->seek(pos);
  398. if(file->read(str, linesize) == -1)
  399. return luaL_error(L, "Read error.");
  400. if(str[linesize-1]=='\r')
  401. linesize -= 1;
  402. lua_pushlstring(L, str, linesize);
  403. // Free the memory. Lua has a copy now.
  404. delete[] str;
  405. // Set the beginning of the next line.
  406. if(!file->eof())
  407. file->seek(newline+1);
  408. return 1;
  409. }
  410. if(close)
  411. {
  412. file->close();
  413. file->release();
  414. }
  415. // else: (newline <= 0)
  416. return 0;
  417. }
  418. int Filesystem::load(lua_State * L)
  419. {
  420. // Need only one arg.
  421. luax_assert_argc(L, 1, 1);
  422. // Must be string.
  423. if(!lua_isstring(L, -1))
  424. return luaL_error(L, "The argument must be a string.");
  425. const char * filename = lua_tostring(L, -1);
  426. // The file must exist.
  427. if(!exists(filename))
  428. return luaL_error(L, "File %s does not exist.", filename);
  429. // Create the file.
  430. File * file = newFile(filename);
  431. // Get the data from the file.
  432. Data * data = file->read();
  433. int status = luaL_loadbuffer(L, (const char *)data->getData(), data->getSize(), filename);
  434. data->release();
  435. file->release();
  436. // Load the chunk, but don't run it.
  437. switch (status)
  438. {
  439. case LUA_ERRMEM:
  440. return luaL_error(L, "Memory allocation error: %s\n", lua_tostring(L, -1));
  441. case LUA_ERRSYNTAX:
  442. return luaL_error(L, "Syntax error: %s\n", lua_tostring(L, -1));
  443. default: // success
  444. return 1;
  445. }
  446. }
  447. } // physfs
  448. } // filesystem
  449. } // love