imported Löve GLES branch (changeset 1ba9037e558b)

This commit is contained in:
Martin Felis
2013-12-05 18:05:13 +01:00
parent 41b2db04a7
commit 2644d1ee18
615 changed files with 150300 additions and 0 deletions
+72
View File
@@ -0,0 +1,72 @@
/**
* Copyright (c) 2006-2013 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.
**/
#include "File.h"
namespace love
{
namespace filesystem
{
File::~File()
{
}
bool File::getConstant(const char *in, Mode &out)
{
return modes.find(in, out);
}
bool File::getConstant(Mode in, const char *&out)
{
return modes.find(in, out);
}
bool File::getConstant(const char *in, BufferMode &out)
{
return bufferModes.find(in, out);
}
bool File::getConstant(BufferMode in, const char *&out)
{
return bufferModes.find(in, out);
}
StringMap<File::Mode, File::MODE_MAX_ENUM>::Entry File::modeEntries[] =
{
{"c", File::CLOSED},
{"r", File::READ},
{"w", File::WRITE},
{"a", File::APPEND},
};
StringMap<File::Mode, File::MODE_MAX_ENUM> File::modes(File::modeEntries, sizeof(File::modeEntries));
StringMap<File::BufferMode, File::BUFFER_MAX_ENUM>::Entry File::bufferModeEntries[] =
{
{"none", File::BUFFER_NONE},
{"line", File::BUFFER_LINE},
{"full", File::BUFFER_FULL},
};
StringMap<File::BufferMode, File::BUFFER_MAX_ENUM> File::bufferModes(File::bufferModeEntries, sizeof(File::bufferModeEntries));
} // filesystem
} // love
+222
View File
@@ -0,0 +1,222 @@
/**
* Copyright (c) 2006-2013 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.
**/
#ifndef LOVE_FILESYSTEM_FILE_H
#define LOVE_FILESYSTEM_FILE_H
// STD
#include <string>
// LOVE
#include "common/Data.h"
#include "common/Object.h"
#include "common/StringMap.h"
#include "common/int.h"
#include "FileData.h"
namespace love
{
namespace filesystem
{
/**
* A File interface, providing generic means of reading from and
* writing to files.
**/
class File : public Object
{
public:
/**
* File open mode.
**/
enum Mode
{
CLOSED,
READ,
WRITE,
APPEND,
MODE_MAX_ENUM
};
enum BufferMode
{
BUFFER_NONE,
BUFFER_LINE,
BUFFER_FULL,
BUFFER_MAX_ENUM
};
/**
* Used to indicate ALL data in a file.
**/
static const int64 ALL = -1;
/**
* Destructor.
**/
virtual ~File();
/**
* Opens the file in a certain mode.
*
* @param mode READ, WRITE, APPEND.
* @return True if successful, false otherwise.
**/
virtual bool open(Mode mode) = 0;
/**
* Closes the file.
*
* @return True if successful, false otherwise.
**/
virtual bool close() = 0;
/**
* Gets whether the file is open.
**/
virtual bool isOpen() const = 0;
/**
* Gets the size of the file.
*
* @return The size of the file.
**/
virtual int64 getSize() = 0;
/**
* Reads data from the file and allocates a Data object.
*
* @param size The number of bytes to attempt reading, or -1 for EOF.
* @return A newly allocated Data object.
**/
virtual FileData *read(int64 size = ALL) = 0;
/**
* Reads data into the destination buffer.
*
* @param dst The destination buffer.
* @param size The number of bytes to attempt reading.
* @return The number of bytes actually read.
**/
virtual int64 read(void *dst, int64 size) = 0;
/**
* Writes data into the File.
*
* @param data The source buffer.
* @param size The size of the buffer.
* @return True of success, false otherwise.
**/
virtual bool write(const void *data, int64 size) = 0;
/**
* Writes a Data object into the File.
*
* @param data The data object to write into the file.
* @param size The number of bytes to attempt writing, or -1 for everything.
* @return True of success, false otherwise.
**/
virtual bool write(const Data *data, int64 size = ALL) = 0;
/**
* Flushes the currently buffered file data to disk. Only applicable in
* write mode.
**/
virtual bool flush() = 0;
/**
* Checks whether we are currently at end-of-file.
*
* @return True if EOF, false otherwise.
**/
virtual bool eof() = 0;
/**
* Gets the current position in the File.
*
* @return The current byte position in the File.
**/
virtual int64 tell() = 0;
/**
* Seeks to a certain position in the File.
*
* @param pos The byte position in the file.
* @return True on success, false otherwise.
**/
virtual bool seek(uint64 pos) = 0;
/**
* Sets the buffering mode for the file. When buffering is enabled, the file
* will not write to disk (or will pre-load data if in read mode) until the
* buffer's capacity is reached.
* In the BUFFER_LINE mode, the file will also write to disk if a newline is
* written.
*
* @param bufmode The buffer mode.
* @param size The size in bytes of the buffer.
**/
virtual bool setBuffer(BufferMode bufmode, int64 size) = 0;
/**
* @param[out] size The size in bytes of the buffer.
* @return The current buffer mode.
**/
virtual BufferMode getBuffer(int64 &size) const = 0;
/**
* Gets the current mode of the File.
* @return The current mode of the File; CLOSED, READ, WRITE or APPEND.
**/
virtual Mode getMode() const = 0;
/**
* Gets the filename for this File, or empty string if none.
* @return The filename for this File.
**/
virtual std::string getFilename() const = 0;
/**
* Gets the file extension for this File, or empty string if none.
* @return The file extension for this File (without the dot).
**/
virtual std::string getExtension() const = 0;
static bool getConstant(const char *in, Mode &out);
static bool getConstant(Mode in, const char *&out);
static bool getConstant(const char *in, BufferMode &out);
static bool getConstant(BufferMode in, const char *&out);
private:
static StringMap<Mode, MODE_MAX_ENUM>::Entry modeEntries[];
static StringMap<Mode, MODE_MAX_ENUM> modes;
static StringMap<BufferMode, BUFFER_MAX_ENUM>::Entry bufferModeEntries[];
static StringMap<BufferMode, BUFFER_MAX_ENUM> bufferModes;
}; // File
} // filesystem
} // love
#endif // LOVE_FILESYSTEM_FILE_H
@@ -0,0 +1,91 @@
/**
* Copyright (c) 2006-2013 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.
**/
#include "FileData.h"
// STD
#include <iostream>
#include <climits>
namespace love
{
namespace filesystem
{
FileData::FileData(uint64 size, const std::string &filename)
: data(new char[(size_t) size])
, size(size)
, filename(filename)
{
if (filename.rfind('.') != std::string::npos)
extension = filename.substr(filename.rfind('.')+1);
}
FileData::~FileData()
{
delete [] data;
}
void *FileData::getData() const
{
return (void *)data;
}
// TODO: Enable this
/*uint64 FileData::getSize() const
{
return size;
}*/
int FileData::getSize() const
{
return size > INT_MAX ? INT_MAX : (int) size;
}
const std::string &FileData::getFilename() const
{
return filename;
}
const std::string &FileData::getExtension() const
{
return extension;
}
bool FileData::getConstant(const char *in, Decoder &out)
{
return decoders.find(in, out);
}
bool FileData::getConstant(Decoder in, const char *&out)
{
return decoders.find(in, out);
}
StringMap<FileData::Decoder, FileData::DECODE_MAX_ENUM>::Entry FileData::decoderEntries[] =
{
{"file", FileData::FILE},
{"base64", FileData::BASE64},
};
StringMap<FileData::Decoder, FileData::DECODE_MAX_ENUM> FileData::decoders(FileData::decoderEntries, sizeof(FileData::decoderEntries));
} // filesystem
} // love
@@ -0,0 +1,84 @@
/**
* Copyright (c) 2006-2013 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.
**/
#ifndef LOVE_FILESYSTEM_FILE_DATA_H
#define LOVE_FILESYSTEM_FILE_DATA_H
// LOVE
#include <string>
#include "common/Data.h"
#include "common/StringMap.h"
#include "common/int.h"
namespace love
{
namespace filesystem
{
class FileData : public Data
{
public:
enum Decoder
{
FILE,
BASE64,
DECODE_MAX_ENUM
}; // Decoder
FileData(uint64 size, const std::string &filename);
virtual ~FileData();
// Implements Data.
void *getData() const;
//TODO: Enable this
//uint64 getSize() const;
int getSize() const;
const std::string &getFilename() const;
const std::string &getExtension() const;
static bool getConstant(const char *in, Decoder &out);
static bool getConstant(Decoder in, const char *&out);
private:
// The actual data.
char *data;
// Size of the data.
uint64 size;
// The filename used for error purposes.
std::string filename;
// The extension (without dot). Used to identify file type.
std::string extension;
static StringMap<Decoder, DECODE_MAX_ENUM>::Entry decoderEntries[];
static StringMap<Decoder, DECODE_MAX_ENUM> decoders;
}; // FileData
} // filesystem
} // love
#endif // LOVE_FILESYSTEM_FILE_DATA_H
@@ -0,0 +1,342 @@
/**
* Copyright (c) 2006-2013 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.
**/
#include "File.h"
// STD
#include <cstring>
// LOVE
#include "Filesystem.h"
#include "filesystem/FileData.h"
namespace love
{
namespace filesystem
{
namespace physfs
{
extern bool hack_setupWriteDirectory();
File::File(const std::string &filename)
: filename(filename)
, file(0)
, mode(CLOSED)
, bufferMode(BUFFER_NONE)
, bufferSize(0)
{
}
File::~File()
{
if (mode != CLOSED)
close();
}
bool File::open(Mode mode)
{
if (mode == CLOSED)
return true;
// File must exist if read mode.
if ((mode == READ) && !PHYSFS_exists(filename.c_str()))
throw love::Exception("Could not open file %s. Does not exist.", filename.c_str());
// Check whether the write directory is set.
if ((mode == APPEND || mode == WRITE) && (PHYSFS_getWriteDir() == 0) && !hack_setupWriteDirectory())
throw love::Exception("Could not set write directory.");
// File already open?
if (file != 0)
return false;
this->mode = mode;
switch (mode)
{
case READ:
file = PHYSFS_openRead(filename.c_str());
break;
case APPEND:
file = PHYSFS_openAppend(filename.c_str());
break;
case WRITE:
file = PHYSFS_openWrite(filename.c_str());
break;
default:
break;
}
if (file != 0 && !setBuffer(bufferMode, bufferSize))
{
// Revert to buffer defaults if we don't successfully set the buffer.
bufferMode = BUFFER_NONE;
bufferSize = 0;
}
return (file != 0);
}
bool File::close()
{
if (!PHYSFS_close(file))
return false;
mode = CLOSED;
file = 0;
return true;
}
bool File::isOpen() const
{
return mode != CLOSED && file != 0;
}
int64 File::getSize()
{
// If the file is closed, open it to
// check the size.
if (file == 0)
{
open(READ);
int64 size = (int64)PHYSFS_fileLength(file);
close();
return size;
}
return (int64)PHYSFS_fileLength(file);
}
FileData *File::read(int64 size)
{
bool isOpen = (file != 0);
if (!isOpen && !open(READ))
throw love::Exception("Could not read file %s.", filename.c_str());
int64 max = getSize();
int64 cur = tell();
size = (size == ALL) ? max : size;
if (size < 0)
throw love::Exception("Invalid read size.");
// Clamping because the file offset may be in a weird position.
if (cur < 0)
cur = 0;
else if (cur > max)
cur = max;
if (cur + size > max)
size = max - cur;
FileData *fileData = new FileData(size, getFilename());
int64 bytesRead = read(fileData->getData(), size);
if (bytesRead < 0 || (bytesRead == 0 && bytesRead != size))
{
delete fileData;
throw love::Exception("Could not read from file.");
}
if (bytesRead < size)
{
FileData *tmpFileData = new FileData(bytesRead, getFilename());
memcpy(tmpFileData->getData(), fileData->getData(), (size_t) bytesRead);
delete fileData;
fileData = tmpFileData;
}
if (!isOpen)
close();
return fileData;
}
int64 File::read(void *dst, int64 size)
{
if (!file || mode != READ)
throw love::Exception("File is not opened for reading.");
int64 max = (int64)PHYSFS_fileLength(file);
size = (size == ALL) ? max : size;
size = (size > max) ? max : size;
// Sadly, we'll have to clamp to 32 bits here
size = (size > LOVE_UINT32_MAX) ? LOVE_UINT32_MAX : size;
if (size < 0)
throw love::Exception("Invalid read size.");
int64 read = (int64)PHYSFS_read(file, dst, 1, (PHYSFS_uint32) size);
return read;
}
bool File::write(const void *data, int64 size)
{
if (!file || (mode != WRITE && mode != APPEND))
throw love::Exception("File is not opened for writing.");
// Another clamp, for the time being.
size = (size > LOVE_UINT32_MAX) ? LOVE_UINT32_MAX : size;
if (size < 0)
throw love::Exception("Invalid write size.");
// Try to write.
int64 written = static_cast<int64>(PHYSFS_write(file, data, 1, (PHYSFS_uint32) size));
// Check that correct amount of data was written.
if (written != size)
return false;
// Manually flush the buffer in BUFFER_LINE mode if we find a newline.
if (bufferMode == BUFFER_LINE && bufferSize > size)
{
if (memchr(data, '\n', (size_t) size) != NULL)
flush();
}
return true;
}
bool File::write(const Data *data, int64 size)
{
return write(data->getData(), (size == ALL) ? data->getSize() : size);
}
bool File::flush()
{
if (!file || (mode != WRITE && mode != APPEND))
throw love::Exception("File is not opened for writing.");
return PHYSFS_flush(file) != 0;
}
#ifdef LOVE_WINDOWS
// MSVC doesn't like the 'this' keyword
// well, we'll use 'that'.
// It zigs, we zag.
inline bool test_eof(File *that, PHYSFS_File *)
{
int64 pos = that->tell();
int64 size = that->getSize();
return pos == -1 || size == -1 || pos >= size;
}
#else
inline bool test_eof(File *, PHYSFS_File *file)
{
return PHYSFS_eof(file);
}
#endif
bool File::eof()
{
if (file == 0 || test_eof(this, file))
return true;
return false;
}
int64 File::tell()
{
if (file == 0)
return -1;
return (int64) PHYSFS_tell(file);
}
bool File::seek(uint64 pos)
{
if (file == 0)
return false;
if (!PHYSFS_seek(file, (PHYSFS_uint64) pos))
return false;
return true;
}
bool File::setBuffer(BufferMode bufmode, int64 size)
{
// No negativity allowed!
if (size < 0)
return false;
// If the file isn't open, we'll make sure the buffer values are set in
// File::open.
if (file == 0 || mode == CLOSED)
{
bufferMode = bufmode;
bufferSize = size;
return true;
}
int ret = 1;
switch (bufmode)
{
case BUFFER_NONE:
default:
ret = PHYSFS_setBuffer(file, 0);
size = 0;
break;
case BUFFER_LINE:
case BUFFER_FULL:
ret = PHYSFS_setBuffer(file, size);
break;
}
if (ret == 0)
return false;
bufferMode = bufmode;
bufferSize = size;
return true;
}
File::BufferMode File::getBuffer(int64 &size) const
{
size = bufferSize;
return bufferMode;
}
std::string File::getFilename() const
{
return filename;
}
std::string File::getExtension() const
{
std::string::size_type idx = filename.rfind('.');
if (idx != std::string::npos)
return filename.substr(idx+1);
else
return std::string();
}
filesystem::File::Mode File::getMode() const
{
return mode;
}
} // physfs
} // filesystem
} // love
@@ -0,0 +1,95 @@
/**
* Copyright (c) 2006-2013 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.
**/
#ifndef LOVE_FILESYSTEM_PHYSFS_FILE_H
#define LOVE_FILESYSTEM_PHYSFS_FILE_H
// LOVE
#include "filesystem/File.h"
// PhysFS
#ifdef LOVE_MACOSX // wacky Mac behavior means different #include syntax!
#include <physfs/physfs.h>
#else
#include <physfs.h>
#endif
// STD
#include <string>
namespace love
{
namespace filesystem
{
namespace physfs
{
class File : public love::filesystem::File
{
public:
/**
* Constructs an File with the given ilename.
* @param filename The relative filepath of the file to load.
**/
File(const std::string &filename);
virtual ~File();
// Implements love::filesystem::File.
bool open(Mode mode);
bool close();
bool isOpen() const;
int64 getSize();
FileData *read(int64 size = ALL);
int64 read(void *dst, int64 size);
bool write(const void *data, int64 size);
bool write(const Data *data, int64 size = ALL);
bool flush();
bool eof();
int64 tell();
bool seek(uint64 pos);
bool setBuffer(BufferMode bufmode, int64 size);
BufferMode getBuffer(int64 &size) const;
Mode getMode() const;
std::string getFilename() const;
std::string getExtension() const;
private:
// filename
std::string filename;
// PHYSFS File handle.
PHYSFS_File *file;
// The current mode of the file.
Mode mode;
BufferMode bufferMode;
int64 bufferSize;
}; // File
} // physfs
} // filesystem
} // love
#endif // LOVE_FILESYSTEM_PHYSFS_FILE_H
@@ -0,0 +1,609 @@
/**
* Copyright (c) 2006-2013 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.
**/
#include "common/config.h"
#include <iostream>
#include "common/utf8.h"
#include "common/b64.h"
#include "Filesystem.h"
namespace
{
size_t getDriveDelim(const std::string &input)
{
for (size_t i = 0; i < input.size(); ++i)
if (input[i] == '/' || input[i] == '\\')
return i;
// Something's horribly wrong
return 0;
}
std::string getDriveRoot(const std::string &input)
{
return input.substr(0, getDriveDelim(input)+1);
}
std::string skipDriveRoot(const std::string &input)
{
return input.substr(getDriveDelim(input)+1);
}
}
namespace love
{
namespace filesystem
{
namespace physfs
{
Filesystem::Filesystem()
: initialized(false)
, fused(false)
, fusedSet(false)
{
}
Filesystem::~Filesystem()
{
if (initialized)
PHYSFS_deinit();
}
const char *Filesystem::getName() const
{
return "love.filesystem.physfs";
}
void Filesystem::init(const char *arg0)
{
if (!PHYSFS_init(arg0))
throw Exception(PHYSFS_getLastError());
initialized = true;
}
void Filesystem::setFused(bool fused)
{
if (fusedSet)
return;
this->fused = fused;
fusedSet = true;
}
bool Filesystem::isFused() const
{
if (!fusedSet)
return false;
return fused;
}
bool Filesystem::setIdentity(const char *ident, bool appendToPath)
{
if (!initialized)
return false;
std::string old_save_path = save_path_full;
// Store the save directory.
save_identity = std::string(ident);
// Generate the relative path to the game save folder.
save_path_relative = std::string(LOVE_APPDATA_PREFIX LOVE_APPDATA_FOLDER LOVE_PATH_SEPARATOR) + save_identity;
// Generate the full path to the game save folder.
save_path_full = std::string(getAppdataDirectory()) + std::string(LOVE_PATH_SEPARATOR);
if (fused)
save_path_full += std::string(LOVE_APPDATA_PREFIX) + save_identity;
else
save_path_full += save_path_relative;
// We now have something like:
// save_identity: game
// save_path_relative: ./LOVE/game
// save_path_full: C:\Documents and Settings\user\Application Data/LOVE/game
// We don't want old read-only save paths to accumulate when we set a new
// identity.
if (!old_save_path.empty())
PHYSFS_removeFromSearchPath(old_save_path.c_str());
// Try to add the save directory to the search path.
// (No error on fail, it means that the path doesn't exist).
PHYSFS_addToSearchPath(save_path_full.c_str(), appendToPath);
return true;
}
const char *Filesystem::getIdentity() const
{
return save_identity.c_str();
}
bool Filesystem::setSource(const char *source)
{
if (!initialized)
return false;
// Check whether directory is already set.
if (!game_source.empty())
return false;
// Add the directory.
if (!PHYSFS_addToSearchPath(source, 1))
return false;
// Save the game source.
game_source = std::string(source);
return true;
}
const char *Filesystem::getSource() const
{
return game_source.c_str();
}
bool Filesystem::setupWriteDirectory()
{
if (!initialized)
return false;
// These must all be set.
if (save_identity.empty() || save_path_full.empty() || save_path_relative.empty())
return false;
// Set the appdata folder as writable directory.
// (We must create the save folder before mounting it).
if (!PHYSFS_setWriteDir(getDriveRoot(save_path_full).c_str()))
return false;
// Create the save folder. (We're now "at" %APPDATA%).
if (!createDirectory(skipDriveRoot(save_path_full).c_str()))
{
// Clear the write directory in case of error.
PHYSFS_setWriteDir(0);
return false;
}
// Set the final write directory.
if (!PHYSFS_setWriteDir(save_path_full.c_str()))
return false;
// Add the directory. (Will not be readded if already present).
if (!PHYSFS_addToSearchPath(save_path_full.c_str(), 0))
{
PHYSFS_setWriteDir(0); // Clear the write directory in case of error.
return false;
}
return true;
}
bool Filesystem::mount(const char *archive, const char *mountpoint, bool appendToPath)
{
if (!initialized || !archive)
return false;
std::string realPath;
std::string sourceBase = getSourceBaseDirectory();
if (isFused() && sourceBase.compare(archive) == 0)
{
// Special case: if the game is fused and the archive is the source's
// base directory, mount it even though it's outside of the save dir.
realPath = sourceBase;
}
else
{
// Not allowed for safety reasons.
if (strlen(archive) == 0 || strstr(archive, "..") || strcmp(archive, "/") == 0)
return false;
const char *realDir = PHYSFS_getRealDir(archive);
if (!realDir)
return false;
realPath = realDir;
// Always disallow mounting of files inside the game source, since it
// won't work anyway if the game source is a zipped .love file.
if (realPath.find(game_source) == 0)
return false;
realPath += LOVE_PATH_SEPARATOR;
realPath += archive;
}
if (realPath.length() == 0)
return false;
return PHYSFS_mount(realPath.c_str(), mountpoint, appendToPath);
}
bool Filesystem::unmount(const char *archive)
{
if (!initialized || !archive)
return false;
std::string realPath;
std::string sourceBase = getSourceBaseDirectory();
if (isFused() && sourceBase.compare(archive) == 0)
{
// Special case: if the game is fused and the archive is the source's
// base directory, unmount it even though it's outside of the save dir.
realPath = sourceBase;
}
else
{
// Not allowed for safety reasons.
if (strlen(archive) == 0 || strstr(archive, "..") || strcmp(archive, "/") == 0)
return false;
const char *realDir = PHYSFS_getRealDir(archive);
if (!realDir)
return false;
realPath = realDir;
realPath += LOVE_PATH_SEPARATOR;
realPath += archive;
}
const char *mountPoint = PHYSFS_getMountPoint(realPath.c_str());
if (!mountPoint)
return false;
return PHYSFS_removeFromSearchPath(realPath.c_str());
}
File *Filesystem::newFile(const char *filename) const
{
return new File(filename);
}
FileData *Filesystem::newFileData(void *data, unsigned int size, const char *filename) const
{
FileData *fd = new FileData(size, std::string(filename));
// Copy the data into FileData.
memcpy(fd->getData(), data, size);
return fd;
}
FileData *Filesystem::newFileData(const char *b64, const char *filename) const
{
int size = strlen(b64);
int outsize = 0;
char *dst = b64_decode(b64, size, outsize);
FileData *fd = new FileData(outsize, std::string(filename));
// Copy the data into FileData.
memcpy(fd->getData(), dst, outsize);
delete [] dst;
return fd;
}
const char *Filesystem::getWorkingDirectory()
{
if (cwd.empty())
{
#ifdef LOVE_WINDOWS
WCHAR w_cwd[LOVE_MAX_PATH];
_wgetcwd(w_cwd, LOVE_MAX_PATH);
cwd = to_utf8(w_cwd);
replace_char(cwd, '\\', '/');
#else
char *cwd_char = new char[LOVE_MAX_PATH];
if (getcwd(cwd_char, LOVE_MAX_PATH))
cwd = cwd_char; // if getcwd fails, cwd_char (and thus cwd) will still be empty
delete [] cwd_char;
#endif
}
return cwd.c_str();
}
const char *Filesystem::getUserDirectory()
{
return PHYSFS_getUserDir();
}
const char *Filesystem::getAppdataDirectory()
{
#ifdef LOVE_WINDOWS
if (appdata.empty())
{
wchar_t *w_appdata = _wgetenv(L"APPDATA");
appdata = to_utf8(w_appdata);
replace_char(appdata, '\\', '/');
}
return appdata.c_str();
#elif defined(LOVE_MACOSX)
if (appdata.empty())
{
std::string udir = getUserDirectory();
udir.append("/Library/Application Support");
appdata = udir;
}
return appdata.c_str();
#elif defined(LOVE_LINUX)
if (appdata.empty())
{
char *xdgdatahome = getenv("XDG_DATA_HOME");
if (!xdgdatahome)
appdata = std::string(getUserDirectory()) + "/.local/share/";
else
appdata = xdgdatahome;
}
return appdata.c_str();
#else
return getUserDirectory();
#endif
}
const char *Filesystem::getSaveDirectory()
{
return save_path_full.c_str();
}
std::string Filesystem::getSourceBaseDirectory() const
{
size_t source_len = game_source.length();
if (source_len == 0)
return "";
// FIXME: This doesn't take into account parent and current directory
// symbols (i.e. '..' and '.')
#ifdef LOVE_WINDOWS
// In windows, delimiters can be either '/' or '\'.
size_t base_end_pos = game_source.find_last_of("/\\", source_len - 2);
#else
size_t base_end_pos = game_source.find_last_of('/', source_len - 2);
#endif
if (base_end_pos == std::string::npos)
return "";
// If the source is in the unix root (aka '/'), we want to keep the '/'.
if (base_end_pos == 0)
base_end_pos = 1;
return game_source.substr(0, base_end_pos);
}
bool Filesystem::exists(const char *file) const
{
return PHYSFS_exists(file);
}
bool Filesystem::isDirectory(const char *file) const
{
return PHYSFS_isDirectory(file);
}
bool Filesystem::isFile(const char *file) const
{
return exists(file) && !isDirectory(file);
}
bool Filesystem::createDirectory(const char *dir)
{
if (PHYSFS_getWriteDir() == 0 && !setupWriteDirectory())
return false;
if (!PHYSFS_mkdir(dir))
return false;
return true;
}
bool Filesystem::remove(const char *file)
{
if (PHYSFS_getWriteDir() == 0 && !setupWriteDirectory())
return false;
if (!PHYSFS_delete(file))
return false;
return true;
}
Data *Filesystem::read(const char *filename, int64 size) const
{
File file(filename);
file.open(File::READ);
// close() is called in the File destructor.
return file.read(size);
}
void Filesystem::write(const char *filename, const void *data, int64 size) const
{
File file(filename);
file.open(File::WRITE);
// close() is called in the File destructor.
if (!file.write(data, size))
throw love::Exception("Data could not be written.");
}
void Filesystem::append(const char *filename, const void *data, int64 size) const
{
File file(filename);
file.open(File::APPEND);
// close() is called in the File destructor.
if (!file.write(data, size))
throw love::Exception("Data could not be written.");
}
int Filesystem::getDirectoryItems(lua_State *L)
{
const char *dir = luaL_checkstring(L, 1);
char **rc = PHYSFS_enumerateFiles(dir);
int index = 1;
lua_newtable(L);
for (char **i = rc; *i != 0; i++)
{
lua_pushstring(L, *i);
lua_rawseti(L, -2, index);
index++;
}
PHYSFS_freeList(rc);
return 1;
}
int Filesystem::lines_i(lua_State *L)
{
const int bufsize = 1024;
char buf[bufsize];
int linesize = 0;
bool newline = false;
File *file = luax_checktype<File>(L, lua_upvalueindex(1), "File", FILESYSTEM_FILE_T);
// Only accept read mode at this point.
if (file->getMode() != File::READ)
return luaL_error(L, "File needs to stay in read mode.");
int64 pos = file->tell();
int64 userpos = -1;
if (lua_isnoneornil(L, lua_upvalueindex(2)) == 0)
{
// User may have changed the file position.
userpos = pos;
pos = (int64) lua_tonumber(L, lua_upvalueindex(2));
if (userpos != pos)
file->seek(pos);
}
while (!newline && !file->eof())
{
// This 64-bit to 32-bit integer cast should be safe as it never exceeds bufsize.
int read = (int) file->read(buf, bufsize);
if (read < 0)
return luaL_error(L, "Could not read from file.");
linesize += read;
for (int i = 0; i < read; i++)
{
if (buf[i] == '\n')
{
linesize -= read - i;
newline = true;
break;
}
}
}
if (newline || (file->eof() && linesize > 0))
{
if (linesize < bufsize)
{
// We have the line in the buffer on the stack. No 'new' and 'read' needed.
lua_pushlstring(L, buf, linesize > 0 && buf[linesize - 1] == '\r' ? linesize - 1 : linesize);
if (userpos < 0)
file->seek(pos + linesize + 1);
}
else
{
char *str = 0;
try
{
str = new char[linesize + 1];
}
catch(std::bad_alloc &)
{
// Can't lua_error (longjmp) in exception handlers.
}
if (!str)
return luaL_error(L, "Out of memory.");
file->seek(pos);
// Read the \n anyway and save us a call to seek.
if (file->read(str, linesize + 1) == -1)
{
delete [] str;
return luaL_error(L, "Could not read from file.");
}
lua_pushlstring(L, str, str[linesize - 1] == '\r' ? linesize - 1 : linesize);
delete [] str;
}
if (userpos >= 0)
{
// Save new position in upvalue.
lua_pushnumber(L, (lua_Number)(pos + linesize + 1));
lua_replace(L, lua_upvalueindex(2));
file->seek(userpos);
}
return 1;
}
// EOF reached.
if (userpos >= 0 && luax_toboolean(L, lua_upvalueindex(3)))
file->seek(userpos);
else
file->close();
return 0;
}
int64 Filesystem::getLastModified(const char *filename) const
{
PHYSFS_sint64 time = PHYSFS_getLastModTime(filename);
if (time == -1)
throw love::Exception("Could not determine file modification date.");
return time;
}
int64 Filesystem::getSize(const char *filename) const
{
File file(filename);
int64 size = file.getSize();
return size;
}
} // physfs
} // filesystem
} // love
@@ -0,0 +1,315 @@
/**
* Copyright (c) 2006-2013 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.
**/
#ifndef LOVE_FILESYSTEM_PHYSFS_FILESYSTEM_H
#define LOVE_FILESYSTEM_PHYSFS_FILESYSTEM_H
// STD
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
// LOVE
#include "common/Module.h"
#include "common/config.h"
#include "common/int.h"
#include "filesystem/FileData.h"
#include "File.h"
// For great CWD. (Current Working Directory)
// Using this instead of boost::filesystem which totally
// cramped our style.
#ifdef LOVE_WINDOWS
# include <windows.h>
# include <direct.h>
#else
# include <sys/param.h>
# include <unistd.h>
#endif
// In Windows, we would like to use "LOVE" as the
// application folder, but in Linux, we like .love.
#define LOVE_APPDATA_PREFIX ""
#ifdef LOVE_WINDOWS
# define LOVE_APPDATA_FOLDER "LOVE"
# define LOVE_PATH_SEPARATOR "/"
# define LOVE_MAX_PATH _MAX_PATH
#else
# ifdef LOVE_MACOSX
# define LOVE_APPDATA_FOLDER "LOVE"
# elif defined(LOVE_LINUX)
# define LOVE_APPDATA_FOLDER "love"
# else
# define LOVE_APPDATA_PREFIX "."
# define LOVE_APPDATA_FOLDER "love"
# endif
# define LOVE_PATH_SEPARATOR "/"
# define LOVE_MAX_PATH MAXPATHLEN
#endif
namespace love
{
namespace filesystem
{
namespace physfs
{
class Filesystem : public Module
{
public:
Filesystem();
virtual ~Filesystem();
const char *getName() const;
void init(const char *arg0);
void setFused(bool fused);
bool isFused() const;
/**
* This sets up the save directory. If the
* it is already set up, nothing happens.
* @return True on success, false otherwise.
**/
bool setupWriteDirectory();
/**
* Sets the name of the save folder.
* @param ident The name of the game. Will be used to
* to create the folder in the LOVE data folder.
**/
bool setIdentity(const char *ident, bool appendToPath = false);
const char *getIdentity() const;
/**
* Sets the path to the game source.
* This can only be set once.
* @param source Path to a directory or a .love-file.
**/
bool setSource(const char *source);
/**
* Gets the path to the game source.
* Returns a 0-length string if the source has not been set.
**/
const char *getSource() const;
bool mount(const char *archive, const char *mountpoint, bool appendToPath = false);
bool unmount(const char *archive);
/**
* Creates a new file.
**/
File *newFile(const char *filename) const;
/**
* Creates a new FileData object. Data will be copied.
* @param data Pointer to the data.
* @param size The size of the data.
* @param filename The full filename used to file type identification.
**/
FileData *newFileData(void *data, unsigned int size, const char *filename) const;
/**
* Creates a new FileData object from base64 data.
* @param b64 The base64 data.
**/
FileData *newFileData(const char *b64, const char *filename) const;
/**
* Gets the current working directory.
**/
const char *getWorkingDirectory();
/**
* Gets the user home directory.
**/
const char *getUserDirectory();
/**
* Gets the APPDATA directory. On Windows, this is the folder
* in the %APPDATA% enviroment variable. On Linux, this is the
* user home folder.
**/
const char *getAppdataDirectory();
/**
* Gets the full path of the save folder.
**/
const char *getSaveDirectory();
/**
* Gets the full path to the directory containing the game source.
* For example if the game source is C:\Games\mygame.love, this will return
* C:\Games.
**/
std::string getSourceBaseDirectory() const;
/**
* Checks whether a file exists in the current search path
* or not.
* @param file The filename to check.
**/
bool exists(const char *file) const;
/**
* Checks if an existing file really is a directory.
* @param file The filename to check.
**/
bool isDirectory(const char *file) const;
/**
* Checks if an existing file really is a file,
* and not a directory.
* @param file The filename to check.
**/
bool isFile(const char *file) const;
/**
* Creates a directory. Write dir must be set.
* @param dir The directory to create.
**/
bool createDirectory(const char *dir);
/**
* Removes a file (or directory).
* @param file The file or directory to remove.
**/
bool remove(const char *file);
/**
* Opens a file for reading or writing. (Depends
* on the mode chosen at the time of creation).
* @param file The file to open.
* @param mode The mode to open the file in.
**/
bool open(File *file, File::Mode mode);
/**
* Closes a file.
* @param file The file to close.
**/
bool close(File *file);
/**
* Reads data from a file.
* @param filename The name of the file to read from.
* @param size The size in bytes of the data to read.
**/
Data *read(const char *filename, int64 size = File::ALL) const;
/**
* Write data to a file.
* @param filename The name of the file to write to.
* @param data The data to write.
* @param size The size in bytes of the data to write.
**/
void write(const char *filename, const void *data, int64 size) const;
/**
* Append data to a file, creating it if it doesn't exist.
* @param filename The name of the file to write to.
* @param data The data to append.
* @param size The size in bytes of the data to append.
**/
void append(const char *filename, const void *data, int64 size) const;
/**
* Check if end-of-file is reached.
* @return True if EOF, false otherwise.
**/
bool eof(File *file);
/**
* Gets the current position in a file.
* @param file An open File.
**/
int tell(File *file);
/**
* Seek to a position within a file.
* @param pos The position to seek to.
**/
bool seek(File *file, uint64 pos);
/**
* This "native" method returns a table of all
* files in a given directory.
**/
int getDirectoryItems(lua_State *L);
/**
* Gets the last modification time of a file, in seconds
* since the Unix epoch.
* @param filename The name of the file.
**/
int64 getLastModified(const char *filename) const;
/**
* Gets the size of a file in bytes.
* @param filename The name of the file.
**/
int64 getSize(const char *filename) const;
/**
* Text file line-reading iterator function used and
* pushed on the Lua stack by love.filesystem.lines
* and File:lines.
**/
static int lines_i(lua_State *L);
private:
// Contains the current working directory (UTF8).
std::string cwd;
// %APPDATA% on Windows.
std::string appdata;
// This name will be used to create the folder
// in the appdata/userdata folder.
std::string save_identity;
// Full and relative paths of the game save folder.
// (Relative to the %APPDATA% folder, meaning that the
// relative string will look something like: ./LOVE/game)
std::string save_path_relative, save_path_full;
// The full path to the source of the game.
std::string game_source;
// Workaround for machines without PhysFS 2.0
bool initialized;
// Allow saving outside of the LOVE_APPDATA_FOLDER
// for release 'builds'
bool fused;
bool fusedSet;
}; // Filesystem
} // physfs
} // filesystem
} // love
#endif // LOVE_FILESYSTEM_PHYSFS_FILESYSTEM_H
@@ -0,0 +1,328 @@
/**
* Copyright (c) 2006-2013 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.
**/
#include "wrap_File.h"
#include "common/Data.h"
#include "common/Exception.h"
#include "common/int.h"
namespace love
{
namespace filesystem
{
namespace physfs
{
int luax_ioError(lua_State *L, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
lua_pushnil(L);
lua_pushvfstring(L, fmt, args);
va_end(args);
return 2;
}
File *luax_checkfile(lua_State *L, int idx)
{
return luax_checktype<File>(L, idx, "File", FILESYSTEM_FILE_T);
}
int w_File_getSize(lua_State *L)
{
File *t = luax_checkfile(L, 1);
int64 size = -1;
try
{
size = t->getSize();
}
catch (love::Exception &e)
{
return luax_ioError(L, "%s", e.what());
}
// Push nil 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 is too large.");
lua_pushnumber(L, (lua_Number) size);
return 1;
}
int w_File_open(lua_State *L)
{
File *file = luax_checkfile(L, 1);
const char *str = luaL_checkstring(L, 2);
File::Mode mode;
if (!File::getConstant(str, mode))
return luaL_error(L, "Incorrect file open mode: %s", str);
try
{
luax_pushboolean(L, file->open(mode));
}
catch (love::Exception &e)
{
return luax_ioError(L, "%s", e.what());
}
return 1;
}
int w_File_close(lua_State *L)
{
File *file = luax_checkfile(L, 1);
luax_pushboolean(L, file->close());
return 1;
}
int w_File_isOpen(lua_State *L)
{
File *file = luax_checkfile(L, 1);
luax_pushboolean(L, file->isOpen());
return 1;
}
int w_File_read(lua_State *L)
{
File *file = luax_checkfile(L, 1);
Data *d = 0;
int64 size = (int64)luaL_optnumber(L, 2, File::ALL);
try
{
d = file->read(size);
}
catch (love::Exception &e)
{
return luax_ioError(L, "%s", e.what());
}
lua_pushlstring(L, (const char *) d->getData(), d->getSize());
lua_pushnumber(L, d->getSize());
d->release();
return 2;
}
int w_File_write(lua_State *L)
{
File *file = luax_checkfile(L, 1);
bool result = false;
if (lua_isstring(L, 2))
{
try
{
size_t datasize = 0;
const char *data = lua_tolstring(L, 2, &datasize);
if (!lua_isnoneornil(L, 3))
datasize = luaL_checkinteger(L, 3);
result = file->write(data, datasize);
}
catch (love::Exception &e)
{
return luax_ioError(L, "%s", e.what());
}
}
else if (luax_istype(L, 2, DATA_T))
{
try
{
love::Data *data = luax_totype<love::Data>(L, 2, "Data", DATA_T);
result = file->write(data, luaL_optinteger(L, 3, data->getSize()));
}
catch (love::Exception &e)
{
return luax_ioError(L, "%s", e.what());
}
}
else
{
return luaL_argerror(L, 2, "string or data expected");
}
luax_pushboolean(L, result);
return 1;
}
int w_File_flush(lua_State *L)
{
File *file = luax_checkfile(L, 1);
bool success = false;
try
{
success = file->flush();
}
catch (love::Exception &e)
{
return luax_ioError(L, "%s", e.what());
}
luax_pushboolean(L, success);
return 1;
}
int w_File_eof(lua_State *L)
{
File *file = luax_checkfile(L, 1);
luax_pushboolean(L, file->eof());
return 1;
}
int w_File_tell(lua_State *L)
{
File *file = luax_checkfile(L, 1);
int64 pos = file->tell();
// Push nil on failure or if pos does not fit into a double precision floating-point number.
if (pos == -1)
return luax_ioError(L, "Invalid position.");
else if (pos >= 0x20000000000000LL)
return luax_ioError(L, "Number is too large.");
else
lua_pushnumber(L, (lua_Number)pos);
return 1;
}
int w_File_seek(lua_State *L)
{
File *file = luax_checkfile(L, 1);
lua_Number pos = luaL_checknumber(L, 2);
// Push false on negative and precision-problematic numbers.
// Better fail than seek to an unknown position.
if (pos < 0.0 || pos >= 9007199254740992.0)
luax_pushboolean(L, false);
else
luax_pushboolean(L, file->seek((uint64)pos));
return 1;
}
int w_File_lines(lua_State *L)
{
File *file = luax_checkfile(L, 1);
lua_pushnumber(L, 0); // File position.
luax_pushboolean(L, file->getMode() != File::CLOSED); // Save current file mode.
if (file->getMode() != File::READ)
{
if (file->getMode() != File::CLOSED)
file->close();
bool success = false;
EXCEPT_GUARD(success = file->open(File::READ);)
if (!success)
return luaL_error(L, "Could not open file.");
}
lua_pushcclosure(L, Filesystem::lines_i, 3);
return 1;
}
int w_File_setBuffer(lua_State *L)
{
File *file = luax_checkfile(L, 1);
const char *str = luaL_checkstring(L, 2);
int64 size = (int64) luaL_optnumber(L, 3, 0.0);
File::BufferMode bufmode;
if (!File::getConstant(str, bufmode))
return luaL_error(L, "Incorrect file buffer mode: %s", str);
bool success = false;
try
{
success = file->setBuffer(bufmode, size);
}
catch (love::Exception &e)
{
return luax_ioError(L, "%s", e.what());
}
luax_pushboolean(L, success);
return 1;
}
int w_File_getBuffer(lua_State *L)
{
File *file = luax_checkfile(L, 1);
int64 size = 0;
File::BufferMode bufmode = file->getBuffer(size);
const char *str = 0;
if (!File::getConstant(bufmode, str))
return luax_ioError(L, "Unknown file buffer mode.");
lua_pushstring(L, str);
lua_pushnumber(L, (lua_Number) size);
return 2;
}
int w_File_getMode(lua_State *L)
{
File *file = luax_checkfile(L, 1);
File::Mode mode = file->getMode();
const char *str = 0;
if (!File::getConstant(mode, str))
return luax_ioError(L, "Unknown file mode.");
lua_pushstring(L, str);
return 1;
}
static const luaL_Reg functions[] =
{
{ "getSize", w_File_getSize },
{ "open", w_File_open },
{ "close", w_File_close },
{ "isOpen", w_File_isOpen },
{ "read", w_File_read },
{ "write", w_File_write },
{ "flush", w_File_flush },
{ "eof", w_File_eof },
{ "tell", w_File_tell },
{ "seek", w_File_seek },
{ "lines", w_File_lines },
{ "setBuffer", w_File_setBuffer },
{ "getBuffer", w_File_getBuffer },
{ "getMode", w_File_getMode },
{ 0, 0 }
};
extern "C" int luaopen_file(lua_State *L)
{
return luax_register_type(L, "File", functions);
}
} // physfs
} // filesystem
} // love
@@ -0,0 +1,60 @@
/**
* Copyright (c) 2006-2013 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.
**/
#ifndef LOVE_FILESYSTEM_PHYSFS_WRAP_FILE_H
#define LOVE_FILESYSTEM_PHYSFS_WRAP_FILE_H
// LOVE
#include "common/runtime.h"
#include "Filesystem.h"
#include "File.h"
namespace love
{
namespace filesystem
{
namespace physfs
{
// Does not use lua_error, so it's safe to call in exception handling code.
int luax_ioError(lua_State *L, const char *fmt, ...);
File *luax_checkfile(lua_State *L, int idx);
int w_File_getSize(lua_State *L);
int w_File_open(lua_State *L);
int w_File_close(lua_State *L);
int w_File_isOpen(lua_State *L);
int w_File_read(lua_State *L);
int w_File_write(lua_State *L);
int w_File_flush(lua_State *L);
int w_File_eof(lua_State *L);
int w_File_tell(lua_State *L);
int w_File_seek(lua_State *L);
int w_File_lines(lua_State *L);
int w_File_setBuffer(lua_State *L);
int w_File_getBuffer(lua_State *L);
int w_File_getMode(lua_State *L);
extern "C" int luaopen_file(lua_State *L);
} // physfs
} // filesystem
} // love
#endif // LOVE_FILESYSTEM_PHYSFS_WRAP_FILE_H
@@ -0,0 +1,71 @@
/**
* Copyright (c) 2006-2013 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.
**/
#include "wrap_FileData.h"
#include "common/wrap_Data.h"
namespace love
{
namespace filesystem
{
namespace physfs
{
FileData *luax_checkfiledata(lua_State *L, int idx)
{
return luax_checktype<FileData>(L, idx, "FileData", FILESYSTEM_FILE_DATA_T);
}
int w_FileData_getFilename(lua_State *L)
{
FileData *t = luax_checkfiledata(L, 1);
lua_pushstring(L, t->getFilename().c_str());
return 1;
}
int w_FileData_getExtension(lua_State *L)
{
FileData *t = luax_checkfiledata(L, 1);
lua_pushstring(L, t->getExtension().c_str());
return 1;
}
static const luaL_Reg w_FileData_functions[] =
{
// Data
{ "getString", w_Data_getString },
{ "getPointer", w_Data_getPointer },
{ "getSize", w_Data_getSize },
{ "getFilename", w_FileData_getFilename },
{ "getExtension", w_FileData_getExtension },
{ 0, 0 }
};
extern "C" int luaopen_filedata(lua_State *L)
{
return luax_register_type(L, "FileData", w_FileData_functions);
}
} // physfs
} // filesystem
} // love
@@ -0,0 +1,45 @@
/**
* Copyright (c) 2006-2013 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.
**/
#ifndef LOVE_FILESYSTEM_PHYSFS_WRAP_FILE_DATA_H
#define LOVE_FILESYSTEM_PHYSFS_WRAP_FILE_DATA_H
// LOVE
#include "common/runtime.h"
#include "filesystem/FileData.h"
namespace love
{
namespace filesystem
{
namespace physfs
{
FileData *luax_checkfiledata(lua_State *L, int idx);
int w_FileData_getFilename(lua_State *L);
int w_FileData_getExtension(lua_State *L);
extern "C" int luaopen_filedata(lua_State *L);
} // physfs
} // filesystem
} // love
#endif // LOVE_FILESYSTEM_PHYSFS_WRAP_FILE_DATA_H
@@ -0,0 +1,617 @@
/**
* Copyright (c) 2006-2013 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);
}
}
lua_pushfstring(L, "\n\tno file \"%s\" in LOVE game directories.\n", (tmp + ".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 = SDL_LoadObject((std::string(instance->getAppdataDirectory()) + LOVE_PATH_SEPARATOR LOVE_APPDATA_FOLDER LOVE_PATH_SEPARATOR + tokenized_name).c_str());
if (!handle && instance->isFused())
handle = SDL_LoadObject((std::string(instance->getSaveDirectory()) + LOVE_PATH_SEPARATOR + tokenized_name).c_str());
if (!handle)
{
lua_pushfstring(L, "\n\tno extension \"%s\" in LOVE paths.\n", filename);
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\textension \"%s\" is incompatible.\n", filename);
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();
love::luax_register_searcher(L, loader, 1);
love::luax_register_searcher(L, extloader, 2);
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
@@ -0,0 +1,76 @@
/**
* Copyright (c) 2006-2013 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.
**/
#ifndef LOVE_FILESYSTEM_PHYSFS_WRAP_FILESYSTEM_H
#define LOVE_FILESYSTEM_PHYSFS_WRAP_FILESYSTEM_H
// LOVE
#include "Filesystem.h"
#include "wrap_File.h"
#include "wrap_FileData.h"
namespace love
{
namespace filesystem
{
namespace physfs
{
bool hack_setupWriteDirectory();
int w_init(lua_State *L);
int w_setFused(lua_State *L);
int w_isFused(lua_State *L);
int w_setIdentity(lua_State *L);
int w_getIdentity(lua_State *L);
int w_setSource(lua_State *L);
int w_getSource(lua_State *L);
int w_mount(lua_State *L);
int w_unmount(lua_State *L);
int w_newFile(lua_State *L);
int w_newFileData(lua_State *L);
int w_getWorkingDirectory(lua_State *L);
int w_getUserDirectory(lua_State *L);
int w_getAppdataDirectory(lua_State *L);
int w_getSaveDirectory(lua_State *L);
int w_getSourceBaseDirectory(lua_State *L);
int w_exists(lua_State *L);
int w_isDirectory(lua_State *L);
int w_isFile(lua_State *L);
int w_createDirectory(lua_State *L);
int w_remove(lua_State *L);
int w_open(lua_State *L);
int w_close(lua_State *L);
int w_read(lua_State *L);
int w_write(lua_State *L);
int w_append(lua_State *L);
int w_getDirectoryItems(lua_State *L);
int w_lines(lua_State *L);
int w_load(lua_State *L);
int w_getLastModified(lua_State *L);
int w_getSize(lua_State *L);
int loader(lua_State *L);
int extloader(lua_State *L);
extern "C" LOVE_EXPORT int luaopen_love_filesystem(lua_State *L);
} // physfs
} // filesystem
} // love
#endif // LOVE_FILESYSTEM_PHYSFS_WRAP_FILESYSTEM_H