Source

love / src / modules / filesystem / physfs / wrap_Filesystem.cpp

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
/**
 * Copyright (c) 2006-2014 LOVE Development Team
 *
 * This software is provided 'as-is', without any express or implied
 * warranty.  In no event will the authors be held liable for any damages
 * arising from the use of this software.
 *
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it
 * freely, subject to the following restrictions:
 *
 * 1. The origin of this software must not be misrepresented; you must not
 *    claim that you wrote the original software. If you use this software
 *    in a product, an acknowledgment in the product documentation would be
 *    appreciated but is not required.
 * 2. Altered source versions must be plainly marked as such, and must not be
 *    misrepresented as being the original software.
 * 3. This notice may not be removed or altered from any source distribution.
 **/

// LOVE
#include "wrap_Filesystem.h"

// SDL
#include <SDL_loadso.h>

namespace love
{
namespace filesystem
{
namespace physfs
{

static Filesystem *instance = 0;

bool hack_setupWriteDirectory()
{
	if (instance != 0)
		return instance->setupWriteDirectory();
	return false;
}

int w_init(lua_State *L)
{
	const char *arg0 = luaL_checkstring(L, 1);
	EXCEPT_GUARD(instance->init(arg0);)
	return 0;
}

int w_setFused(lua_State *L)
{
	// no error checking needed, everything, even nothing
	// can be converted to a boolean
	instance->setFused(luax_toboolean(L, 1));
	return 0;
}

int w_isFused(lua_State *L)
{
	luax_pushboolean(L, instance->isFused());
	return 1;
}

int w_setIdentity(lua_State *L)
{
	const char *arg = luaL_checkstring(L, 1);
	bool append = luax_optboolean(L, 2, false);

	if (!instance->setIdentity(arg, append))
		return luaL_error(L, "Could not set write directory.");

	return 0;
}

int w_getIdentity(lua_State *L)
{
	lua_pushstring(L, instance->getIdentity());
	return 1;
}

int w_setSource(lua_State *L)
{
	const char *arg = luaL_checkstring(L, 1);

	if (!instance->setSource(arg))
		return luaL_error(L, "Could not set source.");

	return 0;
}

int w_getSource(lua_State *L)
{
	lua_pushstring(L, instance->getSource());
	return 1;
}

int w_mount(lua_State *L)
{
	const char *archive = luaL_checkstring(L, 1);
	const char *mountpoint = luaL_checkstring(L, 2);
	bool append = luax_optboolean(L, 3, false);

	luax_pushboolean(L, instance->mount(archive, mountpoint, append));
	return 1;
}

int w_unmount(lua_State *L)
{
	const char *archive = luaL_checkstring(L, 1);

	luax_pushboolean(L, instance->unmount(archive));
	return 1;
}

int w_newFile(lua_State *L)
{
	const char *filename = luaL_checkstring(L, 1);

	const char *str = 0;
	File::Mode mode = File::CLOSED;

	if (lua_isstring(L, 2))
	{
		str = luaL_checkstring(L, 2);
		if (!File::getConstant(str, mode))
			return luaL_error(L, "Incorrect file open mode: %s", str);
	}

	File *t = instance->newFile(filename);

	if (mode != File::CLOSED)
	{
		try
		{
			if (!t->open(mode))
				throw love::Exception("Could not open file.");
		}
		catch (love::Exception &e)
		{
			t->release();
			return luax_ioError(L, "%s", e.what());
		}
	}

	luax_pushtype(L, "File", FILESYSTEM_FILE_T, t);
	return 1;
}

int w_newFileData(lua_State *L)
{
	// Single argument: treat as filepath or File.
	if (lua_gettop(L) == 1)
	{
		if (lua_isstring(L, 1))
			luax_convobj(L, 1, "filesystem", "newFile");

		// Get FileData from the File.
		if (luax_istype(L, 1, FILESYSTEM_FILE_T))
		{
			File *file = luax_checktype<File>(L, 1, "File", FILESYSTEM_FILE_T);

			FileData *data = 0;
			try
			{
				data = file->read();
			}
			catch (love::Exception &e)
			{
				return luax_ioError(L, "%s", e.what());
			}
			luax_pushtype(L, "FileData", FILESYSTEM_FILE_DATA_T, data);
			return 1;
		}
		else
			return luaL_argerror(L, 1, "string or File expected");
	}

	size_t length = 0;
	const char *str = luaL_checklstring(L, 1, &length);
	const char *filename = luaL_checkstring(L, 2);
	const char *decstr = lua_isstring(L, 3) ? lua_tostring(L, 3) : 0;

	FileData::Decoder decoder = FileData::FILE;

	if (decstr && !FileData::getConstant(decstr, decoder))
		return luaL_error(L, "Invalid FileData decoder: %s", decstr);

	FileData *t = 0;

	switch (decoder)
	{
	case FileData::FILE:
		t = instance->newFileData((void *)str, (int)length, filename);
		break;
	case FileData::BASE64:
		t = instance->newFileData(str, filename);
		break;
	default:
		return luaL_error(L, "Invalid FileData decoder: %s", decstr);
	}

	luax_pushtype(L, "FileData", FILESYSTEM_FILE_DATA_T, t);
	return 1;
}

int w_getWorkingDirectory(lua_State *L)
{
	lua_pushstring(L, instance->getWorkingDirectory());
	return 1;
}

int w_getUserDirectory(lua_State *L)
{
	lua_pushstring(L, instance->getUserDirectory());
	return 1;
}

int w_getAppdataDirectory(lua_State *L)
{
	lua_pushstring(L, instance->getAppdataDirectory());
	return 1;
}

int w_getSaveDirectory(lua_State *L)
{
	lua_pushstring(L, instance->getSaveDirectory());
	return 1;
}

int w_getSourceBaseDirectory(lua_State *L)
{
	luax_pushstring(L, instance->getSourceBaseDirectory());
	return 1;
}

int w_exists(lua_State *L)
{
	const char *arg = luaL_checkstring(L, 1);
	luax_pushboolean(L, instance->exists(arg));
	return 1;
}

int w_isDirectory(lua_State *L)
{
	const char *arg = luaL_checkstring(L, 1);
	luax_pushboolean(L, instance->isDirectory(arg));
	return 1;
}

int w_isFile(lua_State *L)
{
	const char *arg = luaL_checkstring(L, 1);
	luax_pushboolean(L, instance->isFile(arg));
	return 1;
}

int w_createDirectory(lua_State *L)
{
	const char *arg = luaL_checkstring(L, 1);
	luax_pushboolean(L, instance->createDirectory(arg));
	return 1;
}

int w_remove(lua_State *L)
{
	const char *arg = luaL_checkstring(L, 1);
	luax_pushboolean(L, instance->remove(arg));
	return 1;
}

int w_read(lua_State *L)
{
	const char *filename = luaL_checkstring(L, 1);
	int64 len = (int64) luaL_optinteger(L, 2, File::ALL);

	Data *data = 0;
	try
	{
		data = instance->read(filename, len);
	}
	catch (love::Exception &e)
	{
		return luax_ioError(L, "%s", e.what());
	}

	if (data == 0)
		return luax_ioError(L, "File could not be read.");

	// Push the string.
	lua_pushlstring(L, (const char *) data->getData(), data->getSize());

	// Push the size.
	lua_pushinteger(L, data->getSize());

	// Lua has a copy now, so we can free it.
	data->release();

	return 2;
}

static int w_write_or_append(lua_State *L, File::Mode mode)
{
	const char *filename = luaL_checkstring(L, 1);

	const char *input = 0;
	size_t len = 0;

	if (luax_istype(L, 2, DATA_T))
	{
		love::Data *data = luax_totype<love::Data>(L, 2, "Data", DATA_T);
		input = (const char *) data->getData();
		len = data->getSize();
	}
	else if (lua_isstring(L, 2))
		input = lua_tolstring(L, 2, &len);
	else
		return luaL_argerror(L, 2, "string or Data expected");

	// Get how much we should write. Length of string default.
	len = luaL_optinteger(L, 3, len);

	try
	{
		if (mode == File::APPEND)
			instance->append(filename, (const void *) input, len);
		else
			instance->write(filename, (const void *) input, len);
	}
	catch (love::Exception &e)
	{
		return luax_ioError(L, "%s", e.what());
	}

	luax_pushboolean(L, true);
	return 1;
}

int w_write(lua_State *L)
{
	return w_write_or_append(L, File::WRITE);
}

int w_append(lua_State *L)
{
	return w_write_or_append(L, File::APPEND);
}

int w_getDirectoryItems(lua_State *L)
{
	return instance->getDirectoryItems(L);
}

int w_lines(lua_State *L)
{
	File *file;

	if (lua_isstring(L, 1))
	{
		file = instance->newFile(lua_tostring(L, 1));
		bool success = false;

		EXCEPT_GUARD(success = file->open(File::READ);)

		if (!success)
			return luaL_error(L, "Could not open file.");
		
		luax_pushtype(L, "File", FILESYSTEM_FILE_T, file);
	}
	else
		return luaL_argerror(L, 1, "expected filename.");

	lua_pushcclosure(L, Filesystem::lines_i, 1);
	return 1;
}

int w_load(lua_State *L)
{
	std::string filename = std::string(luaL_checkstring(L, 1));

	Data *data = 0;
	try
	{
		data = instance->read(filename.c_str());
	}
	catch (love::Exception &e)
	{
		return luax_ioError(L, "%s", e.what());
	}

	int status = luaL_loadbuffer(L, (const char *)data->getData(), data->getSize(), ("@" + filename).c_str());

	data->release();

	// Load the chunk, but don't run it.
	switch (status)
	{
	case LUA_ERRMEM:
		return luaL_error(L, "Memory allocation error: %s\n", lua_tostring(L, -1));
	case LUA_ERRSYNTAX:
		return luaL_error(L, "Syntax error: %s\n", lua_tostring(L, -1));
	default: // success
		return 1;
	}
}

int w_getLastModified(lua_State *L)
{
	const char *filename = luaL_checkstring(L, 1);

	int64 time = 0;
	try
	{
		time = instance->getLastModified(filename);
	}
	catch (love::Exception &e)
	{
		return luax_ioError(L, "%s", e.what());
	}

	lua_pushnumber(L, static_cast<lua_Number>(time));
	return 1;
}

int w_getSize(lua_State *L)
{
	const char *filename = luaL_checkstring(L, 1);

	int64 size = -1;
	try
	{
		size = instance->getSize(filename);
	}
	catch (love::Exception &e)
	{
		return luax_ioError(L, "%s", e.what());
	}

	// Error on failure or if size does not fit into a double precision floating-point number.
	if (size == -1)
		return luax_ioError(L, "Could not determine file size.");
	else if (size >= 0x20000000000000LL)
		return luax_ioError(L, "Size too large to fit into a Lua number!");

	lua_pushnumber(L, (lua_Number) size);
	return 1;
}

int loader(lua_State *L)
{
	const char *filename = lua_tostring(L, -1);

	std::string tmp(filename);
	tmp += ".lua";

	int size = tmp.size();

	for (int i=0; i<size-4; i++)
	{
		if (tmp[i] == '.')
		{
			tmp[i] = '/';
		}
	}

	// Check whether file exists.
	if (instance->exists(tmp.c_str()))
	{
		lua_pop(L, 1);
		lua_pushstring(L, tmp.c_str());
		// Ok, load it.
		return w_load(L);
	}

	tmp = filename;
	size = tmp.size();
	for (int i=0; i<size; i++)
	{
		if (tmp[i] == '.')
		{
			tmp[i] = '/';
		}
	}

	if (instance->isDirectory(tmp.c_str()))
	{
		tmp += "/init.lua";
		if (instance->exists(tmp.c_str()))
		{
			lua_pop(L, 1);
			lua_pushstring(L, tmp.c_str());
			// Ok, load it.
			return w_load(L);
		}
	}

	std::string errstr = "\n\tno file '%s' in LOVE game directories.";
	errstr += errstr;

	lua_pushfstring(L, errstr.c_str(), (tmp + ".lua").c_str(), (tmp + "/init.lua").c_str());
	return 1;
}

inline const char *library_extension()
{
#ifdef LOVE_WINDOWS
	return ".dll";
#else
	return ".so";
#endif
}

int extloader(lua_State *L)
{
	const char *filename = lua_tostring(L, -1);
	std::string tokenized_name(filename);
	std::string tokenized_function(filename);

	for (unsigned int i = 0; i < tokenized_name.size(); i++)
	{
		if (tokenized_name[i] == '.')
		{
			tokenized_name[i] = '/';
			tokenized_function[i] = '_';
		}
	}

	tokenized_name += library_extension();

	void *handle = nullptr;

	// If the game is fused, try looking for the DLL in the game's read paths.
	if (instance->isFused())
	{
		try
		{
			std::string dir = instance->getRealDirectory(tokenized_name.c_str());

			// We don't want to look in the game's source, because it can be a
			// zip sometimes and a folder other times.
			if (dir.find(instance->getSource()) == std::string::npos)
				handle = SDL_LoadObject((dir + LOVE_PATH_SEPARATOR + tokenized_name).c_str());
		}
		catch (love::Exception &)
		{
			// Nothing...
		}
	}

	if (!handle)
	{
		std::string path = std::string(instance->getAppdataDirectory()) + LOVE_PATH_SEPARATOR LOVE_APPDATA_FOLDER LOVE_PATH_SEPARATOR + tokenized_name;
		handle = SDL_LoadObject(path.c_str());
	}

	if (!handle)
	{
		lua_pushfstring(L, "\n\tno file '%s' in LOVE paths.", tokenized_name.c_str());
		return 1;
	}

	void *func = SDL_LoadFunction(handle, ("loveopen_" + tokenized_function).c_str());
	if (!func)
		func = SDL_LoadFunction(handle, ("luaopen_" + tokenized_function).c_str());

	if (!func)
	{
		SDL_UnloadObject(handle);
		lua_pushfstring(L, "\n\tC library '%s' is incompatible.", tokenized_name.c_str());
		return 1;
	}

	lua_pushcfunction(L, (lua_CFunction) func);
	return 1;
}

// List of functions to wrap.
static const luaL_Reg functions[] =
{
	{ "init",  w_init },
	{ "setFused", w_setFused },
	{ "isFused", w_isFused },
	{ "setIdentity",  w_setIdentity },
	{ "getIdentity", w_getIdentity },
	{ "setSource",  w_setSource },
	{ "getSource", w_getSource },
	{ "mount", w_mount },
	{ "unmount", w_unmount },
	{ "newFile",  w_newFile },
	{ "getWorkingDirectory",  w_getWorkingDirectory },
	{ "getUserDirectory",  w_getUserDirectory },
	{ "getAppdataDirectory",  w_getAppdataDirectory },
	{ "getSaveDirectory",  w_getSaveDirectory },
	{ "getSourceBaseDirectory", w_getSourceBaseDirectory },
	{ "exists",  w_exists },
	{ "isDirectory",  w_isDirectory },
	{ "isFile",  w_isFile },
	{ "createDirectory",  w_createDirectory },
	{ "remove",  w_remove },
	{ "read",  w_read },
	{ "write",  w_write },
	{ "append", w_append },
	{ "getDirectoryItems",  w_getDirectoryItems },
	{ "lines",  w_lines },
	{ "load",  w_load },
	{ "getLastModified", w_getLastModified },
	{ "getSize", w_getSize },
	{ "newFileData", w_newFileData },
	{ 0, 0 }
};

static const lua_CFunction types[] =
{
	luaopen_file,
	luaopen_filedata,
	0
};

extern "C" int luaopen_love_filesystem(lua_State *L)
{
	if (instance == 0)
	{
		EXCEPT_GUARD(instance = new Filesystem();)
	}
	else
		instance->retain();

	// The love loaders should be tried after package.preload.
	love::luax_register_searcher(L, loader, 2);
	love::luax_register_searcher(L, extloader, 3);

	WrappedModule w;
	w.module = instance;
	w.name = "filesystem";
	w.flags = MODULE_FILESYSTEM_T;
	w.functions = functions;
	w.types = types;

	return luax_register_module(L, w);
}

} // physfs
} // filesystem
} // love