wrap_Filesystem.cpp 24 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. /**
  2. * Copyright (c) 2006-2022 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 "common/config.h"
  22. #include "wrap_Filesystem.h"
  23. #include "wrap_File.h"
  24. #include "wrap_NativeFile.h"
  25. #include "wrap_FileData.h"
  26. #include "data/wrap_Data.h"
  27. #include "data/wrap_DataModule.h"
  28. #include "physfs/Filesystem.h"
  29. #ifdef LOVE_ANDROID
  30. #include "common/android.h"
  31. #endif
  32. // SDL
  33. #include <SDL_loadso.h>
  34. // STL
  35. #include <vector>
  36. #include <string>
  37. #include <sstream>
  38. #include <algorithm>
  39. namespace love
  40. {
  41. namespace filesystem
  42. {
  43. #define instance() (Module::getInstance<Filesystem>(Module::M_FILESYSTEM))
  44. int w_init(lua_State *L)
  45. {
  46. const char *arg0 = luaL_checkstring(L, 1);
  47. luax_catchexcept(L, [&](){ instance()->init(arg0); });
  48. return 0;
  49. }
  50. int w_setFused(lua_State *L)
  51. {
  52. // no error checking needed, everything, even nothing
  53. // can be converted to a boolean
  54. instance()->setFused(luax_toboolean(L, 1));
  55. return 0;
  56. }
  57. int w_isFused(lua_State *L)
  58. {
  59. luax_pushboolean(L, instance()->isFused());
  60. return 1;
  61. }
  62. int w_setAndroidSaveExternal(lua_State *L)
  63. {
  64. bool useExternal = luax_optboolean(L, 1, false);
  65. instance()->setAndroidSaveExternal(useExternal);
  66. return 0;
  67. }
  68. int w_setIdentity(lua_State *L)
  69. {
  70. const char *arg = luaL_checkstring(L, 1);
  71. bool append = luax_optboolean(L, 2, false);
  72. if (!instance()->setIdentity(arg, append))
  73. return luaL_error(L, "Could not set write directory.");
  74. return 0;
  75. }
  76. int w_getIdentity(lua_State *L)
  77. {
  78. lua_pushstring(L, instance()->getIdentity());
  79. return 1;
  80. }
  81. int w_setSource(lua_State *L)
  82. {
  83. const char *arg = luaL_checkstring(L, 1);
  84. if (!instance()->setSource(arg))
  85. return luaL_error(L, "Could not set source.");
  86. return 0;
  87. }
  88. int w_getSource(lua_State *L)
  89. {
  90. lua_pushstring(L, instance()->getSource());
  91. return 1;
  92. }
  93. int w_mount(lua_State *L)
  94. {
  95. std::string archive;
  96. if (luax_istype(L, 1, Data::type))
  97. {
  98. Data *data = love::data::luax_checkdata(L, 1);
  99. int startidx = 2;
  100. if (luax_istype(L, 1, FileData::type) && !lua_isstring(L, 3))
  101. {
  102. FileData *filedata = luax_checkfiledata(L, 1);
  103. archive = filedata->getFilename();
  104. startidx = 2;
  105. }
  106. else
  107. {
  108. archive = luax_checkstring(L, 2);
  109. startidx = 3;
  110. }
  111. const char *mountpoint = luaL_checkstring(L, startidx + 0);
  112. bool append = luax_optboolean(L, startidx + 1, false);
  113. luax_pushboolean(L, instance()->mount(data, archive.c_str(), mountpoint, append));
  114. return 1;
  115. }
  116. else if (luax_istype(L, 1, NativeFile::type))
  117. {
  118. NativeFile *file = luax_totype<NativeFile>(L, 1);
  119. archive = file->getFilename();
  120. }
  121. else
  122. archive = luax_checkstring(L, 1);
  123. const char *mountpoint = luaL_checkstring(L, 2);
  124. bool append = luax_optboolean(L, 3, false);
  125. luax_pushboolean(L, instance()->mount(archive.c_str(), mountpoint, append));
  126. return 1;
  127. }
  128. int w_mountFullPath(lua_State *L)
  129. {
  130. const char *fullpath = luaL_checkstring(L, 1);
  131. const char *mountpoint = luaL_checkstring(L, 2);
  132. auto permissions = Filesystem::MOUNT_PERMISSIONS_READ;
  133. if (!lua_isnoneornil(L, 3))
  134. {
  135. const char *permissionstr = luaL_checkstring(L, 3);
  136. if (!Filesystem::getConstant(permissionstr, permissions))
  137. return luax_enumerror(L, "mount permissions", Filesystem::getConstants(permissions), permissionstr);
  138. }
  139. bool append = luax_optboolean(L, 4, false);
  140. luax_pushboolean(L, instance()->mountFullPath(fullpath, mountpoint, permissions, append));
  141. return 1;
  142. }
  143. int w_mountCommonPath(lua_State *L)
  144. {
  145. const char *commonpathstr = luaL_checkstring(L, 1);
  146. Filesystem::CommonPath commonpath;
  147. if (!Filesystem::getConstant(commonpathstr, commonpath))
  148. return luax_enumerror(L, "common path", Filesystem::getConstants(commonpath), commonpathstr);
  149. const char *mountpoint = luaL_checkstring(L, 2);
  150. auto permissions = Filesystem::MOUNT_PERMISSIONS_READ;
  151. if (!lua_isnoneornil(L, 3))
  152. {
  153. const char *permissionstr = luaL_checkstring(L, 3);
  154. if (!Filesystem::getConstant(permissionstr, permissions))
  155. return luax_enumerror(L, "mount permissions", Filesystem::getConstants(permissions), permissionstr);
  156. }
  157. bool append = luax_optboolean(L, 4, false);
  158. luax_pushboolean(L, instance()->mountCommonPath(commonpath, mountpoint, permissions, append));
  159. return 1;
  160. }
  161. int w_unmount(lua_State *L)
  162. {
  163. if (luax_istype(L, 1, Data::type))
  164. {
  165. Data *data = love::data::luax_checkdata(L, 1);
  166. luax_pushboolean(L, instance()->unmount(data));
  167. }
  168. else
  169. {
  170. const char *archive = luaL_checkstring(L, 1);
  171. luax_pushboolean(L, instance()->unmount(archive));
  172. }
  173. return 1;
  174. }
  175. int w_unmountFullPath(lua_State *L)
  176. {
  177. const char *fullpath = luaL_checkstring(L, 1);
  178. luax_pushboolean(L, instance()->unmountFullPath(fullpath));
  179. return 1;
  180. }
  181. int w_unmountCommonPath(lua_State *L)
  182. {
  183. const char *commonpathstr = luaL_checkstring(L, 1);
  184. Filesystem::CommonPath commonpath;
  185. if (!Filesystem::getConstant(commonpathstr, commonpath))
  186. return luax_enumerror(L, "common path", Filesystem::getConstants(commonpath), commonpathstr);
  187. luax_pushboolean(L, instance()->unmount(commonpath));
  188. return 1;
  189. }
  190. int w_openFile(lua_State *L)
  191. {
  192. const char *filename = luaL_checkstring(L, 1);
  193. const char *modestr = luaL_checkstring(L, 2);
  194. File::Mode mode = File::MODE_CLOSED;
  195. if (!File::getConstant(modestr, mode))
  196. return luax_enumerror(L, "file open mode", File::getConstants(mode), modestr);
  197. File *t = nullptr;
  198. try
  199. {
  200. t = instance()->openFile(filename, mode);
  201. }
  202. catch (love::Exception &e)
  203. {
  204. return luax_ioError(L, "%s", e.what());
  205. }
  206. luax_pushtype(L, t);
  207. t->release();
  208. return 1;
  209. }
  210. int w_newFile(lua_State* L)
  211. {
  212. luax_markdeprecated(L, 1, "love.filesystem.newFile", API_FUNCTION, DEPRECATED_RENAMED, "love.filesystem.openFile");
  213. const char* filename = luaL_checkstring(L, 1);
  214. File::Mode mode = File::MODE_CLOSED;
  215. if (!lua_isnoneornil(L, 2))
  216. {
  217. const char* modestr = luaL_checkstring(L, 2);
  218. if (!File::getConstant(modestr, mode))
  219. return luax_enumerror(L, "file open mode", File::getConstants(mode), modestr);
  220. }
  221. File* t = nullptr;
  222. try
  223. {
  224. t = instance()->openFile(filename, mode);
  225. }
  226. catch (love::Exception& e)
  227. {
  228. return luax_ioError(L, "%s", e.what());
  229. }
  230. luax_pushtype(L, t);
  231. t->release();
  232. return 1;
  233. }
  234. File *luax_getfile(lua_State *L, int idx)
  235. {
  236. File *file = nullptr;
  237. if (lua_isstring(L, idx))
  238. {
  239. const char *filename = luaL_checkstring(L, idx);
  240. try
  241. {
  242. file = instance()->openFile(filename, File::MODE_CLOSED);
  243. }
  244. catch (love::Exception &e)
  245. {
  246. luax_ioError(L, "%s", e.what());
  247. }
  248. }
  249. else
  250. {
  251. file = luax_checkfile(L, idx);
  252. file->retain();
  253. }
  254. return file;
  255. }
  256. FileData *luax_getfiledata(lua_State *L, int idx, bool ioerror, int &nresults)
  257. {
  258. FileData *data = nullptr;
  259. File *file = nullptr;
  260. nresults = 0;
  261. if (lua_isstring(L, idx) || luax_istype(L, idx, File::type))
  262. {
  263. file = luax_getfile(L, idx);
  264. }
  265. else if (luax_istype(L, idx, FileData::type))
  266. {
  267. data = luax_checkfiledata(L, idx);
  268. data->retain();
  269. }
  270. if (!data && !file)
  271. {
  272. nresults = luaL_argerror(L, idx, "filename, File, or FileData expected");
  273. return nullptr; // Never reached.
  274. }
  275. else if (file && !data)
  276. {
  277. try
  278. {
  279. data = file->read();
  280. }
  281. catch (love::Exception &e)
  282. {
  283. file->release();
  284. if (ioerror)
  285. nresults = luax_ioError(L, "%s", e.what());
  286. else
  287. nresults = luaL_error(L, "%s", e.what());
  288. return nullptr; // Never reached if ioerror is false.
  289. }
  290. file->release();
  291. }
  292. return data;
  293. }
  294. FileData *luax_getfiledata(lua_State *L, int idx)
  295. {
  296. int nresults = 0;
  297. return luax_getfiledata(L, idx, false, nresults);
  298. }
  299. Data *luax_getdata(lua_State *L, int idx)
  300. {
  301. Data *data = nullptr;
  302. File *file = nullptr;
  303. if (lua_isstring(L, idx) || luax_istype(L, idx, File::type))
  304. {
  305. file = luax_getfile(L, idx);
  306. }
  307. else if (luax_istype(L, idx, Data::type))
  308. {
  309. data = data::luax_checkdata(L, idx);
  310. data->retain();
  311. }
  312. if (!data && !file)
  313. {
  314. luaL_argerror(L, idx, "filename, File, or Data expected");
  315. return nullptr; // Never reached.
  316. }
  317. if (file)
  318. {
  319. luax_catchexcept(L,
  320. [&]() { data = file->read(); },
  321. [&](bool) { file->release(); }
  322. );
  323. }
  324. return data;
  325. }
  326. bool luax_cangetfile(lua_State *L, int idx)
  327. {
  328. return lua_isstring(L, idx) || luax_istype(L, idx, File::type);
  329. }
  330. bool luax_cangetfiledata(lua_State *L, int idx)
  331. {
  332. return lua_isstring(L, idx) || luax_istype(L, idx, File::type) || luax_istype(L, idx, FileData::type);
  333. }
  334. bool luax_cangetdata(lua_State *L, int idx)
  335. {
  336. return lua_isstring(L, idx) || luax_istype(L, idx, File::type) || luax_istype(L, idx, Data::type);
  337. }
  338. int w_newFileData(lua_State *L)
  339. {
  340. // Single argument: treat as filepath or File.
  341. if (lua_gettop(L) == 1)
  342. {
  343. int nresults = 0;
  344. FileData *data = luax_getfiledata(L, 1, true, nresults);
  345. if (data == nullptr)
  346. return nresults;
  347. luax_pushtype(L, data);
  348. data->release();
  349. return 1;
  350. }
  351. size_t length = 0;
  352. const void *ptr = nullptr;
  353. if (luax_istype(L, 1, Data::type))
  354. {
  355. Data *data = data::luax_checkdata(L, 1);
  356. ptr = data->getData();
  357. length = data->getSize();
  358. }
  359. else if (lua_isstring(L, 1))
  360. ptr = luaL_checklstring(L, 1, &length);
  361. else
  362. return luaL_argerror(L, 1, "string or Data expected");
  363. const char *filename = luaL_checkstring(L, 2);
  364. FileData *t = nullptr;
  365. luax_catchexcept(L, [&](){ t = instance()->newFileData(ptr, length, filename); });
  366. luax_pushtype(L, t);
  367. t->release();
  368. return 1;
  369. }
  370. int w_getFullCommonPath(lua_State *L)
  371. {
  372. const char *commonpathstr = luaL_checkstring(L, 1);
  373. Filesystem::CommonPath commonpath;
  374. if (!Filesystem::getConstant(commonpathstr, commonpath))
  375. return luax_enumerror(L, "common path", Filesystem::getConstants(commonpath), commonpathstr);
  376. luax_pushstring(L, instance()->getFullCommonPath(commonpath));
  377. return 1;
  378. }
  379. int w_getWorkingDirectory(lua_State *L)
  380. {
  381. lua_pushstring(L, instance()->getWorkingDirectory());
  382. return 1;
  383. }
  384. int w_getUserDirectory(lua_State *L)
  385. {
  386. luax_pushstring(L, instance()->getUserDirectory());
  387. return 1;
  388. }
  389. int w_getAppdataDirectory(lua_State *L)
  390. {
  391. luax_pushstring(L, instance()->getAppdataDirectory());
  392. return 1;
  393. }
  394. int w_getSaveDirectory(lua_State *L)
  395. {
  396. luax_pushstring(L, instance()->getSaveDirectory());
  397. return 1;
  398. }
  399. int w_getSourceBaseDirectory(lua_State *L)
  400. {
  401. luax_pushstring(L, instance()->getSourceBaseDirectory());
  402. return 1;
  403. }
  404. int w_getRealDirectory(lua_State *L)
  405. {
  406. const char *filename = luaL_checkstring(L, 1);
  407. std::string dir;
  408. try
  409. {
  410. dir = instance()->getRealDirectory(filename);
  411. }
  412. catch (love::Exception &e)
  413. {
  414. return luax_ioError(L, "%s", e.what());
  415. }
  416. lua_pushstring(L, dir.c_str());
  417. return 1;
  418. }
  419. int w_getExecutablePath(lua_State *L)
  420. {
  421. luax_pushstring(L, instance()->getExecutablePath());
  422. return 1;
  423. }
  424. int w_exists(lua_State *L)
  425. {
  426. const char *path = luaL_checkstring(L, 1);
  427. luax_pushboolean(L, instance()->exists(path));
  428. return 1;
  429. }
  430. int w_getInfo(lua_State *L)
  431. {
  432. const char *filepath = luaL_checkstring(L, 1);
  433. Filesystem::Info info = {};
  434. int startidx = 2;
  435. Filesystem::FileType filtertype = Filesystem::FILETYPE_MAX_ENUM;
  436. if (lua_isstring(L, startidx))
  437. {
  438. const char *typestr = luaL_checkstring(L, startidx);
  439. if (!Filesystem::getConstant(typestr, filtertype))
  440. return luax_enumerror(L, "file type", Filesystem::getConstants(filtertype), typestr);
  441. startidx++;
  442. }
  443. if (instance()->getInfo(filepath, info))
  444. {
  445. if (filtertype != Filesystem::FILETYPE_MAX_ENUM && info.type != filtertype)
  446. {
  447. lua_pushnil(L);
  448. return 1;
  449. }
  450. const char *typestr = nullptr;
  451. if (!Filesystem::getConstant(info.type, typestr))
  452. return luaL_error(L, "Unknown file type.");
  453. if (lua_istable(L, startidx))
  454. lua_pushvalue(L, startidx);
  455. else
  456. lua_createtable(L, 0, 3);
  457. lua_pushstring(L, typestr);
  458. lua_setfield(L, -2, "type");
  459. luax_pushboolean(L, info.readonly);
  460. lua_setfield(L, -2, "readonly");
  461. // Lua numbers (doubles) can't fit the full range of 64 bit ints.
  462. info.size = std::min<int64>(info.size, 0x20000000000000LL);
  463. if (info.size >= 0)
  464. {
  465. lua_pushnumber(L, (lua_Number) info.size);
  466. lua_setfield(L, -2, "size");
  467. }
  468. info.modtime = std::min<int64>(info.modtime, 0x20000000000000LL);
  469. if (info.modtime >= 0)
  470. {
  471. lua_pushnumber(L, (lua_Number) info.modtime);
  472. lua_setfield(L, -2, "modtime");
  473. }
  474. }
  475. else
  476. lua_pushnil(L);
  477. return 1;
  478. }
  479. int w_createDirectory(lua_State *L)
  480. {
  481. const char *arg = luaL_checkstring(L, 1);
  482. luax_pushboolean(L, instance()->createDirectory(arg));
  483. return 1;
  484. }
  485. int w_remove(lua_State *L)
  486. {
  487. const char *arg = luaL_checkstring(L, 1);
  488. luax_pushboolean(L, instance()->remove(arg));
  489. return 1;
  490. }
  491. int w_read(lua_State *L)
  492. {
  493. love::data::ContainerType ctype = love::data::CONTAINER_STRING;
  494. int startidx = 1;
  495. if (lua_type(L, 2) == LUA_TSTRING)
  496. {
  497. ctype = love::data::luax_checkcontainertype(L, 1);
  498. startidx = 2;
  499. }
  500. const char *filename = luaL_checkstring(L, startidx + 0);
  501. int64 len = (int64) luaL_optinteger(L, startidx + 1, -1);
  502. FileData *data = nullptr;
  503. try
  504. {
  505. if (len >= 0)
  506. data = instance()->read(filename, len);
  507. else
  508. data = instance()->read(filename);
  509. }
  510. catch (love::Exception &e)
  511. {
  512. return luax_ioError(L, "%s", e.what());
  513. }
  514. if (data == nullptr)
  515. return luax_ioError(L, "File could not be read.");
  516. if (ctype == love::data::CONTAINER_DATA)
  517. luax_pushtype(L, data);
  518. else
  519. lua_pushlstring(L, (const char *) data->getData(), data->getSize());
  520. lua_pushinteger(L, data->getSize());
  521. // Lua has a copy now, so we can free it.
  522. data->release();
  523. return 2;
  524. }
  525. static int w_write_or_append(lua_State *L, File::Mode mode)
  526. {
  527. const char *filename = luaL_checkstring(L, 1);
  528. const char *input = nullptr;
  529. size_t len = 0;
  530. if (luax_istype(L, 2, love::Data::type))
  531. {
  532. love::Data *data = luax_totype<love::Data>(L, 2);
  533. input = (const char *) data->getData();
  534. len = data->getSize();
  535. }
  536. else if (lua_isstring(L, 2))
  537. input = lua_tolstring(L, 2, &len);
  538. else
  539. return luaL_argerror(L, 2, "string or Data expected");
  540. // Get how much we should write. Length of string default.
  541. len = luaL_optinteger(L, 3, len);
  542. try
  543. {
  544. if (mode == File::MODE_APPEND)
  545. instance()->append(filename, (const void *) input, len);
  546. else
  547. instance()->write(filename, (const void *) input, len);
  548. }
  549. catch (love::Exception &e)
  550. {
  551. return luax_ioError(L, "%s", e.what());
  552. }
  553. luax_pushboolean(L, true);
  554. return 1;
  555. }
  556. int w_write(lua_State *L)
  557. {
  558. return w_write_or_append(L, File::MODE_WRITE);
  559. }
  560. int w_append(lua_State *L)
  561. {
  562. return w_write_or_append(L, File::MODE_APPEND);
  563. }
  564. int w_getDirectoryItems(lua_State *L)
  565. {
  566. const char *dir = luaL_checkstring(L, 1);
  567. std::vector<std::string> items;
  568. instance()->getDirectoryItems(dir, items);
  569. lua_createtable(L, (int) items.size(), 0);
  570. for (int i = 0; i < (int) items.size(); i++)
  571. {
  572. lua_pushstring(L, items[i].c_str());
  573. lua_rawseti(L, -2, i + 1);
  574. }
  575. // Return the table.
  576. return 1;
  577. }
  578. int w_lines(lua_State *L)
  579. {
  580. if (lua_isstring(L, 1))
  581. {
  582. File *file = nullptr;
  583. luax_catchexcept(L, [&]() { file = instance()->openFile(lua_tostring(L, 1), File::MODE_READ); });
  584. luax_pushtype(L, file);
  585. file->release();
  586. }
  587. else
  588. return luaL_argerror(L, 1, "expected filename.");
  589. lua_pushstring(L, ""); // buffer
  590. lua_pushstring(L, 0); // buffer offset
  591. lua_pushcclosure(L, w_File_lines_i, 3);
  592. return 1;
  593. }
  594. int w_load(lua_State *L)
  595. {
  596. std::string filename = std::string(luaL_checkstring(L, 1));
  597. Filesystem::LoadMode loadMode = Filesystem::LOADMODE_ANY;
  598. if (!lua_isnoneornil(L, 2))
  599. {
  600. const char *mode = luaL_checkstring(L, 2);
  601. if (!Filesystem::getConstant(mode, loadMode))
  602. return luax_enumerror(L, "load mode", Filesystem::getConstants(loadMode), mode);
  603. }
  604. Data *data = nullptr;
  605. try
  606. {
  607. data = instance()->read(filename.c_str());
  608. }
  609. catch (love::Exception &e)
  610. {
  611. return luax_ioError(L, "%s", e.what());
  612. }
  613. int status;
  614. #if (LUA_VERSION_NUM > 501) || defined(LUA_JITLIBNAME)
  615. // LuaJIT support this Lua 5.2 function.
  616. const char *mode;
  617. Filesystem::getConstant(loadMode, mode);
  618. status = luaL_loadbufferx(L, (const char *)data->getData(), data->getSize(), ("@" + filename).c_str(), mode);
  619. #else
  620. if (loadMode == Filesystem::LOADMODE_ANY)
  621. status = luaL_loadbuffer(L, (const char *)data->getData(), data->getSize(), ("@" + filename).c_str());
  622. else
  623. {
  624. // Unsupported
  625. data->release();
  626. return luaL_error(L, "only \"bt\" is supported on this Lua interpreter\n");
  627. }
  628. #endif
  629. data->release();
  630. // Load the chunk, but don't run it.
  631. switch (status)
  632. {
  633. case LUA_ERRMEM:
  634. return luaL_error(L, "Memory allocation error: %s\n", lua_tostring(L, -1));
  635. case LUA_ERRSYNTAX:
  636. return luaL_error(L, "Syntax error: %s\n", lua_tostring(L, -1));
  637. default: // success
  638. return 1;
  639. }
  640. }
  641. int w_setSymlinksEnabled(lua_State *L)
  642. {
  643. instance()->setSymlinksEnabled(luax_checkboolean(L, 1));
  644. return 0;
  645. }
  646. int w_areSymlinksEnabled(lua_State *L)
  647. {
  648. luax_pushboolean(L, instance()->areSymlinksEnabled());
  649. return 1;
  650. }
  651. int w_getRequirePath(lua_State *L)
  652. {
  653. std::stringstream path;
  654. bool seperator = false;
  655. for (auto &element : instance()->getRequirePath())
  656. {
  657. if (seperator)
  658. path << ";";
  659. else
  660. seperator = true;
  661. path << element;
  662. }
  663. luax_pushstring(L, path.str());
  664. return 1;
  665. }
  666. int w_getCRequirePath(lua_State *L)
  667. {
  668. std::stringstream path;
  669. bool seperator = false;
  670. for (auto &element : instance()->getCRequirePath())
  671. {
  672. if (seperator)
  673. path << ";";
  674. else
  675. seperator = true;
  676. path << element;
  677. }
  678. luax_pushstring(L, path.str());
  679. return 1;
  680. }
  681. int w_setRequirePath(lua_State *L)
  682. {
  683. std::string element = luax_checkstring(L, 1);
  684. auto &requirePath = instance()->getRequirePath();
  685. requirePath.clear();
  686. std::stringstream path;
  687. path << element;
  688. while(std::getline(path, element, ';'))
  689. requirePath.push_back(element);
  690. return 0;
  691. }
  692. int w_setCRequirePath(lua_State *L)
  693. {
  694. std::string element = luax_checkstring(L, 1);
  695. auto &requirePath = instance()->getCRequirePath();
  696. requirePath.clear();
  697. std::stringstream path;
  698. path << element;
  699. while(std::getline(path, element, ';'))
  700. requirePath.push_back(element);
  701. return 0;
  702. }
  703. static void replaceAll(std::string &str, const std::string &substr, const std::string &replacement)
  704. {
  705. std::vector<size_t> locations;
  706. size_t pos = 0;
  707. size_t sublen = substr.length();
  708. while ((pos = str.find(substr, pos)) != std::string::npos)
  709. {
  710. locations.push_back(pos);
  711. pos += sublen;
  712. }
  713. for (int i = (int) locations.size() - 1; i >= 0; i--)
  714. str.replace(locations[i], sublen, replacement);
  715. }
  716. int loader(lua_State *L)
  717. {
  718. std::string modulename = luax_checkstring(L, 1);
  719. bool hasSlash = modulename.find('/') != std::string::npos;
  720. for (char &c : modulename)
  721. {
  722. if (c == '.')
  723. c = '/';
  724. }
  725. auto *inst = instance();
  726. for (std::string element : inst->getRequirePath())
  727. {
  728. replaceAll(element, "?", modulename);
  729. Filesystem::Info info = {};
  730. if (inst->getInfo(element.c_str(), info) && info.type != Filesystem::FILETYPE_DIRECTORY)
  731. {
  732. if (hasSlash)
  733. luax_markdeprecated(L, 2, "character in require string (forward slashes), use dots instead.", API_CUSTOM);
  734. lua_pop(L, 1);
  735. lua_pushstring(L, element.c_str());
  736. return w_load(L);
  737. }
  738. }
  739. std::string errstr = "\n\tno '%s' in LOVE game directories.";
  740. lua_pushfstring(L, errstr.c_str(), modulename.c_str());
  741. return 1;
  742. }
  743. static const char *library_extensions[] =
  744. {
  745. #ifdef LOVE_WINDOWS
  746. ".dll"
  747. #elif defined(LOVE_MACOS) || defined(LOVE_IOS)
  748. ".dylib", ".so"
  749. #else
  750. ".so"
  751. #endif
  752. };
  753. int extloader(lua_State *L)
  754. {
  755. std::string filename = luax_checkstring(L, 1);
  756. std::string tokenized_name(filename);
  757. std::string tokenized_function(filename);
  758. // We need both the tokenized filename (dots replaced with slashes)
  759. // and the tokenized function name (dots replaced with underscores)
  760. // NOTE: Lua's loader queries more names than this one.
  761. for (unsigned int i = 0; i < tokenized_name.size(); i++)
  762. {
  763. if (tokenized_name[i] == '.')
  764. {
  765. tokenized_name[i] = '/';
  766. tokenized_function[i] = '_';
  767. }
  768. }
  769. void *handle = nullptr;
  770. auto *inst = instance();
  771. #ifdef LOVE_ANDROID
  772. // Specifically Android, look the library path based on getCRequirePath first
  773. std::string androidPath(love::android::getCRequirePath());
  774. if (!androidPath.empty())
  775. {
  776. // Replace ? with just the dotted filename (not tokenized_name)
  777. replaceAll(androidPath, "?", filename);
  778. // Load directly, don't check for existence.
  779. handle = SDL_LoadObject(androidPath.c_str());
  780. }
  781. if (!handle)
  782. {
  783. #endif // LOVE_ANDROID
  784. for (const std::string &el : inst->getCRequirePath())
  785. {
  786. for (const char *ext : library_extensions)
  787. {
  788. std::string element = el;
  789. // Replace ?? with the filename and extension
  790. replaceAll(element, "??", tokenized_name + ext);
  791. // And ? with just the filename
  792. replaceAll(element, "?", tokenized_name);
  793. Filesystem::Info info = {};
  794. if (!inst->getInfo(element.c_str(), info) || info.type == Filesystem::FILETYPE_DIRECTORY)
  795. continue;
  796. // Now resolve the full path, as we're bypassing physfs for the next part.
  797. std::string filepath = inst->getRealDirectory(element.c_str()) + LOVE_PATH_SEPARATOR + element;
  798. handle = SDL_LoadObject(filepath.c_str());
  799. // Can fail, for instance if it turned out the source was a zip
  800. if (handle)
  801. break;
  802. }
  803. if (handle)
  804. break;
  805. }
  806. #ifdef LOVE_ANDROID
  807. } // if (!handle)
  808. #endif
  809. if (!handle)
  810. {
  811. lua_pushfstring(L, "\n\tno file '%s' in LOVE paths.", tokenized_name.c_str());
  812. return 1;
  813. }
  814. // We look for both loveopen_ and luaopen_, so libraries with specific love support
  815. // can tell when they've been loaded by love.
  816. void *func = SDL_LoadFunction(handle, ("loveopen_" + tokenized_function).c_str());
  817. if (!func)
  818. func = SDL_LoadFunction(handle, ("luaopen_" + tokenized_function).c_str());
  819. if (!func)
  820. {
  821. SDL_UnloadObject(handle);
  822. lua_pushfstring(L, "\n\tC library '%s' is incompatible.", tokenized_name.c_str());
  823. return 1;
  824. }
  825. lua_pushcfunction(L, (lua_CFunction) func);
  826. return 1;
  827. }
  828. // List of functions to wrap.
  829. static const luaL_Reg functions[] =
  830. {
  831. { "init", w_init },
  832. { "setFused", w_setFused },
  833. { "isFused", w_isFused },
  834. { "_setAndroidSaveExternal", w_setAndroidSaveExternal },
  835. { "setIdentity", w_setIdentity },
  836. { "getIdentity", w_getIdentity },
  837. { "setSource", w_setSource },
  838. { "getSource", w_getSource },
  839. { "mount", w_mount },
  840. { "mountFullPath", w_mountFullPath },
  841. { "mountCommonPath", w_mountCommonPath },
  842. { "unmount", w_unmount },
  843. { "unmountFullPath", w_unmountFullPath },
  844. { "unmountCommonPath", w_unmountCommonPath },
  845. { "openFile", w_openFile },
  846. { "getFullCommonPath", w_getFullCommonPath },
  847. { "getWorkingDirectory", w_getWorkingDirectory },
  848. { "getUserDirectory", w_getUserDirectory },
  849. { "getAppdataDirectory", w_getAppdataDirectory },
  850. { "getSaveDirectory", w_getSaveDirectory },
  851. { "getSourceBaseDirectory", w_getSourceBaseDirectory },
  852. { "getRealDirectory", w_getRealDirectory },
  853. { "getExecutablePath", w_getExecutablePath },
  854. { "createDirectory", w_createDirectory },
  855. { "remove", w_remove },
  856. { "read", w_read },
  857. { "write", w_write },
  858. { "append", w_append },
  859. { "getDirectoryItems", w_getDirectoryItems },
  860. { "lines", w_lines },
  861. { "load", w_load },
  862. { "exists", w_exists },
  863. { "getInfo", w_getInfo },
  864. { "setSymlinksEnabled", w_setSymlinksEnabled },
  865. { "areSymlinksEnabled", w_areSymlinksEnabled },
  866. { "newFileData", w_newFileData },
  867. { "getRequirePath", w_getRequirePath },
  868. { "setRequirePath", w_setRequirePath },
  869. { "getCRequirePath", w_getCRequirePath },
  870. { "setCRequirePath", w_setCRequirePath },
  871. // Deprecated
  872. { "newFile", w_newFile },
  873. { 0, 0 }
  874. };
  875. static const lua_CFunction types[] =
  876. {
  877. luaopen_file,
  878. luaopen_nativefile,
  879. luaopen_filedata,
  880. 0
  881. };
  882. extern "C" int luaopen_love_filesystem(lua_State *L)
  883. {
  884. Filesystem *instance = instance();
  885. if (instance == nullptr)
  886. {
  887. luax_catchexcept(L, [&](){ instance = new physfs::Filesystem(); });
  888. }
  889. else
  890. instance->retain();
  891. // The love loaders should be tried after package.preload.
  892. love::luax_register_searcher(L, loader, 2);
  893. love::luax_register_searcher(L, extloader, 3);
  894. WrappedModule w;
  895. w.module = instance;
  896. w.name = "filesystem";
  897. w.type = &Filesystem::type;
  898. w.functions = functions;
  899. w.types = types;
  900. return luax_register_module(L, w);
  901. }
  902. } // filesystem
  903. } // love