wrap_Filesystem.cpp 25 KB

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