GARbro-mirror/GameRes/FileSystem.cs

709 lines
22 KiB
C#
Raw Normal View History

2015-06-08 23:58:51 +08:00
//! \file FileSystem.cs
//! \date Fri Jun 05 15:32:27 2015
//! \brief Gameres file system abstraction.
//
// Copyright (C) 2015 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using GameRes.Strings;
2015-06-08 23:58:51 +08:00
namespace GameRes
{
public interface IFileSystem : IDisposable
{
/// <summary>
2015-09-01 16:15:10 +08:00
/// Returns entry corresponding to the given file or directory within filesystem.
/// </summary>
/// <exception cref="FileNotFoundException">File is not found.</exception>
Entry FindFile (string filename);
2015-09-01 18:13:11 +08:00
/// <summary>
/// System.IO.File.Exists() analog.
/// </summary>
bool FileExists (string filename);
/// <summary>
/// Open file for reading as stream.
2015-06-08 23:58:51 +08:00
/// </summary>
Stream OpenStream (Entry entry);
Stream OpenSeekableStream (Entry entry);
/// <summary>
/// Open file for reading as memory-mapped view.
/// </summary>
2015-06-08 23:58:51 +08:00
ArcView OpenView (Entry entry);
/// <summary>
/// Enumerates subdirectories and files in current directory.
/// </summary>
IEnumerable<Entry> GetFiles ();
2015-09-01 16:15:10 +08:00
/// <summary>
/// System.IO.Path.Combine() analog.
/// </summary>
string CombinePath (string path1, string path2);
2015-06-08 23:58:51 +08:00
/// <summary>
/// Recursively enumerates files in the current directory and its subdirectories.
/// Subdirectory entries are omitted from resulting set.
2015-06-08 23:58:51 +08:00
/// </summary>
IEnumerable<Entry> GetFilesRecursive ();
string CurrentDirectory { get; set; }
}
public class SubDirEntry : Entry
{
public override string Type { get { return "directory"; } }
public SubDirEntry (string name)
{
Name = name;
Size = 0;
}
}
2015-09-01 12:52:47 +08:00
public sealed class PhysicalFileSystem : IFileSystem
2015-06-08 23:58:51 +08:00
{
public string CurrentDirectory
{
get { return Directory.GetCurrentDirectory(); }
set { Directory.SetCurrentDirectory (value); }
}
2015-09-01 16:15:10 +08:00
public string CombinePath (string path1, string path2)
{
return Path.Combine (path1, path2);
}
public Entry FindFile (string filename)
{
var attr = File.GetAttributes (filename);
if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
return new SubDirEntry (filename);
else
return EntryFromFileInfo (new FileInfo (filename));
}
2015-09-01 18:13:11 +08:00
public bool FileExists (string filename)
{
return File.Exists (filename);
}
2015-06-08 23:58:51 +08:00
public IEnumerable<Entry> GetFiles ()
{
var info = new DirectoryInfo (CurrentDirectory);
foreach (var subdir in info.EnumerateDirectories())
{
if (0 != (subdir.Attributes & (FileAttributes.Hidden | FileAttributes.System)))
continue;
yield return new SubDirEntry (subdir.FullName);
}
foreach (var file in info.EnumerateFiles())
{
if (0 != (file.Attributes & FileAttributes.System))
2015-06-08 23:58:51 +08:00
continue;
yield return EntryFromFileInfo (file);
}
}
public IEnumerable<Entry> GetFilesRecursive ()
{
var info = new DirectoryInfo (CurrentDirectory);
foreach (var file in info.EnumerateFiles ("*", SearchOption.AllDirectories))
{
if (0 != (file.Attributes & (FileAttributes.Hidden | FileAttributes.System)))
continue;
yield return EntryFromFileInfo (file);
}
}
private Entry EntryFromFileInfo (FileInfo file)
{
var entry = FormatCatalog.Instance.Create<Entry> (file.FullName);
2015-06-08 23:58:51 +08:00
entry.Size = (uint)Math.Min (file.Length, uint.MaxValue);
return entry;
}
public Stream OpenStream (Entry entry)
{
return File.OpenRead (entry.Name);
}
public Stream OpenSeekableStream (Entry entry)
{
return OpenStream (entry);
}
2015-06-08 23:58:51 +08:00
public ArcView OpenView (Entry entry)
{
return new ArcView (entry.Name);
}
public void Dispose ()
{
GC.SuppressFinalize (this);
}
}
public abstract class ArchiveFileSystem : IFileSystem
2015-06-08 23:58:51 +08:00
{
protected readonly ArcFile m_arc;
protected readonly Dictionary<string, Entry> m_dir;
public ArcFile Source { get { return m_arc; } }
2015-06-08 23:58:51 +08:00
public abstract string CurrentDirectory { get; set; }
2015-06-08 23:58:51 +08:00
public ArchiveFileSystem (ArcFile arc)
2015-06-08 23:58:51 +08:00
{
m_arc = arc;
m_dir = new Dictionary<string, Entry> (arc.Dir.Count, StringComparer.InvariantCultureIgnoreCase);
foreach (var entry in arc.Dir)
{
if (!m_dir.ContainsKey (entry.Name))
m_dir.Add (entry.Name, entry);
}
2015-06-08 23:58:51 +08:00
}
2015-09-01 18:13:11 +08:00
public bool FileExists (string filename)
{
return m_dir.ContainsKey (filename);
}
2015-06-08 23:58:51 +08:00
public Stream OpenStream (Entry entry)
{
return m_arc.OpenEntry (entry);
}
public Stream OpenSeekableStream (Entry entry)
{
return m_arc.OpenSeekableEntry (entry);
}
2015-06-08 23:58:51 +08:00
public ArcView OpenView (Entry entry)
{
return m_arc.OpenView (entry);
}
public abstract Entry FindFile (string filename);
public abstract IEnumerable<Entry> GetFiles ();
2015-06-08 23:58:51 +08:00
public abstract IEnumerable<Entry> GetFilesRecursive ();
2015-06-08 23:58:51 +08:00
public abstract string CombinePath (string path1, string path2);
2015-09-01 16:15:10 +08:00
2015-06-08 23:58:51 +08:00
#region IDisposable Members
bool _arc_disposed = false;
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (!_arc_disposed)
{
if (disposing)
{
m_arc.Dispose();
}
_arc_disposed = true;
}
}
#endregion
}
public class FlatArchiveFileSystem : ArchiveFileSystem
{
public override string CurrentDirectory
{
get { return ""; }
set
{
if (string.IsNullOrEmpty (value))
return;
if (".." == value || "." == value)
return;
if ("\\" == value || "/" == value)
return;
throw new DirectoryNotFoundException();
}
}
public FlatArchiveFileSystem (ArcFile arc) : base (arc)
{
}
public override Entry FindFile (string filename)
{
Entry entry = null;
if (!m_dir.TryGetValue (filename, out entry))
throw new FileNotFoundException();
return entry;
}
public override IEnumerable<Entry> GetFiles ()
{
return m_arc.Dir;
}
public override IEnumerable<Entry> GetFilesRecursive ()
{
return m_arc.Dir;
}
public override string CombinePath (string path1, string path2)
{
return Path.Combine (path1, path2);
}
}
public class TreeArchiveFileSystem : ArchiveFileSystem
2015-06-08 23:58:51 +08:00
{
private string m_cwd;
private string PathDelimiter { get; set; }
private static readonly char[] m_path_delimiters = { '/', '\\' };
public TreeArchiveFileSystem (ArcFile arc) : base (arc)
2015-06-08 23:58:51 +08:00
{
m_cwd = "";
PathDelimiter = "/";
}
public override string CurrentDirectory
{
get { return m_cwd; }
set { ChDir (value); }
}
2015-09-01 16:15:10 +08:00
public override string CombinePath (string path1, string path2)
{
2015-09-05 14:04:38 +08:00
if (0 == path1.Length)
return path2;
if (0 == path2.Length)
return path1;
if (path1.EndsWith (PathDelimiter))
return path1+path2;
2015-09-01 16:15:10 +08:00
return string.Join (PathDelimiter, path1, path2);
}
public override Entry FindFile (string filename)
{
Entry entry = null;
if (m_dir.TryGetValue (filename, out entry))
return entry;
if (m_dir.Keys.Any (n => n.StartsWith (filename + PathDelimiter)))
return new SubDirEntry (filename);
throw new FileNotFoundException();
}
2015-06-08 23:58:51 +08:00
static readonly Regex path_re = new Regex (@"\G[/\\]?([^/\\]+)([/\\])");
public override IEnumerable<Entry> GetFiles ()
{
2015-09-05 14:04:38 +08:00
IEnumerable<Entry> dir = GetFilesRecursive();
var root_dir = m_cwd;
if (!string.IsNullOrEmpty (root_dir))
root_dir += PathDelimiter;
2015-06-08 23:58:51 +08:00
var subdirs = new HashSet<string>();
foreach (var entry in dir)
{
var match = path_re.Match (entry.Name, root_dir.Length);
if (match.Success)
{
string name = match.Groups[1].Value;
if (subdirs.Add (name))
{
PathDelimiter = match.Groups[2].Value;
yield return new SubDirEntry (root_dir+name);
}
}
else
{
yield return entry;
}
}
}
public override IEnumerable<Entry> GetFilesRecursive ()
{
if (0 == m_cwd.Length)
return m_arc.Dir;
else
return from file in m_arc.Dir
where file.Name.StartsWith (m_cwd + PathDelimiter)
select file;
}
2015-09-05 14:04:38 +08:00
public IEnumerable<Entry> GetFilesRecursive (IEnumerable<Entry> list)
{
var result = new List<Entry>();
foreach (var entry in list)
{
if (!(entry is SubDirEntry)) // add ordinary file
result.Add (entry);
else if (".." == entry.Name) // skip reference to parent directory
continue;
else // add all files contained within directory, recursive
result.AddRange (from file in m_arc.Dir
where file.Name.StartsWith (entry.Name+PathDelimiter)
select file);
}
return result;
}
2015-06-08 23:58:51 +08:00
private void ChDir (string path)
{
if (string.IsNullOrEmpty (path))
2015-09-01 16:15:10 +08:00
{
m_cwd = "";
2015-06-08 23:58:51 +08:00
return;
2015-09-01 16:15:10 +08:00
}
var cur_dir = new List<string>();
2015-06-08 23:58:51 +08:00
if (-1 != Array.IndexOf (m_path_delimiters, path[0]))
{
path = path.TrimStart (m_path_delimiters);
}
2015-09-01 16:15:10 +08:00
else if (".." == path && !string.IsNullOrEmpty (m_cwd))
2015-06-08 23:58:51 +08:00
{
cur_dir.AddRange (m_cwd.Split (m_path_delimiters));
2015-06-08 23:58:51 +08:00
}
var path_list = path.Split (m_path_delimiters);
foreach (var dir in path_list)
{
if ("." == dir)
{
continue;
}
else if (".." == dir)
{
if (0 == cur_dir.Count)
continue;
cur_dir.RemoveAt (cur_dir.Count-1);
}
else
{
cur_dir.Add (dir);
}
}
string new_path = string.Join (PathDelimiter, cur_dir);
if (0 != new_path.Length)
{
var entry = m_arc.Dir.FirstOrDefault (e => e.Name.StartsWith (new_path + PathDelimiter));
if (null == entry)
throw new DirectoryNotFoundException();
}
m_cwd = new_path;
}
}
public sealed class FileSystemStack : IDisposable
{
Stack<IFileSystem> m_fs_stack = new Stack<IFileSystem>();
Stack<string> m_arc_name_stack = new Stack<string>();
public IEnumerable<IFileSystem> All { get { return m_fs_stack; } }
public IFileSystem Top { get { return m_fs_stack.Peek(); } }
public int Count { get { return m_fs_stack.Count; } }
public IEnumerable<string> ArcStack { get { return m_arc_name_stack; } }
public ArcFile CurrentArchive { get; private set; }
private IFileSystem LastVisitedArc { get; set; }
private string LastVisitedPath { get; set; }
public FileSystemStack ()
{
m_fs_stack.Push (new PhysicalFileSystem());
}
public void ChDir (Entry entry)
{
if (entry is SubDirEntry)
{
2015-09-01 16:15:10 +08:00
if (Count > 1 && ".." == entry.Name && string.IsNullOrEmpty (Top.CurrentDirectory))
{
2015-09-01 16:15:10 +08:00
Pop();
if (!string.IsNullOrEmpty (LastVisitedPath))
{
Top.CurrentDirectory = Path.GetDirectoryName (LastVisitedPath);
}
}
2015-09-01 16:15:10 +08:00
else
{
2015-09-01 16:15:10 +08:00
Top.CurrentDirectory = entry.Name;
}
return;
}
if (entry.Name == LastVisitedPath && null != LastVisitedArc)
{
Push (LastVisitedPath, LastVisitedArc);
var fs = LastVisitedArc as ArchiveFileSystem;
if (null != fs)
CurrentArchive = fs.Source;
return;
}
Flush();
var arc = ArcFile.TryOpen (entry.Name);
if (null == arc)
{
if (FormatCatalog.Instance.LastError is OperationCanceledException)
throw FormatCatalog.Instance.LastError;
else
throw new UnknownFormatException (FormatCatalog.Instance.LastError);
}
try
{
Push (entry.Name, arc.CreateFileSystem());
CurrentArchive = arc;
}
catch
{
arc.Dispose();
throw;
}
}
private void Push (string path, IFileSystem fs)
{
m_fs_stack.Push (fs);
m_arc_name_stack.Push (path);
}
internal void Pop ()
{
if (m_fs_stack.Count > 1)
{
Flush();
LastVisitedArc = m_fs_stack.Pop();
LastVisitedPath = m_arc_name_stack.Pop();
if (m_fs_stack.Count > 1 && m_fs_stack.Peek() is ArchiveFileSystem)
CurrentArchive = (m_fs_stack.Peek() as ArchiveFileSystem).Source;
else
CurrentArchive = null;
}
}
public void Flush ()
{
if (LastVisitedArc != null && (0 == Count || LastVisitedArc != Top))
{
LastVisitedArc.Dispose();
LastVisitedArc = null;
LastVisitedPath = null;
}
}
private bool _disposed = false;
public void Dispose ()
{
if (!_disposed)
{
Flush();
foreach (var fs in m_fs_stack.Reverse())
fs.Dispose();
_disposed = true;
}
GC.SuppressFinalize (this);
}
}
public static class VFS
{
private static FileSystemStack m_vfs = new FileSystemStack();
/// <summary>
/// Top, or "current" filesystem in VFS hierarchy.
/// </summary>
public static IFileSystem Top { get { return m_vfs.Top; } }
/// <summary>
/// Whether top filesystem is virtual (i.e. represents an archive).
/// </summary>
public static bool IsVirtual { get { return m_vfs.Count > 1; } }
/// <summary>
/// Number of filesystems in hierarchy. ==1 when only physical file system is represented.
/// Always >= 1
/// </summary>
public static int Count { get { return m_vfs.Count; } }
/// <summary>
/// Archive corresponding to the top filesystem, or null if file system doesn't have underlying
/// archive file.
/// </summary>
public static ArcFile CurrentArchive { get { return m_vfs.CurrentArchive; } }
private static string[] m_top_path = new string[1];
public static IEnumerable<string> FullPath
{
get
{
m_top_path[0] = Top.CurrentDirectory;
if (1 == Count)
return m_top_path;
else
2015-09-01 13:23:29 +08:00
return m_vfs.ArcStack.Reverse().Concat (m_top_path);
}
set
{
if (!value.Any())
return;
var desired = value.ToArray();
2015-09-23 02:39:10 +08:00
int desired_vfs_count = desired.Length;
var arc_iterator = m_vfs.ArcStack.Reverse().GetEnumerator();
int i = 0;
while (i < desired_vfs_count - 1 && arc_iterator.MoveNext())
{
2015-09-23 02:39:10 +08:00
if (arc_iterator.Current != desired[i])
break;
++i;
}
2015-09-23 02:39:10 +08:00
while (Count > i+1)
m_vfs.Pop();
while (Count < desired_vfs_count)
{
2015-12-01 15:23:47 +08:00
var entry = m_vfs.Top.FindFile (desired[Count-1]);
if (entry is SubDirEntry)
throw new FileNotFoundException();
m_vfs.ChDir (entry);
}
2015-09-23 02:39:10 +08:00
m_vfs.Top.CurrentDirectory = desired.Last();
}
}
2015-09-01 16:15:10 +08:00
public static string CombinePath (string path1, string path2)
{
return m_vfs.Top.CombinePath (path1, path2);
}
public static Entry FindFile (string filename)
{
if (".." == filename)
return new SubDirEntry ("..");
return m_vfs.Top.FindFile (filename);
}
2015-09-01 18:13:11 +08:00
public static bool FileExists (string filename)
{
return m_vfs.Top.FileExists (filename);
}
public static Stream OpenStream (Entry entry)
{
return m_vfs.Top.OpenStream (entry);
}
public static Stream OpenSeekableStream (Entry entry)
{
return m_vfs.Top.OpenSeekableStream (entry);
}
public static ArcView OpenView (Entry entry)
{
return m_vfs.Top.OpenView (entry);
}
2015-09-01 18:13:11 +08:00
public static Stream OpenStream (string filename)
{
return m_vfs.Top.OpenStream (m_vfs.Top.FindFile (filename));
}
public static Stream OpenSeekableStream (string filename)
{
return m_vfs.Top.OpenSeekableStream (m_vfs.Top.FindFile (filename));
}
public static ArcView OpenView (string filename)
{
return m_vfs.Top.OpenView (m_vfs.Top.FindFile (filename));
}
public static void ChDir (Entry entry)
{
m_vfs.ChDir (entry);
}
public static void ChDir (string path)
{
m_vfs.ChDir (FindFile (path));
}
public static void Flush ()
{
m_vfs.Flush();
}
2016-03-06 19:17:26 +08:00
public static IEnumerable<Entry> GetFiles ()
{
return m_vfs.Top.GetFiles();
}
2016-03-06 19:17:26 +08:00
/// <summary>
/// Returns enumeration of files within current directory that match specified pattern.
/// </summary>
public static IEnumerable<Entry> GetFiles (string pattern)
{
var glob = new FileNameGlob (pattern);
return GetFiles().Where (f => glob.IsMatch (Path.GetFileName (f.Name)));
}
}
public class FileNameGlob
{
Regex m_glob;
public FileNameGlob (string pattern)
{
pattern = Regex.Escape (pattern);
if (pattern.EndsWith (@"\.\*")) // "*" and "*.*" are equivalent
pattern = pattern.Remove (pattern.Length-4) + @"(?:\..*)?";
pattern = pattern.Replace (@"\*", ".*").Replace (@"\?", ".");
m_glob = new Regex ("^"+pattern+"$", RegexOptions.IgnoreCase);
}
public bool IsMatch (string str)
{
return m_glob.IsMatch (str);
}
}
public class UnknownFormatException : FileFormatException
{
public UnknownFormatException () : base (garStrings.MsgUnknownFormat) { }
public UnknownFormatException (Exception inner) : base (garStrings.MsgUnknownFormat, inner) { }
}
2015-06-08 23:58:51 +08:00
}