using System; using System.Collections; using System.Collections.Generic; using System.IO; namespace BizHawk.MultiClient { //todo: //split into "bind" and "open (the bound thing)" //scan archive to flatten interior directories down to a path (maintain our own archive item list) public class HawkFile : IDisposable { public static bool ExistsAt(string path) { using (var file = new HawkFile(path)) { return file.Exists; } } public static byte[] ReadAllBytes(string path) { using (var file = new HawkFile(path)) { if (!file.Exists) throw new FileNotFoundException(path); using (Stream stream = file.GetStream()) { MemoryStream ms = new MemoryStream((int)stream.Length); stream.CopyTo(ms); return ms.GetBuffer(); } } } /// /// returns whether a bound file exists. if there is no bound file, it can't exist /// public bool Exists { get { return exists; } } /// /// gets the directory containing the root /// public string Directory { get { return Path.GetDirectoryName(rootPath); } } /// /// returns a stream for the currently bound file /// public Stream GetStream() { if (boundStream == null) throw new InvalidOperationException("HawkFile: Can't call GetStream() before youve successfully bound something!"); return boundStream; } /// /// indicates whether this instance is bound /// public bool IsBound { get { return boundStream != null; } } /// /// returns the complete canonical full path ("c:\path\to\archive|member") of the bound file /// public string CanonicalFullPath { get { return MakeCanonicalName(rootPath,memberPath); } } /// /// returns the complete canonical name ("archive|member") of the bound file /// public string CanonicalName { get { return MakeCanonicalName(Path.GetFileName(rootPath), memberPath); } } /// /// returns the virtual name of the bound file (disregarding the archive) /// public string Name { get { return GetBoundNameFromCanonical(MakeCanonicalName(rootPath,memberPath)); } } /// /// returns the extension of Name /// public string Extension { get { return Path.GetExtension(Name); } } /// /// Indicates whether this file is an archive /// public bool IsArchive { get { return extractor != null; } } public class ArchiveItem { public string name; public long size; public int index; } public IEnumerable ArchiveItems { get { if (!IsArchive) throw new InvalidOperationException("Cant get archive items from non-archive"); return archiveItems; } } //--- bool exists; bool rootExists; string rootPath; string memberPath; Stream rootStream, boundStream; SevenZip.SevenZipExtractor extractor; List archiveItems; public HawkFile(string path) { string autobind = null; bool isArchivePath = IsCanonicalArchivePath(path); if (isArchivePath) { string[] parts = path.Split('|'); path = parts[0]; autobind = parts[1]; } var fi = new FileInfo(path); rootExists = fi.Exists; if (fi.Exists == false) return; rootPath = path; exists = true; AnalyzeArchive(path); if (extractor == null) { rootStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); //we could autobind here, but i dont want to //bind it later with the desired extensions. } if (autobind == null) { //non-archive files can be automatically bound this way if (!isArchivePath) BindRoot(); } else { autobind = autobind.ToUpperInvariant(); for (int i = 0; i < extractor.ArchiveFileData.Count; i++) { if (FixArchiveFilename(extractor.ArchiveFileNames[i]).ToUpperInvariant() == autobind) { BindArchiveMember(i); return; } } exists = false; } } /// /// is the supplied path a canonical name including an archive? /// bool IsCanonicalArchivePath(string path) { return (path.IndexOf('|') != -1); } /// /// converts a canonical name to a bound name (the bound part, whether or not it is an archive) /// string GetBoundNameFromCanonical(string canonical) { string[] parts = canonical.Split('|'); return parts[parts.Length - 1]; } /// /// makes a canonical name from two parts /// string MakeCanonicalName(string root, string member) { if (member == null) return root; else return string.Format("{0}|{1}", root, member); } string FixArchiveFilename(string fn) { return fn.Replace('\\', '/'); } /// /// binds the selected archive index /// public HawkFile BindArchiveMember(int archiveIndex) { if (!rootExists) return this; if (boundStream != null) throw new InvalidOperationException("stream already bound!"); boundStream = new MemoryStream(); extractor.ExtractFile(archiveIndex, boundStream); boundStream.Position = 0; memberPath = FixArchiveFilename(extractor.ArchiveFileNames[archiveIndex]); //TODO - maybe go through our own list of names? maybe not, its indexes dont match.. Console.WriteLine("bound " + CanonicalFullPath); return this; } /// /// Removes any existing binding /// public void Unbind() { if (boundStream != null && boundStream != rootStream) boundStream.Close(); boundStream = null; memberPath = null; } /// /// causes the root to be bound (in the case of non-archive files) /// void BindRoot() { boundStream = rootStream; Console.WriteLine("bound " + CanonicalFullPath); } /// /// Binds the first item in the archive (or the file itself). Supposing that there is anything in the archive. /// public HawkFile BindFirst() { BindFirstOf(); return this; } /// /// binds one of the supplied extensions if there is only one match in the archive /// public HawkFile BindSoleItemOf(params string[] extensions) { return BindByExtensionCore(false, extensions); } /// /// Binds the first item in the archive (or the file itself) if the extension matches one of the supplied templates. /// You probably should not use this. use BindSoleItemOf or the archive chooser instead /// public HawkFile BindFirstOf(params string[] extensions) { return BindByExtensionCore(true, extensions); } HawkFile BindByExtensionCore(bool first, params string[] extensions) { if (!rootExists) return this; if (boundStream != null) throw new InvalidOperationException("stream already bound!"); if (extractor == null) { //open uncompressed file string extension = Path.GetExtension(rootPath).Substring(1).ToUpperInvariant(); if (extensions.Length == 0 || extension.In(extensions)) { BindRoot(); } return this; } var candidates = new List(); for (int i = 0; i < extractor.ArchiveFileData.Count; i++) { var e = extractor.ArchiveFileData[i]; if (e.IsDirectory) continue; var extension = Path.GetExtension(e.FileName).ToUpperInvariant(); extension = extension.TrimStart('.'); if (extensions.Length == 0 || extension.In(extensions)) { if (first) { BindArchiveMember(i); return this; } candidates.Add(i); } } if (candidates.Count == 1) BindArchiveMember(candidates[0]); return this; } void ScanArchive() { archiveItems = new List(); for (int i = 0; i < extractor.ArchiveFileData.Count; i++) { var afd = extractor.ArchiveFileData[i]; if (afd.IsDirectory) continue; var ai = new ArchiveItem(); ai.name = FixArchiveFilename(afd.FileName); ai.size = (long)afd.Size; //ulong. obnoxious. ai.index = i; archiveItems.Add(ai); } } private void AnalyzeArchive(string path) { SevenZip.FileChecker.ThrowExceptions = false; int offset; bool isExecutable; if (SevenZip.FileChecker.CheckSignature(path, out offset, out isExecutable) != SevenZip.InArchiveFormat.None) { extractor = new SevenZip.SevenZipExtractor(path); try { ScanArchive(); } catch { extractor.Dispose(); extractor = null; archiveItems = null; } } } public void Dispose() { Unbind(); if (extractor != null) extractor.Dispose(); if (rootStream != null) rootStream.Dispose(); extractor = null; rootStream = null; } } }