using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace PhysFS
{
public class PhysFSException : Exception
{
public PhysFSException()
: base(PhysFS.GetLastError())
{ }
}
public class PhysFSLibNotFound : Exception
{
public PhysFSLibNotFound()
: base("Couldn't locate PhysFS library")
{ }
}
///
/// Main class for SharpPhysFS
///
public static class PhysFS
{
public static class LowLevel
{
public static IntPtr OpenWrite(string filename)
{
var val = Interop.PHYSFS_openWrite(filename);
if (val == null)
throw new PhysFSException();
return val;
}
public static IntPtr OpenAppend(string filename)
{
var val = Interop.PHYSFS_openAppend(filename);
if (val == null)
throw new PhysFSException();
return val;
}
public static IntPtr OpenRead(string filename)
{
var val = Interop.PHYSFS_openRead(filename);
if (val == null)
throw new PhysFSException();
return val;
}
public static void Close(IntPtr file)
{
int err = Interop.PHYSFS_close(file);
ThrowException(err);
}
public static long Read(IntPtr file, byte[] buffer, uint objSize, uint objCount)
{
unsafe
{
fixed (void* ptr = buffer)
{
return Interop.PHYSFS_read(file, (IntPtr)ptr, objSize, objCount);
}
}
}
public static long Write(IntPtr file, byte[] buffer, uint objSize, uint objCount)
{
unsafe
{
fixed (void* ptr = buffer)
{
return Interop.PHYSFS_write(file, (IntPtr)ptr, objSize, objCount);
}
}
}
public static bool EOF(IntPtr file)
{
return Interop.PHYSFS_eof(file) != 0;
}
public static long Tell(IntPtr file)
{
return Interop.PHYSFS_tell(file);
}
public static void Seek(IntPtr file, ulong pos)
{
int err = Interop.PHYSFS_seek(file, pos);
ThrowException(err);
}
public static long FileLength(IntPtr file)
{
return Interop.PHYSFS_fileLength(file);
}
public static void SetBuffer(IntPtr file, ulong bufSize)
{
int err = Interop.PHYSFS_setBuffer(file, bufSize);
ThrowException(err);
}
public static void Flush(IntPtr file)
{
int err = Interop.PHYSFS_flush(file);
ThrowException(err);
}
}
static T FromPtr(IntPtr ptr)
{
return (T)Marshal.PtrToStructure(ptr, typeof(T));
}
static void ThrowException(int err)
{
if (err == 0)
{
throw new PhysFSException();
}
}
///
/// Get the version of PhysicsFS that is linked against your program
///
/// The version of PhysicsFS that is linked against your program
public static Version GetLinkedVersion()
{
Version v = new Version();
Interop.PHYSFS_getLinkedVersion(ref v);
return v;
}
///
/// Initialize the PhysicsFS library.
///
///
/// Must be called before any other PhysicsFS function.
/// This should be called prior to any attempts to change your process's current working directory.
///
/// This should be the path of the executable (first arguments passed to main function in C programs)
public static void Init(string argv0)
{
int err = Interop.PHYSFS_init(argv0);
ThrowException(err);
}
///
/// Deinitialize the PhysicsFS library.
///
///
///
/// This closes any files opened via PhysicsFS, blanks the search/write paths, frees memory, and invalidates all of your file handles.
///
///
///
/// This call can throw if there's a file open for writing that refuses to close
/// (for example, the underlying operating system was buffering writes to network filesystem,
/// and the fileserver has crashed, or a hard drive has failed, etc). It is usually best to
/// close all write handles yourself before calling this function, so that you can gracefully handle a specific failure.
/// Once successfully deinitialized, Init can be called again to restart the subsystem.
/// All default API states are restored at this point, with the exception of any custom allocator you might have specified, which survives between initializations.
///
public static void Deinit()
{
int err = Interop.PHYSFS_deinit();
ThrowException(err);
}
///
/// Add an archive or directory to the search path.
///
///
/// If this is a duplicate, the entry is not added again, even though the function succeeds.
/// You may not add the same archive to two different mountpoints: duplicate checking is done against the archive and not the mountpoint.
///
///
/// When you mount an archive, it is added to a virtual file system...all files in all of the archives are interpolated into a single hierachical file tree.
/// Two archives mounted at the same place (or an archive with files overlapping another mountpoint) may have overlapping files:
/// in such a case, the file earliest in the search path is selected, and the other files are inaccessible to the application.
/// This allows archives to be used to override previous revisions; you can use the mounting mechanism to place archives at a specific point
/// in the file tree and prevent overlap; this is useful for downloadable mods that might trample over application data or each other, for example.
///
///
/// The mountpoint does not need to exist prior to mounting, which is different than those familiar with the Unix concept of "mounting" may not expect.
/// As well, more than one archive can be mounted to the same mountpoint, or mountpoints and archive contents can overlap...the interpolation mechanism still functions as usual.
///
/// directory or archive to add to the path, in platform-dependent notation.
/// Location in the interpolated tree that this archive will be "mounted", in platform-independent notation. null or "" is equivalent to "/".
/// True to append to search path, false to prepend.
public static void Mount(string dir, string mountPoint, bool appendToPath)
{
int err = Interop.PHYSFS_mount(dir, mountPoint, appendToPath ? 1 : 0);
ThrowException(err);
}
///
/// Get human-readable error information.
///
///
/// Get the last PhysicsFS error message as a human-readable string.
/// This will be null if there's been no error since the last call to this function.
/// Each thread has a unique error state associated with it, but each time a new error message is set,
/// it will overwrite the previous one associated with that thread.
/// It is safe to call this function at anytime, even before PhysFS.Init().
///
/// String of last error message.
public static string GetLastError()
{
return Marshal.PtrToStringAnsi(Interop.PHYSFS_getLastError());
}
///
/// Get platform-dependent dir separator string.
///
///
/// This returns "\\" on win32, "/" on Unix, and ":" on MacOS.
/// It may be more than one character, depending on the platform, and your code should take that into account.
///
///
/// This is only useful for setting up the search/write paths, since access into those dirs always use '/' (platform-independent notation)
///
/// Platform-dependent dir separator string
public static string GetDirSeparator()
{
return Interop.PHYSFS_getDirSeparator();
}
///
/// Get a file listing of a search path's directory.
///
///
/// Matching directories are interpolated.
/// That is, if "C:\mydir" is in the search path and contains a directory "savegames" that contains "x.sav", "y.sav", and "z.sav",
/// and there is also a "C:\userdir" in the search path that has a "savegames" subdirectory with "w.sav", then the following code:
///
/// foreach(var file in PhysFS.EnumerateFiles("savegames"))
/// {
/// System.Console.WriteLine(" * We've got [{0}].", file);
/// }
///
/// Will print...
///
/// * We've got [x.sav].
/// * We've got [y.sav].
/// * We've got [z.sav].
/// * We've got [w.sav].
///
///
/// Directory in platform-independent notation to enumerate.
public static string[] EnumerateFiles(string dir)
{
var list = new List();
EnumerateFilesCallback(dir, (d, o, f) =>
{
list.Add(f);
}, null);
return list.ToArray();
}
///
/// Get an enumeration of supported archive types.
///
///
/// Get a list of archive types supported by this implementation of PhysicFS.
/// These are the file formats usable for search path entries.
/// This is for informational purposes only.
///
///
/// The extension listed is merely convention: if we list "ZIP", you can open a PkZip-compatible archive with an extension of "XYZ", if you like.
///
/// An enumeration of supported archive types
public static IEnumerable SupportedArchiveTypes()
{
IntPtr archives = Interop.PHYSFS_supportedArchiveTypes();
IntPtr i;
for (i = archives; Marshal.ReadIntPtr(i) != IntPtr.Zero; i = IntPtr.Add(i, 1))
{
IntPtr ptr = Marshal.ReadIntPtr(i);
var info = new ArchiveInfo();
info = FromPtr(ptr);
yield return info;
}
Interop.PHYSFS_freeList(archives);
}
///
/// Enable or disable following of symbolic links.
///
///
/// Some physical filesystems and archives contain files that are just pointers to other files.
/// On the physical filesystem, opening such a link will (transparently) open the file that is pointed to.
///
///
/// By default, PhysicsFS will check if a file is really a symlink during open calls and fail if it is.
/// Otherwise, the link could take you outside the write and search paths, and compromise security.
///
///
/// If you want to take that risk, call this function with a true parameter.
/// Note that this is more for sandboxing a program's scripting language,
/// in case untrusted scripts try to compromise the system.
/// Generally speaking, a user could very well have a legitimate reason to set up a symlink,
/// so unless you feel there's a specific danger in allowing them, you should permit them
///
///
/// Symlinks are only explicitly checked when dealing with filenames in platform-independent notation.
/// That is, when setting up your search and write paths, etc, symlinks are never checked for.
///
/// true to permit symlinks, false to deny linking.
public static void PermitSymbolicLinks(bool permit)
{
Interop.PHYSFS_permitSymbolicLinks(permit ? 1 : 0);
}
///
/// Get an enumeration of paths to available CD-ROM drives.
///
///
/// The dirs returned are platform-dependent ("D:\" on Win32, "/cdrom" or whatnot on Unix).
/// Dirs are only returned if there is a disc ready and accessible in the drive.
/// So if you've got two drives (D: and E:), and only E: has a disc in it, then that's all you get.
/// If the user inserts a disc in D: and you call this function again, you get both drives.
/// If, on a Unix box, the user unmounts a disc and remounts it elsewhere, the next call to this function will reflect that change.
///
///
/// This function refers to "CD-ROM" media, but it really means "inserted disc media," such as DVD-ROM, HD-DVD, CDRW, and Blu-Ray discs.
/// It looks for filesystems, and as such won't report an audio CD, unless there's a mounted filesystem track on it.
///
///
/// This call may block while drives spin up. Be forewarned.
///
/// An enumeration of paths to available CD-ROM drives.
public static string[] GetCdRomDirs()
{
var list = new List();
GetCdRomDirsCallback((d, s) =>
{
list.Add(s);
}, null);
return list.ToArray();
}
///
/// Get the path where the application resides.
///
///
/// It is probably better to use managed methods for this.
///
///
public static string GetBaseDir()
{
return Interop.PHYSFS_getBaseDir();
}
///
/// Get the path where user's home directory resides.
///
///
/// Get the "user dir". This is meant to be a suggestion of where a specific user of the system can store files.
/// On Unix, this is her home directory. On systems with no concept of multiple home directories (MacOS, win95),
/// this will default to something like "C:\mybasedir\users\username" where "username" will either be the login name,
/// or "default" if the platform doesn't support multiple users, either.
///
///
/// You should probably use the user dir as the basis for your write dir, and also put it near the beginning of your search path.
///
/// String of user dir in platform-dependent notation.
public static string GetUserDir()
{
return Interop.PHYSFS_getUserDir();
}
///
/// Get path where PhysicsFS will allow file writing.
///
///
/// Get the current write dir. The default write dir is "".
///
/// String of write dir in platform-dependent notation, OR null IF NO WRITE PATH IS CURRENTLY SET
public static string GetWriteDir()
{
return Interop.PHYSFS_getWriteDir();
}
///
/// Tell PhysicsFS where it may write files.
///
///
/// Set a new write dir. This will override the previous setting.
///
///
/// This call will fail(and fail to change the write dir) if the current write dir still has files open in it.
///
///
/// The new directory to be the root of the write dir, specified in platform-dependent notation.
/// Setting to null disables the write dir, so no files can be opened for writing via PhysicsFS.
///
public static void SetWriteDir(string path)
{
int err = Interop.PHYSFS_setWriteDir(path);
ThrowException(err);
}
///
/// Add an archive or directory to the search path.
///
/// Directory or archive to add to the path, in platform-dependent notation
/// true to append to search path, false to prepend
[Obsolete("AddToSearchPath is deprecated, please use Mount instead")]
public static void AddToSearchPath(string newDir, bool appendToPath)
{
int err = Interop.PHYSFS_addToSearchPath(newDir, appendToPath ? 1 : 0);
ThrowException(err);
}
///
/// Remove a directory or archive from the search path.
///
///
/// This must be a(case-sensitive) match to a dir or archive already in the search path, specified in platform-dependent notation.
///
///
/// This call will fail (and fail to remove from the path) if the element still has files open in it.
///
/// dir/archive to remove.
public static void RemoveFromSearchPath(string oldDir)
{
int err = Interop.PHYSFS_removeFromSearchPath(oldDir);
ThrowException(err);
}
///
/// Get the current search path.
///
public static string[] GetSearchPath()
{
//var dirs = Interop.PHYSFS_getSearchPath();
//return GenEnumerable(dirs);
var list = new List();
GetSearchPathCallback((d, s) =>
{
list.Add(s);
}, null);
return list.ToArray();
}
///
/// Set up sane, default paths.
///
///
/// The write dir will be set to "userdir/.organization/appName", which is created if it doesn't exist.
///
///
/// The above is sufficient to make sure your program's configuration directory is separated from other clutter, and platform-independent.
/// The period before "mygame" even hides the directory on Unix systems.
///
///
/// The search path will be:
///
/// -
///
/// The Write Dir (created if it doesn't exist)
///
///
/// -
///
/// The Base Dir
///
///
/// -
///
/// All found CD-ROM dirs (optionally)
///
///
///
///
///
/// These directories are then searched for files ending with the extension , which,
/// if they are valid and supported archives, will also be added to the search path.
/// If you specified "PKG" for , and there's a file named data.PKG in the base dir, it'll be checked.
/// Archives can either be appended or prepended to the search path in alphabetical order,
/// regardless of which directories they were found in.
///
///
/// All of this can be accomplished from the application, but this just does it all for you. Feel free to add more to the search path manually, too.
///
/// Name of your company/group/etc to be used as a dirname, so keep it small, and no-frills.
/// Program-specific name of your program, to separate it from other programs using PhysicsFS.
///
/// File extension used by your program to specify an archive.
/// For example, Quake 3 uses "pk3", even though they are just zipfiles.
/// Specify null to not dig out archives automatically.
/// Do not specify the '.' char; If you want to look for ZIP files, specify "ZIP" and not ".ZIP" ... the archive search is case-insensitive.
///
///
/// True to include CD-ROMs in the search path, and (if != null) search them for archives.
/// This may cause a significant amount of blocking while discs are accessed, and if there are no discs in the drive (or even not mounted on Unix systems),
/// then they may not be made available anyhow. You may want to specify false and handle the disc setup yourself.
///
/// True to prepend the archives to the search path. False to append them. Ignored if !.
public static void SetSaneConfig(string organization, string appName, string archiveExt, bool includeCdRoms, bool archivesFirst)
{
int err = Interop.PHYSFS_setSaneConfig(organization, appName, archiveExt, includeCdRoms ? 1 : 0, archivesFirst ? 1 : 0);
ThrowException(err);
}
///
/// Create a directory.
///
///
/// This is specified in platform-independent notation in relation to the write dir.
/// All missing parent directories are also created if they don't exist.
///
///
/// So if you've got the write dir set to "C:\mygame\writedir" and call Mkdir("downloads/maps")
/// then the directories "C:\mygame\writedir\downloads" and "C:\mygame\writedir\downloads\maps" will be created if possible.
/// If the creation of "maps" fails after we have successfully created "downloads",
/// then the function leaves the created directory behind and reports failure.
///
/// New dir to create.
public static void Mkdir(string dirName)
{
int err = Interop.PHYSFS_mkdir(dirName);
ThrowException(err);
}
///
/// Delete a file or directory.
///
/// is specified in platform-independent notation in relation to the write dir.
/// A directory must be empty before this call can delete it.
/// Deleting a symlink will remove the link, not what it points to, regardless of whether you "permitSymLinks" or not.
///
/// So if you've got the write dir set to "C:\mygame\writedir" and call Delete("downloads/maps/level1.map")
/// then the file "C:\mygame\writedir\downloads\maps\level1.map" is removed from the physical filesystem,
/// if it exists and the operating system permits the deletion.
///
///
/// Note that on Unix systems, deleting a file may be successful,
/// but the actual file won't be removed until all processes that have an open filehandle to it (including your program) close their handles.
///
///
/// Chances are, the bits that make up the file still exist,
/// they are just made available to be written over at a later point.
/// Don't consider this a security method or anything. :)
///
/// Filename to delete.
public static void Delete(string filename)
{
int err = Interop.PHYSFS_delete(filename);
ThrowException(err);
}
///
/// Figure out where in the search path a file resides.
///
///
/// The file is specified in platform-independent notation.
/// The returned filename will be the element of the search path where the file was found, which may be a directory, or an archive.
/// Even if there are multiple matches in different parts of the search path, only the first one found is used, just like when opening a file.
///
///
/// So, if you look for "maps/level1.map", and C:\mygame is in your search path and C:\mygame\maps\level1.map exists, then "C:\mygame" is returned.
///
/// If a any part of a match is a symbolic link, and you've not explicitly permitted symlinks, then it will be ignored, and the search for a match will continue.
///
/// If you specify a fake directory that only exists as a mount point, it'll be associated with the first archive mounted there,
/// even though that directory isn't necessarily contained in a real archive.
///
/// File to look for.
/// String of element of search path containing the the file in question. null if not found.
public static string GetRealDir(string filename)
{
return Interop.PHYSFS_getRealDir(filename);
}
///
/// Determine if a file exists in the search path.
///
/// Reports true if there is an entry anywhere in the search path by the name of .
///
/// Note that entries that are symlinks are ignored if PhysFS.PermitSymbolicLinks(true) hasn't been called,
/// so you might end up further down in the search path than expected.
///
/// Filename in platform-independent notation.
/// True if filename exists. false otherwise.
public static bool Exists(string fname)
{
return Interop.PHYSFS_exists(fname) != 0;
}
///
/// Determine if a file in the search path is really a directory.
///
/// Determine if the first occurence of in the search path is really a directory entry.
/// Note that entries that are symlinks are ignored if PhysFS.PermitSymbolicLinks(true) hasn't been called, so you might end up further down in the search path than expected.
/// Filename in platform-independent notation.
/// True if filename exists and is a directory. False otherwise.
public static bool IsDirectory(string fname)
{
return Interop.PHYSFS_isDirectory(fname) != 0;
}
///
/// Determine if a file in the search path is really a symbolic link.
///
/// Determine if the first occurence of in the search path is really a symbolic link.
/// Note that entries that are symlinks are ignored if PhysFS.PermitSymbolicLinks(true) hasn't been called, and as such, this function will always return false in that case.
/// Filename in platform-independent notation.
/// True if filename exists and is a symlink. False otherwise.
public static bool IsSymbolicLink(string fname)
{
return Interop.PHYSFS_isSymbolicLink(fname) != 0;
}
///
/// Get the last modification time of a file.
///
///
/// The modtime is returned as a number of seconds since the epoch (Jan 1, 1970).
/// The exact derivation and accuracy of this time depends on the particular archiver.
/// If there is no reasonable way to obtain this information for a particular archiver, or there was some sort of error, this function returns (-1).
///
/// Filename to check, in platform-independent notation.
/// Last modified time of the file. -1 if it can't be determined.
public static long GetLastModTime(string fname)
{
return Interop.PHYSFS_getLastModTime(fname);
}
///
/// Determine if the PhysicsFS library is initialized.
///
///
/// Once PhysFS.Init() returns successfully, this will return true.
/// Before a successful PhysFS.Init() and after PhysFS.Deinit() returns successfully, this will return false. This function is safe to call at any time.
///
/// True if library is initialized, false if library is not.
public static bool IsInit()
{
return Interop.PHYSFS_isInit() != 0;
}
///
/// Determine if the symbolic links are permitted.
///
///
/// This reports the setting from the last call to PhysFS.PermitSymbolicLinks().
/// If PhysFS.PermitSymbolicLinks() hasn't been called since the library was last initialized, symbolic links are implicitly disabled.
///
/// True if symlinks are permitted, false if not.
public static bool SymbolicLinksPermitted()
{
return Interop.PHYSFS_symbolicLinksPermitted() != 0;
}
public static void SetAllocator(Allocator allocator)
{
int err = Interop.PHYSFS_setAllocator(allocator);
ThrowException(err);
}
///
/// Determine a mounted archive's mountpoint.
///
///
/// You give this function the name of an archive or dir you successfully added to the search path, and it reports the location in the interpolated tree where it is mounted.
/// Files mounted with an empty mountpoint or through PhysFS.AddToSearchPath() will report "/".
///
///
/// Directory or archive previously added to the path, in platform-dependent notation.
/// This must match the string used when adding, even if your string would also reference the same file with a different string of characters.
///
/// String of mount point if added to path
public static string GetMountPoint(string dir)
{
var s = Interop.PHYSFS_getMountPoint(dir);
if(s == null)
{
throw new PhysFSException();
}
return s;
}
static StringCallback WrapStringCallback(Action c)
{
return (d, s) =>
{
var obj = (T)GCHandle.FromIntPtr(d).Target;
c(obj, s);
};
}
public static void GetCdRomDirsCallback(StringCallback c, object data)
{
GCHandle objHandle = GCHandle.Alloc(data);
Interop.PHYSFS_getCdRomDirsCallback(c, GCHandle.ToIntPtr(objHandle));
objHandle.Free();
}
///
/// Enumerate CD-ROM directories, using an application-defined callback.
///
/// Type of data passed to callback
/// Callback function to notify about detected drives.
/// Application-defined data passed to callback. Can be null.
public static void GetCdRomDirsCallback(Action c, T data)
{
GetCdRomDirsCallback(WrapStringCallback(c), data);
}
public static void GetSearchPathCallback(StringCallback c, object data)
{
GCHandle objHandle = GCHandle.Alloc(data);
Interop.PHYSFS_getSearchPathCallback(c, GCHandle.ToIntPtr(objHandle));
objHandle.Free();
}
///
/// Enumerate the search path, using an application-defined callback.
///
/// Type of data passed to callback
/// Callback function to notify about search path elements.
/// Application-defined data passed to callback. Can be null.
public static void GetSearchPathCallback(Action c, T data)
{
GetSearchPathCallback(WrapStringCallback(c), data);
}
public static void EnumerateFilesCallback(string dir, EnumFilesCallback c, object data)
{
GCHandle objHandle = GCHandle.Alloc(data);
Interop.PHYSFS_enumerateFilesCallback(dir, c, GCHandle.ToIntPtr(objHandle));
objHandle.Free();
}
///
/// Get a file listing of a search path's directory, using an application-defined callback.
///
/// Type of data passed to callbakc
/// Directory, in platform-independent notation, to enumerate.
/// Callback function to notify about search path elements.
/// Application-defined data passed to callback. Can be null.
public static void EnumerateFilesCallback(string dir, Action c, T data)
{
EnumerateFilesCallback(dir, (d, o, n) =>
{
var obj = (T)GCHandle.FromIntPtr(d).Target;
c(obj, o, n);
}, data);
}
}
}