wrap_Filesystem.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. /**
  2. * Copyright (c) 2006-2015 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. // LOVE
  21. #include "wrap_Filesystem.h"
  22. #include "wrap_File.h"
  23. #include "wrap_DroppedFile.h"
  24. #include "wrap_FileData.h"
  25. #include "physfs/Filesystem.h"
  26. // SDL
  27. #include <SDL_loadso.h>
  28. // STL
  29. #include <vector>
  30. #include <string>
  31. #include <sstream>
  32. namespace love
  33. {
  34. namespace filesystem
  35. {
  36. #define instance() (Module::getInstance<Filesystem>(Module::M_FILESYSTEM))
  37. bool hack_setupWriteDirectory()
  38. {
  39. if (instance() != 0)
  40. return instance()->setupWriteDirectory();
  41. return false;
  42. }
  43. int w_init(lua_State *L)
  44. {
  45. const char *arg0 = luaL_checkstring(L, 1);
  46. luax_catchexcept(L, [&](){ instance()->init(arg0); });
  47. return 0;
  48. }
  49. int w_setFused(lua_State *L)
  50. {
  51. // no error checking needed, everything, even nothing
  52. // can be converted to a boolean
  53. instance()->setFused(luax_toboolean(L, 1));
  54. return 0;
  55. }
  56. int w_isFused(lua_State *L)
  57. {
  58. luax_pushboolean(L, instance()->isFused());
  59. return 1;
  60. }
  61. int w_setIdentity(lua_State *L)
  62. {
  63. const char *arg = luaL_checkstring(L, 1);
  64. bool append = luax_optboolean(L, 2, false);
  65. if (!instance()->setIdentity(arg, append))
  66. return luaL_error(L, "Could not set write directory.");
  67. return 0;
  68. }
  69. int w_getIdentity(lua_State *L)
  70. {
  71. lua_pushstring(L, instance()->getIdentity());
  72. return 1;
  73. }
  74. int w_setSource(lua_State *L)
  75. {
  76. const char *arg = luaL_checkstring(L, 1);
  77. if (!instance()->setSource(arg))
  78. return luaL_error(L, "Could not set source.");
  79. return 0;
  80. }
  81. int w_getSource(lua_State *L)
  82. {
  83. lua_pushstring(L, instance()->getSource());
  84. return 1;
  85. }
  86. int w_mount(lua_State *L)
  87. {
  88. const char *archive = luaL_checkstring(L, 1);
  89. const char *mountpoint = luaL_checkstring(L, 2);
  90. bool append = luax_optboolean(L, 3, false);
  91. luax_pushboolean(L, instance()->mount(archive, mountpoint, append));
  92. return 1;
  93. }
  94. int w_unmount(lua_State *L)
  95. {
  96. const char *archive = luaL_checkstring(L, 1);
  97. luax_pushboolean(L, instance()->unmount(archive));
  98. return 1;
  99. }
  100. int w_newFile(lua_State *L)
  101. {
  102. const char *filename = luaL_checkstring(L, 1);
  103. const char *str = 0;
  104. File::Mode mode = File::MODE_CLOSED;
  105. if (lua_isstring(L, 2))
  106. {
  107. str = luaL_checkstring(L, 2);
  108. if (!File::getConstant(str, mode))
  109. return luaL_error(L, "Incorrect file open mode: %s", str);
  110. }
  111. File *t = instance()->newFile(filename);
  112. if (mode != File::MODE_CLOSED)
  113. {
  114. try
  115. {
  116. if (!t->open(mode))
  117. throw love::Exception("Could not open file.");
  118. }
  119. catch (love::Exception &e)
  120. {
  121. t->release();
  122. return luax_ioError(L, "%s", e.what());
  123. }
  124. }
  125. luax_pushtype(L, "File", FILESYSTEM_FILE_T, t);
  126. t->release();
  127. return 1;
  128. }
  129. FileData *luax_getfiledata(lua_State *L, int idx)
  130. {
  131. FileData *data = nullptr;
  132. File *file = nullptr;
  133. if (lua_isstring(L, idx))
  134. {
  135. const char *filename = luaL_checkstring(L, idx);
  136. file = instance()->newFile(filename);
  137. }
  138. else if (luax_istype(L, idx, FILESYSTEM_FILE_T))
  139. {
  140. file = luax_checkfile(L, idx);
  141. file->retain();
  142. }
  143. else if (luax_istype(L, idx, FILESYSTEM_FILE_DATA_T))
  144. {
  145. data = luax_checkfiledata(L, idx);
  146. data->retain();
  147. }
  148. if (!data && !file)
  149. {
  150. luaL_argerror(L, idx, "filename, File, or FileData expected");
  151. return nullptr; // Never reached.
  152. }
  153. if (file)
  154. {
  155. luax_catchexcept(L,
  156. [&]() { data = file->read(); },
  157. [&]() { file->release(); }
  158. );
  159. }
  160. return data;
  161. }
  162. int w_newFileData(lua_State *L)
  163. {
  164. // Single argument: treat as filepath or File.
  165. if (lua_gettop(L) == 1)
  166. {
  167. // We don't use luax_getfiledata because we want to use an ioError.
  168. if (lua_isstring(L, 1))
  169. luax_convobj(L, 1, "filesystem", "newFile");
  170. // Get FileData from the File.
  171. if (luax_istype(L, 1, FILESYSTEM_FILE_T))
  172. {
  173. File *file = luax_checkfile(L, 1);
  174. FileData *data = 0;
  175. try
  176. {
  177. data = file->read();
  178. }
  179. catch (love::Exception &e)
  180. {
  181. return luax_ioError(L, "%s", e.what());
  182. }
  183. luax_pushtype(L, "FileData", FILESYSTEM_FILE_DATA_T, data);
  184. data->release();
  185. return 1;
  186. }
  187. else
  188. return luaL_argerror(L, 1, "filename or File expected");
  189. }
  190. size_t length = 0;
  191. const char *str = luaL_checklstring(L, 1, &length);
  192. const char *filename = luaL_checkstring(L, 2);
  193. const char *decstr = lua_isstring(L, 3) ? lua_tostring(L, 3) : 0;
  194. FileData::Decoder decoder = FileData::FILE;
  195. if (decstr && !FileData::getConstant(decstr, decoder))
  196. return luaL_error(L, "Invalid FileData decoder: %s", decstr);
  197. FileData *t = 0;
  198. switch (decoder)
  199. {
  200. case FileData::FILE:
  201. t = instance()->newFileData((void *)str, (int)length, filename);
  202. break;
  203. case FileData::BASE64:
  204. t = instance()->newFileData(str, filename);
  205. break;
  206. default:
  207. return luaL_error(L, "Invalid FileData decoder: %s", decstr);
  208. }
  209. luax_pushtype(L, "FileData", FILESYSTEM_FILE_DATA_T, t);
  210. t->release();
  211. return 1;
  212. }
  213. int w_getWorkingDirectory(lua_State *L)
  214. {
  215. lua_pushstring(L, instance()->getWorkingDirectory());
  216. return 1;
  217. }
  218. int w_getUserDirectory(lua_State *L)
  219. {
  220. luax_pushstring(L, instance()->getUserDirectory());
  221. return 1;
  222. }
  223. int w_getAppdataDirectory(lua_State *L)
  224. {
  225. luax_pushstring(L, instance()->getAppdataDirectory());
  226. return 1;
  227. }
  228. int w_getSaveDirectory(lua_State *L)
  229. {
  230. lua_pushstring(L, instance()->getSaveDirectory());
  231. return 1;
  232. }
  233. int w_getSourceBaseDirectory(lua_State *L)
  234. {
  235. luax_pushstring(L, instance()->getSourceBaseDirectory());
  236. return 1;
  237. }
  238. int w_getRealDirectory(lua_State *L)
  239. {
  240. const char *filename = luaL_checkstring(L, 1);
  241. std::string dir;
  242. try
  243. {
  244. dir = instance()->getRealDirectory(filename);
  245. }
  246. catch (love::Exception &e)
  247. {
  248. return luax_ioError(L, "%s", e.what());
  249. }
  250. lua_pushstring(L, dir.c_str());
  251. return 1;
  252. }
  253. int w_isDirectory(lua_State *L)
  254. {
  255. const char *arg = luaL_checkstring(L, 1);
  256. luax_pushboolean(L, instance()->isDirectory(arg));
  257. return 1;
  258. }
  259. int w_isFile(lua_State *L)
  260. {
  261. const char *arg = luaL_checkstring(L, 1);
  262. luax_pushboolean(L, instance()->isFile(arg));
  263. return 1;
  264. }
  265. int w_createDirectory(lua_State *L)
  266. {
  267. const char *arg = luaL_checkstring(L, 1);
  268. luax_pushboolean(L, instance()->createDirectory(arg));
  269. return 1;
  270. }
  271. int w_remove(lua_State *L)
  272. {
  273. const char *arg = luaL_checkstring(L, 1);
  274. luax_pushboolean(L, instance()->remove(arg));
  275. return 1;
  276. }
  277. int w_read(lua_State *L)
  278. {
  279. const char *filename = luaL_checkstring(L, 1);
  280. int64 len = (int64) luaL_optinteger(L, 2, File::ALL);
  281. Data *data = 0;
  282. try
  283. {
  284. data = instance()->read(filename, len);
  285. }
  286. catch (love::Exception &e)
  287. {
  288. return luax_ioError(L, "%s", e.what());
  289. }
  290. if (data == 0)
  291. return luax_ioError(L, "File could not be read.");
  292. // Push the string.
  293. lua_pushlstring(L, (const char *) data->getData(), data->getSize());
  294. // Push the size.
  295. lua_pushinteger(L, data->getSize());
  296. // Lua has a copy now, so we can free it.
  297. data->release();
  298. return 2;
  299. }
  300. static int w_write_or_append(lua_State *L, File::Mode mode)
  301. {
  302. const char *filename = luaL_checkstring(L, 1);
  303. const char *input = 0;
  304. size_t len = 0;
  305. if (luax_istype(L, 2, DATA_T))
  306. {
  307. love::Data *data = luax_totype<love::Data>(L, 2, "Data", DATA_T);
  308. input = (const char *) data->getData();
  309. len = data->getSize();
  310. }
  311. else if (lua_isstring(L, 2))
  312. input = lua_tolstring(L, 2, &len);
  313. else
  314. return luaL_argerror(L, 2, "string or Data expected");
  315. // Get how much we should write. Length of string default.
  316. len = luaL_optinteger(L, 3, len);
  317. try
  318. {
  319. if (mode == File::MODE_APPEND)
  320. instance()->append(filename, (const void *) input, len);
  321. else
  322. instance()->write(filename, (const void *) input, len);
  323. }
  324. catch (love::Exception &e)
  325. {
  326. return luax_ioError(L, "%s", e.what());
  327. }
  328. luax_pushboolean(L, true);
  329. return 1;
  330. }
  331. int w_write(lua_State *L)
  332. {
  333. return w_write_or_append(L, File::MODE_WRITE);
  334. }
  335. int w_append(lua_State *L)
  336. {
  337. return w_write_or_append(L, File::MODE_APPEND);
  338. }
  339. int w_getDirectoryItems(lua_State *L)
  340. {
  341. return instance()->getDirectoryItems(L);
  342. }
  343. int w_lines(lua_State *L)
  344. {
  345. File *file;
  346. if (lua_isstring(L, 1))
  347. {
  348. file = instance()->newFile(lua_tostring(L, 1));
  349. bool success = false;
  350. luax_catchexcept(L, [&](){ success = file->open(File::MODE_READ); });
  351. if (!success)
  352. {
  353. file->release();
  354. return luaL_error(L, "Could not open file.");
  355. }
  356. luax_pushtype(L, "File", FILESYSTEM_FILE_T, file);
  357. file->release();
  358. }
  359. else
  360. return luaL_argerror(L, 1, "expected filename.");
  361. lua_pushcclosure(L, w_File_lines_i, 1);
  362. return 1;
  363. }
  364. int w_load(lua_State *L)
  365. {
  366. std::string filename = std::string(luaL_checkstring(L, 1));
  367. Data *data = 0;
  368. try
  369. {
  370. data = instance()->read(filename.c_str());
  371. }
  372. catch (love::Exception &e)
  373. {
  374. return luax_ioError(L, "%s", e.what());
  375. }
  376. int status = luaL_loadbuffer(L, (const char *)data->getData(), data->getSize(), ("@" + filename).c_str());
  377. data->release();
  378. // Load the chunk, but don't run it.
  379. switch (status)
  380. {
  381. case LUA_ERRMEM:
  382. return luaL_error(L, "Memory allocation error: %s\n", lua_tostring(L, -1));
  383. case LUA_ERRSYNTAX:
  384. return luaL_error(L, "Syntax error: %s\n", lua_tostring(L, -1));
  385. default: // success
  386. return 1;
  387. }
  388. }
  389. int w_getLastModified(lua_State *L)
  390. {
  391. const char *filename = luaL_checkstring(L, 1);
  392. int64 time = 0;
  393. try
  394. {
  395. time = instance()->getLastModified(filename);
  396. }
  397. catch (love::Exception &e)
  398. {
  399. return luax_ioError(L, "%s", e.what());
  400. }
  401. lua_pushnumber(L, static_cast<lua_Number>(time));
  402. return 1;
  403. }
  404. int w_getSize(lua_State *L)
  405. {
  406. const char *filename = luaL_checkstring(L, 1);
  407. int64 size = -1;
  408. try
  409. {
  410. size = instance()->getSize(filename);
  411. }
  412. catch (love::Exception &e)
  413. {
  414. return luax_ioError(L, "%s", e.what());
  415. }
  416. // Error on failure or if size does not fit into a double precision floating-point number.
  417. if (size == -1)
  418. return luax_ioError(L, "Could not determine file size.");
  419. else if (size >= 0x20000000000000LL)
  420. return luax_ioError(L, "Size too large to fit into a Lua number!");
  421. lua_pushnumber(L, (lua_Number) size);
  422. return 1;
  423. }
  424. int w_setSymlinksEnabled(lua_State *L)
  425. {
  426. instance()->setSymlinksEnabled(luax_toboolean(L, 1));
  427. return 0;
  428. }
  429. int w_areSymlinksEnabled(lua_State *L)
  430. {
  431. luax_pushboolean(L, instance()->areSymlinksEnabled());
  432. return 1;
  433. }
  434. int w_isSymlink(lua_State *L)
  435. {
  436. const char *filename = luaL_checkstring(L, 1);
  437. luax_pushboolean(L, instance()->isSymlink(filename));
  438. return 1;
  439. }
  440. int w_getRequirePath(lua_State *L)
  441. {
  442. std::stringstream path;
  443. bool seperator = false;
  444. for (auto &element : instance()->getRequirePath())
  445. {
  446. if (seperator)
  447. path << ";";
  448. else
  449. seperator = true;
  450. path << element;
  451. }
  452. luax_pushstring(L, path.str());
  453. return 1;
  454. }
  455. int w_setRequirePath(lua_State *L)
  456. {
  457. std::string element = luax_checkstring(L, 1);
  458. auto &requirePath = instance()->getRequirePath();
  459. requirePath.clear();
  460. std::stringstream path;
  461. path << element;
  462. while(std::getline(path, element, ';'))
  463. requirePath.push_back(element);
  464. return 0;
  465. }
  466. int loader(lua_State *L)
  467. {
  468. std::string modulename = luax_tostring(L, 1);
  469. for (char &c : modulename)
  470. {
  471. if (c == '.')
  472. c = '/';
  473. }
  474. auto *inst = instance();
  475. for (std::string element : inst->getRequirePath())
  476. {
  477. size_t pos = element.find('?');
  478. if (pos != std::string::npos)
  479. element.replace(pos, 1, modulename);
  480. if (inst->isFile(element.c_str()))
  481. {
  482. lua_pop(L, 1);
  483. lua_pushstring(L, element.c_str());
  484. return w_load(L);
  485. }
  486. }
  487. std::string errstr = "\n\tno '%s' in LOVE game directories.";
  488. lua_pushfstring(L, errstr.c_str(), modulename.c_str());
  489. return 1;
  490. }
  491. inline const char *library_extension()
  492. {
  493. #ifdef LOVE_WINDOWS
  494. return ".dll";
  495. #else
  496. return ".so";
  497. #endif
  498. }
  499. int extloader(lua_State *L)
  500. {
  501. const char *filename = lua_tostring(L, -1);
  502. std::string tokenized_name(filename);
  503. std::string tokenized_function(filename);
  504. for (unsigned int i = 0; i < tokenized_name.size(); i++)
  505. {
  506. if (tokenized_name[i] == '.')
  507. {
  508. tokenized_name[i] = '/';
  509. tokenized_function[i] = '_';
  510. }
  511. }
  512. tokenized_name += library_extension();
  513. void *handle = nullptr;
  514. // If the game is fused, try looking for the DLL in the game's read paths.
  515. if (instance()->isFused())
  516. {
  517. try
  518. {
  519. std::string dir = instance()->getRealDirectory(tokenized_name.c_str());
  520. // We don't want to look in the game's source, because it can be a
  521. // zip sometimes and a folder other times.
  522. if (dir.find(instance()->getSource()) == std::string::npos)
  523. handle = SDL_LoadObject((dir + LOVE_PATH_SEPARATOR + tokenized_name).c_str());
  524. }
  525. catch (love::Exception &)
  526. {
  527. // Nothing...
  528. }
  529. }
  530. if (!handle)
  531. {
  532. std::string path = std::string(instance()->getAppdataDirectory()) + LOVE_PATH_SEPARATOR LOVE_APPDATA_FOLDER LOVE_PATH_SEPARATOR + tokenized_name;
  533. handle = SDL_LoadObject(path.c_str());
  534. }
  535. if (!handle)
  536. {
  537. lua_pushfstring(L, "\n\tno file '%s' in LOVE paths.", tokenized_name.c_str());
  538. return 1;
  539. }
  540. void *func = SDL_LoadFunction(handle, ("loveopen_" + tokenized_function).c_str());
  541. if (!func)
  542. func = SDL_LoadFunction(handle, ("luaopen_" + tokenized_function).c_str());
  543. if (!func)
  544. {
  545. SDL_UnloadObject(handle);
  546. lua_pushfstring(L, "\n\tC library '%s' is incompatible.", tokenized_name.c_str());
  547. return 1;
  548. }
  549. lua_pushcfunction(L, (lua_CFunction) func);
  550. return 1;
  551. }
  552. // List of functions to wrap.
  553. static const luaL_Reg functions[] =
  554. {
  555. { "init", w_init },
  556. { "setFused", w_setFused },
  557. { "isFused", w_isFused },
  558. { "setIdentity", w_setIdentity },
  559. { "getIdentity", w_getIdentity },
  560. { "setSource", w_setSource },
  561. { "getSource", w_getSource },
  562. { "mount", w_mount },
  563. { "unmount", w_unmount },
  564. { "newFile", w_newFile },
  565. { "getWorkingDirectory", w_getWorkingDirectory },
  566. { "getUserDirectory", w_getUserDirectory },
  567. { "getAppdataDirectory", w_getAppdataDirectory },
  568. { "getSaveDirectory", w_getSaveDirectory },
  569. { "getSourceBaseDirectory", w_getSourceBaseDirectory },
  570. { "getRealDirectory", w_getRealDirectory },
  571. { "isDirectory", w_isDirectory },
  572. { "isFile", w_isFile },
  573. { "createDirectory", w_createDirectory },
  574. { "remove", w_remove },
  575. { "read", w_read },
  576. { "write", w_write },
  577. { "append", w_append },
  578. { "getDirectoryItems", w_getDirectoryItems },
  579. { "lines", w_lines },
  580. { "load", w_load },
  581. { "getLastModified", w_getLastModified },
  582. { "getSize", w_getSize },
  583. { "setSymlinksEnabled", w_setSymlinksEnabled },
  584. { "areSymlinksEnabled", w_areSymlinksEnabled },
  585. { "isSymlink", w_isSymlink },
  586. { "newFileData", w_newFileData },
  587. { "getRequirePath", w_getRequirePath },
  588. { "setRequirePath", w_setRequirePath },
  589. { 0, 0 }
  590. };
  591. static const lua_CFunction types[] =
  592. {
  593. luaopen_file,
  594. luaopen_droppedfile,
  595. luaopen_filedata,
  596. 0
  597. };
  598. extern "C" int luaopen_love_filesystem(lua_State *L)
  599. {
  600. Filesystem *instance = instance();
  601. if (instance == nullptr)
  602. {
  603. luax_catchexcept(L, [&](){ instance = new physfs::Filesystem(); });
  604. }
  605. else
  606. instance->retain();
  607. // The love loaders should be tried after package.preload.
  608. love::luax_register_searcher(L, loader, 2);
  609. love::luax_register_searcher(L, extloader, 3);
  610. WrappedModule w;
  611. w.module = instance;
  612. w.name = "filesystem";
  613. w.flags = MODULE_FILESYSTEM_T;
  614. w.functions = functions;
  615. w.types = types;
  616. return luax_register_module(L, w);
  617. }
  618. } // filesystem
  619. } // love