wrap_Filesystem.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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, FILESYSTEM_FILE_ID, 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_ID))
  139. {
  140. file = luax_checkfile(L, idx);
  141. file->retain();
  142. }
  143. else if (luax_istype(L, idx, FILESYSTEM_FILE_DATA_ID))
  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. [&](bool) { 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_ID))
  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, FILESYSTEM_FILE_DATA_ID, 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, FILESYSTEM_FILE_DATA_ID, 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_getExecutablePath(lua_State *L)
  254. {
  255. luax_pushstring(L, instance()->getExecutablePath());
  256. return 1;
  257. }
  258. int w_isDirectory(lua_State *L)
  259. {
  260. const char *arg = luaL_checkstring(L, 1);
  261. luax_pushboolean(L, instance()->isDirectory(arg));
  262. return 1;
  263. }
  264. int w_isFile(lua_State *L)
  265. {
  266. const char *arg = luaL_checkstring(L, 1);
  267. luax_pushboolean(L, instance()->isFile(arg));
  268. return 1;
  269. }
  270. int w_createDirectory(lua_State *L)
  271. {
  272. const char *arg = luaL_checkstring(L, 1);
  273. luax_pushboolean(L, instance()->createDirectory(arg));
  274. return 1;
  275. }
  276. int w_remove(lua_State *L)
  277. {
  278. const char *arg = luaL_checkstring(L, 1);
  279. luax_pushboolean(L, instance()->remove(arg));
  280. return 1;
  281. }
  282. int w_read(lua_State *L)
  283. {
  284. const char *filename = luaL_checkstring(L, 1);
  285. int64 len = (int64) luaL_optinteger(L, 2, File::ALL);
  286. Data *data = 0;
  287. try
  288. {
  289. data = instance()->read(filename, len);
  290. }
  291. catch (love::Exception &e)
  292. {
  293. return luax_ioError(L, "%s", e.what());
  294. }
  295. if (data == 0)
  296. return luax_ioError(L, "File could not be read.");
  297. // Push the string.
  298. lua_pushlstring(L, (const char *) data->getData(), data->getSize());
  299. // Push the size.
  300. lua_pushinteger(L, data->getSize());
  301. // Lua has a copy now, so we can free it.
  302. data->release();
  303. return 2;
  304. }
  305. static int w_write_or_append(lua_State *L, File::Mode mode)
  306. {
  307. const char *filename = luaL_checkstring(L, 1);
  308. const char *input = 0;
  309. size_t len = 0;
  310. if (luax_istype(L, 2, DATA_ID))
  311. {
  312. love::Data *data = luax_totype<love::Data>(L, 2, DATA_ID);
  313. input = (const char *) data->getData();
  314. len = data->getSize();
  315. }
  316. else if (lua_isstring(L, 2))
  317. input = lua_tolstring(L, 2, &len);
  318. else
  319. return luaL_argerror(L, 2, "string or Data expected");
  320. // Get how much we should write. Length of string default.
  321. len = luaL_optinteger(L, 3, len);
  322. try
  323. {
  324. if (mode == File::MODE_APPEND)
  325. instance()->append(filename, (const void *) input, len);
  326. else
  327. instance()->write(filename, (const void *) input, len);
  328. }
  329. catch (love::Exception &e)
  330. {
  331. return luax_ioError(L, "%s", e.what());
  332. }
  333. luax_pushboolean(L, true);
  334. return 1;
  335. }
  336. int w_write(lua_State *L)
  337. {
  338. return w_write_or_append(L, File::MODE_WRITE);
  339. }
  340. int w_append(lua_State *L)
  341. {
  342. return w_write_or_append(L, File::MODE_APPEND);
  343. }
  344. int w_getDirectoryItems(lua_State *L)
  345. {
  346. const char *dir = luaL_checkstring(L, 1);
  347. std::vector<std::string> items;
  348. instance()->getDirectoryItems(dir, items);
  349. lua_createtable(L, (int) items.size(), 0);
  350. for (int i = 0; i < (int) items.size(); i++)
  351. {
  352. lua_pushstring(L, items[i].c_str());
  353. lua_rawseti(L, -2, i + 1);
  354. }
  355. // Return the table.
  356. return 1;
  357. }
  358. int w_lines(lua_State *L)
  359. {
  360. File *file;
  361. if (lua_isstring(L, 1))
  362. {
  363. file = instance()->newFile(lua_tostring(L, 1));
  364. bool success = false;
  365. luax_catchexcept(L, [&](){ success = file->open(File::MODE_READ); });
  366. if (!success)
  367. {
  368. file->release();
  369. return luaL_error(L, "Could not open file.");
  370. }
  371. luax_pushtype(L, FILESYSTEM_FILE_ID, file);
  372. file->release();
  373. }
  374. else
  375. return luaL_argerror(L, 1, "expected filename.");
  376. lua_pushcclosure(L, w_File_lines_i, 1);
  377. return 1;
  378. }
  379. int w_load(lua_State *L)
  380. {
  381. std::string filename = std::string(luaL_checkstring(L, 1));
  382. Data *data = 0;
  383. try
  384. {
  385. data = instance()->read(filename.c_str());
  386. }
  387. catch (love::Exception &e)
  388. {
  389. return luax_ioError(L, "%s", e.what());
  390. }
  391. int status = luaL_loadbuffer(L, (const char *)data->getData(), data->getSize(), ("@" + filename).c_str());
  392. data->release();
  393. // Load the chunk, but don't run it.
  394. switch (status)
  395. {
  396. case LUA_ERRMEM:
  397. return luaL_error(L, "Memory allocation error: %s\n", lua_tostring(L, -1));
  398. case LUA_ERRSYNTAX:
  399. return luaL_error(L, "Syntax error: %s\n", lua_tostring(L, -1));
  400. default: // success
  401. return 1;
  402. }
  403. }
  404. int w_getLastModified(lua_State *L)
  405. {
  406. const char *filename = luaL_checkstring(L, 1);
  407. int64 time = 0;
  408. try
  409. {
  410. time = instance()->getLastModified(filename);
  411. }
  412. catch (love::Exception &e)
  413. {
  414. return luax_ioError(L, "%s", e.what());
  415. }
  416. lua_pushnumber(L, static_cast<lua_Number>(time));
  417. return 1;
  418. }
  419. int w_getSize(lua_State *L)
  420. {
  421. const char *filename = luaL_checkstring(L, 1);
  422. int64 size = -1;
  423. try
  424. {
  425. size = instance()->getSize(filename);
  426. }
  427. catch (love::Exception &e)
  428. {
  429. return luax_ioError(L, "%s", e.what());
  430. }
  431. // Error on failure or if size does not fit into a double precision floating-point number.
  432. if (size == -1)
  433. return luax_ioError(L, "Could not determine file size.");
  434. else if (size >= 0x20000000000000LL)
  435. return luax_ioError(L, "Size too large to fit into a Lua number!");
  436. lua_pushnumber(L, (lua_Number) size);
  437. return 1;
  438. }
  439. int w_setSymlinksEnabled(lua_State *L)
  440. {
  441. instance()->setSymlinksEnabled(luax_toboolean(L, 1));
  442. return 0;
  443. }
  444. int w_areSymlinksEnabled(lua_State *L)
  445. {
  446. luax_pushboolean(L, instance()->areSymlinksEnabled());
  447. return 1;
  448. }
  449. int w_isSymlink(lua_State *L)
  450. {
  451. const char *filename = luaL_checkstring(L, 1);
  452. luax_pushboolean(L, instance()->isSymlink(filename));
  453. return 1;
  454. }
  455. int w_getRequirePath(lua_State *L)
  456. {
  457. std::stringstream path;
  458. bool seperator = false;
  459. for (auto &element : instance()->getRequirePath())
  460. {
  461. if (seperator)
  462. path << ";";
  463. else
  464. seperator = true;
  465. path << element;
  466. }
  467. luax_pushstring(L, path.str());
  468. return 1;
  469. }
  470. int w_setRequirePath(lua_State *L)
  471. {
  472. std::string element = luax_checkstring(L, 1);
  473. auto &requirePath = instance()->getRequirePath();
  474. requirePath.clear();
  475. std::stringstream path;
  476. path << element;
  477. while(std::getline(path, element, ';'))
  478. requirePath.push_back(element);
  479. return 0;
  480. }
  481. int loader(lua_State *L)
  482. {
  483. std::string modulename = luax_tostring(L, 1);
  484. for (char &c : modulename)
  485. {
  486. if (c == '.')
  487. c = '/';
  488. }
  489. auto *inst = instance();
  490. for (std::string element : inst->getRequirePath())
  491. {
  492. size_t pos = element.find('?');
  493. if (pos != std::string::npos)
  494. element.replace(pos, 1, modulename);
  495. if (inst->isFile(element.c_str()))
  496. {
  497. lua_pop(L, 1);
  498. lua_pushstring(L, element.c_str());
  499. return w_load(L);
  500. }
  501. }
  502. std::string errstr = "\n\tno '%s' in LOVE game directories.";
  503. lua_pushfstring(L, errstr.c_str(), modulename.c_str());
  504. return 1;
  505. }
  506. inline const char *library_extension()
  507. {
  508. #ifdef LOVE_WINDOWS
  509. return ".dll";
  510. #else
  511. return ".so";
  512. #endif
  513. }
  514. int extloader(lua_State *L)
  515. {
  516. const char *filename = lua_tostring(L, -1);
  517. std::string tokenized_name(filename);
  518. std::string tokenized_function(filename);
  519. for (unsigned int i = 0; i < tokenized_name.size(); i++)
  520. {
  521. if (tokenized_name[i] == '.')
  522. {
  523. tokenized_name[i] = '/';
  524. tokenized_function[i] = '_';
  525. }
  526. }
  527. tokenized_name += library_extension();
  528. void *handle = nullptr;
  529. // If the game is fused, try looking for the DLL in the game's read paths.
  530. if (instance()->isFused())
  531. {
  532. try
  533. {
  534. std::string dir = instance()->getRealDirectory(tokenized_name.c_str());
  535. // We don't want to look in the game's source, because it can be a
  536. // zip sometimes and a folder other times.
  537. if (dir.find(instance()->getSource()) == std::string::npos)
  538. handle = SDL_LoadObject((dir + LOVE_PATH_SEPARATOR + tokenized_name).c_str());
  539. }
  540. catch (love::Exception &)
  541. {
  542. // Nothing...
  543. }
  544. }
  545. if (!handle)
  546. {
  547. std::string path = std::string(instance()->getAppdataDirectory()) + LOVE_PATH_SEPARATOR LOVE_APPDATA_FOLDER LOVE_PATH_SEPARATOR + tokenized_name;
  548. handle = SDL_LoadObject(path.c_str());
  549. }
  550. if (!handle)
  551. {
  552. lua_pushfstring(L, "\n\tno file '%s' in LOVE paths.", tokenized_name.c_str());
  553. return 1;
  554. }
  555. void *func = SDL_LoadFunction(handle, ("loveopen_" + tokenized_function).c_str());
  556. if (!func)
  557. func = SDL_LoadFunction(handle, ("luaopen_" + tokenized_function).c_str());
  558. if (!func)
  559. {
  560. SDL_UnloadObject(handle);
  561. lua_pushfstring(L, "\n\tC library '%s' is incompatible.", tokenized_name.c_str());
  562. return 1;
  563. }
  564. lua_pushcfunction(L, (lua_CFunction) func);
  565. return 1;
  566. }
  567. // List of functions to wrap.
  568. static const luaL_Reg functions[] =
  569. {
  570. { "init", w_init },
  571. { "setFused", w_setFused },
  572. { "isFused", w_isFused },
  573. { "setIdentity", w_setIdentity },
  574. { "getIdentity", w_getIdentity },
  575. { "setSource", w_setSource },
  576. { "getSource", w_getSource },
  577. { "mount", w_mount },
  578. { "unmount", w_unmount },
  579. { "newFile", w_newFile },
  580. { "getWorkingDirectory", w_getWorkingDirectory },
  581. { "getUserDirectory", w_getUserDirectory },
  582. { "getAppdataDirectory", w_getAppdataDirectory },
  583. { "getSaveDirectory", w_getSaveDirectory },
  584. { "getSourceBaseDirectory", w_getSourceBaseDirectory },
  585. { "getRealDirectory", w_getRealDirectory },
  586. { "getExecutablePath", w_getExecutablePath },
  587. { "isDirectory", w_isDirectory },
  588. { "isFile", w_isFile },
  589. { "createDirectory", w_createDirectory },
  590. { "remove", w_remove },
  591. { "read", w_read },
  592. { "write", w_write },
  593. { "append", w_append },
  594. { "getDirectoryItems", w_getDirectoryItems },
  595. { "lines", w_lines },
  596. { "load", w_load },
  597. { "getLastModified", w_getLastModified },
  598. { "getSize", w_getSize },
  599. { "setSymlinksEnabled", w_setSymlinksEnabled },
  600. { "areSymlinksEnabled", w_areSymlinksEnabled },
  601. { "isSymlink", w_isSymlink },
  602. { "newFileData", w_newFileData },
  603. { "getRequirePath", w_getRequirePath },
  604. { "setRequirePath", w_setRequirePath },
  605. { 0, 0 }
  606. };
  607. static const lua_CFunction types[] =
  608. {
  609. luaopen_file,
  610. luaopen_droppedfile,
  611. luaopen_filedata,
  612. 0
  613. };
  614. extern "C" int luaopen_love_filesystem(lua_State *L)
  615. {
  616. Filesystem *instance = instance();
  617. if (instance == nullptr)
  618. {
  619. luax_catchexcept(L, [&](){ instance = new physfs::Filesystem(); });
  620. }
  621. else
  622. instance->retain();
  623. // The love loaders should be tried after package.preload.
  624. love::luax_register_searcher(L, loader, 2);
  625. love::luax_register_searcher(L, extloader, 3);
  626. WrappedModule w;
  627. w.module = instance;
  628. w.name = "filesystem";
  629. w.type = MODULE_FILESYSTEM_ID;
  630. w.functions = functions;
  631. w.types = types;
  632. return luax_register_module(L, w);
  633. }
  634. } // filesystem
  635. } // love