diff --git a/BizHawk.Emulation/BizHawk.Emulation_v4.5.csproj b/BizHawk.Emulation/BizHawk.Emulation_v4.5.csproj deleted file mode 100644 index 0ff914c21d..0000000000 --- a/BizHawk.Emulation/BizHawk.Emulation_v4.5.csproj +++ /dev/null @@ -1,608 +0,0 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {197D4314-8A9F-49BA-977D-54ACEFAEB6BA} - Library - Properties - BizHawk.Emulation - BizHawk.Emulation - v4.5 - 512 - - - 3.5 - - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - x86 - true - false - AllRules.ruleset - false - - - pdbonly - true - bin\Release\ - TRACE;VS2012 - prompt - 4 - x86 - true - AllRules.ruleset - false - false - - - - False - ..\BizHawk.MultiClient\output\dll\EMU7800.dll - - - - 3.5 - - - - - 3.5 - - - 3.5 - - - - - - - VersionInfo.cs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - - - - - - - Code - - - - Code - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - - - Code - - - - - - - - - - - - Code - - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - Code - - - Code - - - - - - - - - - Code - - - - Code - - - Code - - - - Code - - - Code - - - - Code - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - - - - - - - - - - - - - - - - - "$(SolutionDir)subwcrev.bat" "$(ProjectDir)" - "$(SolutionDir)subwcrev.sh" "$(ProjectDir)" - - - \ No newline at end of file diff --git a/BizHawk.Emulation/Consoles/Nintendo/Gameboy/Gambatte.cs b/BizHawk.Emulation/Consoles/Nintendo/Gameboy/Gambatte.cs index 30ea61310b..f5fc2c0380 100644 --- a/BizHawk.Emulation/Consoles/Nintendo/Gameboy/Gambatte.cs +++ b/BizHawk.Emulation/Consoles/Nintendo/Gameboy/Gambatte.cs @@ -194,9 +194,14 @@ namespace BizHawk.Emulation.Consoles.GB LibGambatte.gambatte_runfor(GambatteState, VideoBuffer, 160, soundbuff, ref nsamp); if (rendersound) + { soundbuffcontains = (int)nsamp; + ProcessSound(); + } else + { soundbuffcontains = 0; + } FrameAdvancePost(); } @@ -777,7 +782,7 @@ namespace BizHawk.Emulation.Consoles.GB #region ISoundProvider public ISoundProvider SoundProvider { get { return null; } } - public ISyncSoundProvider SyncSoundProvider { get { return dcfilter; } } + public ISyncSoundProvider SyncSoundProvider { get { return this; } } public bool StartAsyncSound() { return false; } public void EndAsyncSound() { } @@ -790,21 +795,58 @@ namespace BizHawk.Emulation.Consoles.GB /// int soundbuffcontains = 0; - Sound.Utilities.SpeexResampler resampler; - Sound.Utilities.DCFilter dcfilter; + int soundoutbuffcontains = 0; + + short[] soundoutbuff = new short[2048]; + + int latchaudio = 0; + + //Sound.Utilities.SpeexResampler resampler; + //Sound.Utilities.DCFilter dcfilter; + + Sound.Utilities.BlipBuffer blip; + + void ProcessSound() + { + for (uint i = 0; i < soundbuffcontains; i++) + { + int curr = soundbuff[i * 2]; + + if (curr != latchaudio) + { + int diff = latchaudio - curr; + latchaudio = curr; + blip.AddDelta(i, diff); + } + } + blip.EndFrame((uint)soundbuffcontains); + + soundoutbuffcontains = blip.SamplesAvailable(); + + blip.ReadSamples(soundoutbuff, soundoutbuffcontains, true); + for (int i = 0; i < soundoutbuffcontains * 2; i += 2) + soundoutbuff[i + 1] = soundoutbuff[i]; + + soundbuffcontains = 0; + + } void InitSound() { - resampler = new Sound.Utilities.SpeexResampler(2, 2097152, 44100, 2097152, 44100, null, this); + //resampler = new Sound.Utilities.SpeexResampler(2, 2097152, 44100, 2097152, 44100, null, this); //dcfilter = Sound.Utilities.DCFilter.AsISyncSoundProvider(resampler, 65536); // lowpass filtering on an actual GB was probably pretty aggressive? - dcfilter = Sound.Utilities.DCFilter.AsISyncSoundProvider(resampler, 2048); + //dcfilter = Sound.Utilities.DCFilter.AsISyncSoundProvider(resampler, 2048); + blip = new Sound.Utilities.BlipBuffer(1024); + blip.SetRates(2097152, 44100); } void DisposeSound() { - resampler.Dispose(); - resampler = null; + blip.Dispose(); + blip = null; + //resampler.Dispose(); + //resampler = null; } public void DiscardSamples() @@ -814,8 +856,8 @@ namespace BizHawk.Emulation.Consoles.GB public void GetSamples(out short[] samples, out int nsamp) { - samples = soundbuff; - nsamp = soundbuffcontains; + samples = soundoutbuff; + nsamp = soundoutbuffcontains; } #endregion diff --git a/BizHawk.Emulation/Database/FirmwareDatabase.cs b/BizHawk.Emulation/Database/FirmwareDatabase.cs index 82ef8a84a6..d50f79024f 100644 --- a/BizHawk.Emulation/Database/FirmwareDatabase.cs +++ b/BizHawk.Emulation/Database/FirmwareDatabase.cs @@ -33,7 +33,6 @@ namespace BizHawk FirmwareAndOption("300C20DF6731A33952DED8C436F7F186D25D3492", "GBA", "Bios", "gbabios.rom", "Bios"); //FirmwareAndOption("24F67BDEA115A2C847C8813A262502EE1607B7DF", "NDS", "Bios_Arm7", "biosnds7.rom", "ARM7 Bios"); //FirmwareAndOption("BFAAC75F101C135E32E2AAF541DE6B1BE4C8C62D", "NDS", "Bios_Arm9", "biosnds9.rom", "ARM9 Bios"); - FirmwareAndOption("EF66DAD3E7B2B6A86F326765E7DFD7D1A308AD8F", "TI83", "Rom", "ti83_1.rom", "TI-83 Rom"); FirmwareAndOption("5A65B922B562CB1F57DAB51B73151283F0E20C7A", "INTV", "EROM", "erom.bin", "Executive Rom"); FirmwareAndOption("F9608BB4AD1CFE3640D02844C7AD8E0BCD974917", "INTV", "GROM", "grom.bin", "Graphics Rom"); FirmwareAndOption("1D503E56DF85A62FEE696E7618DC5B4E781DF1BB", "C64", "Kernal", "c64-kernal.bin", "Kernal Rom"); @@ -61,6 +60,25 @@ namespace BizHawk Option("SAT", "E", ss_100a_ue); Option("SAT", "E", ss_100_j); Option("SAT", "E", ss_101_j); + + var ti83_102 = File("CE08F6A808701FC6672230A790167EE485157561", "ti83_102.rom", "TI-83 Rom v1.02"); + var ti83_103 = File("8399E384804D8D29866CAA4C8763D7A61946A467", "ti83_103.rom", "TI-83 Rom v1.03"); + var ti83_104 = File("33877FF637DC5F4C5388799FD7E2159B48E72893", "ti83_104.rom", "TI-83 Rom v1.04"); + var ti83_106 = File("3D65C2A1B771CE8E5E5A0476EC1AA9C9CDC0E833", "ti83_106.rom", "TI-83 Rom v1.06"); + var ti83_107 = File("EF66DAD3E7B2B6A86F326765E7DFD7D1A308AD8F", "ti83_107.rom", "TI-83 Rom v1.07"); //formerly the 1.?? recommended one + var ti83_108 = File("9C74F0B61655E9E160E92164DB472AD7EE02B0F8", "ti83_108.rom", "TI-83 Rom v1.08"); + var ti83p_103 = File("37EAEEB9FB5C18FB494E322B75070E80CC4D858E", "ti83p_103b.rom", "TI-83 Plus Rom v1.03"); + var ti83p_112 = File("6615DF5554076B6B81BD128BF847D2FF046E556B", "ti83p_112.rom", "TI-83 Plus Rom v1.12"); + + Firmware("TI83", "Rom", "TI-83 Rom"); + Option("TI83", "Rom", ti83_102); + Option("TI83", "Rom", ti83_103); + Option("TI83", "Rom", ti83_104); + Option("TI83", "Rom", ti83_106); + Option("TI83", "Rom", ti83_107); + Option("TI83", "Rom", ti83_108); + Option("TI83", "Rom", ti83p_103); + Option("TI83", "Rom", ti83p_112); } //adds a defined firmware ID to the database diff --git a/BizHawk.Util/7z/ArchiveEmulationStreamProxy.cs b/BizHawk.Util/7z/ArchiveEmulationStreamProxy.cs deleted file mode 100644 index c0bdaed292..0000000000 --- a/BizHawk.Util/7z/ArchiveEmulationStreamProxy.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System.IO; -using System; - -namespace SevenZip -{ - /// - /// The Stream extension class to emulate the archive part of a stream. - /// - internal class ArchiveEmulationStreamProxy : Stream, IDisposable - { - /// - /// Gets the file offset. - /// - public int Offset { get; private set; } - - /// - /// The source wrapped stream. - /// - public Stream Source { get; private set; } - - /// - /// Initializes a new instance of the ArchiveEmulationStream class. - /// - /// The stream to wrap. - /// The stream offset. - public ArchiveEmulationStreamProxy(Stream stream, int offset) - { - Source = stream; - Offset = offset; - Source.Position = offset; - } - - public override bool CanRead - { - get { return Source.CanRead; } - } - - public override bool CanSeek - { - get { return Source.CanSeek; } - } - - public override bool CanWrite - { - get { return Source.CanWrite; } - } - - public override void Flush() - { - Source.Flush(); - } - - public override long Length - { - get { return Source.Length - Offset; } - } - - public override long Position - { - get - { - return Source.Position - Offset; - } - set - { - Source.Position = value; - } - } - - public override int Read(byte[] buffer, int offset, int count) - { - return Source.Read(buffer, offset, count); - } - - public override long Seek(long offset, SeekOrigin origin) - { - return Source.Seek(origin == SeekOrigin.Begin ? offset + Offset : offset, - origin) - Offset; - } - - public override void SetLength(long value) - { - Source.SetLength(value); - } - - public override void Write(byte[] buffer, int offset, int count) - { - Source.Write(buffer, offset, count); - } - - public new void Dispose() - { - Source.Dispose(); - } - - public override void Close() - { - Source.Close(); - } - } -} diff --git a/BizHawk.Util/7z/ArchiveExtractCallback.cs b/BizHawk.Util/7z/ArchiveExtractCallback.cs deleted file mode 100644 index d9aedc0f7a..0000000000 --- a/BizHawk.Util/7z/ArchiveExtractCallback.cs +++ /dev/null @@ -1,602 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -#if MONO -using SevenZip.Mono.COM; -using System.Runtime.InteropServices; -#endif - -namespace SevenZip -{ -#if UNMANAGED - /// - /// Archive extraction callback to handle the process of unpacking files - /// - internal sealed class ArchiveExtractCallback : CallbackBase, IArchiveExtractCallback, ICryptoGetTextPassword, - IDisposable - { - private List _actualIndexes; - private IInArchive _archive; - - /// - /// For Compressing event. - /// - private long _bytesCount; - - private long _bytesWritten; - private long _bytesWrittenOld; - private string _directory; - - /// - /// Rate of the done work from [0, 1]. - /// - private float _doneRate; - - private SevenZipExtractor _extractor; - private FakeOutStreamWrapper _fakeStream; - private uint? _fileIndex; - private int _filesCount; - private OutStreamWrapper _fileStream; - private bool _directoryStructure; - private int _currentIndex; -#if !WINCE - const int MEMORY_PRESSURE = 64 * 1024 * 1024; //64mb seems to be the maximum value -#endif - #region Constructors - - /// - /// Initializes a new instance of the ArchiveExtractCallback class - /// - /// IInArchive interface for the archive - /// Directory where files are to be unpacked to - /// The archive files count' - /// The owner of the callback - /// The list of actual indexes (solid archives support) - /// The value indicating whether to preserve directory structure of extracted files. - public ArchiveExtractCallback(IInArchive archive, string directory, int filesCount, bool directoryStructure, - List actualIndexes, SevenZipExtractor extractor) - { - Init(archive, directory, filesCount, directoryStructure, actualIndexes, extractor); - } - - /// - /// Initializes a new instance of the ArchiveExtractCallback class - /// - /// IInArchive interface for the archive - /// Directory where files are to be unpacked to - /// The archive files count - /// Password for the archive - /// The owner of the callback - /// The list of actual indexes (solid archives support) - /// The value indicating whether to preserve directory structure of extracted files. - public ArchiveExtractCallback(IInArchive archive, string directory, int filesCount, bool directoryStructure, - List actualIndexes, string password, SevenZipExtractor extractor) - : base(password) - { - Init(archive, directory, filesCount, directoryStructure, actualIndexes, extractor); - } - - /// - /// Initializes a new instance of the ArchiveExtractCallback class - /// - /// IInArchive interface for the archive - /// The stream where files are to be unpacked to - /// The archive files count - /// The file index for the stream - /// The owner of the callback - public ArchiveExtractCallback(IInArchive archive, Stream stream, int filesCount, uint fileIndex, - SevenZipExtractor extractor) - { - Init(archive, stream, filesCount, fileIndex, extractor); - } - - /// - /// Initializes a new instance of the ArchiveExtractCallback class - /// - /// IInArchive interface for the archive - /// The stream where files are to be unpacked to - /// The archive files count - /// The file index for the stream - /// Password for the archive - /// The owner of the callback - public ArchiveExtractCallback(IInArchive archive, Stream stream, int filesCount, uint fileIndex, string password, - SevenZipExtractor extractor) - : base(password) - { - Init(archive, stream, filesCount, fileIndex, extractor); - } - - private void Init(IInArchive archive, string directory, int filesCount, bool directoryStructure, - List actualIndexes, SevenZipExtractor extractor) - { - CommonInit(archive, filesCount, extractor); - _directory = directory; - _actualIndexes = actualIndexes; - _directoryStructure = directoryStructure; - if (!directory.EndsWith("" + Path.DirectorySeparatorChar, StringComparison.CurrentCulture)) - { - _directory += Path.DirectorySeparatorChar; - } - } - - private void Init(IInArchive archive, Stream stream, int filesCount, uint fileIndex, SevenZipExtractor extractor) - { - CommonInit(archive, filesCount, extractor); - _fileStream = new OutStreamWrapper(stream, false); - _fileStream.BytesWritten += IntEventArgsHandler; - _fileIndex = fileIndex; - } - - private void CommonInit(IInArchive archive, int filesCount, SevenZipExtractor extractor) - { - _archive = archive; - _filesCount = filesCount; - _fakeStream = new FakeOutStreamWrapper(); - _fakeStream.BytesWritten += IntEventArgsHandler; - _extractor = extractor; -#if !WINCE - GC.AddMemoryPressure(MEMORY_PRESSURE); -#endif - } - #endregion - - #region Events - - /// - /// Occurs when a new file is going to be unpacked - /// - /// Occurs when 7-zip engine requests for an output stream for a new file to unpack in - public event EventHandler FileExtractionStarted; - - /// - /// Occurs when a file has been successfully unpacked - /// - public event EventHandler FileExtractionFinished; - - /// - /// Occurs when the archive is opened and 7-zip sends the size of unpacked data - /// - public event EventHandler Open; - - /// - /// Occurs when the extraction is performed - /// - public event EventHandler Extracting; - - /// - /// Occurs during the extraction when a file already exists - /// - public event EventHandler FileExists; - - private void OnFileExists(FileOverwriteEventArgs e) - { - if (FileExists != null) - { - FileExists(this, e); - } - } - - private void OnOpen(OpenEventArgs e) - { - if (Open != null) - { - Open(this, e); - } - } - - private void OnFileExtractionStarted(FileInfoEventArgs e) - { - if (FileExtractionStarted != null) - { - FileExtractionStarted(this, e); - } - } - - private void OnFileExtractionFinished(FileInfoEventArgs e) - { - if (FileExtractionFinished != null) - { - FileExtractionFinished(this, e); - } - } - - private void OnExtracting(ProgressEventArgs e) - { - if (Extracting != null) - { - Extracting(this, e); - } - } - - private void IntEventArgsHandler(object sender, IntEventArgs e) - { - var pold = (int)((_bytesWrittenOld * 100) / _bytesCount); - _bytesWritten += e.Value; - var pnow = (int)((_bytesWritten * 100) / _bytesCount); - if (pnow > pold) - { - if (pnow > 100) - { - pold = pnow = 0; - } - _bytesWrittenOld = _bytesWritten; - OnExtracting(new ProgressEventArgs((byte)pnow, (byte)(pnow - pold))); - } - } - - #endregion - - #region IArchiveExtractCallback Members - - /// - /// Gives the size of the unpacked archive files - /// - /// Size of the unpacked archive files (in bytes) - public void SetTotal(ulong total) - { - _bytesCount = (long)total; - OnOpen(new OpenEventArgs(total)); - } - - public void SetCompleted(ref ulong completeValue) { } - - /// - /// Sets output stream for writing unpacked data - /// - /// Current file index - /// Output stream pointer - /// Extraction mode - /// 0 if OK - public int GetStream(uint index, out -#if !MONO - ISequentialOutStream -#else - HandleRef -#endif - outStream, AskMode askExtractMode) - { -#if !MONO - outStream = null; -#else - outStream = new System.Runtime.InteropServices.HandleRef(null, IntPtr.Zero); -#endif - if (Canceled) - { - return -1; - } - _currentIndex = (int)index; - if (askExtractMode == AskMode.Extract) - { - var fileName = _directory; - if (!_fileIndex.HasValue) - { - #region Extraction to a file - - if (_actualIndexes == null || _actualIndexes.Contains(index)) - { - var data = new PropVariant(); - _archive.GetProperty(index, ItemPropId.Path, ref data); - string entryName = NativeMethods.SafeCast(data, ""); - - #region Get entryName - - if (String.IsNullOrEmpty(entryName)) - { - if (_filesCount == 1) - { - var archName = Path.GetFileName(_extractor.FileName); - archName = archName.Substring(0, archName.LastIndexOf('.')); - if (!archName.EndsWith(".tar", StringComparison.OrdinalIgnoreCase)) - { - archName += ".tar"; - } - entryName = archName; - } - else - { - entryName = "[no name] " + index.ToString(CultureInfo.InvariantCulture); - } - } - - #endregion - - fileName = Path.Combine(_directory, _directoryStructure? entryName : Path.GetFileName(entryName)); - _archive.GetProperty(index, ItemPropId.IsDirectory, ref data); - try - { - fileName = ValidateFileName(fileName); - } - catch (Exception e) - { - AddException(e); - goto FileExtractionStartedLabel; - } - if (!NativeMethods.SafeCast(data, false)) - { - #region Branch - - _archive.GetProperty(index, ItemPropId.LastWriteTime, ref data); - var time = NativeMethods.SafeCast(data, DateTime.MinValue); - if (File.Exists(fileName)) - { - var fnea = new FileOverwriteEventArgs(fileName); - OnFileExists(fnea); - if (fnea.Cancel) - { - Canceled = true; - return -1; - } - if (String.IsNullOrEmpty(fnea.FileName)) - { -#if !MONO - outStream = _fakeStream; -#else - outStream = _fakeStream.Handle; -#endif - goto FileExtractionStartedLabel; - } - fileName = fnea.FileName; - } - try - { - _fileStream = new OutStreamWrapper(File.Create(fileName), fileName, time, true); - } - catch (Exception e) - { - if (e is FileNotFoundException) - { - AddException( - new IOException("The file \"" + fileName + - "\" was not extracted due to the File.Create fail.")); - } - else - { - AddException(e); - } - outStream = _fakeStream; - goto FileExtractionStartedLabel; - } - _fileStream.BytesWritten += IntEventArgsHandler; - outStream = _fileStream; - - #endregion - } - else - { - #region Branch - - if (!Directory.Exists(fileName)) - { - try - { - Directory.CreateDirectory(fileName); - } - catch (Exception e) - { - AddException(e); - } - outStream = _fakeStream; - } - - #endregion - } - } - else - { - outStream = _fakeStream; - } - - #endregion - } - else - { - #region Extraction to a stream - - if (index == _fileIndex) - { - outStream = _fileStream; - _fileIndex = null; - } - else - { - outStream = _fakeStream; - } - - #endregion - } - - FileExtractionStartedLabel: - _doneRate += 1.0f / _filesCount; - var iea = new FileInfoEventArgs( - _extractor.ArchiveFileData[(int)index], PercentDoneEventArgs.ProducePercentDone(_doneRate)); - OnFileExtractionStarted(iea); - if (iea.Cancel) - { - if (!String.IsNullOrEmpty(fileName)) - { - _fileStream.Dispose(); - if (File.Exists(fileName)) - { - try - { - File.Delete(fileName); - } - catch (Exception e) - { - AddException(e); - } - } - } - Canceled = true; - return -1; - } - } - return 0; - } - - public void PrepareOperation(AskMode askExtractMode) { } - - /// - /// Called when the archive was extracted - /// - /// - public void SetOperationResult(OperationResult operationResult) - { - if (operationResult != OperationResult.Ok && ReportErrors) - { - switch (operationResult) - { - case OperationResult.CrcError: - AddException(new ExtractionFailedException("File is corrupted. Crc check has failed.")); - break; - case OperationResult.DataError: - AddException(new ExtractionFailedException("File is corrupted. Data error has occured.")); - break; - case OperationResult.UnsupportedMethod: - AddException(new ExtractionFailedException("Unsupported method error has occured.")); - break; - } - } - else - { - if (_fileStream != null && !_fileIndex.HasValue) - { - try - { - _fileStream.BytesWritten -= IntEventArgsHandler; - _fileStream.Dispose(); - } - catch (ObjectDisposedException) { } - _fileStream = null; - GC.Collect(); - GC.WaitForPendingFinalizers(); - } - var iea = new FileInfoEventArgs( - _extractor.ArchiveFileData[_currentIndex], PercentDoneEventArgs.ProducePercentDone(_doneRate)); - OnFileExtractionFinished(iea); - if (iea.Cancel) - { - Canceled = true; - } - } - } - - #endregion - - #region ICryptoGetTextPassword Members - - /// - /// Sets password for the archive - /// - /// Password for the archive - /// Zero if everything is OK - public int CryptoGetTextPassword(out string password) - { - password = Password; - return 0; - } - - #endregion - - #region IDisposable Members - - public void Dispose() - { -#if !WINCE - GC.RemoveMemoryPressure(MEMORY_PRESSURE); -#endif - if (_fileStream != null) - { - try - { - _fileStream.Dispose(); - } - catch (ObjectDisposedException) { } - _fileStream = null; - } - if (_fakeStream != null) - { - try - { - _fakeStream.Dispose(); - } - catch (ObjectDisposedException) { } - _fakeStream = null; - } - } - - #endregion - - /// - /// Validates the file name and ensures that the directory to the file name is valid and creates intermediate directories if necessary - /// - /// File name - /// The valid file name - private static string ValidateFileName(string fileName) - { - if (String.IsNullOrEmpty(fileName)) - { - throw new SevenZipArchiveException("some archive name is null or empty."); - } - var splittedFileName = new List(fileName.Split(Path.DirectorySeparatorChar)); -#if !WINCE - foreach (char chr in Path.GetInvalidFileNameChars()) - { - for (int i = 0; i < splittedFileName.Count; i++) - { - if (chr == ':' && i == 0) - { - continue; - } - if (String.IsNullOrEmpty(splittedFileName[i])) - { - continue; - } - while (splittedFileName[i].IndexOf(chr) > -1) - { - splittedFileName[i] = splittedFileName[i].Replace(chr, '_'); - } - } - } -#endif - if (fileName.StartsWith(new string(Path.DirectorySeparatorChar, 2), - StringComparison.CurrentCultureIgnoreCase)) - { - splittedFileName.RemoveAt(0); - splittedFileName.RemoveAt(0); - splittedFileName[0] = new string(Path.DirectorySeparatorChar, 2) + splittedFileName[0]; - } - if (splittedFileName.Count > 2) - { - string tfn = splittedFileName[0]; - for (int i = 1; i < splittedFileName.Count - 1; i++) - { - tfn += Path.DirectorySeparatorChar + splittedFileName[i]; - if (!Directory.Exists(tfn)) - { - Directory.CreateDirectory(tfn); - } - } - } - return String.Join(new string(Path.DirectorySeparatorChar, 1), splittedFileName.ToArray()); - } - } -#endif -} diff --git a/BizHawk.Util/7z/ArchiveOpenCallback.cs b/BizHawk.Util/7z/ArchiveOpenCallback.cs deleted file mode 100644 index d870be30bb..0000000000 --- a/BizHawk.Util/7z/ArchiveOpenCallback.cs +++ /dev/null @@ -1,192 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Runtime.InteropServices; -#if MONO -using SevenZip.Mono; -using SevenZip.Mono.COM; -#endif - -namespace SevenZip -{ - #if UNMANAGED - /// - /// Callback to handle the archive opening - /// - internal sealed class ArchiveOpenCallback : CallbackBase, IArchiveOpenCallback, IArchiveOpenVolumeCallback, - ICryptoGetTextPassword, IDisposable - { - private FileInfo _fileInfo; - private Dictionary _wrappers = - new Dictionary(); - public readonly List VolumeFileNames = new List(); - - /// - /// Performs the common initialization. - /// - /// Volume file name. - private void Init(string fileName) - { - if (!String.IsNullOrEmpty(fileName)) - { - _fileInfo = new FileInfo(fileName); - VolumeFileNames.Add(fileName); - } - } - - /// - /// Initializes a new instance of the ArchiveOpenCallback class. - /// - /// The archive file name. - public ArchiveOpenCallback(string fileName) - { - Init(fileName); - } - - /// - /// Initializes a new instance of the ArchiveOpenCallback class. - /// - /// The archive file name. - /// Password for the archive. - public ArchiveOpenCallback(string fileName, string password) : base(password) - { - Init(fileName); - } - - #region IArchiveOpenCallback Members - - public void SetTotal(IntPtr files, IntPtr bytes) {} - - public void SetCompleted(IntPtr files, IntPtr bytes) {} - - #endregion - - #region IArchiveOpenVolumeCallback Members - - public int GetProperty(ItemPropId propId, ref PropVariant value) - { - switch (propId) - { - case ItemPropId.Name: - value.VarType = VarEnum.VT_BSTR; - value.Value = Marshal.StringToBSTR(_fileInfo.FullName); - break; - case ItemPropId.IsDirectory: - value.VarType = VarEnum.VT_BOOL; - value.UInt64Value = (byte) (_fileInfo.Attributes & FileAttributes.Directory); - break; - case ItemPropId.Size: - value.VarType = VarEnum.VT_UI8; - value.UInt64Value = (UInt64) _fileInfo.Length; - break; - case ItemPropId.Attributes: - value.VarType = VarEnum.VT_UI4; - value.UInt32Value = (uint) _fileInfo.Attributes; - break; - case ItemPropId.CreationTime: - value.VarType = VarEnum.VT_FILETIME; - value.Int64Value = _fileInfo.CreationTime.ToFileTime(); - break; - case ItemPropId.LastAccessTime: - value.VarType = VarEnum.VT_FILETIME; - value.Int64Value = _fileInfo.LastAccessTime.ToFileTime(); - break; - case ItemPropId.LastWriteTime: - value.VarType = VarEnum.VT_FILETIME; - value.Int64Value = _fileInfo.LastWriteTime.ToFileTime(); - break; - } - return 0; - } - - public int GetStream(string name, out IInStream inStream) - { - if (!File.Exists(name)) - { - name = Path.Combine(Path.GetDirectoryName(_fileInfo.FullName), name); - if (!File.Exists(name)) - { - inStream = null; - AddException(new FileNotFoundException("The volume \"" + name + "\" was not found. Extraction can be impossible.")); - return 1; - } - } - VolumeFileNames.Add(name); - if (_wrappers.ContainsKey(name)) - { - inStream = _wrappers[name]; - } - else - { - try - { - var wrapper = new InStreamWrapper( - new FileStream(name, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), true); - _wrappers.Add(name, wrapper); - inStream = wrapper; - } - catch (Exception) - { - AddException(new FileNotFoundException("Failed to open the volume \"" + name + "\". Extraction is impossible.")); - inStream = null; - return 1; - } - } - return 0; - } - - #endregion - - #region ICryptoGetTextPassword Members - - /// - /// Sets password for the archive - /// - /// Password for the archive - /// Zero if everything is OK - public int CryptoGetTextPassword(out string password) - { - password = Password; - return 0; - } - - #endregion - - #region IDisposable Members - - public void Dispose() - { - if (_wrappers != null) - { - foreach (InStreamWrapper wrap in _wrappers.Values) - { - wrap.Dispose(); - } - _wrappers = null; - } -#if MONO - libp7zInvokerRaw.FreeObject(Handle); -#endif - GC.SuppressFinalize(this); - } - - #endregion - } -#endif -} diff --git a/BizHawk.Util/7z/ArchiveUpdateCallback.cs b/BizHawk.Util/7z/ArchiveUpdateCallback.cs deleted file mode 100644 index 9e8be21990..0000000000 --- a/BizHawk.Util/7z/ArchiveUpdateCallback.cs +++ /dev/null @@ -1,806 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Runtime.InteropServices; -#if MONO -using SevenZip.Mono.COM; -#endif - -namespace SevenZip -{ -#if UNMANAGED -#if COMPRESS - /// - /// Archive update callback to handle the process of packing files - /// - internal sealed class ArchiveUpdateCallback : CallbackBase, IArchiveUpdateCallback, ICryptoGetTextPassword2, - IDisposable - { - #region Fields - /// - /// _files.Count if do not count directories - /// - private int _actualFilesCount; - - /// - /// For Compressing event. - /// - private long _bytesCount; - - private long _bytesWritten; - private long _bytesWrittenOld; - private SevenZipCompressor _compressor; - - /// - /// No directories. - /// - private bool _directoryStructure; - - /// - /// Rate of the done work from [0, 1] - /// - private float _doneRate; - - /// - /// The names of the archive entries - /// - private string[] _entries; - - /// - /// Array of files to pack - /// - private FileInfo[] _files; - - private InStreamWrapper _fileStream; - - private uint _indexInArchive; - private uint _indexOffset; - - /// - /// Common root of file names length. - /// - private int _rootLength; - - /// - /// Input streams to be compressed. - /// - private Stream[] _streams; - - private UpdateData _updateData; - private List _wrappersToDispose; - - /// - /// Gets or sets the default item name used in MemoryStream compression. - /// - public string DefaultItemName { private get; set; } - - /// - /// Gets or sets the value indicating whether to compress as fast as possible, without calling events. - /// - public bool FastCompression { private get; set; } -#if !WINCE - private int _memoryPressure; -#endif - #endregion - - #region Constructors - - /// - /// Initializes a new instance of the ArchiveUpdateCallback class - /// - /// Array of files to pack - /// Common file names root length - /// The owner of the callback - /// The compression parameters. - /// Preserve directory structure. - public ArchiveUpdateCallback( - FileInfo[] files, int rootLength, - SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure) - { - Init(files, rootLength, compressor, updateData, directoryStructure); - } - - /// - /// Initializes a new instance of the ArchiveUpdateCallback class - /// - /// Array of files to pack - /// Common file names root length - /// The archive password - /// The owner of the callback - /// The compression parameters. - /// Preserve directory structure. - public ArchiveUpdateCallback( - FileInfo[] files, int rootLength, string password, - SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure) - : base(password) - { - Init(files, rootLength, compressor, updateData, directoryStructure); - } - - /// - /// Initializes a new instance of the ArchiveUpdateCallback class - /// - /// The input stream - /// The owner of the callback - /// The compression parameters. - /// Preserve directory structure. - public ArchiveUpdateCallback( - Stream stream, SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure) - { - Init(stream, compressor, updateData, directoryStructure); - } - - /// - /// Initializes a new instance of the ArchiveUpdateCallback class - /// - /// The input stream - /// The archive password - /// The owner of the callback - /// The compression parameters. - /// Preserve directory structure. - public ArchiveUpdateCallback( - Stream stream, string password, SevenZipCompressor compressor, UpdateData updateData, - bool directoryStructure) - : base(password) - { - Init(stream, compressor, updateData, directoryStructure); - } - - /// - /// Initializes a new instance of the ArchiveUpdateCallback class - /// - /// Dictionary<file stream, name of the archive entry> - /// The owner of the callback - /// The compression parameters. - /// Preserve directory structure. - public ArchiveUpdateCallback( - Dictionary streamDict, - SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure) - { - Init(streamDict, compressor, updateData, directoryStructure); - } - - /// - /// Initializes a new instance of the ArchiveUpdateCallback class - /// - /// Dictionary<file stream, name of the archive entry> - /// The archive password - /// The owner of the callback - /// The compression parameters. - /// Preserve directory structure. - public ArchiveUpdateCallback( - Dictionary streamDict, string password, - SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure) - : base(password) - { - Init(streamDict, compressor, updateData, directoryStructure); - } - - private void CommonInit(SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure) - { - _compressor = compressor; - _indexInArchive = updateData.FilesCount; - _indexOffset = updateData.Mode != InternalCompressionMode.Append ? 0 : _indexInArchive; - if (_compressor.ArchiveFormat == OutArchiveFormat.Zip) - { - _wrappersToDispose = new List(); - } - _updateData = updateData; - _directoryStructure = directoryStructure; - DefaultItemName = "default"; - } - - private void Init( - FileInfo[] files, int rootLength, SevenZipCompressor compressor, - UpdateData updateData, bool directoryStructure) - { - _files = files; - _rootLength = rootLength; - if (files != null) - { - foreach (var fi in files) - { - if (fi.Exists) - { - _bytesCount += fi.Length; - if ((fi.Attributes & FileAttributes.Directory) == 0) - { - _actualFilesCount++; - } - } - } - } - CommonInit(compressor, updateData, directoryStructure); - } - - private void Init( - Stream stream, SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure) - { - _fileStream = new InStreamWrapper(stream, false); - _fileStream.BytesRead += IntEventArgsHandler; - _actualFilesCount = 1; - try - { - _bytesCount = stream.Length; - } - catch (NotSupportedException) - { - _bytesCount = -1; - } - try - { - stream.Seek(0, SeekOrigin.Begin); - } - catch (NotSupportedException) - { - _bytesCount = -1; - } - CommonInit(compressor, updateData, directoryStructure); - } - - private void Init( - Dictionary streamDict, - SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure) - { - _streams = new Stream[streamDict.Count]; - streamDict.Values.CopyTo(_streams, 0); - _entries = new string[streamDict.Count]; - streamDict.Keys.CopyTo(_entries, 0); - _actualFilesCount = streamDict.Count; - foreach (Stream str in _streams) - { - if (str != null) - { - _bytesCount += str.Length; - } - } - CommonInit(compressor, updateData, directoryStructure); - } - - #endregion - - /// - /// Gets or sets the dictionary size. - /// - public float DictionarySize - { - set - { -#if !WINCE - _memoryPressure = (int)(value * 1024 * 1024); - GC.AddMemoryPressure(_memoryPressure); -#endif - } - } - - /// - /// Raises events for the GetStream method. - /// - /// The current item index. - /// True if not cancelled; otherwise, false. - private bool EventsForGetStream(uint index) - { - if (!FastCompression) - { - if (_fileStream != null) - { - _fileStream.BytesRead += IntEventArgsHandler; - } - _doneRate += 1.0f / _actualFilesCount; - var fiea = new FileNameEventArgs(_files != null? _files[index].Name : _entries[index], - PercentDoneEventArgs.ProducePercentDone(_doneRate)); - OnFileCompression(fiea); - if (fiea.Cancel) - { - Canceled = true; - return false; - } - } - return true; - } - - #region Events - - /// - /// Occurs when the next file is going to be packed. - /// - /// Occurs when 7-zip engine requests for an input stream for the next file to pack it - public event EventHandler FileCompressionStarted; - - /// - /// Occurs when data are being compressed. - /// - public event EventHandler Compressing; - - /// - /// Occurs when the current file was compressed. - /// - public event EventHandler FileCompressionFinished; - - private void OnFileCompression(FileNameEventArgs e) - { - if (FileCompressionStarted != null) - { - FileCompressionStarted(this, e); - } - } - - private void OnCompressing(ProgressEventArgs e) - { - if (Compressing != null) - { - Compressing(this, e); - } - } - - private void OnFileCompressionFinished(EventArgs e) - { - if (FileCompressionFinished != null) - { - FileCompressionFinished(this, e); - } - } - - #endregion - - #region IArchiveUpdateCallback Members - - public void SetTotal(ulong total) {} - - public void SetCompleted(ref ulong completeValue) {} - - public int GetUpdateItemInfo(uint index, ref int newData, ref int newProperties, ref uint indexInArchive) - { - switch (_updateData.Mode) - { - case InternalCompressionMode.Create: - newData = 1; - newProperties = 1; - indexInArchive = UInt32.MaxValue; - break; - case InternalCompressionMode.Append: - if (index < _indexInArchive) - { - newData = 0; - newProperties = 0; - indexInArchive = index; - } - else - { - newData = 1; - newProperties = 1; - indexInArchive = UInt32.MaxValue; - } - break; - case InternalCompressionMode.Modify: - newData = 0; - newProperties = Convert.ToInt32(_updateData.FileNamesToModify.ContainsKey((int)index) - && _updateData.FileNamesToModify[(int)index] != null); - if (_updateData.FileNamesToModify.ContainsKey((int)index) - && _updateData.FileNamesToModify[(int)index] == null) - { - indexInArchive = (UInt32)_updateData.ArchiveFileData.Count; - foreach (KeyValuePair pairModification in _updateData.FileNamesToModify) - if ((pairModification.Key <= index) && (pairModification.Value == null)) - { - do - { - indexInArchive--; - } - while ((indexInArchive > 0) && _updateData.FileNamesToModify.ContainsKey((Int32)indexInArchive) - && (_updateData.FileNamesToModify[(Int32)indexInArchive] == null)); - } - } - else - { - indexInArchive = index; - } - break; - } - return 0; - } - - public int GetProperty(uint index, ItemPropId propID, ref PropVariant value) - { - index -= _indexOffset; - try - { - switch (propID) - { - case ItemPropId.IsAnti: - value.VarType = VarEnum.VT_BOOL; - value.UInt64Value = 0; - break; - case ItemPropId.Path: - #region Path - - value.VarType = VarEnum.VT_BSTR; - string val = DefaultItemName; - if (_updateData.Mode != InternalCompressionMode.Modify) - { - if (_files == null) - { - if (_entries != null) - { - val = _entries[index]; - } - } - else - { - if (_directoryStructure) - { - if (_rootLength > 0) - { - val = _files[index].FullName.Substring(_rootLength); - } - else - { - val = _files[index].FullName[0] + _files[index].FullName.Substring(2); - } - } - else - { - val = _files[index].Name; - } - } - } - else - { - val = _updateData.FileNamesToModify[(int) index]; - } - value.Value = Marshal.StringToBSTR(val); - #endregion - break; - case ItemPropId.IsDirectory: - value.VarType = VarEnum.VT_BOOL; - if (_updateData.Mode != InternalCompressionMode.Modify) - { - if (_files == null) - { - if (_streams == null) - { - value.UInt64Value = 0; - } - else - { - value.UInt64Value = (ulong)(_streams[index] == null ? 1 : 0); - } - } - else - { - value.UInt64Value = (byte)(_files[index].Attributes & FileAttributes.Directory); - } - } - else - { - value.UInt64Value = Convert.ToUInt64(_updateData.ArchiveFileData[(int) index].IsDirectory); - } - break; - case ItemPropId.Size: - #region Size - - value.VarType = VarEnum.VT_UI8; - UInt64 size; - if (_updateData.Mode != InternalCompressionMode.Modify) - { - if (_files == null) - { - if (_streams == null) - { - size = _bytesCount > 0 ? (ulong) _bytesCount : 0; - } - else - { - size = (ulong) (_streams[index] == null? 0 : _streams[index].Length); - } - } - else - { - size = (_files[index].Attributes & FileAttributes.Directory) == 0 - ? (ulong) _files[index].Length - : 0; - } - } - else - { - size = _updateData.ArchiveFileData[(int) index].Size; - } - value.UInt64Value = size; - - #endregion - break; - case ItemPropId.Attributes: - value.VarType = VarEnum.VT_UI4; - if (_updateData.Mode != InternalCompressionMode.Modify) - { - if (_files == null) - { - if (_streams == null) - { - value.UInt32Value = (uint)FileAttributes.Normal; - } - else - { - value.UInt32Value = (uint)(_streams[index] == null ? FileAttributes.Directory : FileAttributes.Normal); - } - } - else - { - value.UInt32Value = (uint) _files[index].Attributes; - } - } - else - { - value.UInt32Value = _updateData.ArchiveFileData[(int) index].Attributes; - } - break; - #region Times - case ItemPropId.CreationTime: - value.VarType = VarEnum.VT_FILETIME; - if (_updateData.Mode != InternalCompressionMode.Modify) - { - value.Int64Value = _files == null - ? DateTime.Now.ToFileTime() - : _files[index].CreationTime.ToFileTime(); - } - else - { - value.Int64Value = _updateData.ArchiveFileData[(int) index].CreationTime.ToFileTime(); - } - break; - case ItemPropId.LastAccessTime: - value.VarType = VarEnum.VT_FILETIME; - if (_updateData.Mode != InternalCompressionMode.Modify) - { - value.Int64Value = _files == null - ? DateTime.Now.ToFileTime() - : _files[index].LastAccessTime.ToFileTime(); - } - else - { - value.Int64Value = _updateData.ArchiveFileData[(int) index].LastAccessTime.ToFileTime(); - } - break; - case ItemPropId.LastWriteTime: - value.VarType = VarEnum.VT_FILETIME; - if (_updateData.Mode != InternalCompressionMode.Modify) - { - value.Int64Value = _files == null - ? DateTime.Now.ToFileTime() - : _files[index].LastWriteTime.ToFileTime(); - } - else - { - value.Int64Value = _updateData.ArchiveFileData[(int) index].LastWriteTime.ToFileTime(); - } - break; - #endregion - case ItemPropId.Extension: - #region Extension - - value.VarType = VarEnum.VT_BSTR; - if (_updateData.Mode != InternalCompressionMode.Modify) - { - try - { - val = _files != null - ? _files[index].Extension.Substring(1) - : _entries == null - ? "" - : Path.GetExtension(_entries[index]); - value.Value = Marshal.StringToBSTR(val); - } - catch (ArgumentException) - { - value.Value = Marshal.StringToBSTR(""); - } - } - else - { - val = Path.GetExtension(_updateData.ArchiveFileData[(int) index].FileName); - value.Value = Marshal.StringToBSTR(val); - } - - #endregion - break; - } - } - catch (Exception e) - { - AddException(e); - } - return 0; - } - - /// - /// Gets the stream for 7-zip library. - /// - /// File index - /// Input file stream - /// Zero if Ok - public int GetStream(uint index, out -#if !MONO - ISequentialInStream -#else - HandleRef -#endif - inStream) - { - index -= _indexOffset; - if (_files != null) - { - _fileStream = null; - try - { - if (File.Exists(_files[index].FullName)) - { - _fileStream = new InStreamWrapper( - new FileStream(_files[index].FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), - true); - } - } - catch (Exception e) - { - AddException(e); - inStream = null; - return -1; - } - inStream = _fileStream; - if (!EventsForGetStream(index)) - { - return -1; - } - } - else - { - if (_streams == null) - { - inStream = _fileStream; - } - else - { - _fileStream = new InStreamWrapper(_streams[index], true); - inStream = _fileStream; - if (!EventsForGetStream(index)) - { - return -1; - } - } - } - return 0; - } - - public long EnumProperties(IntPtr enumerator) - { - //Not implemented HRESULT - return 0x80004001L; - } - - public void SetOperationResult(OperationResult operationResult) - { - if (operationResult != OperationResult.Ok && ReportErrors) - { - switch (operationResult) - { - case OperationResult.CrcError: - AddException(new ExtractionFailedException("File is corrupted. Crc check has failed.")); - break; - case OperationResult.DataError: - AddException(new ExtractionFailedException("File is corrupted. Data error has occured.")); - break; - case OperationResult.UnsupportedMethod: - AddException(new ExtractionFailedException("Unsupported method error has occured.")); - break; - } - } - if (_fileStream != null) - { - - _fileStream.BytesRead -= IntEventArgsHandler; - //Specific Zip implementation - can not Dispose files for Zip. - if (_compressor.ArchiveFormat != OutArchiveFormat.Zip) - { - try - { - _fileStream.Dispose(); - } - catch (ObjectDisposedException) {} - } - else - { - _wrappersToDispose.Add(_fileStream); - } - _fileStream = null; - GC.Collect(); - // Issue #6987 - //GC.WaitForPendingFinalizers(); - } - OnFileCompressionFinished(EventArgs.Empty); - } - - #endregion - - #region ICryptoGetTextPassword2 Members - - public int CryptoGetTextPassword2(ref int passwordIsDefined, out string password) - { - passwordIsDefined = String.IsNullOrEmpty(Password) ? 0 : 1; - password = Password; - return 0; - } - - #endregion - - #region IDisposable Members - - public void Dispose() - { -#if !WINCE - GC.RemoveMemoryPressure(_memoryPressure); -#endif - if (_fileStream != null) - { - try - { - _fileStream.Dispose(); - } - catch (ObjectDisposedException) {} - } - if (_wrappersToDispose != null) - { - foreach (var wrapper in _wrappersToDispose) - { - try - { - wrapper.Dispose(); - } - catch (ObjectDisposedException) {} - } - } - GC.SuppressFinalize(this); - } - - #endregion - - private void IntEventArgsHandler(object sender, IntEventArgs e) - { - lock (this) - { - var pold = (byte) ((_bytesWrittenOld*100)/_bytesCount); - _bytesWritten += e.Value; - byte pnow; - if (_bytesCount < _bytesWritten) //Holy shit, this check for ZIP is golden - { - pnow = 100; - } - else - { - pnow = (byte)((_bytesWritten * 100) / _bytesCount); - } - if (pnow > pold) - { - _bytesWrittenOld = _bytesWritten; - OnCompressing(new ProgressEventArgs(pnow, (byte) (pnow - pold))); - } - } - } - } -#endif -#endif -} diff --git a/BizHawk.Util/7z/COM.cs b/BizHawk.Util/7z/COM.cs deleted file mode 100644 index 31d2a4d863..0000000000 --- a/BizHawk.Util/7z/COM.cs +++ /dev/null @@ -1,1244 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General public License for more details. - - You should have received a copy of the GNU Lesser General public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Runtime.InteropServices; -using System.Security.Permissions; -#if !WINCE -using FILETIME=System.Runtime.InteropServices.ComTypes.FILETIME; -#elif WINCE -using FILETIME=OpenNETCF.Runtime.InteropServices.ComTypes.FILETIME; -#endif - -namespace SevenZip -{ - #if UNMANAGED - - /// - /// The structure to fix x64 and x32 variant size mismatch. - /// - [StructLayout(LayoutKind.Sequential)] - internal struct PropArray - { - uint _cElems; - IntPtr _pElems; - } - - /// - /// COM VARIANT structure with special interface routines. - /// - [StructLayout(LayoutKind.Explicit)] - internal struct PropVariant - { - [FieldOffset(0)] private ushort _vt; - - /// - /// IntPtr variant value. - /// - [FieldOffset(8)] private IntPtr _value; - - /*/// - /// Byte variant value. - /// - [FieldOffset(8)] - private byte _ByteValue;*/ - - /// - /// Signed int variant value. - /// - [FieldOffset(8)] - private Int32 _int32Value; - - /// - /// Unsigned int variant value. - /// - [FieldOffset(8)] private UInt32 _uInt32Value; - - /// - /// Long variant value. - /// - [FieldOffset(8)] private Int64 _int64Value; - - /// - /// Unsigned long variant value. - /// - [FieldOffset(8)] private UInt64 _uInt64Value; - - /// - /// FILETIME variant value. - /// - [FieldOffset(8)] private FILETIME _fileTime; - - /// - /// The PropArray instance to fix the variant size on x64 bit systems. - /// - [FieldOffset(8)] - private PropArray _propArray; - - /// - /// Gets or sets variant type. - /// - public VarEnum VarType - { - private get - { - return (VarEnum) _vt; - } - - set - { - _vt = (ushort) value; - } - } - - /// - /// Gets or sets the pointer value of the COM variant - /// - public IntPtr Value - { - private get - { - return _value; - } - - set - { - _value = value; - } - } - - /* - /// - /// Gets or sets the byte value of the COM variant - /// - public byte ByteValue - { - get - { - return _ByteValue; - } - - set - { - _ByteValue = value; - } - } -*/ - - /// - /// Gets or sets the UInt32 value of the COM variant. - /// - public UInt32 UInt32Value - { - private get - { - return _uInt32Value; - } - set - { - _uInt32Value = value; - } - } - - /// - /// Gets or sets the UInt32 value of the COM variant. - /// - public Int32 Int32Value - { - private get - { - return _int32Value; - } - set - { - _int32Value = value; - } - } - - /// - /// Gets or sets the Int64 value of the COM variant - /// - public Int64 Int64Value - { - private get - { - return _int64Value; - } - - set - { - _int64Value = value; - } - } - - /// - /// Gets or sets the UInt64 value of the COM variant - /// - public UInt64 UInt64Value - { - private get - { - return _uInt64Value; - } - set - { - _uInt64Value = value; - } - } - - /* - /// - /// Gets or sets the FILETIME value of the COM variant - /// - public System.Runtime.InteropServices.ComTypes.FILETIME FileTime - { - get - { - return _fileTime; - } - - set - { - _fileTime = value; - } - } -*/ - - /*/// - /// Gets or sets variant type (ushort). - /// - public ushort VarTypeNative - { - get - { - return _vt; - } - - set - { - _vt = value; - } - }*/ - - /*/// - /// Clears variant - /// - public void Clear() - { - switch (VarType) - { - case VarEnum.VT_EMPTY: - break; - case VarEnum.VT_NULL: - case VarEnum.VT_I2: - case VarEnum.VT_I4: - case VarEnum.VT_R4: - case VarEnum.VT_R8: - case VarEnum.VT_CY: - case VarEnum.VT_DATE: - case VarEnum.VT_ERROR: - case VarEnum.VT_BOOL: - case VarEnum.VT_I1: - case VarEnum.VT_UI1: - case VarEnum.VT_UI2: - case VarEnum.VT_UI4: - case VarEnum.VT_I8: - case VarEnum.VT_UI8: - case VarEnum.VT_INT: - case VarEnum.VT_UINT: - case VarEnum.VT_HRESULT: - case VarEnum.VT_FILETIME: - _vt = 0; - break; - default: - if (NativeMethods.PropVariantClear(ref this) != (int)OperationResult.Ok) - { - throw new ArgumentException("PropVariantClear has failed for some reason."); - } - break; - } - }*/ - - /// - /// Gets the object for this PropVariant. - /// - /// - public object Object - { - get - { -#if !WINCE - var sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); - sp.Demand(); -#endif - switch (VarType) - { - case VarEnum.VT_EMPTY: - return null; - case VarEnum.VT_FILETIME: - try - { - return DateTime.FromFileTime(Int64Value); - } - catch (ArgumentOutOfRangeException) - { - return DateTime.MinValue; - } - default: - GCHandle propHandle = GCHandle.Alloc(this, GCHandleType.Pinned); - try - { - return Marshal.GetObjectForNativeVariant(propHandle.AddrOfPinnedObject()); - } -#if WINCE - catch (NotSupportedException) - { - switch (VarType) - { - case VarEnum.VT_UI8: - return UInt64Value; - case VarEnum.VT_UI4: - return UInt32Value; - case VarEnum.VT_I8: - return Int64Value; - case VarEnum.VT_I4: - return Int32Value; - default: - return 0; - } - } -#endif - finally - { - propHandle.Free(); - } - } - } - } - - /// - /// Determines whether the specified System.Object is equal to the current PropVariant. - /// - /// The System.Object to compare with the current PropVariant. - /// true if the specified System.Object is equal to the current PropVariant; otherwise, false. - public override bool Equals(object obj) - { - return (obj is PropVariant) ? Equals((PropVariant) obj) : false; - } - - /// - /// Determines whether the specified PropVariant is equal to the current PropVariant. - /// - /// The PropVariant to compare with the current PropVariant. - /// true if the specified PropVariant is equal to the current PropVariant; otherwise, false. - private bool Equals(PropVariant afi) - { - if (afi.VarType != VarType) - { - return false; - } - if (VarType != VarEnum.VT_BSTR) - { - return afi.Int64Value == Int64Value; - } - return afi.Value == Value; - } - - /// - /// Serves as a hash function for a particular type. - /// - /// A hash code for the current PropVariant. - public override int GetHashCode() - { - return Value.GetHashCode(); - } - - /// - /// Returns a System.String that represents the current PropVariant. - /// - /// A System.String that represents the current PropVariant. - public override string ToString() - { - return "[" + Value + "] " + Int64Value.ToString(CultureInfo.CurrentCulture); - } - - /// - /// Determines whether the specified PropVariant instances are considered equal. - /// - /// The first PropVariant to compare. - /// The second PropVariant to compare. - /// true if the specified PropVariant instances are considered equal; otherwise, false. - public static bool operator ==(PropVariant afi1, PropVariant afi2) - { - return afi1.Equals(afi2); - } - - /// - /// Determines whether the specified PropVariant instances are not considered equal. - /// - /// The first PropVariant to compare. - /// The second PropVariant to compare. - /// true if the specified PropVariant instances are not considered equal; otherwise, false. - public static bool operator !=(PropVariant afi1, PropVariant afi2) - { - return !afi1.Equals(afi2); - } - } - - /// - /// Stores file extraction modes. - /// - internal enum AskMode - { - /// - /// Extraction mode - /// - Extract = 0, - /// - /// Test mode - /// - Test, - /// - /// Skip mode - /// - Skip - } - - /// - /// Stores operation result values - /// - public enum OperationResult - { - /// - /// Success - /// - Ok = 0, - /// - /// Method is unsupported - /// - UnsupportedMethod, - /// - /// Data error has occured - /// - DataError, - /// - /// CrcError has occured - /// - CrcError - } - - /// - /// Codes of item properities - /// - internal enum ItemPropId : uint - { - /// - /// No property - /// - NoProperty = 0, - /// - /// Handler item index - /// - HandlerItemIndex = 2, - /// - /// Item path - /// - Path, - /// - /// Item name - /// - Name, - /// - /// Item extension - /// - Extension, - /// - /// true if the item is a folder; otherwise, false - /// - IsDirectory, - /// - /// Item size - /// - Size, - /// - /// Item packed sise; usually absent - /// - PackedSize, - /// - /// Item attributes; usually absent - /// - Attributes, - /// - /// Item creation time; usually absent - /// - CreationTime, - /// - /// Item last access time; usually absent - /// - LastAccessTime, - /// - /// Item last write time - /// - LastWriteTime, - /// - /// true if the item is solid; otherwise, false - /// - Solid, - /// - /// true if the item is commented; otherwise, false - /// - Commented, - /// - /// true if the item is encrypted; otherwise, false - /// - Encrypted, - /// - /// (?) - /// - SplitBefore, - /// - /// (?) - /// - SplitAfter, - /// - /// Dictionary size(?) - /// - DictionarySize, - /// - /// Item CRC checksum - /// - Crc, - /// - /// Item type(?) - /// - Type, - /// - /// (?) - /// - IsAnti, - /// - /// Compression method - /// - Method, - /// - /// (?); usually absent - /// - HostOS, - /// - /// Item file system; usually absent - /// - FileSystem, - /// - /// Item user(?); usually absent - /// - User, - /// - /// Item group(?); usually absent - /// - Group, - /// - /// Bloack size(?) - /// - Block, - /// - /// Item comment; usually absent - /// - Comment, - /// - /// Item position - /// - Position, - /// - /// Item prefix(?) - /// - Prefix, - /// - /// Number of subdirectories - /// - NumSubDirs, - /// - /// Numbers of subfiles - /// - NumSubFiles, - /// - /// The archive legacy unpacker version - /// - UnpackVersion, - /// - /// Volume(?) - /// - Volume, - /// - /// Is a volume - /// - IsVolume, - /// - /// Offset value(?) - /// - Offset, - /// - /// Links(?) - /// - Links, - /// - /// Number of blocks - /// - NumBlocks, - /// - /// Number of volumes(?) - /// - NumVolumes, - /// - /// Time type(?) - /// - TimeType, - /// - /// 64-bit(?) - /// - Bit64, - /// - /// BigEndian - /// - BigEndian, - /// - /// Cpu(?) - /// - Cpu, - /// - /// Physical archive size - /// - PhysicalSize, - /// - /// Headers size - /// - HeadersSize, - /// - /// Archive checksum - /// - Checksum, - /// - /// (?) - /// - TotalSize = 0x1100, - /// - /// (?) - /// - FreeSpace, - /// - /// Cluster size(?) - /// - ClusterSize, - /// - /// Volume name(?) - /// - VolumeName, - /// - /// Local item name(?); usually absent - /// - LocalName = 0x1200, - /// - /// (?) - /// - Provider, - /// - /// User defined property; usually absent - /// - UserDefined = 0x10000 - } - - /*/// - /// Codes of archive properties or modes. - /// - internal enum ArchivePropId : uint - { - Name = 0, - ClassID, - Extension, - AddExtension, - Update, - KeepName, - StartSignature, - FinishSignature, - Associate - }*/ - - /// - /// PropId string names dictionary wrapper. - /// - internal static class PropIdToName - { - /// - /// PropId string names - /// - public static readonly Dictionary PropIdNames = - #region Initialization - new Dictionary(46) - { - {ItemPropId.Path, "Path"}, - {ItemPropId.Name, "Name"}, - {ItemPropId.IsDirectory, "Folder"}, - {ItemPropId.Size, "Size"}, - {ItemPropId.PackedSize, "Packed Size"}, - {ItemPropId.Attributes, "Attributes"}, - {ItemPropId.CreationTime, "Created"}, - {ItemPropId.LastAccessTime, "Accessed"}, - {ItemPropId.LastWriteTime, "Modified"}, - {ItemPropId.Solid, "Solid"}, - {ItemPropId.Commented, "Commented"}, - {ItemPropId.Encrypted, "Encrypted"}, - {ItemPropId.SplitBefore, "Split Before"}, - {ItemPropId.SplitAfter, "Split After"}, - { - ItemPropId.DictionarySize, - "Dictionary Size" - }, - {ItemPropId.Crc, "CRC"}, - {ItemPropId.Type, "Type"}, - {ItemPropId.IsAnti, "Anti"}, - {ItemPropId.Method, "Method"}, - {ItemPropId.HostOS, "Host OS"}, - {ItemPropId.FileSystem, "File System"}, - {ItemPropId.User, "User"}, - {ItemPropId.Group, "Group"}, - {ItemPropId.Block, "Block"}, - {ItemPropId.Comment, "Comment"}, - {ItemPropId.Position, "Position"}, - {ItemPropId.Prefix, "Prefix"}, - { - ItemPropId.NumSubDirs, - "Number of subdirectories" - }, - { - ItemPropId.NumSubFiles, - "Number of subfiles" - }, - { - ItemPropId.UnpackVersion, - "Unpacker version" - }, - {ItemPropId.Volume, "Volume"}, - {ItemPropId.IsVolume, "IsVolume"}, - {ItemPropId.Offset, "Offset"}, - {ItemPropId.Links, "Links"}, - { - ItemPropId.NumBlocks, - "Number of blocks" - }, - { - ItemPropId.NumVolumes, - "Number of volumes" - }, - {ItemPropId.TimeType, "Time type"}, - {ItemPropId.Bit64, "64-bit"}, - {ItemPropId.BigEndian, "Big endian"}, - {ItemPropId.Cpu, "CPU"}, - { - ItemPropId.PhysicalSize, - "Physical Size" - }, - {ItemPropId.HeadersSize, "Headers Size"}, - {ItemPropId.Checksum, "Checksum"}, - {ItemPropId.FreeSpace, "Free Space"}, - {ItemPropId.ClusterSize, "Cluster Size"} - }; - #endregion - } - - /// - /// 7-zip IArchiveOpenCallback imported interface to handle the opening of an archive. - /// - [ComImport] - [Guid("23170F69-40C1-278A-0000-000600100000")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IArchiveOpenCallback - { - // ref ulong replaced with IntPtr because handlers often pass null value - // read actual value with Marshal.ReadInt64 - /// - /// Sets total data size - /// - /// Files pointer - /// Total size in bytes - void SetTotal( - IntPtr files, - IntPtr bytes); - - /// - /// Sets completed size - /// - /// Files pointer - /// Completed size in bytes - void SetCompleted( - IntPtr files, - IntPtr bytes); - } - - /// - /// 7-zip ICryptoGetTextPassword imported interface to get the archive password. - /// - [ComImport] - [Guid("23170F69-40C1-278A-0000-000500100000")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface ICryptoGetTextPassword - { - /// - /// Gets password for the archive - /// - /// Password for the archive - /// Zero if everything is OK - [PreserveSig] - int CryptoGetTextPassword( - [MarshalAs(UnmanagedType.BStr)] out string password); - } - - /// - /// 7-zip ICryptoGetTextPassword2 imported interface for setting the archive password. - /// - [ComImport] - [Guid("23170F69-40C1-278A-0000-000500110000")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface ICryptoGetTextPassword2 - { - /// - /// Sets password for the archive - /// - /// Specifies whether archive has a password or not (0 if not) - /// Password for the archive - /// Zero if everything is OK - [PreserveSig] - int CryptoGetTextPassword2( - ref int passwordIsDefined, - [MarshalAs(UnmanagedType.BStr)] out string password); - } - - /// - /// 7-zip IArchiveExtractCallback imported interface. - /// - [ComImport] - [Guid("23170F69-40C1-278A-0000-000600200000")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IArchiveExtractCallback - { - /// - /// Gives the size of the unpacked archive files - /// - /// Size of the unpacked archive files (in bytes) - void SetTotal(ulong total); - - /// - /// SetCompleted 7-zip function - /// - /// - void SetCompleted([In] ref ulong completeValue); - - /// - /// Gets the stream for file extraction - /// - /// File index in the archive file table - /// Pointer to the stream - /// Extraction mode - /// S_OK - OK, S_FALSE - skip this file - [PreserveSig] - int GetStream( - uint index, - [Out, MarshalAs(UnmanagedType.Interface)] out ISequentialOutStream outStream, - AskMode askExtractMode); - - /// - /// PrepareOperation 7-zip function - /// - /// Ask mode - void PrepareOperation(AskMode askExtractMode); - - /// - /// Sets the operaton result - /// - /// The operation result - void SetOperationResult(OperationResult operationResult); - } - - /// - /// 7-zip IArchiveUpdateCallback imported interface. - /// - [ComImport] - [Guid("23170F69-40C1-278A-0000-000600800000")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IArchiveUpdateCallback - { - /// - /// Gives the size of the unpacked archive files. - /// - /// Size of the unpacked archive files (in bytes) - void SetTotal(ulong total); - - /// - /// SetCompleted 7-zip internal function. - /// - /// - void SetCompleted([In] ref ulong completeValue); - - /// - /// Gets archive update mode. - /// - /// File index - /// 1 if new, 0 if not - /// 1 if new, 0 if not - /// -1 if doesn't matter - /// - [PreserveSig] - int GetUpdateItemInfo( - uint index, ref int newData, - ref int newProperties, ref uint indexInArchive); - - /// - /// Gets the archive item property data. - /// - /// Item index - /// Property identificator - /// Property value - /// Zero if Ok - [PreserveSig] - int GetProperty(uint index, ItemPropId propId, ref PropVariant value); - - /// - /// Gets the stream for reading. - /// - /// The item index. - /// The ISequentialInStream pointer for reading. - /// Zero if Ok - [PreserveSig] - int GetStream( - uint index, - [Out, MarshalAs(UnmanagedType.Interface)] out ISequentialInStream inStream); - - /// - /// Sets the result for currently performed operation. - /// - /// The result value. - void SetOperationResult(OperationResult operationResult); - - /// - /// EnumProperties 7-zip internal function. - /// - /// The enumerator pointer. - /// - long EnumProperties(IntPtr enumerator); - } - - /// - /// 7-zip IArchiveOpenVolumeCallback imported interface to handle archive volumes. - /// - [ComImport] - [Guid("23170F69-40C1-278A-0000-000600300000")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IArchiveOpenVolumeCallback - { - /// - /// Gets the archive property data. - /// - /// The property identificator. - /// The property value. - [PreserveSig] - int GetProperty( - ItemPropId propId, ref PropVariant value); - - /// - /// Gets the stream for reading the volume. - /// - /// The volume file name. - /// The IInStream pointer for reading. - /// Zero if Ok - [PreserveSig] - int GetStream( - [MarshalAs(UnmanagedType.LPWStr)] string name, - [Out, MarshalAs(UnmanagedType.Interface)] out IInStream inStream); - } - - /// - /// 7-zip ISequentialInStream imported interface - /// - [ComImport] - [Guid("23170F69-40C1-278A-0000-000300010000")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface ISequentialInStream - { - /// - /// Writes data to 7-zip packer - /// - /// Array of bytes available for writing - /// Array size - /// S_OK if success - /// If (size > 0) and there are bytes in stream, - /// this function must read at least 1 byte. - /// This function is allowed to read less than "size" bytes. - /// You must call Read function in loop, if you need exact amount of data. - /// - int Read( - [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data, - uint size); - } - - /// - /// 7-zip ISequentialOutStream imported interface - /// - [ComImport] - [Guid("23170F69-40C1-278A-0000-000300020000")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface ISequentialOutStream - { - /// - /// Writes data to unpacked file stream - /// - /// Array of bytes available for reading - /// Array size - /// Processed data size - /// S_OK if success - /// If size != 0, return value is S_OK and (*processedSize == 0), - /// then there are no more bytes in stream. - /// If (size > 0) and there are bytes in stream, - /// this function must read at least 1 byte. - /// This function is allowed to rwrite less than "size" bytes. - /// You must call Write function in loop, if you need exact amount of data. - /// - [PreserveSig] - int Write( - [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data, - uint size, IntPtr processedSize); - } - - /// - /// 7-zip IInStream imported interface - /// - [ComImport] - [Guid("23170F69-40C1-278A-0000-000300030000")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IInStream - { - /// - /// Read routine - /// - /// Array of bytes to set - /// Array size - /// Zero if Ok - int Read( - [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data, - uint size); - - /// - /// Seek routine - /// - /// Offset value - /// Seek origin value - /// New position pointer - void Seek( - long offset, SeekOrigin seekOrigin, IntPtr newPosition); - } - - /// - /// 7-zip IOutStream imported interface - /// - [ComImport] - [Guid("23170F69-40C1-278A-0000-000300040000")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IOutStream - { - /// - /// Write routine - /// - /// Array of bytes to get - /// Array size - /// Processed size - /// Zero if Ok - [PreserveSig] - int Write( - [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data, - uint size, - IntPtr processedSize); - - /// - /// Seek routine - /// - /// Offset value - /// Seek origin value - /// New position pointer - void Seek( - long offset, SeekOrigin seekOrigin, IntPtr newPosition); - - /// - /// Set size routine - /// - /// New size value - /// Zero if Ok - [PreserveSig] - int SetSize(long newSize); - } - - /// - /// 7-zip essential in archive interface - /// - [ComImport] - [Guid("23170F69-40C1-278A-0000-000600600000")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IInArchive - { - /// - /// Opens archive for reading. - /// - /// Archive file stream - /// Maximum start position for checking - /// Callback for opening archive - /// - [PreserveSig] - int Open( - IInStream stream, - [In] ref ulong maxCheckStartPosition, - [MarshalAs(UnmanagedType.Interface)] IArchiveOpenCallback openArchiveCallback); - - /// - /// Closes the archive. - /// - void Close(); - - /// - /// Gets the number of files in the archive file table . - /// - /// The number of files in the archive - uint GetNumberOfItems(); - - /// - /// Retrieves specific property data. - /// - /// File index in the archive file table - /// Property code - /// Property variant value - void GetProperty( - uint index, - ItemPropId propId, - ref PropVariant value); // PropVariant - - /// - /// Extracts files from the opened archive. - /// - /// indexes of files to be extracted (must be sorted) - /// 0xFFFFFFFF means all files - /// testMode != 0 means "test files operation" - /// IArchiveExtractCallback for operations handling - /// 0 if success - [PreserveSig] - int Extract( - [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] uint[] indexes, - uint numItems, - int testMode, - [MarshalAs(UnmanagedType.Interface)] IArchiveExtractCallback extractCallback); - - /// - /// Gets archive property data - /// - /// Archive property identificator - /// Archive property value - void GetArchiveProperty( - ItemPropId propId, // PROPID - ref PropVariant value); // PropVariant - - /// - /// Gets the number of properties - /// - /// The number of properties - uint GetNumberOfProperties(); - - /// - /// Gets property information - /// - /// Item index - /// Name - /// Property identificator - /// Variant type - void GetPropertyInfo( - uint index, - [MarshalAs(UnmanagedType.BStr)] out string name, - out ItemPropId propId, // PROPID - out ushort varType); //VARTYPE - - /// - /// Gets the number of archive properties - /// - /// The number of archive properties - uint GetNumberOfArchiveProperties(); - - /// - /// Gets the archive property information - /// - /// Item index - /// Name - /// Property identificator - /// Variant type - void GetArchivePropertyInfo( - uint index, - [MarshalAs(UnmanagedType.BStr)] out string name, - out ItemPropId propId, // PROPID - out ushort varType); //VARTYPE - } - - /// - /// 7-zip essential out archive interface - /// - [ComImport] - [Guid("23170F69-40C1-278A-0000-000600A00000")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IOutArchive - { - /// - /// Updates archive items - /// - /// The ISequentialOutStream pointer for writing the archive data - /// Number of archive items - /// The IArchiveUpdateCallback pointer - /// Zero if Ok - [PreserveSig] - int UpdateItems( - [MarshalAs(UnmanagedType.Interface)] ISequentialOutStream outStream, - uint numItems, - [MarshalAs(UnmanagedType.Interface)] IArchiveUpdateCallback updateCallback); - - /// - /// Gets file time type(?) - /// - /// Type pointer - void GetFileTimeType(IntPtr type); - } - - /// - /// 7-zip ISetProperties interface for setting various archive properties - /// - [ComImport] - [Guid("23170F69-40C1-278A-0000-000600030000")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface ISetProperties - { - /// - /// Sets the archive properties - /// - /// The names of the properties - /// The values of the properties - /// The properties count - /// - int SetProperties(IntPtr names, IntPtr values, int numProperties); - } -#endif -} \ No newline at end of file diff --git a/BizHawk.Util/7z/Common.cs b/BizHawk.Util/7z/Common.cs deleted file mode 100644 index dd88cfbf2c..0000000000 --- a/BizHawk.Util/7z/Common.cs +++ /dev/null @@ -1,833 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Globalization; -#if !WINCE -using System.Runtime.Remoting.Messaging; -#endif -#if DOTNET20 -using System.Threading; -#else -using System.Windows.Threading; -#endif -#if MONO -using SevenZip.Mono.COM; -#endif - -namespace SevenZip -{ -#if UNMANAGED - - /// - /// The way of the event synchronization. - /// - public enum EventSynchronizationStrategy - { - /// - /// Events are called synchronously if user can do some action; that is, cancel the execution process for example. - /// - Default, - /// - /// Always call events asynchronously. - /// - AlwaysAsynchronous, - /// - /// Always call events synchronously. - /// - AlwaysSynchronous - } - - /// - /// SevenZip Extractor/Compressor base class. Implements Password string, ReportErrors flag. - /// - public class SevenZipBase : MarshalByRefObject - { - private readonly string _password; - private readonly bool _reportErrors; - private readonly int _uniqueID; - private static readonly List Identificators = new List(); -#if !WINCE - internal static readonly AsyncCallback AsyncCallbackImplementation = AsyncCallbackMethod; - - /// - /// True if the instance of the class needs to be recreated in new thread context; otherwise, false. - /// - protected internal bool NeedsToBeRecreated; - - /// - /// AsyncCallback implementation used in asynchronous invocations. - /// - /// IAsyncResult instance. - internal static void AsyncCallbackMethod(IAsyncResult ar) - { - var result = (AsyncResult) ar; - result.AsyncDelegate.GetType().GetMethod("EndInvoke").Invoke(result.AsyncDelegate, new[] { ar }); - ((SevenZipBase)ar.AsyncState).ReleaseContext(); - } - - virtual internal void SaveContext( -#if !DOTNET20 - DispatcherPriority priority = DispatcherPriority.Normal -#endif - ) - { -#if !DOTNET20 - Dispatcher = Dispatcher.CurrentDispatcher; - Priority = priority; -#else - Context = SynchronizationContext.Current; -#endif - NeedsToBeRecreated = true; - } - - internal void ReleaseContext() - { -#if !DOTNET20 - Dispatcher = null; -#else - Context = null; -#endif - NeedsToBeRecreated = true; - } - - private delegate void EventHandlerDelegate(EventHandler handler, T e) where T : EventArgs; - - internal void OnEvent(EventHandler handler, T e, bool synchronous) where T: EventArgs - { - try - { - if (handler != null) - { - switch (EventSynchronization) - { - case EventSynchronizationStrategy.AlwaysAsynchronous: - synchronous = false; - break; - case EventSynchronizationStrategy.AlwaysSynchronous: - synchronous = true; - break; - } - if ( -#if !DOTNET20 - Dispatcher == null -#else - Context == null -#endif -) - { - // Usual synchronous call - handler(this, e); - } - else - { -#if !DOTNET20 - var eventHandlerDelegate = new EventHandlerDelegate((h, ee) => h(this, ee)); - if (synchronous) - { - // Could be just handler(this, e); - Dispatcher.Invoke(eventHandlerDelegate, Priority, handler, e); - } - else - { - Dispatcher.BeginInvoke(eventHandlerDelegate, Priority, handler, e); - } -#else - var callback = new SendOrPostCallback((obj) => - { - var array = (object[])obj; - ((EventHandler)array[0])(array[1], (T)array[2]); - }); - if (synchronous) - { - // Could be just handler(this, e); - this.Context.Send(callback, new object[] { handler, this, e }); - } - else - { - this.Context.Post(callback, new object[] { handler, this, e }); - } -#endif - } - } - } - catch (Exception ex) - { - AddException(ex); - } - } - -#if !DOTNET20 - /// - /// Gets or sets the Dispatcher object for this instance. - /// It will be used to fire events in the user context. - /// - internal Dispatcher Dispatcher { get; set; } - - /// - /// Gets or sets the Dispatcher priority of calling user events. - /// - internal DispatcherPriority Priority { get; set; } -#else - internal SynchronizationContext Context { get; set; } -#endif - /// - /// Gets or sets the event synchronization strategy. - /// - public EventSynchronizationStrategy EventSynchronization { get; set; } -#else // WINCE - internal void OnEvent(EventHandler handler, T e, bool synchronous) where T : System.EventArgs - { - try - { - handler(this, e); - } - catch (Exception ex) - { - AddException(ex); - } - } -#endif - /// - /// Gets the unique identificator of this SevenZipBase instance. - /// - public int UniqueID - { - get - { - return _uniqueID; - } - } - - /// - /// User exceptions thrown during the requested operations, for example, in events. - /// - private readonly List _exceptions = new List(); - - private static int GetUniqueID() - { - int id; - var rnd = new Random(DateTime.Now.Millisecond); - do - { - id = rnd.Next(Int32.MaxValue); - } - while (Identificators.Contains(id)); - Identificators.Add(id); - return id; - } - - #region Constructors - /// - /// Initializes a new instance of the SevenZipBase class. - /// - protected SevenZipBase() - { - _password = ""; - _reportErrors = true; - _uniqueID = GetUniqueID(); - } - - /// - /// Initializes a new instance of the SevenZipBase class - /// - /// The archive password. - protected SevenZipBase(string password) - { - if (String.IsNullOrEmpty(password)) - { - throw new SevenZipException("Empty password was specified."); - } - _password = password; - _reportErrors = true; - _uniqueID = GetUniqueID(); - } - #endregion - - /// - /// Removes the UniqueID from the list. - /// - ~SevenZipBase() - { - Identificators.Remove(_uniqueID); - } - - /// - /// Gets or sets the archive password - /// - public string Password - { - get - { - return _password; - } - } - - /// - /// Gets or sets throw exceptions on archive errors flag - /// - internal bool ReportErrors - { - get - { - return _reportErrors; - } - } - - /// - /// Gets the user exceptions thrown during the requested operations, for example, in events. - /// - internal ReadOnlyCollection Exceptions - { - get - { - return new ReadOnlyCollection(_exceptions); - } - } - - internal void AddException(Exception e) - { - _exceptions.Add(e); - } - - internal void ClearExceptions() - { - _exceptions.Clear(); - } - - internal bool HasExceptions - { - get - { - return _exceptions.Count > 0; - } - } - - /// - /// Throws the specified exception when is able to. - /// - /// The exception to throw. - /// The handler responsible for the exception. - internal bool ThrowException(CallbackBase handler, params Exception[] e) - { - if (_reportErrors && (handler == null || !handler.Canceled)) - { - throw e[0]; - } - return false; - } - - internal void ThrowUserException() - { - if (HasExceptions) - { - throw new SevenZipException(SevenZipException.USER_EXCEPTION_MESSAGE); - } - } - - /// - /// Throws exception if HRESULT != 0. - /// - /// Result code to check. - /// Exception message. - /// The class responsible for the callback. - internal void CheckedExecute(int hresult, string message, CallbackBase handler) - { - if (hresult != (int) OperationResult.Ok || handler.HasExceptions) - { - if (!handler.HasExceptions) - { - if (hresult < -2000000000) - { - ThrowException(handler, - new SevenZipException( - "The execution has failed due to the bug in the SevenZipSharp.\n" + - "Please report about it to http://sevenzipsharp.codeplex.com/WorkItem/List.aspx, post the release number and attach the archive.")); - } - else - { - ThrowException(handler, - new SevenZipException(message + hresult.ToString(CultureInfo.InvariantCulture) + - '.')); - } - } - else - { - ThrowException(handler, handler.Exceptions[0]); - } - } - } - -#if !WINCE && !MONO - /// - /// Changes the path to the 7-zip native library. - /// - /// The path to the 7-zip native library. - public static void SetLibraryPath(string libraryPath) - { - SevenZipLibraryManager.SetLibraryPath(libraryPath); - } -#endif - /// - /// Gets the current library features. - /// - public static LibraryFeature CurrentLibraryFeatures - { - get - { - return SevenZipLibraryManager.CurrentLibraryFeatures; - } - } - - /// - /// Determines whether the specified System.Object is equal to the current SevenZipBase. - /// - /// The System.Object to compare with the current SevenZipBase. - /// true if the specified System.Object is equal to the current SevenZipBase; otherwise, false. - public override bool Equals(object obj) - { - var inst = obj as SevenZipBase; - if (inst == null) - { - return false; - } - return _uniqueID == inst._uniqueID; - } - - /// - /// Serves as a hash function for a particular type. - /// - /// A hash code for the current SevenZipBase. - public override int GetHashCode() - { - return _uniqueID; - } - - /// - /// Returns a System.String that represents the current SevenZipBase. - /// - /// A System.String that represents the current SevenZipBase. - public override string ToString() - { - var type = "SevenZipBase"; - if (this is SevenZipExtractor) - { - type = "SevenZipExtractor"; - } - if (this is SevenZipCompressor) - { - type = "SevenZipCompressor"; - } - return string.Format("{0} [{1}]", type, _uniqueID); - } - } - - internal class CallbackBase : MarshalByRefObject - { - private readonly string _password; - private readonly bool _reportErrors; - /// - /// User exceptions thrown during the requested operations, for example, in events. - /// - private readonly List _exceptions = new List(); - - #region Constructors - /// - /// Initializes a new instance of the CallbackBase class. - /// - protected CallbackBase() - { - _password = ""; - _reportErrors = true; - } - - /// - /// Initializes a new instance of the CallbackBase class. - /// - /// The archive password. - protected CallbackBase(string password) - { - if (String.IsNullOrEmpty(password)) - { - throw new SevenZipException("Empty password was specified."); - } - _password = password; - _reportErrors = true; - } - #endregion - - /// - /// Gets or sets the archive password - /// - public string Password - { - get - { - return _password; - } - } - - /// - /// Gets or sets the value indicating whether the current procedure was cancelled. - /// - public bool Canceled { get; set; } - - /// - /// Gets or sets throw exceptions on archive errors flag - /// - public bool ReportErrors - { - get - { - return _reportErrors; - } - } - - /// - /// Gets the user exceptions thrown during the requested operations, for example, in events. - /// - public ReadOnlyCollection Exceptions - { - get - { - return new ReadOnlyCollection(_exceptions); - } - } - - public void AddException(Exception e) - { - _exceptions.Add(e); - } - - public void ClearExceptions() - { - _exceptions.Clear(); - } - - public bool HasExceptions - { - get - { - return _exceptions.Count > 0; - } - } - - /// - /// Throws the specified exception when is able to. - /// - /// The exception to throw. - /// The handler responsible for the exception. - public bool ThrowException(CallbackBase handler, params Exception[] e) - { - if (_reportErrors && (handler == null || !handler.Canceled)) - { - throw e[0]; - } - return false; - } - - /// - /// Throws the first exception in the list if any exists. - /// - /// True means no exceptions. - public bool ThrowException() - { - if (HasExceptions && _reportErrors) - { - throw _exceptions[0]; - } - return true; - } - - public void ThrowUserException() - { - if (HasExceptions) - { - throw new SevenZipException(SevenZipException.USER_EXCEPTION_MESSAGE); - } - } - } - - /// - /// Struct for storing information about files in the 7-zip archive. - /// - public struct ArchiveFileInfo - { - /// - /// Gets or sets index of the file in the archive file table. - /// - public int Index { get; set; } - - /// - /// Gets or sets file name - /// - public string FileName { get; set; } - - /// - /// Gets or sets the file last write time. - /// - public DateTime LastWriteTime { get; set; } - - /// - /// Gets or sets the file creation time. - /// - public DateTime CreationTime { get; set; } - - /// - /// Gets or sets the file creation time. - /// - public DateTime LastAccessTime { get; set; } - - /// - /// Gets or sets size of the file (unpacked). - /// - public ulong Size { get; set; } - - /// - /// Gets or sets CRC checksum of the file. - /// - public uint Crc { get; set; } - - /// - /// Gets or sets file attributes. - /// - public uint Attributes { get; set; } - - /// - /// Gets or sets being a directory. - /// - public bool IsDirectory { get; set; } - - /// - /// Gets or sets being encrypted. - /// - public bool Encrypted { get; set; } - - /// - /// Gets or sets comment for the file. - /// - public string Comment { get; set; } - - /// - /// Determines whether the specified System.Object is equal to the current ArchiveFileInfo. - /// - /// The System.Object to compare with the current ArchiveFileInfo. - /// true if the specified System.Object is equal to the current ArchiveFileInfo; otherwise, false. - public override bool Equals(object obj) - { - return (obj is ArchiveFileInfo) ? Equals((ArchiveFileInfo) obj) : false; - } - - /// - /// Determines whether the specified ArchiveFileInfo is equal to the current ArchiveFileInfo. - /// - /// The ArchiveFileInfo to compare with the current ArchiveFileInfo. - /// true if the specified ArchiveFileInfo is equal to the current ArchiveFileInfo; otherwise, false. - public bool Equals(ArchiveFileInfo afi) - { - return afi.Index == Index && afi.FileName == FileName; - } - - /// - /// Serves as a hash function for a particular type. - /// - /// A hash code for the current ArchiveFileInfo. - public override int GetHashCode() - { - return FileName.GetHashCode() ^ Index; - } - - /// - /// Returns a System.String that represents the current ArchiveFileInfo. - /// - /// A System.String that represents the current ArchiveFileInfo. - public override string ToString() - { - return "[" + Index.ToString(CultureInfo.CurrentCulture) + "] " + FileName; - } - - /// - /// Determines whether the specified ArchiveFileInfo instances are considered equal. - /// - /// The first ArchiveFileInfo to compare. - /// The second ArchiveFileInfo to compare. - /// true if the specified ArchiveFileInfo instances are considered equal; otherwise, false. - public static bool operator ==(ArchiveFileInfo afi1, ArchiveFileInfo afi2) - { - return afi1.Equals(afi2); - } - - /// - /// Determines whether the specified ArchiveFileInfo instances are not considered equal. - /// - /// The first ArchiveFileInfo to compare. - /// The second ArchiveFileInfo to compare. - /// true if the specified ArchiveFileInfo instances are not considered equal; otherwise, false. - public static bool operator !=(ArchiveFileInfo afi1, ArchiveFileInfo afi2) - { - return !afi1.Equals(afi2); - } - } - - /// - /// Archive property struct. - /// - public struct ArchiveProperty - { - /// - /// Gets the name of the archive property. - /// - public string Name { get; internal set; } - - /// - /// Gets the value of the archive property. - /// - public object Value { get; internal set; } - - /// - /// Determines whether the specified System.Object is equal to the current ArchiveProperty. - /// - /// The System.Object to compare with the current ArchiveProperty. - /// true if the specified System.Object is equal to the current ArchiveProperty; otherwise, false. - public override bool Equals(object obj) - { - return (obj is ArchiveProperty) ? Equals((ArchiveProperty) obj) : false; - } - - /// - /// Determines whether the specified ArchiveProperty is equal to the current ArchiveProperty. - /// - /// The ArchiveProperty to compare with the current ArchiveProperty. - /// true if the specified ArchiveProperty is equal to the current ArchiveProperty; otherwise, false. - public bool Equals(ArchiveProperty afi) - { - return afi.Name == Name && afi.Value == Value; - } - - /// - /// Serves as a hash function for a particular type. - /// - /// A hash code for the current ArchiveProperty. - public override int GetHashCode() - { - return Name.GetHashCode() ^ Value.GetHashCode(); - } - - /// - /// Returns a System.String that represents the current ArchiveProperty. - /// - /// A System.String that represents the current ArchiveProperty. - public override string ToString() - { - return Name + " = " + Value; - } - - /// - /// Determines whether the specified ArchiveProperty instances are considered equal. - /// - /// The first ArchiveProperty to compare. - /// The second ArchiveProperty to compare. - /// true if the specified ArchiveProperty instances are considered equal; otherwise, false. - public static bool operator ==(ArchiveProperty afi1, ArchiveProperty afi2) - { - return afi1.Equals(afi2); - } - - /// - /// Determines whether the specified ArchiveProperty instances are not considered equal. - /// - /// The first ArchiveProperty to compare. - /// The second ArchiveProperty to compare. - /// true if the specified ArchiveProperty instances are not considered equal; otherwise, false. - public static bool operator !=(ArchiveProperty afi1, ArchiveProperty afi2) - { - return !afi1.Equals(afi2); - } - } - -#if COMPRESS - - /// - /// Archive compression mode. - /// - public enum CompressionMode - { - /// - /// Create a new archive; overwrite the existing one. - /// - Create, - /// - /// Add data to the archive. - /// - Append, - } - - internal enum InternalCompressionMode - { - /// - /// Create a new archive; overwrite the existing one. - /// - Create, - /// - /// Add data to the archive. - /// - Append, - /// - /// Modify archive data. - /// - Modify - } - - /// - /// Zip encryption method enum. - /// - public enum ZipEncryptionMethod - { - /// - /// ZipCrypto encryption method. - /// - ZipCrypto, - /// - /// AES 128 bit encryption method. - /// - Aes128, - /// - /// AES 192 bit encryption method. - /// - Aes192, - /// - /// AES 256 bit encryption method. - /// - Aes256 - } - - /// - /// Archive update data for UpdateCallback. - /// - internal struct UpdateData - { - public uint FilesCount; - public InternalCompressionMode Mode; - - public Dictionary FileNamesToModify { get; set; } - - public List ArchiveFileData { get; set; } - } -#endif -#endif -} \ No newline at end of file diff --git a/BizHawk.Util/7z/EventArgs.cs b/BizHawk.Util/7z/EventArgs.cs deleted file mode 100644 index 8f3928b295..0000000000 --- a/BizHawk.Util/7z/EventArgs.cs +++ /dev/null @@ -1,383 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.IO; - -namespace SevenZip -{ - /// - /// EventArgs for storing PercentDone property. - /// - public class PercentDoneEventArgs : EventArgs - { - private readonly byte _percentDone; - - /// - /// Initializes a new instance of the PercentDoneEventArgs class. - /// - /// The percent of finished work. - /// - public PercentDoneEventArgs(byte percentDone) - { - if (percentDone > 100 || percentDone < 0) - { - throw new ArgumentOutOfRangeException("percentDone", - "The percent of finished work must be between 0 and 100."); - } - _percentDone = percentDone; - } - - /// - /// Gets the percent of finished work. - /// - public byte PercentDone - { - get - { - return _percentDone; - } - } - - /// - /// Gets or sets whether to stop the current archive operation. - /// - public bool Cancel { get; set; } - - /// - /// Converts a [0, 1] rate to its percent equivalent. - /// - /// The rate of the done work. - /// Percent integer equivalent. - /// - internal static byte ProducePercentDone(float doneRate) - { -#if !WINCE - return (byte) Math.Round(Math.Min(100*doneRate, 100), MidpointRounding.AwayFromZero); -#else - return (byte) Math.Round(Math.Min(100*doneRate, 100)); -#endif - } - } - - /// - /// The EventArgs class for accurate progress handling. - /// - public sealed class ProgressEventArgs : PercentDoneEventArgs - { - private readonly byte _delta; - - /// - /// Initializes a new instance of the ProgressEventArgs class. - /// - /// The percent of finished work. - /// The percent of work done after the previous event. - public ProgressEventArgs(byte percentDone, byte percentDelta) - : base(percentDone) - { - _delta = percentDelta; - } - - /// - /// Gets the change in done work percentage. - /// - public byte PercentDelta - { - get - { - return _delta; - } - } - } - -#if UNMANAGED - /// - /// EventArgs used to report the file information which is going to be packed. - /// - public sealed class FileInfoEventArgs : PercentDoneEventArgs - { - private readonly ArchiveFileInfo _fileInfo; - - /// - /// Initializes a new instance of the FileInfoEventArgs class. - /// - /// The current ArchiveFileInfo. - /// The percent of finished work. - public FileInfoEventArgs(ArchiveFileInfo fileInfo, byte percentDone) - : base(percentDone) - { - _fileInfo = fileInfo; - } - - /// - /// Gets the corresponding FileInfo to the event. - /// - public ArchiveFileInfo FileInfo - { - get - { - return _fileInfo; - } - } - } - - /// - /// EventArgs used to report the size of unpacked archive data - /// - public sealed class OpenEventArgs : EventArgs - { - private readonly ulong _totalSize; - - /// - /// Initializes a new instance of the OpenEventArgs class - /// - /// Size of unpacked archive data - public OpenEventArgs(ulong totalSize) - { - _totalSize = totalSize; - } - - /// - /// Gets the size of unpacked archive data - /// - public ulong TotalSize - { - get - { - return _totalSize; - } - } - } - - /// - /// Stores an int number - /// - public sealed class IntEventArgs : EventArgs - { - private readonly int _value; - - /// - /// Initializes a new instance of the IntEventArgs class - /// - /// Useful data carried by the IntEventArgs class - public IntEventArgs(int value) - { - _value = value; - } - - /// - /// Gets the value of the IntEventArgs class - /// - public int Value - { - get - { - return _value; - } - } - } - - /// - /// EventArgs class which stores the file name. - /// - public sealed class FileNameEventArgs : PercentDoneEventArgs - { - private readonly string _fileName; - - /// - /// Initializes a new instance of the FileNameEventArgs class. - /// - /// The file name. - /// The percent of finished work - public FileNameEventArgs(string fileName, byte percentDone) : - base(percentDone) - { - _fileName = fileName; - } - - /// - /// Gets the file name. - /// - public string FileName - { - get - { - return _fileName; - } - } - } - - /// - /// EventArgs for FileExists event, stores the file name and asks whether to overwrite it in case it already exists. - /// - public sealed class FileOverwriteEventArgs : EventArgs - { - /// - /// Initializes a new instance of the FileOverwriteEventArgs class - /// - /// The file name. - public FileOverwriteEventArgs(string fileName) - { - FileName = fileName; - } - - /// - /// Gets or sets the value indicating whether to cancel the extraction. - /// - public bool Cancel { get; set; } - - /// - /// Gets or sets the file name to extract to. Null means skip. - /// - public string FileName { get; set; } - } - - /// - /// The reason for calling . - /// - public enum ExtractFileCallbackReason - { - /// - /// is called the first time for a file. - /// - Start, - - /// - /// All data has been written to the target without any exceptions. - /// - Done, - - /// - /// An exception occured during extraction of the file. - /// - Failure - } - - /// - /// The arguments passed to . - /// - /// - /// For each file, is first called with - /// set to . If the callback chooses to extract the - /// file data by setting or , the callback - /// will be called a second time with set to - /// or - /// to allow for any cleanup task like closing the stream. - /// - public class ExtractFileCallbackArgs : EventArgs - { - private readonly ArchiveFileInfo _archiveFileInfo; - private Stream _extractToStream; - - /// - /// Initializes a new instance of the class. - /// - /// The information about file in the archive. - public ExtractFileCallbackArgs(ArchiveFileInfo archiveFileInfo) - { - Reason = ExtractFileCallbackReason.Start; - _archiveFileInfo = archiveFileInfo; - } - - /// - /// Information about file in the archive. - /// - /// Information about file in the archive. - public ArchiveFileInfo ArchiveFileInfo - { - get - { - return _archiveFileInfo; - } - } - - /// - /// The reason for calling . - /// - /// - /// If neither nor is set, - /// will not be called after . - /// - /// The reason. - public ExtractFileCallbackReason Reason { get; internal set; } - - /// - /// The exception that occurred during extraction. - /// - /// The _Exception. - /// - /// If the callback is called with set to , - /// this member contains the _Exception that occurred. - /// The default behavior is to rethrow the _Exception after return of the callback. - /// However the callback can set to null to swallow the _Exception - /// and continue extraction with the next file. - /// - public Exception Exception { get; set; } - - /// - /// Gets or sets a value indicating whether to cancel the extraction. - /// - /// true to cancel the extraction; false to continue. The default is false. - public bool CancelExtraction { get; set; } - - /// - /// Gets or sets whether and where to extract the file. - /// - /// The path where to extract the file to. - /// - /// If is set, this mmember will be ignored. - /// - public string ExtractToFile { get; set; } - - /// - /// Gets or sets whether and where to extract the file. - /// - /// The the extracted data is written to. - /// - /// If both this member and are null (the defualt), the file - /// will not be extracted and the callback will be be executed a second time with the - /// set to or . - /// - public Stream ExtractToStream - { - get - { - return _extractToStream; - } - set - { - if (_extractToStream != null && !_extractToStream.CanWrite) - { - throw new ExtractionFailedException("The specified stream is not writable!"); - } - _extractToStream = value; - } - } - - /// - /// Gets or sets any data that will be preserved between the callback call - /// and the or calls. - /// - /// The data. - public object ObjectData { get; set; } - } - - /// - /// Callback delegate for . - /// - public delegate void ExtractFileCallback(ExtractFileCallbackArgs extractFileCallbackArgs); -#endif -} \ No newline at end of file diff --git a/BizHawk.Util/7z/Exceptions.cs b/BizHawk.Util/7z/Exceptions.cs deleted file mode 100644 index 8a8410e0d8..0000000000 --- a/BizHawk.Util/7z/Exceptions.cs +++ /dev/null @@ -1,464 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -#if !WINCE -using System.Runtime.Serialization; -#endif - -namespace SevenZip -{ - /// - /// Base SevenZip exception class. - /// - [Serializable] - public class SevenZipException : Exception - { - /// - /// The message for thrown user exceptions. - /// - internal const string USER_EXCEPTION_MESSAGE = "The extraction was successful but" + - "some exceptions were thrown in your events. Check UserExceptions for details."; - - /// - /// Initializes a new instance of the SevenZipException class - /// - public SevenZipException() : base("SevenZip unknown exception.") {} - - /// - /// Initializes a new instance of the SevenZipException class - /// - /// Default exception message - public SevenZipException(string defaultMessage) - : base(defaultMessage) {} - - /// - /// Initializes a new instance of the SevenZipException class - /// - /// Default exception message - /// Additional detailed message - public SevenZipException(string defaultMessage, string message) - : base(defaultMessage + " Message: " + message) {} - - /// - /// Initializes a new instance of the SevenZipException class - /// - /// Default exception message - /// Additional detailed message - /// Inner exception occured - public SevenZipException(string defaultMessage, string message, Exception inner) - : base( - defaultMessage + (defaultMessage.EndsWith(" ", StringComparison.CurrentCulture) ? "" : " Message: ") + - message, inner) {} - - /// - /// Initializes a new instance of the SevenZipException class - /// - /// Default exception message - /// Inner exception occured - public SevenZipException(string defaultMessage, Exception inner) - : base(defaultMessage, inner) {} -#if !WINCE - /// - /// Initializes a new instance of the SevenZipException class - /// - /// All data needed for serialization or deserialization - /// Serialized stream descriptor - protected SevenZipException( - SerializationInfo info, StreamingContext context) - : base(info, context) {} -#endif - } - -#if UNMANAGED - - /// - /// Exception class for ArchiveExtractCallback. - /// - [Serializable] - public class ExtractionFailedException : SevenZipException - { - /// - /// Exception dafault message which is displayed if no extra information is specified - /// - public const string DEFAULT_MESSAGE = "Could not extract files!"; - - /// - /// Initializes a new instance of the ExtractionFailedException class - /// - public ExtractionFailedException() : base(DEFAULT_MESSAGE) {} - - /// - /// Initializes a new instance of the ExtractionFailedException class - /// - /// Additional detailed message - public ExtractionFailedException(string message) : base(DEFAULT_MESSAGE, message) {} - - /// - /// Initializes a new instance of the ExtractionFailedException class - /// - /// Additional detailed message - /// Inner exception occured - public ExtractionFailedException(string message, Exception inner) : base(DEFAULT_MESSAGE, message, inner) {} -#if !WINCE - /// - /// Initializes a new instance of the ExtractionFailedException class - /// - /// All data needed for serialization or deserialization - /// Serialized stream descriptor - protected ExtractionFailedException( - SerializationInfo info, StreamingContext context) - : base(info, context) {} -#endif - } - -#if COMPRESS - - /// - /// Exception class for ArchiveUpdateCallback. - /// - [Serializable] - public class CompressionFailedException : SevenZipException - { - /// - /// Exception dafault message which is displayed if no extra information is specified - /// - public const string DEFAULT_MESSAGE = "Could not pack files!"; - - /// - /// Initializes a new instance of the CompressionFailedException class - /// - public CompressionFailedException() : base(DEFAULT_MESSAGE) {} - - /// - /// Initializes a new instance of the CompressionFailedException class - /// - /// Additional detailed message - public CompressionFailedException(string message) : base(DEFAULT_MESSAGE, message) {} - - /// - /// Initializes a new instance of the CompressionFailedException class - /// - /// Additional detailed message - /// Inner exception occured - public CompressionFailedException(string message, Exception inner) : base(DEFAULT_MESSAGE, message, inner) {} -#if !WINCE - /// - /// Initializes a new instance of the CompressionFailedException class - /// - /// All data needed for serialization or deserialization - /// Serialized stream descriptor - protected CompressionFailedException( - SerializationInfo info, StreamingContext context) - : base(info, context) {} -#endif - } -#endif -#endif - - /// - /// Exception class for LZMA operations. - /// - [Serializable] - public class LzmaException : SevenZipException - { - /// - /// Exception dafault message which is displayed if no extra information is specified - /// - public const string DEFAULT_MESSAGE = "Specified stream is not a valid LZMA compressed stream!"; - - /// - /// Initializes a new instance of the LzmaException class - /// - public LzmaException() : base(DEFAULT_MESSAGE) {} - - /// - /// Initializes a new instance of the LzmaException class - /// - /// Additional detailed message - public LzmaException(string message) : base(DEFAULT_MESSAGE, message) {} - - /// - /// Initializes a new instance of the LzmaException class - /// - /// Additional detailed message - /// Inner exception occured - public LzmaException(string message, Exception inner) : base(DEFAULT_MESSAGE, message, inner) {} -#if !WINCE - /// - /// Initializes a new instance of the LzmaException class - /// - /// All data needed for serialization or deserialization - /// Serialized stream descriptor - protected LzmaException( - SerializationInfo info, StreamingContext context) - : base(info, context) {} -#endif - } - -#if UNMANAGED - - /// - /// Exception class for 7-zip archive open or read operations. - /// - [Serializable] - public class SevenZipArchiveException : SevenZipException - { - /// - /// Exception dafault message which is displayed if no extra information is specified - /// - public const string DEFAULT_MESSAGE = - "Invalid archive: open/read error! Is it encrypted and a wrong password was provided?\n" + - "If your archive is an exotic one, it is possible that SevenZipSharp has no signature for "+ - "its format and thus decided it is TAR by mistake."; - - /// - /// Initializes a new instance of the SevenZipArchiveException class - /// - public SevenZipArchiveException() : base(DEFAULT_MESSAGE) {} - - /// - /// Initializes a new instance of the SevenZipArchiveException class - /// - /// Additional detailed message - public SevenZipArchiveException(string message) : base(DEFAULT_MESSAGE, message) {} - - /// - /// Initializes a new instance of the SevenZipArchiveException class - /// - /// Additional detailed message - /// Inner exception occured - public SevenZipArchiveException(string message, Exception inner) : base(DEFAULT_MESSAGE, message, inner) {} -#if !WINCE - /// - /// Initializes a new instance of the SevenZipArchiveException class - /// - /// All data needed for serialization or deserialization - /// Serialized stream descriptor - protected SevenZipArchiveException( - SerializationInfo info, StreamingContext context) - : base(info, context) {} -#endif - } - - /// - /// Exception class for empty common root if file name array in SevenZipCompressor. - /// - [Serializable] - public class SevenZipInvalidFileNamesException : SevenZipException - { - /// - /// Exception dafault message which is displayed if no extra information is specified - /// - public const string DEFAULT_MESSAGE = "Invalid file names have been specified: "; - - /// - /// Initializes a new instance of the SevenZipInvalidFileNamesException class - /// - public SevenZipInvalidFileNamesException() : base(DEFAULT_MESSAGE) {} - - /// - /// Initializes a new instance of the SevenZipInvalidFileNamesException class - /// - /// Additional detailed message - public SevenZipInvalidFileNamesException(string message) : base(DEFAULT_MESSAGE, message) {} - - /// - /// Initializes a new instance of the SevenZipInvalidFileNamesException class - /// - /// Additional detailed message - /// Inner exception occured - public SevenZipInvalidFileNamesException(string message, Exception inner) : base(DEFAULT_MESSAGE, message, inner) {} -#if !WINCE - /// - /// Initializes a new instance of the SevenZipInvalidFileNamesException class - /// - /// All data needed for serialization or deserialization - /// Serialized stream descriptor - protected SevenZipInvalidFileNamesException( - SerializationInfo info, StreamingContext context) - : base(info, context) {} -#endif - } - -#if COMPRESS - - /// - /// Exception class for fail to create an archive in SevenZipCompressor. - /// - [Serializable] - public class SevenZipCompressionFailedException : SevenZipException - { - /// - /// Exception dafault message which is displayed if no extra information is specified - /// - public const string DEFAULT_MESSAGE = "The compression has failed for an unknown reason with code "; - - /// - /// Initializes a new instance of the SevenZipCompressionFailedException class - /// - public SevenZipCompressionFailedException() : base(DEFAULT_MESSAGE) {} - - /// - /// Initializes a new instance of the SevenZipCompressionFailedException class - /// - /// Additional detailed message - public SevenZipCompressionFailedException(string message) : base(DEFAULT_MESSAGE, message) {} - - /// - /// Initializes a new instance of the SevenZipCompressionFailedException class - /// - /// Additional detailed message - /// Inner exception occured - public SevenZipCompressionFailedException(string message, Exception inner) - : base(DEFAULT_MESSAGE, message, inner) {} -#if !WINCE - /// - /// Initializes a new instance of the SevenZipCompressionFailedException class - /// - /// All data needed for serialization or deserialization - /// Serialized stream descriptor - protected SevenZipCompressionFailedException( - SerializationInfo info, StreamingContext context) - : base(info, context) {} -#endif - } -#endif - - /// - /// Exception class for fail to extract an archive in SevenZipExtractor. - /// - [Serializable] - public class SevenZipExtractionFailedException : SevenZipException - { - /// - /// Exception dafault message which is displayed if no extra information is specified - /// - public const string DEFAULT_MESSAGE = "The extraction has failed for an unknown reason with code "; - - /// - /// Initializes a new instance of the SevenZipExtractionFailedException class - /// - public SevenZipExtractionFailedException() : base(DEFAULT_MESSAGE) {} - - /// - /// Initializes a new instance of the SevenZipExtractionFailedException class - /// - /// Additional detailed message - public SevenZipExtractionFailedException(string message) : base(DEFAULT_MESSAGE, message) {} - - /// - /// Initializes a new instance of the SevenZipExtractionFailedException class - /// - /// Additional detailed message - /// Inner exception occured - public SevenZipExtractionFailedException(string message, Exception inner) : base(DEFAULT_MESSAGE, message, inner) {} -#if !WINCE - /// - /// Initializes a new instance of the SevenZipExtractionFailedException class - /// - /// All data needed for serialization or deserialization - /// Serialized stream descriptor - protected SevenZipExtractionFailedException( - SerializationInfo info, StreamingContext context) - : base(info, context) {} -#endif - } - - /// - /// Exception class for 7-zip library operations. - /// - [Serializable] - public class SevenZipLibraryException : SevenZipException - { - /// - /// Exception dafault message which is displayed if no extra information is specified - /// - public const string DEFAULT_MESSAGE = "Can not load 7-zip library or internal COM error!"; - - /// - /// Initializes a new instance of the SevenZipLibraryException class - /// - public SevenZipLibraryException() : base(DEFAULT_MESSAGE) {} - - /// - /// Initializes a new instance of the SevenZipLibraryException class - /// - /// Additional detailed message - public SevenZipLibraryException(string message) : base(DEFAULT_MESSAGE, message) {} - - /// - /// Initializes a new instance of the SevenZipLibraryException class - /// - /// Additional detailed message - /// Inner exception occured - public SevenZipLibraryException(string message, Exception inner) : base(DEFAULT_MESSAGE, message, inner) {} -#if !WINCE - /// - /// Initializes a new instance of the SevenZipLibraryException class - /// - /// All data needed for serialization or deserialization - /// Serialized stream descriptor - protected SevenZipLibraryException( - SerializationInfo info, StreamingContext context) - : base(info, context) {} -#endif - } -#endif - -#if SFX - - /// - /// Exception class for 7-zip sfx settings validation. - /// - [Serializable] - public class SevenZipSfxValidationException : SevenZipException - { - /// - /// Exception dafault message which is displayed if no extra information is specified - /// - public static readonly string DefaultMessage = "Sfx settings validation failed."; - - /// - /// Initializes a new instance of the SevenZipSfxValidationException class - /// - public SevenZipSfxValidationException() : base(DefaultMessage) {} - - /// - /// Initializes a new instance of the SevenZipSfxValidationException class - /// - /// Additional detailed message - public SevenZipSfxValidationException(string message) : base(DefaultMessage, message) {} - - /// - /// Initializes a new instance of the SevenZipSfxValidationException class - /// - /// Additional detailed message - /// Inner exception occured - public SevenZipSfxValidationException(string message, Exception inner) : base(DefaultMessage, message, inner) {} -#if !WINCE - /// - /// Initializes a new instance of the SevenZipSfxValidationException class - /// - /// All data needed for serialization or deserialization - /// Serialized stream descriptor - protected SevenZipSfxValidationException( - SerializationInfo info, StreamingContext context) - : base(info, context) {} -#endif - } -#endif -} \ No newline at end of file diff --git a/BizHawk.Util/7z/FileSignatureChecker.cs b/BizHawk.Util/7z/FileSignatureChecker.cs deleted file mode 100644 index 7f89935697..0000000000 --- a/BizHawk.Util/7z/FileSignatureChecker.cs +++ /dev/null @@ -1,252 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.IO; - -namespace SevenZip -{ -#if UNMANAGED - /// - /// The signature checker class. Original code by Siddharth Uppal, adapted by Markhor. - /// - /// Based on the code at http://blog.somecreativity.com/2008/04/08/how-to-check-if-a-file-is-compressed-in-c/# - public static class FileChecker - { - public static bool ThrowExceptions = true; - - private const int SIGNATURE_SIZE = 16; - private const int SFX_SCAN_LENGTH = 256 * 1024; - - private static bool SpecialDetect(Stream stream, int offset, InArchiveFormat expectedFormat) - { - if (stream.Length > offset + SIGNATURE_SIZE) - { - var signature = new byte[SIGNATURE_SIZE]; - int bytesRequired = SIGNATURE_SIZE; - int index = 0; - stream.Seek(offset, SeekOrigin.Begin); - while (bytesRequired > 0) - { - int bytesRead = stream.Read(signature, index, bytesRequired); - bytesRequired -= bytesRead; - index += bytesRead; - } - string actualSignature = BitConverter.ToString(signature); - foreach (string expectedSignature in Formats.InSignatureFormats.Keys) - { - if (Formats.InSignatureFormats[expectedSignature] != expectedFormat) - { - continue; - } - if (actualSignature.StartsWith(expectedSignature, StringComparison.OrdinalIgnoreCase)) - { - return true; - } - } - } - return false; - } - - /// - /// Gets the InArchiveFormat for a specific extension. - /// - /// The stream to identify. - /// The archive beginning offset. - /// True if the original format of the stream is PE; otherwise, false. - /// Corresponding InArchiveFormat. - public static InArchiveFormat CheckSignature(Stream stream, out int offset, out bool isExecutable) - { - offset = 0; - isExecutable = false; - - if (!stream.CanRead) - { - if (ThrowExceptions) - throw new ArgumentException("The stream must be readable."); - else return InArchiveFormat.None; - } - if (stream.Length < SIGNATURE_SIZE) - { - if (ThrowExceptions) - throw new ArgumentException("The stream is invalid."); - else return InArchiveFormat.None; - } - - #region Get file signature - - var signature = new byte[SIGNATURE_SIZE]; - int bytesRequired = SIGNATURE_SIZE; - int index = 0; - stream.Seek(0, SeekOrigin.Begin); - while (bytesRequired > 0) - { - int bytesRead = stream.Read(signature, index, bytesRequired); - bytesRequired -= bytesRead; - index += bytesRead; - } - string actualSignature = BitConverter.ToString(signature); - - #endregion - - InArchiveFormat suspectedFormat = InArchiveFormat.XZ; // any except PE and Cab - isExecutable = false; - - foreach (string expectedSignature in Formats.InSignatureFormats.Keys) - { - if (actualSignature.StartsWith(expectedSignature, StringComparison.OrdinalIgnoreCase) || - actualSignature.Substring(6).StartsWith(expectedSignature, StringComparison.OrdinalIgnoreCase) && - Formats.InSignatureFormats[expectedSignature] == InArchiveFormat.Lzh) - { - if (Formats.InSignatureFormats[expectedSignature] == InArchiveFormat.PE) - { - suspectedFormat = InArchiveFormat.PE; - isExecutable = true; - } - else - { - return Formats.InSignatureFormats[expectedSignature]; - } - } - } - - // Many Microsoft formats - if (actualSignature.StartsWith("D0-CF-11-E0-A1-B1-1A-E1", StringComparison.OrdinalIgnoreCase)) - { - suspectedFormat = InArchiveFormat.Cab; // != InArchiveFormat.XZ - } - - #region SpecialDetect - try - { - SpecialDetect(stream, 257, InArchiveFormat.Tar); - } - catch (ArgumentException) {} - if (SpecialDetect(stream, 0x8001, InArchiveFormat.Iso)) - { - return InArchiveFormat.Iso; - } - if (SpecialDetect(stream, 0x8801, InArchiveFormat.Iso)) - { - return InArchiveFormat.Iso; - } - if (SpecialDetect(stream, 0x9001, InArchiveFormat.Iso)) - { - return InArchiveFormat.Iso; - } - if (SpecialDetect(stream, 0x9001, InArchiveFormat.Iso)) - { - return InArchiveFormat.Iso; - } - if (SpecialDetect(stream, 0x400, InArchiveFormat.Hfs)) - { - return InArchiveFormat.Hfs; - } - #region Last resort for tar - can mistake - if (stream.Length >= 1024) - { - stream.Seek(-1024, SeekOrigin.End); - byte[] buf = new byte[1024]; - stream.Read(buf, 0, 1024); - bool istar = true; - for (int i = 0; i < 1024; i++) - { - istar = istar && buf[i] == 0; - } - if (istar) - { - return InArchiveFormat.Tar; - } - } - #endregion - #endregion - - #region Check if it is an SFX archive or a file with an embedded archive. - if (suspectedFormat != InArchiveFormat.XZ) - { - #region Get first Min(stream.Length, SFX_SCAN_LENGTH) bytes - var scanLength = Math.Min(stream.Length, SFX_SCAN_LENGTH); - signature = new byte[scanLength]; - bytesRequired = (int)scanLength; - index = 0; - stream.Seek(0, SeekOrigin.Begin); - while (bytesRequired > 0) - { - int bytesRead = stream.Read(signature, index, bytesRequired); - bytesRequired -= bytesRead; - index += bytesRead; - } - actualSignature = BitConverter.ToString(signature); - #endregion - - foreach (var format in new InArchiveFormat[] - { - InArchiveFormat.Zip, - InArchiveFormat.SevenZip, - InArchiveFormat.Rar, - InArchiveFormat.Cab, - InArchiveFormat.Arj - }) - { - int pos = actualSignature.IndexOf(Formats.InSignatureFormatsReversed[format]); - if (pos > -1) - { - offset = pos / 3; - return format; - } - } - // Nothing - if (suspectedFormat == InArchiveFormat.PE) - { - return InArchiveFormat.PE; - } - } - #endregion - - if (ThrowExceptions) - throw new ArgumentException("The stream is invalid or no corresponding signature was found."); - else return InArchiveFormat.None; - } - - /// - /// Gets the InArchiveFormat for a specific file name. - /// - /// The archive file name. - /// The archive beginning offset. - /// True if the original format of the file is PE; otherwise, false. - /// Corresponding InArchiveFormat. - /// - public static InArchiveFormat CheckSignature(string fileName, out int offset, out bool isExecutable) - { - using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) - { - try - { - InArchiveFormat format = CheckSignature(fs, out offset, out isExecutable); - if (format != InArchiveFormat.None) return format; - } - catch (ArgumentException) - { - } - - offset = 0; - isExecutable = false; - return Formats.FormatByFileName(fileName, true); - } - } - } -#endif -} \ No newline at end of file diff --git a/BizHawk.Util/7z/Formats.cs b/BizHawk.Util/7z/Formats.cs deleted file mode 100644 index bd978baf18..0000000000 --- a/BizHawk.Util/7z/Formats.cs +++ /dev/null @@ -1,540 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.Collections.Generic; -using System.IO; - -namespace SevenZip -{ -#if UNMANAGED - /// - /// Readable archive format enumeration. - /// - public enum InArchiveFormat - { - /// - /// Open 7-zip archive format. - /// - /// Wikipedia information - SevenZip, - /// - /// Proprietary Arj archive format. - /// - /// Wikipedia information - Arj, - /// - /// Open Bzip2 archive format. - /// - /// Wikipedia information - BZip2, - /// - /// Microsoft cabinet archive format. - /// - /// Wikipedia information - Cab, - /// - /// Microsoft Compiled HTML Help file format. - /// - /// Wikipedia information - Chm, - /// - /// Microsoft Compound file format. - /// - /// Wikipedia information - Compound, - /// - /// Open Cpio archive format. - /// - /// Wikipedia information - Cpio, - /// - /// Open Debian software package format. - /// - /// Wikipedia information - Deb, - /// - /// Open Gzip archive format. - /// - /// Wikipedia information - GZip, - /// - /// Open ISO disk image format. - /// - /// Wikipedia information - Iso, - /// - /// Open Lzh archive format. - /// - /// Wikipedia information - Lzh, - /// - /// Open core 7-zip Lzma raw archive format. - /// - /// Wikipedia information - Lzma, - /// - /// Nullsoft installation package format. - /// - /// Wikipedia information - Nsis, - /// - /// RarLab Rar archive format. - /// - /// Wikipedia information - Rar, - /// - /// Open Rpm software package format. - /// - /// Wikipedia information - Rpm, - /// - /// Open split file format. - /// - /// Wikipedia information - Split, - /// - /// Open Tar archive format. - /// - /// Wikipedia information - Tar, - /// - /// Microsoft Windows Imaging disk image format. - /// - /// Wikipedia information - Wim, - /// - /// Open LZW archive format; implemented in "compress" program; also known as "Z" archive format. - /// - /// Wikipedia information - Lzw, - /// - /// Open Zip archive format. - /// - /// Wikipedia information - Zip, - /// - /// Open Udf disk image format. - /// - Udf, - /// - /// Xar open source archive format. - /// - /// Wikipedia information - Xar, - /// - /// Mub - /// - Mub, - /// - /// Macintosh Disk Image on CD. - /// - /// Wikipedia information - Hfs, - /// - /// Apple Mac OS X Disk Copy Disk Image format. - /// - Dmg, - /// - /// Open Xz archive format. - /// - /// Wikipedia information - XZ, - /// - /// MSLZ archive format. - /// - Mslz, - /// - /// Flash video format. - /// - /// Wikipedia information - Flv, - /// - /// Shockwave Flash format. - /// - /// Wikipedia information - Swf, - /// - /// Windows PE executable format. - /// - /// Wikipedia information - PE, - /// - /// Linux executable Elf format. - /// - /// Wikipedia information - Elf, - /// - /// Windows Installer Database. - /// - /// Wikipedia information - Msi, - /// - /// Microsoft virtual hard disk file format. - /// - /// Wikipedia information - Vhd, - /// - /// Not an archive - /// - None - } - -#if COMPRESS - /// - /// Writable archive format enumeration. - /// - public enum OutArchiveFormat - { - /// - /// Open 7-zip archive format. - /// - /// Wikipedia information - SevenZip, - /// - /// Open Zip archive format. - /// - /// Wikipedia information - Zip, - /// - /// Open Gzip archive format. - /// - /// Wikipedia information - GZip, - /// - /// Open Bzip2 archive format. - /// - /// Wikipedia information - BZip2, - /// - /// Open Tar archive format. - /// - /// Wikipedia information - Tar, - /// - /// Open Xz archive format. - /// - /// Wikipedia information - XZ - } - - /// - /// Compression level enumeration - /// - public enum CompressionLevel - { - /// - /// No compression - /// - None, - /// - /// Very low compression level - /// - Fast, - /// - /// Low compression level - /// - Low, - /// - /// Normal compression level (default) - /// - Normal, - /// - /// High compression level - /// - High, - /// - /// The best compression level (slow) - /// - Ultra - } - - /// - /// Compression method enumeration. - /// - /// Some methods are applicable only to Zip format, some - only to 7-zip. - public enum CompressionMethod - { - /// - /// Zip or 7-zip|no compression method. - /// - Copy, - /// - /// Zip|Deflate method. - /// - Deflate, - /// - /// Zip|Deflate64 method. - /// - Deflate64, - /// - /// Zip or 7-zip|Bzip2 method. - /// - /// Wikipedia information - BZip2, - /// - /// Zip or 7-zip|LZMA method based on Lempel-Ziv algorithm, it is default for 7-zip. - /// - Lzma, - /// - /// 7-zip|LZMA version 2, LZMA with improved multithreading and usually slight archive size decrease. - /// - Lzma2, - /// - /// Zip or 7-zip|PPMd method based on Dmitry Shkarin's PPMdH source code, very efficient for compressing texts. - /// - /// Wikipedia information - Ppmd, - /// - /// No method change. - /// - Default - } -#endif - - /// - /// Archive format routines - /// - public static class Formats - { - /*/// - /// Gets the max value of the specified enum type. - /// - /// Type of the enum - /// Max value - internal static int GetMaxValue(Type type) - { - List enumList = new List((IEnumerable)Enum.GetValues(type)); - enumList.Sort(); - return enumList[enumList.Count - 1]; - }*/ - - /// - /// List of readable archive format interface guids for 7-zip COM interop. - /// - internal static readonly Dictionary InFormatGuids = - new Dictionary(20) - #region InFormatGuids initialization - - { - {InArchiveFormat.SevenZip, new Guid("23170f69-40c1-278a-1000-000110070000")}, - {InArchiveFormat.Arj, new Guid("23170f69-40c1-278a-1000-000110040000")}, - {InArchiveFormat.BZip2, new Guid("23170f69-40c1-278a-1000-000110020000")}, - {InArchiveFormat.Cab, new Guid("23170f69-40c1-278a-1000-000110080000")}, - {InArchiveFormat.Chm, new Guid("23170f69-40c1-278a-1000-000110e90000")}, - {InArchiveFormat.Compound, new Guid("23170f69-40c1-278a-1000-000110e50000")}, - {InArchiveFormat.Cpio, new Guid("23170f69-40c1-278a-1000-000110ed0000")}, - {InArchiveFormat.Deb, new Guid("23170f69-40c1-278a-1000-000110ec0000")}, - {InArchiveFormat.GZip, new Guid("23170f69-40c1-278a-1000-000110ef0000")}, - {InArchiveFormat.Iso, new Guid("23170f69-40c1-278a-1000-000110e70000")}, - {InArchiveFormat.Lzh, new Guid("23170f69-40c1-278a-1000-000110060000")}, - {InArchiveFormat.Lzma, new Guid("23170f69-40c1-278a-1000-0001100a0000")}, - {InArchiveFormat.Nsis, new Guid("23170f69-40c1-278a-1000-000110090000")}, - {InArchiveFormat.Rar, new Guid("23170f69-40c1-278a-1000-000110030000")}, - {InArchiveFormat.Rpm, new Guid("23170f69-40c1-278a-1000-000110eb0000")}, - {InArchiveFormat.Split, new Guid("23170f69-40c1-278a-1000-000110ea0000")}, - {InArchiveFormat.Tar, new Guid("23170f69-40c1-278a-1000-000110ee0000")}, - {InArchiveFormat.Wim, new Guid("23170f69-40c1-278a-1000-000110e60000")}, - {InArchiveFormat.Lzw, new Guid("23170f69-40c1-278a-1000-000110050000")}, - {InArchiveFormat.Zip, new Guid("23170f69-40c1-278a-1000-000110010000")}, - {InArchiveFormat.Udf, new Guid("23170f69-40c1-278a-1000-000110E00000")}, - {InArchiveFormat.Xar, new Guid("23170f69-40c1-278a-1000-000110E10000")}, - {InArchiveFormat.Mub, new Guid("23170f69-40c1-278a-1000-000110E20000")}, - {InArchiveFormat.Hfs, new Guid("23170f69-40c1-278a-1000-000110E30000")}, - {InArchiveFormat.Dmg, new Guid("23170f69-40c1-278a-1000-000110E40000")}, - {InArchiveFormat.XZ, new Guid("23170f69-40c1-278a-1000-0001100C0000")}, - {InArchiveFormat.Mslz, new Guid("23170f69-40c1-278a-1000-000110D50000")}, - {InArchiveFormat.PE, new Guid("23170f69-40c1-278a-1000-000110DD0000")}, - {InArchiveFormat.Elf, new Guid("23170f69-40c1-278a-1000-000110DE0000")}, - {InArchiveFormat.Swf, new Guid("23170f69-40c1-278a-1000-000110D70000")}, - {InArchiveFormat.Vhd, new Guid("23170f69-40c1-278a-1000-000110DC0000")} - }; - - #endregion - -#if COMPRESS - /// - /// List of writable archive format interface guids for 7-zip COM interop. - /// - internal static readonly Dictionary OutFormatGuids = - new Dictionary(2) - #region OutFormatGuids initialization - - { - {OutArchiveFormat.SevenZip, new Guid("23170f69-40c1-278a-1000-000110070000")}, - {OutArchiveFormat.Zip, new Guid("23170f69-40c1-278a-1000-000110010000")}, - {OutArchiveFormat.BZip2, new Guid("23170f69-40c1-278a-1000-000110020000")}, - {OutArchiveFormat.GZip, new Guid("23170f69-40c1-278a-1000-000110ef0000")}, - {OutArchiveFormat.Tar, new Guid("23170f69-40c1-278a-1000-000110ee0000")}, - {OutArchiveFormat.XZ, new Guid("23170f69-40c1-278a-1000-0001100C0000")}, - }; - - #endregion - - internal static readonly Dictionary MethodNames = - new Dictionary(6) - #region MethodNames initialization - - { - {CompressionMethod.Copy, "Copy"}, - {CompressionMethod.Deflate, "Deflate"}, - {CompressionMethod.Deflate64, "Deflate64"}, - {CompressionMethod.Lzma, "LZMA"}, - {CompressionMethod.Lzma2, "LZMA2"}, - {CompressionMethod.Ppmd, "PPMd"}, - {CompressionMethod.BZip2, "BZip2"} - }; - - #endregion - - internal static readonly Dictionary InForOutFormats = - new Dictionary(6) - #region InForOutFormats initialization - - { - {OutArchiveFormat.SevenZip, InArchiveFormat.SevenZip}, - {OutArchiveFormat.GZip, InArchiveFormat.GZip}, - {OutArchiveFormat.BZip2, InArchiveFormat.BZip2}, - {OutArchiveFormat.Tar, InArchiveFormat.Tar}, - {OutArchiveFormat.XZ, InArchiveFormat.XZ}, - {OutArchiveFormat.Zip, InArchiveFormat.Zip} - }; - - #endregion - -#endif - - /// - /// List of archive formats corresponding to specific extensions - /// - private static readonly Dictionary InExtensionFormats = - new Dictionary - #region InExtensionFormats initialization - - {{"7z", InArchiveFormat.SevenZip}, - {"gz", InArchiveFormat.GZip}, - {"tar", InArchiveFormat.Tar}, - {"rar", InArchiveFormat.Rar}, - {"zip", InArchiveFormat.Zip}, - {"lzma", InArchiveFormat.Lzma}, - {"lzh", InArchiveFormat.Lzh}, - {"arj", InArchiveFormat.Arj}, - {"bz2", InArchiveFormat.BZip2}, - {"cab", InArchiveFormat.Cab}, - {"chm", InArchiveFormat.Chm}, - {"deb", InArchiveFormat.Deb}, - {"iso", InArchiveFormat.Iso}, - {"rpm", InArchiveFormat.Rpm}, - {"wim", InArchiveFormat.Wim}, - {"udf", InArchiveFormat.Udf}, - {"mub", InArchiveFormat.Mub}, - {"xar", InArchiveFormat.Xar}, - {"hfs", InArchiveFormat.Hfs}, - {"dmg", InArchiveFormat.Dmg}, - {"Z", InArchiveFormat.Lzw}, - {"xz", InArchiveFormat.XZ}, - {"flv", InArchiveFormat.Flv}, - {"swf", InArchiveFormat.Swf}, - {"exe", InArchiveFormat.PE}, - {"dll", InArchiveFormat.PE}, - {"vhd", InArchiveFormat.Vhd} - }; - - #endregion - - /// - /// List of archive formats corresponding to specific signatures - /// - /// Based on the information at this site. - internal static readonly Dictionary InSignatureFormats = - new Dictionary - #region InSignatureFormats initialization - - {{"37-7A-BC-AF-27-1C", InArchiveFormat.SevenZip}, - {"1F-8B-08", InArchiveFormat.GZip}, - {"75-73-74-61-72", InArchiveFormat.Tar}, - //257 byte offset - {"52-61-72-21-1A-07-00", InArchiveFormat.Rar}, - {"50-4B-03-04", InArchiveFormat.Zip}, - {"5D-00-00-40-00", InArchiveFormat.Lzma}, - {"2D-6C-68", InArchiveFormat.Lzh}, - //^ 2 byte offset - {"1F-9D-90", InArchiveFormat.Lzw}, - {"60-EA", InArchiveFormat.Arj}, - {"42-5A-68", InArchiveFormat.BZip2}, - //{"4D-53-43-46", InArchiveFormat.Cab}, - //{"49-54-53-46", InArchiveFormat.Chm}, - //{"21-3C-61-72-63-68-3E-0A-64-65-62-69-61-6E-2D-62-69-6E-61-72-79", InArchiveFormat.Deb}, - //{"43-44-30-30-31", InArchiveFormat.Iso}, - //^ 0x8001, 0x8801 or 0x9001 byte offset - //{"ED-AB-EE-DB", InArchiveFormat.Rpm}, - //{"4D-53-57-49-4D-00-00-00", InArchiveFormat.Wim}, - //{"udf", InArchiveFormat.Udf}, - //{"mub", InArchiveFormat.Mub}, - //{"78-61-72-21", InArchiveFormat.Xar}, - //0x400 byte offset - //{"48-2B", InArchiveFormat.Hfs}, - {"FD-37-7A-58-5A", InArchiveFormat.XZ}, - //{"46-4C-56", InArchiveFormat.Flv}, - //{"46-57-53", InArchiveFormat.Swf}, - //{"4D-5A", InArchiveFormat.PE}, - //{"7F-45-4C-46", InArchiveFormat.Elf}, - //{"78", InArchiveFormat.Dmg}, - //{"63-6F-6E-65-63-74-69-78", InArchiveFormat.Vhd}, - {"4E-45-53", InArchiveFormat.None} - }; - - #endregion - - internal static Dictionary InSignatureFormatsReversed; - - static Formats() - { - InSignatureFormatsReversed = new Dictionary(InSignatureFormats.Count); - foreach (var pair in InSignatureFormats) - { - InSignatureFormatsReversed.Add(pair.Value, pair.Key); - } - } - - /// - /// Gets InArchiveFormat for specified archive file name - /// - /// Archive file name - /// Indicates whether to throw exceptions - /// InArchiveFormat recognized by the file name extension - /// - public static InArchiveFormat FormatByFileName(string fileName, bool reportErrors) - { - if (String.IsNullOrEmpty(fileName) && reportErrors) - { - throw new ArgumentException("File name is null or empty string!"); - } - string extension = Path.GetExtension(fileName); - if (extension.StartsWith(".")) - extension = extension.Substring(1); - if (!InExtensionFormats.ContainsKey(extension) && reportErrors) - { - if (FileChecker.ThrowExceptions) - throw new ArgumentException("Extension \"" + extension + "\" is not a supported archive file name extension."); - else return InArchiveFormat.None; - - } - return InExtensionFormats[extension]; - } - } -#endif -} \ No newline at end of file diff --git a/BizHawk.Util/7z/LibraryFeature.cs b/BizHawk.Util/7z/LibraryFeature.cs deleted file mode 100644 index fdc1d5a3bf..0000000000 --- a/BizHawk.Util/7z/LibraryFeature.cs +++ /dev/null @@ -1,112 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; - -namespace SevenZip -{ - /// - /// The set of features supported by the library. - /// - [Flags] - public enum LibraryFeature : uint - { - /// - /// Default feature. - /// - None = 0, - /// - /// The library can extract 7zip archives compressed with LZMA method. - /// - Extract7z = 0x1, - /// - /// The library can extract 7zip archives compressed with LZMA2 method. - /// - Extract7zLZMA2 = 0x2, - /// - /// The library can extract 7z archives compressed with all known methods. - /// - Extract7zAll = Extract7z|Extract7zLZMA2|0x4, - /// - /// The library can extract zip archives. - /// - ExtractZip = 0x8, - /// - /// The library can extract rar archives. - /// - ExtractRar = 0x10, - /// - /// The library can extract gzip archives. - /// - ExtractGzip = 0x20, - /// - /// The library can extract bzip2 archives. - /// - ExtractBzip2 = 0x40, - /// - /// The library can extract tar archives. - /// - ExtractTar = 0x80, - /// - /// The library can extract xz archives. - /// - ExtractXz = 0x100, - /// - /// The library can extract all types of archives supported. - /// - ExtractAll = Extract7zAll|ExtractZip|ExtractRar|ExtractGzip|ExtractBzip2|ExtractTar|ExtractXz, - /// - /// The library can compress data to 7zip archives with LZMA method. - /// - Compress7z = 0x200, - /// - /// The library can compress data to 7zip archives with LZMA2 method. - /// - Compress7zLZMA2 = 0x400, - /// - /// The library can compress data to 7zip archives with all methods known. - /// - Compress7zAll = Compress7z|Compress7zLZMA2|0x800, - /// - /// The library can compress data to tar archives. - /// - CompressTar = 0x1000, - /// - /// The library can compress data to gzip archives. - /// - CompressGzip = 0x2000, - /// - /// The library can compress data to bzip2 archives. - /// - CompressBzip2 = 0x4000, - /// - /// The library can compress data to xz archives. - /// - CompressXz = 0x8000, - /// - /// The library can compress data to zip archives. - /// - CompressZip = 0x10000, - /// - /// The library can compress data to all types of archives supported. - /// - CompressAll = Compress7zAll|CompressTar|CompressGzip|CompressBzip2|CompressXz|CompressZip, - /// - /// The library can modify archives. - /// - Modify = 0x20000 - } -} diff --git a/BizHawk.Util/7z/LibraryManager.cs b/BizHawk.Util/7z/LibraryManager.cs deleted file mode 100644 index 86ad2f7c86..0000000000 --- a/BizHawk.Util/7z/LibraryManager.cs +++ /dev/null @@ -1,567 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.Collections.Generic; -#if !WINCE && !MONO -using System.Configuration; -using System.Diagnostics; -using System.Security.Permissions; -#endif -#if WINCE -using OpenNETCF.Diagnostics; -#endif -using System.IO; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Text; -#if MONO -using SevenZip.Mono.COM; -#endif - -namespace SevenZip -{ -#if UNMANAGED - /// - /// 7-zip library low-level wrapper. - /// - internal static class SevenZipLibraryManager - { -#if !WINCE && !MONO - /// - /// Path to the 7-zip dll. - /// - /// 7zxa.dll supports only decoding from .7z archives. - /// Features of 7za.dll: - /// - Supporting 7z format; - /// - Built encoders: LZMA, PPMD, BCJ, BCJ2, COPY, AES-256 Encryption. - /// - Built decoders: LZMA, PPMD, BCJ, BCJ2, COPY, AES-256 Encryption, BZip2, Deflate. - /// 7z.dll (from the 7-zip distribution) supports every InArchiveFormat for encoding and decoding. - /// - //private static string _libraryFileName = ConfigurationManager.AppSettings["7zLocation"] ?? Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "7z.dll"); - private static string _libraryFileName = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "7z.dll"); -#endif -#if WINCE - private static string _libraryFileName = - Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase), "7z.dll"); -#endif - /// - /// 7-zip library handle. - /// - private static IntPtr _modulePtr; - - /// - /// 7-zip library features. - /// - private static LibraryFeature? _features; - - private static Dictionary> _inArchives; -#if COMPRESS - private static Dictionary> _outArchives; -#endif - private static int _totalUsers; - - // private static string _LibraryVersion; - private static bool? _modifyCapabale; - - private static void InitUserInFormat(object user, InArchiveFormat format) - { - if (!_inArchives.ContainsKey(user)) - { - _inArchives.Add(user, new Dictionary()); - } - if (!_inArchives[user].ContainsKey(format)) - { - _inArchives[user].Add(format, null); - _totalUsers++; - } - } - -#if COMPRESS - private static void InitUserOutFormat(object user, OutArchiveFormat format) - { - if (!_outArchives.ContainsKey(user)) - { - _outArchives.Add(user, new Dictionary()); - } - if (!_outArchives[user].ContainsKey(format)) - { - _outArchives[user].Add(format, null); - _totalUsers++; - } - } -#endif - - private static void Init() - { - _inArchives = new Dictionary>(); -#if COMPRESS - _outArchives = new Dictionary>(); -#endif - } - - /// - /// Loads the 7-zip library if necessary and adds user to the reference list - /// - /// Caller of the function - /// Archive format - public static void LoadLibrary(object user, Enum format) - { - if (_inArchives == null -#if COMPRESS - || _outArchives == null -#endif - ) - { - Init(); - } -#if !WINCE && !MONO - if (_modulePtr == IntPtr.Zero) - { - //zero 29-oct-2012 - this check isnt useful since LoadLibrary can pretty much check for the same thing. and it wrecks our dll relocation scheme - //if (!File.Exists(_libraryFileName)) - //{ - // throw new SevenZipLibraryException("DLL file does not exist."); - //} - if ((_modulePtr = NativeMethods.LoadLibrary(_libraryFileName)) == IntPtr.Zero) - { - //try a different directory - string alternateFilename = Path.Combine(Path.Combine(Path.GetDirectoryName(_libraryFileName),"dll"),"7z.dll"); - if ((_modulePtr = NativeMethods.LoadLibrary(alternateFilename)) == IntPtr.Zero) - throw new SevenZipLibraryException("failed to load library."); - } - if (NativeMethods.GetProcAddress(_modulePtr, "GetHandlerProperty") == IntPtr.Zero) - { - NativeMethods.FreeLibrary(_modulePtr); - throw new SevenZipLibraryException("library is invalid."); - } - } -#endif - if (format is InArchiveFormat) - { - InitUserInFormat(user, (InArchiveFormat) format); - return; - } -#if COMPRESS - if (format is OutArchiveFormat) - { - InitUserOutFormat(user, (OutArchiveFormat) format); - return; - } -#endif - throw new ArgumentException( - "Enum " + format + " is not a valid archive format attribute!"); - } - - /*/// - /// Gets the native 7zip library version string. - /// - public static string LibraryVersion - { - get - { - if (String.IsNullOrEmpty(_LibraryVersion)) - { - FileVersionInfo dllVersionInfo = FileVersionInfo.GetVersionInfo(_libraryFileName); - _LibraryVersion = String.Format( - System.Globalization.CultureInfo.CurrentCulture, - "{0}.{1}", - dllVersionInfo.FileMajorPart, dllVersionInfo.FileMinorPart); - } - return _LibraryVersion; - } - }*/ - - /// - /// Gets the value indicating whether the library supports modifying archives. - /// - public static bool ModifyCapable - { - get - { - if (!_modifyCapabale.HasValue) - { -#if !WINCE && !MONO - FileVersionInfo dllVersionInfo = FileVersionInfo.GetVersionInfo(_libraryFileName); - _modifyCapabale = dllVersionInfo.FileMajorPart >= 9; -#else - _modifyCapabale = true; -#endif - } - return _modifyCapabale.Value; - } - } - - static readonly string Namespace = Assembly.GetExecutingAssembly().GetManifestResourceNames()[0].Split('.')[0]; - - private static string GetResourceString(string str) - { - return Namespace + ".arch." + str; - } - - private static bool ExtractionBenchmark(string archiveFileName, Stream outStream, - ref LibraryFeature? features, LibraryFeature testedFeature) - { - var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream( - GetResourceString(archiveFileName)); - try - { - using (var extr = new SevenZipExtractor(stream)) - { - extr.ExtractFile(0, outStream); - } - } - catch(Exception) - { - return false; - } - features |= testedFeature; - return true; - } - - private static bool CompressionBenchmark(Stream inStream, Stream outStream, - OutArchiveFormat format, CompressionMethod method, - ref LibraryFeature? features, LibraryFeature testedFeature) - { - try - { - var compr = new SevenZipCompressor {ArchiveFormat = format, CompressionMethod = method}; - compr.CompressStream(inStream, outStream); - } - catch (Exception) - { - return false; - } - features |= testedFeature; - return true; - } - - public static LibraryFeature CurrentLibraryFeatures - { - get - { - if (_features != null && _features.HasValue) - { - return _features.Value; - } - _features = LibraryFeature.None; - #region Benchmark - #region Extraction features - using (var outStream = new MemoryStream()) - { - ExtractionBenchmark("Test.lzma.7z", outStream, ref _features, LibraryFeature.Extract7z); - ExtractionBenchmark("Test.lzma2.7z", outStream, ref _features, LibraryFeature.Extract7zLZMA2); - int i = 0; - if (ExtractionBenchmark("Test.bzip2.7z", outStream, ref _features, _features.Value)) - { - i++; - } - if (ExtractionBenchmark("Test.ppmd.7z", outStream, ref _features, _features.Value)) - { - i++; - if (i == 2 && (_features & LibraryFeature.Extract7z) != 0 && - (_features & LibraryFeature.Extract7zLZMA2) != 0) - { - _features |= LibraryFeature.Extract7zAll; - } - } - ExtractionBenchmark("Test.rar", outStream, ref _features, LibraryFeature.ExtractRar); - ExtractionBenchmark("Test.tar", outStream, ref _features, LibraryFeature.ExtractTar); - ExtractionBenchmark("Test.txt.bz2", outStream, ref _features, LibraryFeature.ExtractBzip2); - ExtractionBenchmark("Test.txt.gz", outStream, ref _features, LibraryFeature.ExtractGzip); - ExtractionBenchmark("Test.txt.xz", outStream, ref _features, LibraryFeature.ExtractXz); - ExtractionBenchmark("Test.zip", outStream, ref _features, LibraryFeature.ExtractZip); - } - #endregion - #region Compression features - using (var inStream = new MemoryStream()) - { - inStream.Write(Encoding.UTF8.GetBytes("Test"), 0, 4); - using (var outStream = new MemoryStream()) - { - CompressionBenchmark(inStream, outStream, - OutArchiveFormat.SevenZip, CompressionMethod.Lzma, - ref _features, LibraryFeature.Compress7z); - CompressionBenchmark(inStream, outStream, - OutArchiveFormat.SevenZip, CompressionMethod.Lzma2, - ref _features, LibraryFeature.Compress7zLZMA2); - int i = 0; - if (CompressionBenchmark(inStream, outStream, - OutArchiveFormat.SevenZip, CompressionMethod.BZip2, - ref _features, _features.Value)) - { - i++; - } - if (CompressionBenchmark(inStream, outStream, - OutArchiveFormat.SevenZip, CompressionMethod.Ppmd, - ref _features, _features.Value)) - { - i++; - if (i == 2 && (_features & LibraryFeature.Compress7z) != 0 && - (_features & LibraryFeature.Compress7zLZMA2) != 0) - { - _features |= LibraryFeature.Compress7zAll; - } - } - CompressionBenchmark(inStream, outStream, - OutArchiveFormat.Zip, CompressionMethod.Default, - ref _features, LibraryFeature.CompressZip); - CompressionBenchmark(inStream, outStream, - OutArchiveFormat.BZip2, CompressionMethod.Default, - ref _features, LibraryFeature.CompressBzip2); - CompressionBenchmark(inStream, outStream, - OutArchiveFormat.GZip, CompressionMethod.Default, - ref _features, LibraryFeature.CompressGzip); - CompressionBenchmark(inStream, outStream, - OutArchiveFormat.Tar, CompressionMethod.Default, - ref _features, LibraryFeature.CompressTar); - CompressionBenchmark(inStream, outStream, - OutArchiveFormat.XZ, CompressionMethod.Default, - ref _features, LibraryFeature.CompressXz); - } - } - #endregion - #endregion - if (ModifyCapable && (_features.Value & LibraryFeature.Compress7z) != 0) - { - _features |= LibraryFeature.Modify; - } - return _features.Value; - } - } - - /// - /// Removes user from reference list and frees the 7-zip library if it becomes empty - /// - /// Caller of the function - /// Archive format - public static void FreeLibrary(object user, Enum format) - { -#if !WINCE && !MONO - var sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); - sp.Demand(); -#endif - if (_modulePtr != IntPtr.Zero) - { - if (format is InArchiveFormat) - { - if (_inArchives != null && _inArchives.ContainsKey(user) && - _inArchives[user].ContainsKey((InArchiveFormat) format) && - _inArchives[user][(InArchiveFormat) format] != null) - { - try - { - Marshal.ReleaseComObject(_inArchives[user][(InArchiveFormat) format]); - } - catch (InvalidComObjectException) {} - _inArchives[user].Remove((InArchiveFormat) format); - _totalUsers--; - if (_inArchives[user].Count == 0) - { - _inArchives.Remove(user); - } - } - } -#if COMPRESS - if (format is OutArchiveFormat) - { - if (_outArchives != null && _outArchives.ContainsKey(user) && - _outArchives[user].ContainsKey((OutArchiveFormat) format) && - _outArchives[user][(OutArchiveFormat) format] != null) - { - try - { - Marshal.ReleaseComObject(_outArchives[user][(OutArchiveFormat) format]); - } - catch (InvalidComObjectException) {} - _outArchives[user].Remove((OutArchiveFormat) format); - _totalUsers--; - if (_outArchives[user].Count == 0) - { - _outArchives.Remove(user); - } - } - } -#endif - if ((_inArchives == null || _inArchives.Count == 0) -#if COMPRESS - && (_outArchives == null || _outArchives.Count == 0) -#endif - ) - { - _inArchives = null; -#if COMPRESS - _outArchives = null; -#endif - if (_totalUsers == 0) - { -#if !WINCE && !MONO - NativeMethods.FreeLibrary(_modulePtr); - -#endif - _modulePtr = IntPtr.Zero; - } - } - } - } - - /// - /// Gets IInArchive interface to extract 7-zip archives. - /// - /// Archive format. - /// Archive format user. - public static IInArchive InArchive(InArchiveFormat format, object user) - { -#if !WINCE && !MONO - lock (_libraryFileName) - { -#endif - if (_inArchives[user][format] == null) - { -#if !WINCE && !MONO - var sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); - sp.Demand(); - - if (_modulePtr == IntPtr.Zero) - { - LoadLibrary(user, format); - if (_modulePtr == IntPtr.Zero) - { - throw new SevenZipLibraryException(); - } - } - var createObject = (NativeMethods.CreateObjectDelegate) - Marshal.GetDelegateForFunctionPointer( - NativeMethods.GetProcAddress(_modulePtr, "CreateObject"), - typeof(NativeMethods.CreateObjectDelegate)); - if (createObject == null) - { - throw new SevenZipLibraryException(); - } -#endif - object result; - Guid interfaceId = -#if !WINCE && !MONO - typeof(IInArchive).GUID; -#else - new Guid(((GuidAttribute)typeof(IInArchive).GetCustomAttributes(typeof(GuidAttribute), false)[0]).Value); -#endif - Guid classID = Formats.InFormatGuids[format]; - try - { -#if !WINCE && !MONO - createObject(ref classID, ref interfaceId, out result); -#elif !MONO - NativeMethods.CreateCOMObject(ref classID, ref interfaceId, out result); -#else - result = SevenZip.Mono.Factory.CreateInterface(user, classID, interfaceId); -#endif - } - catch (Exception) - { - throw new SevenZipLibraryException("Your 7-zip library does not support this archive type."); - } - InitUserInFormat(user, format); - _inArchives[user][format] = result as IInArchive; - } -#if !WINCE && !MONO - } -#endif - return _inArchives[user][format]; - } - -#if COMPRESS - /// - /// Gets IOutArchive interface to pack 7-zip archives. - /// - /// Archive format. - /// Archive format user. - public static IOutArchive OutArchive(OutArchiveFormat format, object user) - { -#if !WINCE && !MONO - lock (_libraryFileName) - { -#endif - if (_outArchives[user][format] == null) - { -#if !WINCE && !MONO - var sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); - sp.Demand(); - if (_modulePtr == IntPtr.Zero) - { - throw new SevenZipLibraryException(); - } - var createObject = (NativeMethods.CreateObjectDelegate) - Marshal.GetDelegateForFunctionPointer( - NativeMethods.GetProcAddress(_modulePtr, "CreateObject"), - typeof(NativeMethods.CreateObjectDelegate)); - if (createObject == null) - { - throw new SevenZipLibraryException(); - } -#endif - object result; - Guid interfaceId = -#if !WINCE && !MONO - typeof(IOutArchive).GUID; -#else - new Guid(((GuidAttribute)typeof(IOutArchive).GetCustomAttributes(typeof(GuidAttribute), false)[0]).Value); -#endif - Guid classID = Formats.OutFormatGuids[format]; - try - { -#if !WINCE && !MONO - createObject(ref classID, ref interfaceId, out result); -#elif !MONO - NativeMethods.CreateCOMObject(ref classID, ref interfaceId, out result); -#else - result = SevenZip.Mono.Factory.CreateInterface(classID, interfaceId, user); -#endif - } - catch (Exception) - { - throw new SevenZipLibraryException("Your 7-zip library does not support this archive type."); - } - InitUserOutFormat(user, format); - _outArchives[user][format] = result as IOutArchive; - } -#if !WINCE && !MONO - } -#endif - return _outArchives[user][format]; - } -#endif -#if !WINCE && !MONO - public static void SetLibraryPath(string libraryPath) - { - if (_modulePtr != IntPtr.Zero && !Path.GetFullPath(libraryPath).Equals( - Path.GetFullPath(_libraryFileName), StringComparison.OrdinalIgnoreCase)) - { - throw new SevenZipLibraryException( - "can not change the library path while the library \"" + _libraryFileName + "\" is being used."); - } - if (!File.Exists(libraryPath)) - { - throw new SevenZipLibraryException( - "can not change the library path because the file \"" + libraryPath + "\" does not exist."); - } - _libraryFileName = libraryPath; - _features = null; - } -#endif - } -#endif -} \ No newline at end of file diff --git a/BizHawk.Util/7z/LzmaDecodeStream.cs b/BizHawk.Util/7z/LzmaDecodeStream.cs deleted file mode 100644 index 16946d5a1a..0000000000 --- a/BizHawk.Util/7z/LzmaDecodeStream.cs +++ /dev/null @@ -1,240 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.IO; -using SevenZip.Sdk.Compression.Lzma; - -namespace SevenZip -{ -#if LZMA_STREAM - /// - /// The stream which decompresses data with LZMA on the fly. - /// - public class LzmaDecodeStream : Stream - { - private readonly MemoryStream _buffer = new MemoryStream(); - private readonly Decoder _decoder = new Decoder(); - private readonly Stream _input; - private byte[] _commonProperties; - private bool _error; - private bool _firstChunkRead; - - /// - /// Initializes a new instance of the LzmaDecodeStream class. - /// - /// A compressed stream. - public LzmaDecodeStream(Stream encodedStream) - { - if (!encodedStream.CanRead) - { - throw new ArgumentException("The specified stream can not read.", "encodedStream"); - } - _input = encodedStream; - } - - /// - /// Gets the chunk size. - /// - public int ChunkSize - { - get - { - return (int) _buffer.Length; - } - } - - /// - /// Gets a value indicating whether the current stream supports reading. - /// - public override bool CanRead - { - get - { - return true; - } - } - - /// - /// Gets a value indicating whether the current stream supports seeking. - /// - public override bool CanSeek - { - get - { - return false; - } - } - - /// - /// Gets a value indicating whether the current stream supports writing. - /// - public override bool CanWrite - { - get - { - return false; - } - } - - /// - /// Gets the length in bytes of the output stream. - /// - public override long Length - { - get - { - if (_input.CanSeek) - { - return _input.Length; - } - return _buffer.Length; - } - } - - /// - /// Gets or sets the position within the output stream. - /// - public override long Position - { - get - { - if (_input.CanSeek) - { - return _input.Position; - } - return _buffer.Position; - } - set - { - throw new NotSupportedException(); - } - } - - private void ReadChunk() - { - long size; - byte[] properties; - try - { - properties = SevenZipExtractor.GetLzmaProperties(_input, out size); - } - catch (LzmaException) - { - _error = true; - return; - } - if (!_firstChunkRead) - { - _commonProperties = properties; - } - if (_commonProperties[0] != properties[0] || - _commonProperties[1] != properties[1] || - _commonProperties[2] != properties[2] || - _commonProperties[3] != properties[3] || - _commonProperties[4] != properties[4]) - { - _error = true; - return; - } - if (_buffer.Capacity < (int) size) - { - _buffer.Capacity = (int) size; - } - _buffer.SetLength(size); - _decoder.SetDecoderProperties(properties); - _buffer.Position = 0; - _decoder.Code( - _input, _buffer, 0, size, null); - _buffer.Position = 0; - } - - /// - /// Does nothing. - /// - public override void Flush() {} - - /// - /// Reads a sequence of bytes from the current stream and decompresses data if necessary. - /// - /// An array of bytes. - /// The zero-based byte offset in buffer at which to begin storing the data read from the current stream. - /// The maximum number of bytes to be read from the current stream. - /// The total number of bytes read into the buffer. - public override int Read(byte[] buffer, int offset, int count) - { - if (_error) - { - return 0; - } - - if (!_firstChunkRead) - { - ReadChunk(); - _firstChunkRead = true; - } - int readCount = 0; - while (count > _buffer.Length - _buffer.Position && !_error) - { - var buf = new byte[_buffer.Length - _buffer.Position]; - _buffer.Read(buf, 0, buf.Length); - buf.CopyTo(buffer, offset); - offset += buf.Length; - count -= buf.Length; - readCount += buf.Length; - ReadChunk(); - } - if (!_error) - { - _buffer.Read(buffer, offset, count); - readCount += count; - } - return readCount; - } - - /// - /// Sets the position within the current stream. - /// - /// A byte offset relative to the origin parameter. - /// A value of type System.IO.SeekOrigin indicating the reference point used to obtain the new position. - /// The new position within the current stream. - public override long Seek(long offset, SeekOrigin origin) - { - throw new NotSupportedException(); - } - - /// - /// Sets the length of the current stream. - /// - /// The desired length of the current stream in bytes. - public override void SetLength(long value) - { - throw new NotSupportedException(); - } - - /// - /// Writes a sequence of bytes to the current stream. - /// - /// An array of bytes. - /// The zero-based byte offset in buffer at which to begin storing the data read from the current stream. - /// The maximum number of bytes to be read from the current stream. - public override void Write(byte[] buffer, int offset, int count) - { - throw new NotSupportedException(); - } - } -#endif -} \ No newline at end of file diff --git a/BizHawk.Util/7z/LzmaEncodeStream.cs b/BizHawk.Util/7z/LzmaEncodeStream.cs deleted file mode 100644 index bc9165e39f..0000000000 --- a/BizHawk.Util/7z/LzmaEncodeStream.cs +++ /dev/null @@ -1,304 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.IO; -using SevenZip.Sdk.Compression.Lzma; - -namespace SevenZip -{ -#if LZMA_STREAM -#if COMPRESS - /// - /// The stream which compresses data with LZMA on the fly. - /// - public class LzmaEncodeStream : Stream - { - private const int MAX_BUFFER_CAPACITY = 1 << 30; //1 Gb - private readonly MemoryStream _buffer = new MemoryStream(); - private readonly int _bufferCapacity = 1 << 18; //256 kb - private readonly bool _ownOutput; - private bool _disposed; - private Encoder _lzmaEncoder; - private Stream _output; - - /// - /// Initializes a new instance of the LzmaEncodeStream class. - /// - public LzmaEncodeStream() - { - _output = new MemoryStream(); - _ownOutput = true; - Init(); - } - - /// - /// Initializes a new instance of the LzmaEncodeStream class. - /// - /// The buffer size. The bigger size, the better compression. - public LzmaEncodeStream(int bufferCapacity) - { - _output = new MemoryStream(); - _ownOutput = true; - if (bufferCapacity > MAX_BUFFER_CAPACITY) - { - throw new ArgumentException("Too large capacity.", "bufferCapacity"); - } - _bufferCapacity = bufferCapacity; - Init(); - } - - /// - /// Initializes a new instance of the LzmaEncodeStream class. - /// - /// An output stream which supports writing. - public LzmaEncodeStream(Stream outputStream) - { - if (!outputStream.CanWrite) - { - throw new ArgumentException("The specified stream can not write.", "outputStream"); - } - _output = outputStream; - Init(); - } - - /// - /// Initializes a new instance of the LzmaEncodeStream class. - /// - /// An output stream which supports writing. - /// A buffer size. The bigger size, the better compression. - public LzmaEncodeStream(Stream outputStream, int bufferCapacity) - { - if (!outputStream.CanWrite) - { - throw new ArgumentException("The specified stream can not write.", "outputStream"); - } - _output = outputStream; - if (bufferCapacity > 1 << 30) - { - throw new ArgumentException("Too large capacity.", "bufferCapacity"); - } - _bufferCapacity = bufferCapacity; - Init(); - } - - /// - /// Gets a value indicating whether the current stream supports reading. - /// - public override bool CanRead - { - get - { - return false; - } - } - - /// - /// Gets a value indicating whether the current stream supports seeking. - /// - public override bool CanSeek - { - get - { - return false; - } - } - - /// - /// Gets a value indicating whether the current stream supports writing. - /// - public override bool CanWrite - { - get - { - DisposedCheck(); - return _buffer.CanWrite; - } - } - - /// - /// Gets the length in bytes of the output stream. - /// - public override long Length - { - get - { - DisposedCheck(); - if (_output.CanSeek) - { - return _output.Length; - } - return _buffer.Position; - } - } - - /// - /// Gets or sets the position within the output stream. - /// - public override long Position - { - get - { - DisposedCheck(); - if (_output.CanSeek) - { - return _output.Position; - } - return _buffer.Position; - } - set - { - throw new NotSupportedException(); - } - } - - private void Init() - { - _buffer.Capacity = _bufferCapacity; - SevenZipCompressor.LzmaDictionarySize = _bufferCapacity; - _lzmaEncoder = new Encoder(); - SevenZipCompressor.WriteLzmaProperties(_lzmaEncoder); - } - - /// - /// Checked whether the class was disposed. - /// - /// - private void DisposedCheck() - { - if (_disposed) - { - throw new ObjectDisposedException("SevenZipExtractor"); - } - } - - private void WriteChunk() - { - _lzmaEncoder.WriteCoderProperties(_output); - long streamSize = _buffer.Position; - if (_buffer.Length != _buffer.Position) - { - _buffer.SetLength(_buffer.Position); - } - _buffer.Position = 0; - for (int i = 0; i < 8; i++) - { - _output.WriteByte((byte) (streamSize >> (8*i))); - } - _lzmaEncoder.Code(_buffer, _output, -1, -1, null); - _buffer.Position = 0; - } - - /// - /// Converts the LzmaEncodeStream to the LzmaDecodeStream to read data. - /// - /// - public LzmaDecodeStream ToDecodeStream() - { - DisposedCheck(); - Flush(); - return new LzmaDecodeStream(_output); - } - - /// - /// Clears all buffers for this stream and causes any buffered data to be compressed and written. - /// - public override void Flush() - { - DisposedCheck(); - WriteChunk(); - } - - /// - /// Releases all unmanaged resources used by LzmaEncodeStream. - /// - protected override void Dispose(bool disposing) - { - if (!_disposed) - { - if (disposing) - { - Flush(); - _buffer.Close(); - if (_ownOutput) - { - _output.Dispose(); - } - _output = null; - } - _disposed = true; - } - } - - /// - /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. - /// - /// An array of bytes. - /// The zero-based byte offset in buffer at which to begin storing the data read from the current stream. - /// The maximum number of bytes to be read from the current stream. - /// The total number of bytes read into the buffer. - public override int Read(byte[] buffer, int offset, int count) - { - DisposedCheck(); - throw new NotSupportedException(); - } - - /// - /// Sets the position within the current stream. - /// - /// A byte offset relative to the origin parameter. - /// A value of type System.IO.SeekOrigin indicating the reference point used to obtain the new position. - /// The new position within the current stream. - public override long Seek(long offset, SeekOrigin origin) - { - DisposedCheck(); - throw new NotSupportedException(); - } - - /// - /// Sets the length of the current stream. - /// - /// The desired length of the current stream in bytes. - public override void SetLength(long value) - { - DisposedCheck(); - throw new NotSupportedException(); - } - - /// - /// Writes a sequence of bytes to the current stream and compresses it if necessary. - /// - /// An array of bytes. - /// The zero-based byte offset in buffer at which to begin storing the data read from the current stream. - /// The maximum number of bytes to be read from the current stream. - public override void Write(byte[] buffer, int offset, int count) - { - DisposedCheck(); - int dataLength = Math.Min(buffer.Length - offset, count); - while (_buffer.Position + dataLength >= _bufferCapacity) - { - int length = _bufferCapacity - (int) _buffer.Position; - _buffer.Write(buffer, offset, length); - offset = length + offset; - dataLength -= length; - WriteChunk(); - } - _buffer.Write(buffer, offset, dataLength); - } - } -#endif -#endif -} \ No newline at end of file diff --git a/BizHawk.Util/7z/LzmaProgressCallback.cs b/BizHawk.Util/7z/LzmaProgressCallback.cs deleted file mode 100644 index fee8c7abad..0000000000 --- a/BizHawk.Util/7z/LzmaProgressCallback.cs +++ /dev/null @@ -1,72 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using SevenZip.Sdk; - -namespace SevenZip -{ - /// - /// Callback to implement the ICodeProgress interface - /// - internal sealed class LzmaProgressCallback : ICodeProgress - { - private readonly long _inSize; - private float _oldPercentDone; - - /// - /// Initializes a new instance of the LzmaProgressCallback class - /// - /// The input size - /// Progress event handler - public LzmaProgressCallback(long inSize, EventHandler working) - { - _inSize = inSize; - Working += working; - } - - #region ICodeProgress Members - - /// - /// Sets the progress - /// - /// The processed input size - /// The processed output size - public void SetProgress(long inSize, long outSize) - { - if (Working != null) - { - float newPercentDone = (inSize + 0.0f) / _inSize; - float delta = newPercentDone - _oldPercentDone; - if (delta * 100 < 1.0) - { - delta = 0; - } - else - { - _oldPercentDone = newPercentDone; - } - Working(this, new ProgressEventArgs( - PercentDoneEventArgs.ProducePercentDone(newPercentDone), - delta > 0 ? PercentDoneEventArgs.ProducePercentDone(delta) : (byte)0)); - } - } - - #endregion - - public event EventHandler Working; - } -} diff --git a/BizHawk.Util/7z/NativeMethods.cs b/BizHawk.Util/7z/NativeMethods.cs deleted file mode 100644 index 02ef5e7eb4..0000000000 --- a/BizHawk.Util/7z/NativeMethods.cs +++ /dev/null @@ -1,77 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.Runtime.InteropServices; -#if MONO -using SevenZip.Mono.COM; -#endif - -namespace SevenZip -{ -#if UNMANAGED - internal static class NativeMethods - { - #if !WINCE && !MONO - #region Delegates - - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - public delegate int CreateObjectDelegate( - [In] ref Guid classID, - [In] ref Guid interfaceID, - [MarshalAs(UnmanagedType.Interface)] out object outObject); - - #endregion - - [DllImport("kernel32.dll", BestFitMapping = false, ThrowOnUnmappableChar = true)] - public static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string fileName); - - [DllImport("kernel32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool FreeLibrary(IntPtr hModule); - - [DllImport("kernel32.dll", BestFitMapping = false, ThrowOnUnmappableChar = true)] - public static extern IntPtr GetProcAddress(IntPtr hModule, [MarshalAs(UnmanagedType.LPStr)] string procName); - #endif - - #if WINCE - [DllImport("7z.dll", EntryPoint="CreateObject")] - public static extern int CreateCOMObject( - [In] ref Guid classID, - [In] ref Guid interfaceID, - [MarshalAs(UnmanagedType.Interface)] out object outObject); - #endif - - public static T SafeCast(PropVariant var, T def) - { - object obj; - try - { - obj = var.Object; - } - catch (Exception) - { - return def; - } - if (obj != null && obj is T) - { - return (T) obj; - } - return def; - } - } -#endif -} \ No newline at end of file diff --git a/BizHawk.Util/7z/SevenZipCompressor.cs b/BizHawk.Util/7z/SevenZipCompressor.cs deleted file mode 100644 index 2227150f97..0000000000 --- a/BizHawk.Util/7z/SevenZipCompressor.cs +++ /dev/null @@ -1,2048 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -#if DOTNET20 -using System.Threading; -#else -using System.Linq; -#endif -using System.Runtime.InteropServices; -#if !WINCE -using System.Security.Permissions; -#endif -using SevenZip.Sdk; -using SevenZip.Sdk.Compression.Lzma; -#if MONO -using SevenZip.Mono.COM; -#endif - -namespace SevenZip -{ -#if COMPRESS - /// - /// Class for packing files into 7-zip archives - /// - public sealed partial class SevenZipCompressor -#if UNMANAGED - : SevenZipBase -#endif - { -#if UNMANAGED - #region Fields - private bool _compressingFilesOnDisk; - /// - /// Gets or sets the archiving compression level. - /// - public CompressionLevel CompressionLevel { get; set; } - private OutArchiveFormat _archiveFormat = OutArchiveFormat.SevenZip; - private CompressionMethod _compressionMethod = CompressionMethod.Default; - /// - /// Gets the custom compression parameters - for advanced users only. - /// - public Dictionary CustomParameters { get; private set; } - private int _volumeSize; - private string _archiveName; - /// - /// Gets or sets the value indicating whether to include empty directories to archives. Default is true. - /// - public bool IncludeEmptyDirectories { get; set; } - /// - /// Gets or sets the value indicating whether to preserve the directory root for CompressDirectory. - /// - public bool PreserveDirectoryRoot { get; set; } - /// - /// Gets or sets the value indicating whether to preserve the directory structure. - /// - public bool DirectoryStructure { get; set; } - private bool _directoryCompress; - /// - /// Gets or sets the compression mode. - /// - public CompressionMode CompressionMode { get; set; } - private UpdateData _updateData; - private uint _oldFilesCount; - /// - /// Gets or sets the value indicating whether to encrypt 7-Zip archive headers. - /// - public bool EncryptHeaders { get; set; } - /// - /// Gets or sets the value indicating whether to compress files only open for writing. - /// - public bool ScanOnlyWritable { get; set; } - /// - /// Gets or sets the encryption method for zip archives. - /// - public ZipEncryptionMethod ZipEncryptionMethod { get; set; } - /// - /// Gets or sets the temporary folder path. - /// - public string TempFolderPath { get; set; } - /// - /// Gets or sets the default archive item name used when an item to be compressed has no name, - /// for example, when you compress a MemoryStream instance. - /// - public string DefaultItemName { get; set; } - /// - /// Gets or sets the value indicating whether to compress as fast as possible, without calling events. - /// - public bool FastCompression { get; set; } - #endregion -#endif - private static int _lzmaDictionarySize = 1 << 22; - -#if UNMANAGED - - private void CommonInit() - { - DirectoryStructure = true; - IncludeEmptyDirectories = true; - CompressionLevel = CompressionLevel.Normal; - CompressionMode = CompressionMode.Create; - ZipEncryptionMethod = ZipEncryptionMethod.ZipCrypto; - CustomParameters = new Dictionary(); - _updateData = new UpdateData(); - DefaultItemName = "default"; - } - - /// - /// Initializes a new instance of the SevenZipCompressor class. - /// - public SevenZipCompressor() - { - try - { -#if !WINCE - TempFolderPath = Path.GetTempPath(); - //TempFolderPath = Environment.GetEnvironmentVariable("TEMP", EnvironmentVariableTarget.User); -#else - TempFolderPath = "Temp"; -#endif - } - catch (System.Security.SecurityException) // Registry access is not allowed, etc. - { - /*throw new SevenZipCompressionFailedException( - "Attempted to get TEMP environment variable but registry access was not allowed (security settings on your machine). You must call SevenZipCompressor constructor overload with your own temporary path."); - */ - throw new SevenZipCompressionFailedException( - "Path.GetTempPath() threw a System.Security.SecurityException. You must call SevenZipCompressor constructor overload with your own temporary path."); - } - CommonInit(); - } - - /// - /// Initializes a new instance of the SevenZipCompressor class. - /// - /// Your own temporary path (default is set in the parameterless constructor overload.) - public SevenZipCompressor(string temporaryPath) - { - TempFolderPath = temporaryPath; - if (!Directory.Exists(TempFolderPath)) - { - try - { - Directory.CreateDirectory(TempFolderPath); - } - catch (Exception) - { - throw new SevenZipCompressionFailedException("The specified temporary path is invalid."); - } - } - CommonInit(); - } -#endif - - /// - /// Checks if the specified stream supports compression. - /// - /// The stream to check. - private static void ValidateStream(Stream stream) - { - if (!stream.CanWrite || !stream.CanSeek) - { - throw new ArgumentException("The specified stream can not seek or is not writable.", "stream"); - } - } - -#if UNMANAGED - - #region Private functions - - private IOutArchive MakeOutArchive(IInStream inArchiveStream) - { - IInArchive inArchive = SevenZipLibraryManager.InArchive( - Formats.InForOutFormats[_archiveFormat], this); - using (ArchiveOpenCallback openCallback = GetArchiveOpenCallback()) - { - ulong checkPos = 1 << 15; - if (inArchive.Open(inArchiveStream, ref checkPos, openCallback) != (int) OperationResult.Ok) - { - if ( - !ThrowException(null, new SevenZipArchiveException("Can not update the archive: Open() failed."))) - { - return null; - } - } - _oldFilesCount = inArchive.GetNumberOfItems(); - } - return (IOutArchive) inArchive; - } - - /// - /// Guaranties the correct work of the SetCompressionProperties function - /// - /// The compression method to check - /// The value indicating whether the specified method is valid for the current ArchiveFormat - private bool MethodIsValid(CompressionMethod method) - { - if (method == CompressionMethod.Default) - { - return true; - } - switch (_archiveFormat) - { - case OutArchiveFormat.Zip: - return method != CompressionMethod.Ppmd; - case OutArchiveFormat.GZip: - return method == CompressionMethod.Deflate; - case OutArchiveFormat.BZip2: - return method == CompressionMethod.BZip2; - case OutArchiveFormat.SevenZip: - return method != CompressionMethod.Deflate && method != CompressionMethod.Deflate64; - case OutArchiveFormat.Tar: - return method == CompressionMethod.Copy; - default: - return true; - } - } - - private bool SwitchIsInCustomParameters(string name) - { - return CustomParameters.ContainsKey(name); - } - - /// - /// Sets the compression properties - /// - private void SetCompressionProperties() - { - switch (_archiveFormat) - { - case OutArchiveFormat.Tar: - break; - default: - ISetProperties setter = CompressionMode == CompressionMode.Create && _updateData.FileNamesToModify == null - ? (ISetProperties) SevenZipLibraryManager.OutArchive( - _archiveFormat, this) - : (ISetProperties) SevenZipLibraryManager.InArchive( - Formats.InForOutFormats[_archiveFormat], this); - if (setter == null) - { - if (!ThrowException(null, - new CompressionFailedException( - "The specified archive format is unsupported."))) - { - return; - } - } - if (_volumeSize > 0 && ArchiveFormat != OutArchiveFormat.SevenZip) - { - throw new CompressionFailedException("Unfortunately, the creation of multivolume non-7Zip archives is not implemented. It will be one day, though."); - } - if (CustomParameters.ContainsKey("x") || CustomParameters.ContainsKey("m")) - { - if ( - !ThrowException(null, - new CompressionFailedException( - "The specified compression parameters are invalid."))) - { - return; - } - } - var names = new List(2 + CustomParameters.Count); - var values = new List(2 + CustomParameters.Count); -#if !WINCE - var sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); - sp.Demand(); -#endif - #region Initialize compression properties - - if (_compressionMethod == CompressionMethod.Default) - { - names.Add(Marshal.StringToBSTR("x")); - values.Add(new PropVariant()); - foreach (var pair in CustomParameters) - { - names.Add(Marshal.StringToBSTR(pair.Key)); - var pv = new PropVariant(); - if (pair.Key == "fb" || pair.Key == "pass" || pair.Key == "d") - { - pv.VarType = VarEnum.VT_UI4; - pv.UInt32Value = Convert.ToUInt32(pair.Value, CultureInfo.InvariantCulture); - } - else - { - pv.VarType = VarEnum.VT_BSTR; - pv.Value = Marshal.StringToBSTR(pair.Value); - } - values.Add(pv); - } - } - else - { - names.Add(Marshal.StringToBSTR("x")); - names.Add(_archiveFormat == OutArchiveFormat.Zip - ? Marshal.StringToBSTR("m") - : Marshal.StringToBSTR("0")); - values.Add(new PropVariant()); - var pv = new PropVariant - { - VarType = VarEnum.VT_BSTR, - Value = Marshal.StringToBSTR(Formats.MethodNames[_compressionMethod]) - }; - values.Add(pv); - foreach (var pair in CustomParameters) - { - names.Add(Marshal.StringToBSTR(pair.Key)); - pv = new PropVariant(); - if (pair.Key == "fb" || pair.Key == "pass" || pair.Key == "d") - { - pv.VarType = VarEnum.VT_UI4; - pv.UInt32Value = Convert.ToUInt32(pair.Value, CultureInfo.InvariantCulture); - } - else - { - pv.VarType = VarEnum.VT_BSTR; - pv.Value = Marshal.StringToBSTR(pair.Value); - } - values.Add(pv); - } - } - - #endregion - - #region Set compression level - - PropVariant clpv = values[0]; - clpv.VarType = VarEnum.VT_UI4; - switch (CompressionLevel) - { - case CompressionLevel.None: - clpv.UInt32Value = 0; - break; - case CompressionLevel.Fast: - clpv.UInt32Value = 1; - break; - case CompressionLevel.Low: - clpv.UInt32Value = 3; - break; - case CompressionLevel.Normal: - clpv.UInt32Value = 5; - break; - case CompressionLevel.High: - clpv.UInt32Value = 7; - break; - case CompressionLevel.Ultra: - clpv.UInt32Value = 9; - break; - } - values[0] = clpv; - - #endregion - - #region Encrypt headers - - if (EncryptHeaders && _archiveFormat == OutArchiveFormat.SevenZip && - !SwitchIsInCustomParameters("he")) - { - names.Add(Marshal.StringToBSTR("he")); - var tmp = new PropVariant {VarType = VarEnum.VT_BSTR, Value = Marshal.StringToBSTR("on")}; - values.Add(tmp); - } - - #endregion - - #region Zip Encryption - - if (_archiveFormat == OutArchiveFormat.Zip && ZipEncryptionMethod != ZipEncryptionMethod.ZipCrypto && - !SwitchIsInCustomParameters("em")) - { - names.Add(Marshal.StringToBSTR("em")); - var tmp = new PropVariant - { - VarType = VarEnum.VT_BSTR, - Value = Marshal.StringToBSTR( -#if !WINCE - Enum.GetName(typeof (ZipEncryptionMethod), ZipEncryptionMethod)) -#else - OpenNETCF.Enum2.GetName(typeof (ZipEncryptionMethod), ZipEncryptionMethod)) -#endif - }; - values.Add(tmp); - } - - #endregion - - var namesHandle = GCHandle.Alloc(names.ToArray(), GCHandleType.Pinned); - var valuesHandle = GCHandle.Alloc(values.ToArray(), GCHandleType.Pinned); - try - { - if (setter != null) //ReSharper - setter.SetProperties(namesHandle.AddrOfPinnedObject(), valuesHandle.AddrOfPinnedObject(), - names.Count); - } - finally - { - namesHandle.Free(); - valuesHandle.Free(); - } - break; - } - } - - /// - /// Finds the common root of file names - /// - /// Array of file names - /// Common root - private static int CommonRoot(ICollection files) - { - var splittedFileNames = new List(files.Count); -#if CS4 - splittedFileNames.AddRange(files.Select(fn => fn.Split(Path.DirectorySeparatorChar))); -#else - foreach (string fn in files) - { - splittedFileNames.Add(fn.Split(Path.DirectorySeparatorChar)); - } -#endif - int minSplitLength = splittedFileNames[0].Length - 1; - if (files.Count > 1) - { - for (int i = 1; i < files.Count; i++) - { - if (minSplitLength > splittedFileNames[i].Length) - { - minSplitLength = splittedFileNames[i].Length; - } - } - } - string res = ""; - for (int i = 0; i < minSplitLength; i++) - { - bool common = true; - for (int j = 1; j < files.Count; j++) - { - if (!(common &= splittedFileNames[j - 1][i] == splittedFileNames[j][i])) - { - break; - } - } - if (common) - { - res += splittedFileNames[0][i] + Path.DirectorySeparatorChar; - } - else - { - break; - } - } - return res.Length; - } - - /// - /// Validates the common root - /// - /// The length of the common root of the file names. - /// Array of file names - private static void CheckCommonRoot(string[] files, ref int commonRootLength) - { - string commonRoot; - try - { - commonRoot = files[0].Substring(0, commonRootLength); - } - catch (ArgumentOutOfRangeException) - { - throw new SevenZipInvalidFileNamesException("invalid common root."); - } - if (commonRoot.EndsWith(new string(Path.DirectorySeparatorChar, 1), StringComparison.CurrentCulture)) - { - commonRoot = commonRoot.Substring(0, commonRootLength - 1); - commonRootLength--; - } -#if CS4 - if (files.Any(fn => !fn.StartsWith(commonRoot, StringComparison.CurrentCulture))) - { - throw new SevenZipInvalidFileNamesException("invalid common root."); - } -#else - foreach (string fn in files) - { - if (!fn.StartsWith(commonRoot, StringComparison.CurrentCulture)) - { - throw new SevenZipInvalidFileNamesException("invalid common root."); - } - } -#endif - } - - /// - /// Ensures that directory directory is not empty - /// - /// Directory name - /// False if is not empty - private static bool RecursiveDirectoryEmptyCheck(string directory) - { - var di = new DirectoryInfo(directory); - if (di.GetFiles().Length > 0) - { - return false; - } - bool empty = true; - foreach (DirectoryInfo cdi in di.GetDirectories()) - { - empty &= RecursiveDirectoryEmptyCheck(cdi.FullName); - if (!empty) - { - return false; - } - } - return true; - } - - /// - /// Makes special FileInfo array for the archive file table. - /// - /// Array of files to pack. - /// The length of the common root of file names - /// The value indicating whether to produce the array for files in a particular directory or just for an array of files. - /// Preserve directory structure. - /// Special FileInfo array for the archive file table. - private static FileInfo[] ProduceFileInfoArray( - string[] files, int commonRootLength, - bool directoryCompress, bool directoryStructure) - { - var fis = new List(files.Length); - string commonRoot = files[0].Substring(0, commonRootLength); - if (directoryCompress) - { -#if CS4 - fis.AddRange(files.Select(fn => new FileInfo(fn))); -#else - foreach (string fn in files) - { - fis.Add(new FileInfo(fn)); - } -#endif - } - else - { - if (!directoryStructure) - { -#if CS4 - fis.AddRange(from fn in files where !Directory.Exists(fn) select new FileInfo(fn)); -#else - foreach (string fn in files) - { - if (!Directory.Exists(fn)) - { - fis.Add(new FileInfo(fn)); - } - } -#endif - } - else - { - var fns = new List(files.Length); - CheckCommonRoot(files, ref commonRootLength); - if (commonRootLength > 0) - { - commonRootLength++; - foreach (string f in files) - { - string[] splittedAfn = f.Substring(commonRootLength).Split(Path.DirectorySeparatorChar); - string cfn = commonRoot; - foreach (string t in splittedAfn) { - cfn += Path.DirectorySeparatorChar + t; - if (!fns.Contains(cfn)) - { - fis.Add(new FileInfo(cfn)); - fns.Add(cfn); - } - } - } - } - else - { - foreach (string f in files) - { - string[] splittedAfn = f.Substring(commonRootLength).Split(Path.DirectorySeparatorChar); - string cfn = splittedAfn[0]; - for (int i = 1; i < splittedAfn.Length; i++) - { - cfn += Path.DirectorySeparatorChar + splittedAfn[i]; - if (!fns.Contains(cfn)) - { - fis.Add(new FileInfo(cfn)); - fns.Add(cfn); - } - } - } - } - } - } - return fis.ToArray(); - } - - /// - /// Recursive function for adding files in directory - /// - /// Directory directory - /// List of files - /// Search string, such as "*.txt" - private void AddFilesFromDirectory(string directory, ICollection files, string searchPattern) - { - var di = new DirectoryInfo(directory); - foreach (FileInfo fi in di.GetFiles(searchPattern)) - { - if (!ScanOnlyWritable) - { - files.Add(fi.FullName); - } - else - { - try - { - using (fi.OpenWrite()) {} - files.Add(fi.FullName); - } - catch (IOException) {} - } - } - foreach (DirectoryInfo cdi in di.GetDirectories()) - { - if (IncludeEmptyDirectories) - { - files.Add(cdi.FullName); - } - AddFilesFromDirectory(cdi.FullName, files, searchPattern); - } - } - - #endregion - - #region GetArchiveUpdateCallback overloads - - /// - /// Performs the common ArchiveUpdateCallback initialization. - /// - /// The ArchiveUpdateCallback instance to initialize. - private void CommonUpdateCallbackInit(ArchiveUpdateCallback auc) - { - auc.FileCompressionStarted += FileCompressionStartedEventProxy; - auc.Compressing += CompressingEventProxy; - auc.FileCompressionFinished += FileCompressionFinishedEventProxy; - auc.DefaultItemName = DefaultItemName; - auc.FastCompression = FastCompression; - } - - private float GetDictionarySize() - { - float dictionarySize = 0.001f; - switch (_compressionMethod) - { - case CompressionMethod.Default: - case CompressionMethod.Lzma: - case CompressionMethod.Lzma2: - switch (CompressionLevel) - { - case CompressionLevel.None: - dictionarySize = 0.001f; - break; - case CompressionLevel.Fast: - dictionarySize = 1.0f / 16 * 7.5f + 4; - break; - case CompressionLevel.Low: - dictionarySize = 7.5f * 11.5f + 4; - break; - case CompressionLevel.Normal: - dictionarySize = 16 * 11.5f + 4; - break; - case CompressionLevel.High: - dictionarySize = 32 * 11.5f + 4; - break; - case CompressionLevel.Ultra: - dictionarySize = 64 * 11.5f + 4; - break; - } - break; - case CompressionMethod.BZip2: - switch (CompressionLevel) - { - case CompressionLevel.None: - dictionarySize = 0; - break; - case CompressionLevel.Fast: - dictionarySize = 0.095f; - break; - case CompressionLevel.Low: - dictionarySize = 0.477f; - break; - case CompressionLevel.Normal: - case CompressionLevel.High: - case CompressionLevel.Ultra: - dictionarySize = 0.858f; - break; - } - break; - case CompressionMethod.Deflate: - case CompressionMethod.Deflate64: - dictionarySize = 32; - break; - case CompressionMethod.Ppmd: - dictionarySize = 16; - break; - } - return dictionarySize; - } - - /// - /// Produces a new instance of ArchiveUpdateCallback class. - /// - /// Array of FileInfo - files to pack - /// Length of the common root of file names - /// The archive password - /// - private ArchiveUpdateCallback GetArchiveUpdateCallback( - FileInfo[] files, int rootLength, string password) - { - SetCompressionProperties(); - var auc = (String.IsNullOrEmpty(password)) - ? new ArchiveUpdateCallback(files, rootLength, this, GetUpdateData(), DirectoryStructure) - { DictionarySize = GetDictionarySize() } - : new ArchiveUpdateCallback(files, rootLength, password, this, GetUpdateData(), DirectoryStructure) - { DictionarySize = GetDictionarySize() }; - CommonUpdateCallbackInit(auc); - return auc; - } - - /// - /// Produces a new instance of ArchiveUpdateCallback class. - /// - /// The archive input stream. - /// The archive password. - /// - private ArchiveUpdateCallback GetArchiveUpdateCallback(Stream inStream, string password) - { - SetCompressionProperties(); - var auc = (String.IsNullOrEmpty(password)) - ? new ArchiveUpdateCallback(inStream, this, GetUpdateData(), DirectoryStructure) - { DictionarySize = GetDictionarySize() } - : new ArchiveUpdateCallback(inStream, password, this, GetUpdateData(), DirectoryStructure) - { DictionarySize = GetDictionarySize() }; - CommonUpdateCallbackInit(auc); - return auc; - } - - /// - /// Produces a new instance of ArchiveUpdateCallback class. - /// - /// Dictionary<name of the archive entry, stream>. - /// The archive password - /// - private ArchiveUpdateCallback GetArchiveUpdateCallback( - Dictionary streamDict, string password) - { - SetCompressionProperties(); - var auc = (String.IsNullOrEmpty(password)) - ? new ArchiveUpdateCallback(streamDict, this, GetUpdateData(), DirectoryStructure) - { DictionarySize = GetDictionarySize() } - : new ArchiveUpdateCallback(streamDict, password, this, GetUpdateData(), DirectoryStructure) - { DictionarySize = GetDictionarySize() }; - CommonUpdateCallbackInit(auc); - return auc; - } - - #endregion - - #region Service "Get" functions - - private void FreeCompressionCallback(ArchiveUpdateCallback callback) - { - callback.FileCompressionStarted -= FileCompressionStartedEventProxy; - callback.Compressing -= CompressingEventProxy; - callback.FileCompressionFinished -= FileCompressionFinishedEventProxy; - } - - private string GetTempArchiveFileName(string archiveName) - { - return Path.Combine(TempFolderPath, Path.GetFileName(archiveName) + ".~"); - } - - private FileStream GetArchiveFileStream(string archiveName) - { - if ((CompressionMode != CompressionMode.Create || _updateData.FileNamesToModify != null) && !File.Exists(archiveName)) - { - if ( - !ThrowException(null, new CompressionFailedException("file \"" + archiveName + "\" does not exist."))) - { - return null; - } - } - return _volumeSize == 0 - ? CompressionMode == CompressionMode.Create && _updateData.FileNamesToModify == null - ? File.Create(archiveName) - : File.Create(GetTempArchiveFileName(archiveName)) - : null; - } - - private void FinalizeUpdate() - { - if (_volumeSize == 0 && (CompressionMode != CompressionMode.Create || _updateData.FileNamesToModify != null)) - { - File.Move(GetTempArchiveFileName(_archiveName), _archiveName); - } - } - - private UpdateData GetUpdateData() - { - if (_updateData.FileNamesToModify == null) - { - var updateData = new UpdateData {Mode = (InternalCompressionMode) ((int) CompressionMode)}; - switch (CompressionMode) - { - case CompressionMode.Create: - updateData.FilesCount = UInt32.MaxValue; - break; - case CompressionMode.Append: - updateData.FilesCount = _oldFilesCount; - break; - } - return updateData; - } - return _updateData; - } - - private ISequentialOutStream GetOutStream(Stream outStream) - { - if (!_compressingFilesOnDisk) - { - return new OutStreamWrapper(outStream, false); - } - if (_volumeSize == 0 || CompressionMode != CompressionMode.Create || _updateData.FileNamesToModify != null) - { - return new OutStreamWrapper(outStream, true); - } - return new OutMultiStreamWrapper(_archiveName, _volumeSize); - } - - private IInStream GetInStream() - { - return File.Exists(_archiveName) && - (CompressionMode != CompressionMode.Create && _compressingFilesOnDisk || _updateData.FileNamesToModify != null) - ? - new InStreamWrapper( - new FileStream(_archiveName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), - true) - : null; - } - - private ArchiveOpenCallback GetArchiveOpenCallback() - { - return String.IsNullOrEmpty(Password) - ? - new ArchiveOpenCallback(_archiveName) - : - new ArchiveOpenCallback(_archiveName, Password); - } - - #endregion - - #region Core public Members - - #region Events - - /// - /// Occurs when the next file is going to be packed. - /// - /// Occurs when 7-zip engine requests for an input stream for the next file to pack it - public event EventHandler FileCompressionStarted; - - /// - /// Occurs when the current file was compressed. - /// - public event EventHandler FileCompressionFinished; - - /// - /// Occurs when data are being compressed - /// - /// Use this event for accurate progress handling and various ProgressBar.StepBy(e.PercentDelta) routines - public event EventHandler Compressing; - - /// - /// Occurs when all files information was determined and SevenZipCompressor is about to start to compress them. - /// - /// The incoming int value indicates the number of scanned files. - public event EventHandler FilesFound; - - /// - /// Occurs when the compression procedure is finished - /// - public event EventHandler CompressionFinished; - - #region Event proxies - /// - /// Event proxy for FileCompressionStarted. - /// - /// The sender of the event. - /// The event arguments. - private void FileCompressionStartedEventProxy(object sender, FileNameEventArgs e) - { - OnEvent(FileCompressionStarted, e, false); - } - - /// - /// Event proxy for FileCompressionFinished. - /// - /// The sender of the event. - /// The event arguments. - private void FileCompressionFinishedEventProxy(object sender, EventArgs e) - { - OnEvent(FileCompressionFinished, e, false); - } - - /// - /// Event proxy for Compressing. - /// - /// The sender of the event. - /// The event arguments. - private void CompressingEventProxy(object sender, ProgressEventArgs e) - { - OnEvent(Compressing, e, false); - } - - /// - /// Event proxy for FilesFound. - /// - /// The sender of the event. - /// The event arguments. - private void FilesFoundEventProxy(object sender, IntEventArgs e) - { - OnEvent(FilesFound, e, false); - } - #endregion - #endregion - - #region Properties - - /// - /// Gets or sets the archive format - /// - public OutArchiveFormat ArchiveFormat - { - get - { - return _archiveFormat; - } - - set - { - _archiveFormat = value; - if (!MethodIsValid(_compressionMethod)) - { - _compressionMethod = CompressionMethod.Default; - } - } - } - - /// - /// Gets or sets the compression method - /// - public CompressionMethod CompressionMethod - { - get - { - return _compressionMethod; - } - - set - { - _compressionMethod = !MethodIsValid(value) ? CompressionMethod.Default : value; - } - } - - /// - /// Gets or sets the size in bytes of an archive volume (0 for no volumes). - /// - public int VolumeSize - { - get - { - return _volumeSize; - } - - set - { - _volumeSize = value > 0 ? value : 0; - } - } - #endregion - - #region CompressFiles overloads - - /// - /// Packs files into the archive. - /// - /// Array of file names to pack. - /// The archive file name. - public void CompressFiles( - string archiveName, params string[] fileFullNames) - { - CompressFilesEncrypted(archiveName, "", fileFullNames); - } - - /// - /// Packs files into the archive. - /// - /// Array of file names to pack. - /// The archive output stream. - /// Use CompressFiles(string archiveName ... ) overloads for archiving to disk. - public void CompressFiles( - Stream archiveStream, params string[] fileFullNames) - { - CompressFilesEncrypted(archiveStream, "", fileFullNames); - } - - /// - /// Packs files into the archive. - /// - /// Array of file names to pack. - /// The length of the common root of the file names. - /// The archive file name. - public void CompressFiles( - string archiveName, int commonRootLength, params string[] fileFullNames) - { - CompressFilesEncrypted(archiveName, commonRootLength, "", fileFullNames); - } - - /// - /// Packs files into the archive. - /// - /// Array of file names to pack. - /// The length of the common root of the file names. - /// The archive output stream. - /// Use CompressFiles(string archiveName, ... ) overloads for archiving to disk. - public void CompressFiles( - Stream archiveStream, int commonRootLength, params string[] fileFullNames) - { - CompressFilesEncrypted(archiveStream, commonRootLength, "", fileFullNames); - } - - /// - /// Packs files into the archive. - /// - /// Array of file names to pack. - /// The archive file name. - /// The archive password. - public void CompressFilesEncrypted( - string archiveName, string password, params string[] fileFullNames) - { - CompressFilesEncrypted(archiveName, CommonRoot(fileFullNames), password, fileFullNames); - } - - /// - /// Packs files into the archive. - /// - /// Array of file names to pack. - /// The archive output stream. - /// Use CompressFiles( ... string archiveName ... ) overloads for archiving to disk. - /// The archive password. - public void CompressFilesEncrypted( - Stream archiveStream, string password, params string[] fileFullNames) - { - CompressFilesEncrypted(archiveStream, CommonRoot(fileFullNames), password, fileFullNames); - } - - /// - /// Packs files into the archive. - /// - /// Array of file names to pack. - /// The length of the common root of the file names. - /// The archive file name. - /// The archive password. - public void CompressFilesEncrypted( - string archiveName, int commonRootLength, string password, params string[] fileFullNames) - { - _compressingFilesOnDisk = true; - _archiveName = archiveName; - using (FileStream fs = GetArchiveFileStream(archiveName)) - { - if (fs == null) - { - return; - } - CompressFilesEncrypted(fs, commonRootLength, password, fileFullNames); - } - FinalizeUpdate(); - } - - /// - /// Packs files into the archive. - /// - /// Array of file names to pack. - /// The length of the common root of the file names. - /// The archive output stream. - /// Use CompressFiles( ... string archiveName ... ) overloads for archiving to disk. - /// The archive password. - public void CompressFilesEncrypted( - Stream archiveStream, int commonRootLength, string password, params string[] fileFullNames) - { - ClearExceptions(); - if (fileFullNames.Length > 1 && - (_archiveFormat == OutArchiveFormat.BZip2 || _archiveFormat == OutArchiveFormat.GZip || - _archiveFormat == OutArchiveFormat.XZ)) - { - if (!ThrowException(null, - new CompressionFailedException("Can not compress more than one file in this format."))) - { - return; - } - } - if (_volumeSize == 0 || !_compressingFilesOnDisk) - { - ValidateStream(archiveStream); - } - FileInfo[] files = null; - try - { - files = ProduceFileInfoArray(fileFullNames, commonRootLength, _directoryCompress, DirectoryStructure); - } - catch (Exception e) - { - if (!ThrowException(null, e)) - { - return; - } - } - _directoryCompress = false; - if (FilesFound != null) - { - FilesFound(this, new IntEventArgs(fileFullNames.Length)); - } - try - { - ISequentialOutStream sequentialArchiveStream; - using ((sequentialArchiveStream = GetOutStream(archiveStream)) as IDisposable) - { - IInStream inArchiveStream; - using ((inArchiveStream = GetInStream()) as IDisposable) - { - IOutArchive outArchive; - if (CompressionMode == CompressionMode.Create || !_compressingFilesOnDisk) - { - SevenZipLibraryManager.LoadLibrary(this, _archiveFormat); - outArchive = SevenZipLibraryManager.OutArchive(_archiveFormat, this); - } - else - { - // Create IInArchive, read it and convert to IOutArchive - SevenZipLibraryManager.LoadLibrary( - this, Formats.InForOutFormats[_archiveFormat]); - if ((outArchive = MakeOutArchive(inArchiveStream)) == null) - { - return; - } - } - using (var auc = GetArchiveUpdateCallback(files, commonRootLength, password)) - { - try - { - if (files != null) //ReSharper - CheckedExecute( - outArchive.UpdateItems( - sequentialArchiveStream, (uint) files.Length + _oldFilesCount, auc), - SevenZipCompressionFailedException.DEFAULT_MESSAGE, auc); - } - finally - { - FreeCompressionCallback(auc); - } - } - } - } - } - finally - { - if (CompressionMode == CompressionMode.Create || !_compressingFilesOnDisk) - { - SevenZipLibraryManager.FreeLibrary(this, _archiveFormat); - } - else - { - SevenZipLibraryManager.FreeLibrary(this, Formats.InForOutFormats[_archiveFormat]); - File.Delete(_archiveName); - } - _compressingFilesOnDisk = false; - OnEvent(CompressionFinished, EventArgs.Empty, false); - } - ThrowUserException(); - } - - #endregion - - #region CompressDirectory overloads - -#if !CS4 - /// - /// Recursively packs all files in the specified directory. - /// - /// The directory to compress. - /// The archive file name. - public void CompressDirectory( - string directory, string archiveName) - { - CompressDirectory(directory, archiveName, "", "*", true); - } - - /// - /// Recursively packs all files in the specified directory. - /// - /// The directory to compress. - /// The archive output stream. - /// Use CompressDirectory( ... string archiveName ... ) overloads for archiving to disk. - public void CompressDirectory( - string directory, Stream archiveStream) - { - CompressDirectory(directory, archiveStream, "", "*", true); - } - - /// - /// Recursively packs all files in the specified directory. - /// - /// The directory to compress. - /// The archive file name. - /// The archive password. - public void CompressDirectory( - string directory, string archiveName, string password) - { - CompressDirectory(directory, archiveName, password, "*", true); - } - - /// - /// Recursively packs all files in the specified directory. - /// - /// The directory to compress. - /// The archive output stream. - /// Use CompressDirectory( ... string archiveName ... ) overloads for archiving to disk. - /// The archive password. - public void CompressDirectory( - string directory, Stream archiveStream, string password) - { - CompressDirectory(directory, archiveStream, password, "*", true); - } - - /// - /// Packs all files in the specified directory. - /// - /// The directory to compress. - /// The archive file name. - /// If true, files will be searched for recursively; otherwise, not. - public void CompressDirectory( - string directory, string archiveName, bool recursion) - { - CompressDirectory(directory, archiveName, "", "*", recursion); - } - - /// - /// Packs all files in the specified directory. - /// - /// The directory to compress. - /// The archive output stream. - /// Use CompressDirectory( ... string archiveName ... ) overloads for archiving to disk. - /// If true, files will be searched for recursively; otherwise, not. - public void CompressDirectory( - string directory, Stream archiveStream, bool recursion) - { - CompressDirectory(directory, archiveStream, "", "*", recursion); - } - - /// - /// Packs all files found by the specified pattern in the specified directory. - /// - /// The directory to compress. - /// The archive file name. - /// Search string, such as "*.txt". - /// If true, files will be searched for recursively; otherwise, not. - public void CompressDirectory( - string directory, string archiveName, - string searchPattern, bool recursion) - { - CompressDirectory(directory, archiveName, "", searchPattern, recursion); - } - - /// - /// Packs all files found by the specified pattern in the specified directory. - /// - /// The directory to compress. - /// The archive output stream. - /// Use CompressDirectory( ... string archiveName ... ) overloads for archiving to disk. - /// Search string, such as "*.txt". - /// If true, files will be searched for recursively; otherwise, not. - public void CompressDirectory( - string directory, Stream archiveStream, - string searchPattern, bool recursion) - { - CompressDirectory(directory, archiveStream, "", searchPattern, recursion); - } - - /// - /// Packs all files in the specified directory. - /// - /// The directory to compress. - /// The archive file name. - /// If true, files will be searched for recursively; otherwise, not. - /// The archive password. - public void CompressDirectory( - string directory, string archiveName, - bool recursion, string password) - { - CompressDirectory(directory, archiveName, password, "*", recursion); - } - - /// - /// Packs all files in the specified directory. - /// - /// The directory to compress. - /// The archive output stream. - /// Use CompressDirectory( ... string archiveName ... ) overloads for archiving to disk. - /// If true, files will be searched for recursively; otherwise, not. - /// The archive password. - public void CompressDirectory( - string directory, Stream archiveStream, - bool recursion, string password) - { - CompressDirectory(directory, archiveStream, password, "*", recursion); - } -#endif - -#if !CS4 - /// - /// Packs all files in the specified directory. - /// - /// The directory to compress. - /// The archive file name. - /// The archive password. - /// Search string, such as "*.txt". - /// If true, files will be searched for recursively; otherwise, not. - public void CompressDirectory( - string directory, string archiveName, - string password, string searchPattern, bool recursion) -#else - /// - /// Packs all files in the specified directory. - /// - /// The directory to compress. - /// The archive file name. - /// The archive password. - /// Search string, such as "*.txt". - /// If true, files will be searched for recursively; otherwise, not. - public void CompressDirectory( - string directory, string archiveName, - string password = "", string searchPattern = "*", bool recursion = true) -#endif - { - _compressingFilesOnDisk = true; - _archiveName = archiveName; - using (FileStream fs = GetArchiveFileStream(archiveName)) - { - if (fs == null && _volumeSize == 0) - { - return; - } - CompressDirectory(directory, fs, password, searchPattern, recursion); - } - FinalizeUpdate(); - } - -#if !CS4 - /// - /// Packs all files in the specified directory. - /// - /// The directory to compress. - /// The archive output stream. - /// Use CompressDirectory( ... string archiveName ... ) overloads for archiving to disk. - /// The archive password. - /// Search string, such as "*.txt". - /// If true, files will be searched for recursively; otherwise, not. - public void CompressDirectory( - string directory, Stream archiveStream, - string password, string searchPattern, bool recursion) -#else - /// - /// Packs all files in the specified directory. - /// - /// The directory to compress. - /// The archive output stream. - /// Use CompressDirectory( ... string archiveName ... ) overloads for archiving to disk. - /// The archive password. - /// Search string, such as "*.txt". - /// If true, files will be searched for recursively; otherwise, not. - public void CompressDirectory( - string directory, Stream archiveStream, - string password = "", string searchPattern = "*", bool recursion = true) -#endif - { - var files = new List(); - if (!Directory.Exists(directory)) - { - throw new ArgumentException("Directory \"" + directory + "\" does not exist!"); - } - if (RecursiveDirectoryEmptyCheck(directory)) - { - throw new SevenZipInvalidFileNamesException("the specified directory is empty!"); - } - if (recursion) - { - AddFilesFromDirectory(directory, files, searchPattern); - } - else - { -#if CS4 - files.AddRange((new DirectoryInfo(directory)).GetFiles(searchPattern).Select(fi => fi.FullName)); -#else - foreach (FileInfo fi in (new DirectoryInfo(directory)).GetFiles(searchPattern)) - { - files.Add(fi.FullName); - } -#endif - } - int commonRootLength = directory.Length; - if (directory.EndsWith("\\", StringComparison.OrdinalIgnoreCase)) - { - directory = directory.Substring(0, directory.Length - 1); - } - else - { - commonRootLength++; - } - if (PreserveDirectoryRoot) - { - var upperRoot = Path.GetDirectoryName(directory); - commonRootLength = upperRoot.Length + - (upperRoot.EndsWith("\\", StringComparison.OrdinalIgnoreCase) ? 0 : 1); - } - _directoryCompress = true; - CompressFilesEncrypted(archiveStream, commonRootLength, password, files.ToArray()); - } - - #endregion - - #region CompressFileDictionary overloads - -#if !CS4 - /// - /// Packs the specified file dictionary. - /// - /// Dictionary<name of the archive entry, file name>. - /// If a file name is null, the corresponding archive entry becomes a directory. - /// The archive file name. - public void CompressFileDictionary( - Dictionary fileDictionary, string archiveName) - { - CompressFileDictionary(fileDictionary, archiveName, ""); - } - - /// - /// Packs the specified file dictionary. - /// - /// Dictionary<name of the archive entry, file name>. - /// If a file name is null, the corresponding archive entry becomes a directory. - /// The archive output stream. - /// Use CompressFileDictionary( ... string archiveName ... ) overloads for archiving to disk. - public void CompressFileDictionary( - Dictionary fileDictionary, Stream archiveStream) - { - CompressFileDictionary(fileDictionary, archiveStream, ""); - } -#endif - -#if !CS4 - /// - /// Packs the specified file dictionary. - /// - /// Dictionary<name of the archive entry, file name>. - /// If a file name is null, the corresponding archive entry becomes a directory. - /// The archive file name. - /// The archive password. - public void CompressFileDictionary( - Dictionary fileDictionary, string archiveName, string password) -#else - /// - /// Packs the specified file dictionary. - /// - /// Dictionary<name of the archive entry, file name>. - /// If a file name is null, the corresponding archive entry becomes a directory. - /// The archive file name. - /// The archive password. - public void CompressFileDictionary( - Dictionary fileDictionary, string archiveName, string password = "") -#endif - { - _compressingFilesOnDisk = true; - _archiveName = archiveName; - using (FileStream fs = GetArchiveFileStream(archiveName)) - { - if (fs == null) - { - return; - } - CompressFileDictionary(fileDictionary, fs, password); - } - FinalizeUpdate(); - } - -#if !CS4 - /// - /// Packs the specified file dictionary. - /// - /// Dictionary<name of the archive entry, file name>. - /// If a file name is null, the corresponding archive entry becomes a directory. - /// The archive output stream. - /// Use CompressStreamDictionary( ... string archiveName ... ) overloads for archiving to disk. - /// The archive password. - public void CompressFileDictionary( - Dictionary fileDictionary, Stream archiveStream, string password) -#else - /// - /// Packs the specified file dictionary. - /// - /// Dictionary<name of the archive entry, file name>. - /// If a file name is null, the corresponding archive entry becomes a directory. - /// The archive output stream. - /// Use CompressStreamDictionary( ... string archiveName ... ) overloads for archiving to disk. - /// The archive password. - public void CompressFileDictionary( - Dictionary fileDictionary, Stream archiveStream, string password = "") -#endif - { - var streamDict = new Dictionary(fileDictionary.Count); - foreach (var pair in fileDictionary) - { - if (pair.Value == null) - { - streamDict.Add(pair.Key, null); - } - else - { - if (!File.Exists(pair.Value)) - { - throw new CompressionFailedException("The file corresponding to the archive entry \"" + pair.Key + "\" does not exist."); - } - streamDict.Add( - pair.Key, - new FileStream(pair.Value, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)); - } - } - //The created streams will be automatically disposed inside. - CompressStreamDictionary(streamDict, archiveStream, password); - } - - #endregion - - #region CompressStreamDictionary overloads -#if !CS4 - /// - /// Packs the specified stream dictionary. - /// - /// Dictionary<name of the archive entry, stream>. - /// If a stream is null, the corresponding string becomes a directory name. - /// The archive file name. - public void CompressStreamDictionary( - Dictionary streamDictionary, string archiveName) - { - CompressStreamDictionary(streamDictionary, archiveName, ""); - } - - /// - /// Packs the specified stream dictionary. - /// - /// Dictionary<name of the archive entry, stream>. - /// If a stream is null, the corresponding string becomes a directory name. - /// The archive output stream. - /// Use CompressStreamDictionary( ... string archiveName ... ) overloads for archiving to disk. - public void CompressStreamDictionary( - Dictionary streamDictionary, Stream archiveStream) - { - CompressStreamDictionary(streamDictionary, archiveStream, ""); - } -#endif - -#if !CS4 - /// - /// Packs the specified stream dictionary. - /// - /// Dictionary<name of the archive entry, stream>. - /// If a stream is null, the corresponding string becomes a directory name. - /// The archive file name. - /// The archive password. - public void CompressStreamDictionary( - Dictionary streamDictionary, string archiveName, string password) -#else - /// - /// Packs the specified stream dictionary. - /// - /// Dictionary<name of the archive entry, stream>. - /// If a stream is null, the corresponding string becomes a directory name. - /// The archive file name. - /// The archive password. - public void CompressStreamDictionary( - Dictionary streamDictionary, string archiveName, string password = "") -#endif - { - _compressingFilesOnDisk = true; - _archiveName = archiveName; - using (FileStream fs = GetArchiveFileStream(archiveName)) - { - if (fs == null) - { - return; - } - CompressStreamDictionary(streamDictionary, fs, password); - } - FinalizeUpdate(); - } - -#if !CS4 - /// - /// Packs the specified stream dictionary. - /// - /// Dictionary<name of the archive entry, stream>. - /// If a stream is null, the corresponding string becomes a directory name. - /// The archive output stream. - /// Use CompressStreamDictionary( ... string archiveName ... ) overloads for archiving to disk. - /// The archive password. - public void CompressStreamDictionary( - Dictionary streamDictionary, Stream archiveStream, string password) -#else - /// - /// Packs the specified stream dictionary. - /// - /// Dictionary<name of the archive entry, stream>. - /// If a stream is null, the corresponding string becomes a directory name. - /// The archive output stream. - /// Use CompressStreamDictionary( ... string archiveName ... ) overloads for archiving to disk. - /// The archive password. - public void CompressStreamDictionary( - Dictionary streamDictionary, Stream archiveStream, string password = "") -#endif - { - ClearExceptions(); - if (streamDictionary.Count > 1 && - (_archiveFormat == OutArchiveFormat.BZip2 || _archiveFormat == OutArchiveFormat.GZip || - _archiveFormat == OutArchiveFormat.XZ)) - { - if (!ThrowException(null, - new CompressionFailedException("Can not compress more than one file/stream in this format."))) - { - return; - } - } - if (_volumeSize == 0 || !_compressingFilesOnDisk) - { - ValidateStream(archiveStream); - } -#if CS4 - if (streamDictionary.Where( - pair => pair.Value != null && (!pair.Value.CanSeek || !pair.Value.CanRead)).Any( - pair => !ThrowException(null, - new ArgumentException("The specified stream dictionary contains an invalid stream corresponding to the archive entry \"" - + pair.Key + "\".", "streamDictionary")))) { - return; - } -#else - foreach (var pair in streamDictionary) - { - if (pair.Value != null && (!pair.Value.CanSeek || !pair.Value.CanRead)) - { - if (!ThrowException(null, new ArgumentException( - "The specified stream dictionary contains an invalid stream corresponding to the archive entry \"" + pair.Key + "\".", - "streamDictionary"))) - { - return; - } - } - } -#endif - try - { - ISequentialOutStream sequentialArchiveStream; - using ((sequentialArchiveStream = GetOutStream(archiveStream)) as IDisposable) - { - IInStream inArchiveStream; - using ((inArchiveStream = GetInStream()) as IDisposable) - { - IOutArchive outArchive; - if (CompressionMode == CompressionMode.Create || !_compressingFilesOnDisk) - { - SevenZipLibraryManager.LoadLibrary(this, _archiveFormat); - outArchive = SevenZipLibraryManager.OutArchive(_archiveFormat, this); - } - else - { - // Create IInArchive, read it and convert to IOutArchive - SevenZipLibraryManager.LoadLibrary( - this, Formats.InForOutFormats[_archiveFormat]); - if ((outArchive = MakeOutArchive(inArchiveStream)) == null) - { - return; - } - } - using (ArchiveUpdateCallback auc = GetArchiveUpdateCallback( - streamDictionary, password)) - { - try - { - CheckedExecute(outArchive.UpdateItems(sequentialArchiveStream, - (uint)streamDictionary.Count + _oldFilesCount, auc), - SevenZipCompressionFailedException.DEFAULT_MESSAGE, auc); - } - finally - { - FreeCompressionCallback(auc); - } - } - } - } - } - finally - { - if (CompressionMode == CompressionMode.Create || !_compressingFilesOnDisk) - { - SevenZipLibraryManager.FreeLibrary(this, _archiveFormat); - } - else - { - SevenZipLibraryManager.FreeLibrary(this, Formats.InForOutFormats[_archiveFormat]); - File.Delete(_archiveName); - } - _compressingFilesOnDisk = false; - OnEvent(CompressionFinished, EventArgs.Empty, false); - } - ThrowUserException(); - } - - #endregion - - #region CompressStream overloads - -#if !CS4 - /// - /// Compresses the specified stream. - /// - /// The source uncompressed stream. - /// The destination compressed stream. - /// ArgumentException: at least one of the specified streams is invalid. - public void CompressStream(Stream inStream, Stream outStream) - { - CompressStream(inStream, outStream, ""); - } -#endif - /// - /// Compresses the specified stream. - /// - /// The source uncompressed stream. - /// The destination compressed stream. - /// The archive password. - /// ArgumentException: at least one of the specified streams is invalid. - public void CompressStream(Stream inStream, Stream outStream, string password -#if CS4 - = "" -#endif - ) - { - ClearExceptions(); - if (!inStream.CanSeek || !inStream.CanRead || !outStream.CanWrite) - { - if (!ThrowException(null, new ArgumentException("The specified streams are invalid."))) - { - return; - } - } - try - { - SevenZipLibraryManager.LoadLibrary(this, _archiveFormat); - ISequentialOutStream sequentialArchiveStream; - using ((sequentialArchiveStream = GetOutStream(outStream)) as IDisposable) - { - using (ArchiveUpdateCallback auc = GetArchiveUpdateCallback(inStream, password)) - { - try - { - CheckedExecute( - SevenZipLibraryManager.OutArchive(_archiveFormat, this).UpdateItems( - sequentialArchiveStream, 1, auc), - SevenZipCompressionFailedException.DEFAULT_MESSAGE, auc); - } - finally - { - FreeCompressionCallback(auc); - } - } - } - } - finally - { - SevenZipLibraryManager.FreeLibrary(this, _archiveFormat); - OnEvent(CompressionFinished, EventArgs.Empty, false); - } - ThrowUserException(); - } - - #endregion - - #region ModifyArchive overloads -#if !CS4 - /// - /// Modifies the existing archive (renames files or deletes them). - /// - /// The archive file name. - /// New file names. Null value to delete the corresponding index. - public void ModifyArchive(string archiveName, Dictionary newFileNames) - { - ModifyArchive(archiveName, newFileNames, ""); - } -#endif - - /// - /// Modifies the existing archive (renames files or deletes them). - /// - /// The archive file name. - /// New file names. Null value to delete the corresponding index. - /// The archive password. - public void ModifyArchive(string archiveName, Dictionary newFileNames, string password -#if CS4 - = "" -#endif - ) - { - ClearExceptions(); - if (!SevenZipLibraryManager.ModifyCapable) - { - throw new SevenZipLibraryException("The specified 7zip native library does not support this method."); - } - if (!File.Exists(archiveName)) - { - if (!ThrowException(null, new ArgumentException("The specified archive does not exist.", "archiveName"))) - { - return; - } - } - if (newFileNames == null || newFileNames.Count == 0) - { - if (!ThrowException(null, new ArgumentException("Invalid new file names.", "newFileNames"))) - { - return; - } - } - try - { - using (var extr = new SevenZipExtractor(archiveName)) - { - _updateData = new UpdateData(); - var archiveData = new ArchiveFileInfo[extr.ArchiveFileData.Count]; - extr.ArchiveFileData.CopyTo(archiveData, 0); - _updateData.ArchiveFileData = new List(archiveData); - } - _updateData.FileNamesToModify = newFileNames; - _updateData.Mode = InternalCompressionMode.Modify; - } - catch (SevenZipException e) - { - if (!ThrowException(null, e)) - { - return; - } - } - try - { - ISequentialOutStream sequentialArchiveStream; - _compressingFilesOnDisk = true; - using ((sequentialArchiveStream = GetOutStream(GetArchiveFileStream(archiveName))) as IDisposable) - { - IInStream inArchiveStream; - _archiveName = archiveName; - using ((inArchiveStream = GetInStream()) as IDisposable) - { - IOutArchive outArchive; - // Create IInArchive, read it and convert to IOutArchive - SevenZipLibraryManager.LoadLibrary( - this, Formats.InForOutFormats[_archiveFormat]); - if ((outArchive = MakeOutArchive(inArchiveStream)) == null) - { - return; - } - using (ArchiveUpdateCallback auc = GetArchiveUpdateCallback(null, 0, password)) - { - UInt32 deleteCount = 0; - if (_updateData.FileNamesToModify != null) - { -#if CS4 // System.Linq of C# 4 is great - deleteCount = (UInt32)_updateData.FileNamesToModify.Sum( - pairDeleted => pairDeleted.Value == null ? 1 : 0); -#else - foreach(var pairDeleted in _updateData.FileNamesToModify) - { - if (pairDeleted.Value == null) - { - deleteCount++; - } - } -#endif - } - try - { - CheckedExecute( - outArchive.UpdateItems( - sequentialArchiveStream, _oldFilesCount - deleteCount, auc), - SevenZipCompressionFailedException.DEFAULT_MESSAGE, auc); - } - finally - { - FreeCompressionCallback(auc); - } - } - } - } - } - finally - { - SevenZipLibraryManager.FreeLibrary(this, Formats.InForOutFormats[_archiveFormat]); - File.Delete(archiveName); - FinalizeUpdate(); - _compressingFilesOnDisk = false; - _updateData.FileNamesToModify = null; - _updateData.ArchiveFileData = null; - OnEvent(CompressionFinished, EventArgs.Empty, false); - } - ThrowUserException(); - } - #endregion - - #endregion - -#endif - - /// - /// Gets or sets the dictionary size for the managed LZMA algorithm. - /// - public static int LzmaDictionarySize - { - get - { - return _lzmaDictionarySize; - } - set - { - _lzmaDictionarySize = value; - } - } - - internal static void WriteLzmaProperties(Encoder encoder) - { - #region LZMA properties definition - - CoderPropId[] propIDs = - { - CoderPropId.DictionarySize, - CoderPropId.PosStateBits, - CoderPropId.LitContextBits, - CoderPropId.LitPosBits, - CoderPropId.Algorithm, - CoderPropId.NumFastBytes, - CoderPropId.MatchFinder, - CoderPropId.EndMarker - }; - object[] properties = - { - _lzmaDictionarySize, - 2, - 3, - 0, - 2, - 256, - "bt4", - false - }; - - #endregion - - encoder.SetCoderProperties(propIDs, properties); - } - - /// - /// Compresses the specified stream with LZMA algorithm (C# inside) - /// - /// The source uncompressed stream - /// The destination compressed stream - /// The length of uncompressed data (null for inStream.Length) - /// The event for handling the code progress - public static void CompressStream(Stream inStream, Stream outStream, int? inLength, - EventHandler codeProgressEvent) - { - if (!inStream.CanRead || !outStream.CanWrite) - { - throw new ArgumentException("The specified streams are invalid."); - } - var encoder = new Encoder(); - WriteLzmaProperties(encoder); - encoder.WriteCoderProperties(outStream); - long streamSize = inLength.HasValue ? inLength.Value : inStream.Length; - for (int i = 0; i < 8; i++) - { - outStream.WriteByte((byte) (streamSize >> (8*i))); - } - encoder.Code(inStream, outStream, -1, -1, new LzmaProgressCallback(streamSize, codeProgressEvent)); - } - - /// - /// Compresses byte array with LZMA algorithm (C# inside) - /// - /// Byte array to compress - /// Compressed byte array - public static byte[] CompressBytes(byte[] data) - { - using (var inStream = new MemoryStream(data)) - { - using (var outStream = new MemoryStream()) - { - var encoder = new Encoder(); - WriteLzmaProperties(encoder); - encoder.WriteCoderProperties(outStream); - long streamSize = inStream.Length; - for (int i = 0; i < 8; i++) - outStream.WriteByte((byte) (streamSize >> (8*i))); - encoder.Code(inStream, outStream, -1, -1, null); - return outStream.ToArray(); - } - } - } - } -#endif -} \ No newline at end of file diff --git a/BizHawk.Util/7z/SevenZipCompressorAsynchronous.cs b/BizHawk.Util/7z/SevenZipCompressorAsynchronous.cs deleted file mode 100644 index 11af46cf73..0000000000 --- a/BizHawk.Util/7z/SevenZipCompressorAsynchronous.cs +++ /dev/null @@ -1,689 +0,0 @@ -namespace SevenZip -{ - using System.Collections.Generic; - using System.IO; -#if DOTNET20 - using System.Threading; -#else - using System.Windows.Threading; -#endif - - partial class SevenZipCompressor - { - #region Delegates - private delegate void CompressFiles1Delegate(string archiveName, string[] fileFullNames); - private delegate void CompressFiles2Delegate(Stream archiveStream, string[] fileFullNames); - private delegate void CompressFiles3Delegate(string archiveName, int commonRootLength, string[] fileFullNames); - private delegate void CompressFiles4Delegate(Stream archiveStream, int commonRootLength, string[] fileFullNames); - - private delegate void CompressFilesEncrypted1Delegate(string archiveName, string password, string[] fileFullNames); - private delegate void CompressFilesEncrypted2Delegate(Stream archiveStream, string password, string[] fileFullNames); - private delegate void CompressFilesEncrypted3Delegate(string archiveName, int commonRootLength, string password, string[] fileFullNames); - private delegate void CompressFilesEncrypted4Delegate(Stream archiveStream, int commonRootLength, string password, string[] fileFullNames); - - private delegate void CompressDirectory1Delegate(string directory, string archiveName); - private delegate void CompressDirectory2Delegate(string directory, Stream archiveStream); - private delegate void CompressDirectory3Delegate(string directory, string archiveName, string password); - private delegate void CompressDirectory4Delegate(string directory, Stream archiveStream, string password); - private delegate void CompressDirectory5Delegate(string directory, string archiveName, - string password, string searchPattern, bool recursion); - private delegate void CompressDirectory6Delegate(string directory, Stream archiveStream, - string password, string searchPattern, bool recursion); - - private delegate void CompressStream1Delegate(Stream inStream, Stream outStream); - private delegate void CompressStream2Delegate(Stream inStream, Stream outStream, string password); - - private delegate void ModifyArchive1Delegate(string archiveName, Dictionary newFileNames); - private delegate void ModifyArchive2Delegate(string archiveName, Dictionary newFileNames, - string password); - #endregion - - #region CompressFiles overloads -#if !DOTNET20 - /// - /// Packs files into the archive asynchronously. - /// - /// Array of file names to pack. - /// The archive file name. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Packs files into the archive asynchronously. - /// - /// Array of file names to pack. - /// The archive file name. -#endif - public void BeginCompressFiles( - string archiveName -#if !DOTNET20 - , DispatcherPriority eventPriority -#endif - , params string[] fileFullNames - ) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new CompressFiles1Delegate(CompressFiles)).BeginInvoke(archiveName, fileFullNames, - AsyncCallbackImplementation, this); - } - -#if !DOTNET20 - /// - /// Packs files into the archive asynchronously. - /// - /// Array of file names to pack. - /// The archive output stream. - /// Use CompressFiles(string archiveName ... ) overloads for archiving to disk. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Packs files into the archive asynchronously. - /// - /// Array of file names to pack. - /// The archive output stream. - /// Use CompressFiles(string archiveName ... ) overloads for archiving to disk. -#endif - public void BeginCompressFiles( - Stream archiveStream -#if !DOTNET20 - , DispatcherPriority eventPriority -#endif - , params string[] fileFullNames - ) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new CompressFiles2Delegate(CompressFiles)).BeginInvoke(archiveStream, fileFullNames, - AsyncCallbackImplementation, this); - } - -#if !DOTNET20 - /// - /// Packs files into the archive asynchronously. - /// - /// Array of file names to pack. - /// The length of the common root of the file names. - /// The archive file name. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Packs files into the archive asynchronously. - /// - /// Array of file names to pack. - /// The length of the common root of the file names. - /// The archive file name. -#endif - public void BeginCompressFiles( - string archiveName, int commonRootLength -#if !DOTNET20 - , DispatcherPriority eventPriority -#endif - , params string[] fileFullNames - ) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new CompressFiles3Delegate(CompressFiles)).BeginInvoke(archiveName, commonRootLength, fileFullNames, - AsyncCallbackImplementation, this); - } - -#if !DOTNET20 - /// - /// Packs files into the archive asynchronously. - /// - /// Array of file names to pack. - /// The length of the common root of the file names. - /// The archive output stream. - /// Use CompressFiles(string archiveName, ... ) overloads for archiving to disk. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Packs files into the archive asynchronously. - /// - /// Array of file names to pack. - /// The length of the common root of the file names. - /// The archive output stream. - /// Use CompressFiles(string archiveName, ... ) overloads for archiving to disk. -#endif - public void BeginCompressFiles( - Stream archiveStream, int commonRootLength -#if !DOTNET20 - , DispatcherPriority eventPriority -#endif - , params string[] fileFullNames - ) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new CompressFiles4Delegate(CompressFiles)).BeginInvoke(archiveStream, commonRootLength, fileFullNames, - AsyncCallbackImplementation, this); - } - -#if !DOTNET20 - /// - /// Packs files into the archive asynchronously. - /// - /// Array of file names to pack. - /// The archive file name - /// The archive password. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Packs files into the archive asynchronously. - /// - /// Array of file names to pack. - /// The archive file name - /// The archive password. -#endif - public void BeginCompressFilesEncrypted( - string archiveName, string password -#if !DOTNET20 - , DispatcherPriority eventPriority -#endif - , params string[] fileFullNames - ) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new CompressFilesEncrypted1Delegate(CompressFilesEncrypted)).BeginInvoke(archiveName, password, fileFullNames, - AsyncCallbackImplementation, this); - } - -#if !DOTNET20 - /// - /// Packs files into the archive asynchronously. - /// - /// Array of file names to pack. - /// The archive output stream. - /// Use CompressFiles( ... string archiveName ... ) overloads for archiving to disk. - /// The archive password. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Packs files into the archive asynchronously. - /// - /// Array of file names to pack. - /// The archive output stream. - /// Use CompressFiles( ... string archiveName ... ) overloads for archiving to disk. - /// The archive password. -#endif - public void BeginCompressFilesEncrypted( - Stream archiveStream, string password -#if !DOTNET20 - , DispatcherPriority eventPriority -#endif - , params string[] fileFullNames - ) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new CompressFilesEncrypted2Delegate(CompressFilesEncrypted)).BeginInvoke(archiveStream, password, fileFullNames, - AsyncCallbackImplementation, this); - } - -#if !DOTNET20 - /// - /// Packs files into the archive asynchronously. - /// - /// Array of file names to pack. - /// The archive file name - /// The archive password. - /// The length of the common root of the file names. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Packs files into the archive asynchronously. - /// - /// Array of file names to pack. - /// The archive file name - /// The archive password. - /// The length of the common root of the file names. -#endif - public void BeginCompressFilesEncrypted( - string archiveName, int commonRootLength, string password -#if !DOTNET20 - , DispatcherPriority eventPriority -#endif - , params string[] fileFullNames - ) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new CompressFilesEncrypted3Delegate(CompressFilesEncrypted)).BeginInvoke(archiveName, commonRootLength, password, - fileFullNames, AsyncCallbackImplementation, this); - } - -#if !DOTNET20 - /// - /// Packs files into the archive asynchronously. - /// - /// Array of file names to pack. - /// The archive output stream. - /// Use CompressFiles( ... string archiveName ... ) overloads for archiving to disk. - /// The archive password. - /// The length of the common root of the file names. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Packs files into the archive asynchronously. - /// - /// Array of file names to pack. - /// The archive output stream. - /// Use CompressFiles( ... string archiveName ... ) overloads for archiving to disk. - /// The archive password. - /// The length of the common root of the file names. -#endif - public void BeginCompressFilesEncrypted( - Stream archiveStream, int commonRootLength, string password -#if !DOTNET20 -, DispatcherPriority eventPriority -#endif - , params string[] fileFullNames - ) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new CompressFilesEncrypted4Delegate(CompressFilesEncrypted)).BeginInvoke(archiveStream, commonRootLength, password, - fileFullNames, AsyncCallbackImplementation, this); - } - #endregion - - #region BeginCompressDirectory overloads - -#if !CS4 -#if !DOTNET20 - /// - /// Recursively packs all files in the specified directory. - /// - /// The directory to compress. - /// The archive file name. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Recursively packs all files in the specified directory. - /// - /// The directory to compress. - /// The archive file name. -#endif - public void BeginCompressDirectory( - string directory, string archiveName -#if !DOTNET20 - , DispatcherPriority eventPriority -#endif - ) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new CompressDirectory1Delegate(CompressDirectory)).BeginInvoke(directory, archiveName, - AsyncCallbackImplementation, this); - } - -#if !DOTNET20 - /// - /// Recursively packs all files in the specified directory. - /// - /// The directory to compress. - /// The archive output stream. - /// Use CompressDirectory( ... string archiveName ... ) overloads for archiving to disk. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Recursively packs all files in the specified directory. - /// - /// The directory to compress. - /// The archive output stream. - /// Use CompressDirectory( ... string archiveName ... ) overloads for archiving to disk. -#endif - public void BeginCompressDirectory( - string directory, Stream archiveStream -#if !DOTNET20 - , DispatcherPriority eventPriority -#endif - ) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new CompressDirectory2Delegate(CompressDirectory)).BeginInvoke(directory, archiveStream, - AsyncCallbackImplementation, this); - } - -#if !DOTNET20 - /// - /// Recursively packs all files in the specified directory. - /// - /// The directory to compress. - /// The archive file name. - /// The archive password. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Recursively packs all files in the specified directory. - /// - /// The directory to compress. - /// The archive file name. - /// The archive password. -#endif - public void BeginCompressDirectory( - string directory, string archiveName, string password -#if !DOTNET20 - , DispatcherPriority eventPriority -#endif - ) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new CompressDirectory3Delegate(CompressDirectory)).BeginInvoke(directory, archiveName, - password, AsyncCallbackImplementation, this); - } - -#if !DOTNET20 - /// - /// Recursively packs all files in the specified directory. - /// - /// The directory to compress. - /// The archive output stream. - /// Use CompressDirectory( ... string archiveName ... ) overloads for archiving to disk. - /// The archive password. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Recursively packs all files in the specified directory. - /// - /// The directory to compress. - /// The archive output stream. - /// Use CompressDirectory( ... string archiveName ... ) overloads for archiving to disk. - /// The archive password. -#endif - public void BeginCompressDirectory( - string directory, Stream archiveStream, string password -#if !DOTNET20 - , DispatcherPriority eventPriority -#endif - ) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new CompressDirectory4Delegate(CompressDirectory)).BeginInvoke(directory, archiveStream, - password, AsyncCallbackImplementation, this); - } -#endif - -#if !DOTNET20 - /// - /// Packs all files in the specified directory asynchronously. - /// - /// The directory to compress. - /// The archive file name. - /// The archive password. - /// Search string, such as "*.txt". - /// If true, files will be searched for recursively; otherwise, not. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Packs all files in the specified directory asynchronously. - /// - /// The directory to compress. - /// The archive file name. - /// The archive password. - /// Search string, such as "*.txt". - /// If true, files will be searched for recursively; otherwise, not. -#endif - public void BeginCompressDirectory(string directory, string archiveName, - string password -#if CS4 - = "" -#endif - , string searchPattern -#if CS4 - = "*" -#endif - , bool recursion -#if CS4 - = true -#endif -#if !DOTNET20 - , DispatcherPriority eventPriority -#if CS4 - = DispatcherPriority.Normal -#endif -#endif -) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new CompressDirectory5Delegate(CompressDirectory)).BeginInvoke(directory, archiveName, - password, searchPattern, recursion, AsyncCallbackImplementation, this); - } - -#if !DOTNET20 - /// - /// Packs all files in the specified directory asynchronously. - /// - /// The directory to compress. - /// The archive output stream. - /// Use CompressDirectory( ... string archiveName ... ) overloads for archiving to disk. - /// The archive password. - /// Search string, such as "*.txt". - /// If true, files will be searched for recursively; otherwise, not. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Packs all files in the specified directory asynchronously. - /// - /// The directory to compress. - /// The archive output stream. - /// Use CompressDirectory( ... string archiveName ... ) overloads for archiving to disk. - /// The archive password. - /// Search string, such as "*.txt". - /// If true, files will be searched for recursively; otherwise, not. -#endif - public void BeginCompressDirectory(string directory, Stream archiveStream, - string password -#if CS4 - = "" -#endif - , string searchPattern -#if CS4 - = "*" -#endif - , bool recursion -#if CS4 - = true -#endif -#if !DOTNET20 - , DispatcherPriority eventPriority -#if CS4 - = DispatcherPriority.Normal -#endif -#endif - ) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new CompressDirectory6Delegate(CompressDirectory)).BeginInvoke(directory, archiveStream, - password, searchPattern, recursion, AsyncCallbackImplementation, this); - } -#endregion - - #region BeginCompressStream overloads -#if !CS4 -#if !DOTNET20 - /// - /// Compresses the specified stream. - /// - /// The source uncompressed stream. - /// The destination compressed stream. - /// ArgumentException: at least one of the specified streams is invalid. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Compresses the specified stream. - /// - /// The source uncompressed stream. - /// The destination compressed stream. - /// ArgumentException: at least one of the specified streams is invalid. -#endif - public void BeginCompressStream(Stream inStream, Stream outStream -#if !DOTNET20 - , DispatcherPriority eventPriority -#endif - ) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new CompressStream1Delegate(CompressStream)).BeginInvoke(inStream, outStream, AsyncCallbackImplementation, this); - } -#endif - -#if !DOTNET20 - /// - /// Compresses the specified stream. - /// - /// The source uncompressed stream. - /// The destination compressed stream. - /// The archive password. - /// ArgumentException: at least one of the specified streams is invalid. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Compresses the specified stream. - /// - /// The source uncompressed stream. - /// The destination compressed stream. - /// The archive password. - /// ArgumentException: at least one of the specified streams is invalid. -#endif - public void BeginCompressStream(Stream inStream, Stream outStream, string password -#if !DOTNET20 - , DispatcherPriority eventPriority -#if CS4 - = DispatcherPriority.Normal -#endif -#endif - ) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new CompressStream2Delegate(CompressStream)).BeginInvoke(inStream, outStream, password, AsyncCallbackImplementation, this); - - } - #endregion - - #region BeginModifyArchive overloads -#if !CS4 -#if !DOTNET20 - /// - /// Modifies the existing archive asynchronously (renames files or deletes them). - /// - /// The archive file name. - /// New file names. Null value to delete the corresponding index. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Modifies the existing archive asynchronously (renames files or deletes them). - /// - /// The archive file name. - /// New file names. Null value to delete the corresponding index. -#endif - public void BeginModifyArchive(string archiveName, Dictionary newFileNames -#if !DOTNET20 - , DispatcherPriority eventPriority -#endif - ) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new ModifyArchive1Delegate(ModifyArchive)).BeginInvoke(archiveName, newFileNames, AsyncCallbackImplementation, this); - } -#endif - -#if !DOTNET20 - /// - /// Modifies the existing archive asynchronously (renames files or deletes them). - /// - /// The archive file name. - /// New file names. Null value to delete the corresponding index. - /// The archive password. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Modifies the existing archive asynchronously (renames files or deletes them). - /// - /// The archive file name. - /// New file names. Null value to delete the corresponding index. - /// The archive password. -#endif - public void BeginModifyArchive(string archiveName, Dictionary newFileNames, - string password -#if CS4 - = "" -#endif -#if !DOTNET20 - , DispatcherPriority eventPriority -#if CS4 - = DispatcherPriority.Normal -#endif -#endif - ) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new ModifyArchive2Delegate(ModifyArchive)).BeginInvoke(archiveName, newFileNames, password, AsyncCallbackImplementation, this); - } - #endregion - } -} diff --git a/BizHawk.Util/7z/SevenZipExtractor.cs b/BizHawk.Util/7z/SevenZipExtractor.cs deleted file mode 100644 index 90562496b9..0000000000 --- a/BizHawk.Util/7z/SevenZipExtractor.cs +++ /dev/null @@ -1,1374 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Diagnostics; -using System.Globalization; -using System.IO; -#if DOTNET20 -using System.Threading; -#else -using System.Linq; -#endif -using SevenZip.Sdk.Compression.Lzma; -#if MONO -using SevenZip.Mono.COM; -#endif - -namespace SevenZip -{ - /// - /// Class for extracting and getting information about 7-zip archives - /// - public sealed partial class SevenZipExtractor -#if UNMANAGED - : SevenZipBase, IDisposable -#endif - { -#if UNMANAGED - private List _archiveFileData; - private IInArchive _archive; - private IInStream _archiveStream; - private int _offset; - private ArchiveOpenCallback _openCallback; - private string _fileName; - private Stream _inStream; - private long? _packedSize; - private long? _unpackedSize; - private uint? _filesCount; - private bool? _isSolid; - private bool _opened; - private bool _disposed; - private InArchiveFormat _format; - private ReadOnlyCollection _archiveFileInfoCollection; - private ReadOnlyCollection _archiveProperties; - private ReadOnlyCollection _volumeFileNames; - - #region Constructors - /// - /// General initialization function. - /// - /// The archive file name. - private void Init(string archiveFullName) - { - _fileName = archiveFullName; - bool isExecutable; - _format = FileChecker.CheckSignature(archiveFullName, out _offset, out isExecutable); - PreserveDirectoryStructure = true; - SevenZipLibraryManager.LoadLibrary(this, _format); - try - { - _archive = SevenZipLibraryManager.InArchive(_format, this); - } - catch (SevenZipLibraryException) - { - SevenZipLibraryManager.FreeLibrary(this, _format); - throw; - } - if (isExecutable && _format != InArchiveFormat.PE) - { - if (!Check()) - { - CommonDispose(); - _format = InArchiveFormat.PE; - SevenZipLibraryManager.LoadLibrary(this, _format); - try - { - _archive = SevenZipLibraryManager.InArchive(_format, this); - } - catch (SevenZipLibraryException) - { - SevenZipLibraryManager.FreeLibrary(this, _format); - throw; - } - } - } - } - - /// - /// General initialization function. - /// - /// The stream to read the archive from. - private void Init(Stream stream) - { - ValidateStream(stream); - bool isExecutable; - _format = FileChecker.CheckSignature(stream, out _offset, out isExecutable); - PreserveDirectoryStructure = true; - SevenZipLibraryManager.LoadLibrary(this, _format); - try - { - _inStream = new ArchiveEmulationStreamProxy(stream, _offset); - _packedSize = stream.Length; - _archive = SevenZipLibraryManager.InArchive(_format, this); - } - catch (SevenZipLibraryException) - { - SevenZipLibraryManager.FreeLibrary(this, _format); - throw; - } - if (isExecutable && _format != InArchiveFormat.PE) - { - if (!Check()) - { - CommonDispose(); - _format = InArchiveFormat.PE; - try - { - _inStream = new ArchiveEmulationStreamProxy(stream, _offset); - _packedSize = stream.Length; - _archive = SevenZipLibraryManager.InArchive(_format, this); - } - catch (SevenZipLibraryException) - { - SevenZipLibraryManager.FreeLibrary(this, _format); - throw; - } - } - } - } - - /// - /// Initializes a new instance of SevenZipExtractor class. - /// - /// The stream to read the archive from. - /// Use SevenZipExtractor(string) to extract from disk, though it is not necessary. - /// The archive format is guessed by the signature. - public SevenZipExtractor(Stream archiveStream) - { - Init(archiveStream); - } - - /// - /// Initializes a new instance of SevenZipExtractor class - /// - /// The archive full file name - public SevenZipExtractor(string archiveFullName) - { - Init(archiveFullName); - } - - /// - /// Initializes a new instance of SevenZipExtractor class. - /// - /// The archive full file name. - /// Password for an encrypted archive. - public SevenZipExtractor(string archiveFullName, string password) - : base(password) - { - Init(archiveFullName); - } - - /// - /// Initializes a new instance of SevenZipExtractor class. - /// - /// The stream to read the archive from. - /// Password for an encrypted archive. - /// The archive format is guessed by the signature. - public SevenZipExtractor( - Stream archiveStream, string password) - : base(password) - { - Init(archiveStream); - } - - #endregion - - #region Properties - - /// - /// Gets or sets archive full file name - /// - public string FileName - { - get - { - DisposedCheck(); - return _fileName; - } - } - - /// - /// Gets the size of the archive file - /// - public long PackedSize - { - get - { - DisposedCheck(); - return _packedSize.HasValue - ? - _packedSize.Value - : - _fileName != null - ? - (new FileInfo(_fileName)).Length - : - -1; - } - } - - /// - /// Gets the size of unpacked archive data - /// - public long UnpackedSize - { - get - { - DisposedCheck(); - if (!_unpackedSize.HasValue) - { - return -1; - } - return _unpackedSize.Value; - } - } - - /// - /// Gets a value indicating whether the archive is solid - /// - public bool IsSolid - { - get - { - DisposedCheck(); - if (!_isSolid.HasValue) - { - GetArchiveInfo(true); - } - if (_isSolid != null) - { - return _isSolid.Value; - } - throw new SevenZipException("_isSolid == null"); - } - } - - /// - /// Gets the number of files in the archive - /// - public uint FilesCount - { - get - { - DisposedCheck(); - if (!_filesCount.HasValue) - { - GetArchiveInfo(true); - } - if (_filesCount != null) - { - return _filesCount.Value; - } - throw new SevenZipException("_filesCount == null"); - } - } - - /// - /// Gets archive format - /// - public InArchiveFormat Format - { - get - { - DisposedCheck(); - return _format; - } - } - - /// - /// Gets or sets the value indicatin whether to preserve the directory structure of extracted files. - /// - public bool PreserveDirectoryStructure { get; set; } - #endregion - - /// - /// Checked whether the class was disposed. - /// - /// - private void DisposedCheck() - { - if (_disposed) - { - throw new ObjectDisposedException("SevenZipExtractor"); - } -#if !WINCE - RecreateInstanceIfNeeded(); -#endif - } - - #region Core private functions - - private ArchiveOpenCallback GetArchiveOpenCallback() - { - return _openCallback ?? (_openCallback = String.IsNullOrEmpty(Password) - ? new ArchiveOpenCallback(_fileName) - : new ArchiveOpenCallback(_fileName, Password)); - } - - /// - /// Gets the archive input stream. - /// - /// The archive input wrapper stream. - private IInStream GetArchiveStream(bool dispose) - { - if (_archiveStream != null) - { - if (_archiveStream is DisposeVariableWrapper) - { - (_archiveStream as DisposeVariableWrapper).DisposeStream = dispose; - } - return _archiveStream; - } - - if (_inStream != null) - { - _inStream.Seek(0, SeekOrigin.Begin); - _archiveStream = new InStreamWrapper(_inStream, false); - } - else - { - if (!_fileName.EndsWith(".001", StringComparison.OrdinalIgnoreCase)) - { - _archiveStream = new InStreamWrapper( - new ArchiveEmulationStreamProxy(new FileStream( - _fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), - _offset), - dispose); - } - else - { - _archiveStream = new InMultiStreamWrapper(_fileName, dispose); - _packedSize = (_archiveStream as InMultiStreamWrapper).Length; - } - } - return _archiveStream; - } - - /// - /// Opens the archive and throws exceptions or returns OperationResult.DataError if any error occurs. - /// - /// The IInStream compliant class instance, that is, the input stream. - /// The ArchiveOpenCallback instance. - /// OperationResult.Ok if Open() succeeds. - private OperationResult OpenArchiveInner(IInStream archiveStream, - IArchiveOpenCallback openCallback) - { - ulong checkPos = 1 << 15; - int res = _archive.Open(archiveStream, ref checkPos, openCallback); - return (OperationResult)res; - } - - /// - /// Opens the archive and throws exceptions or returns OperationResult.DataError if any error occurs. - /// - /// The IInStream compliant class instance, that is, the input stream. - /// The ArchiveOpenCallback instance. - /// True if Open() succeeds; otherwise, false. - private bool OpenArchive(IInStream archiveStream, - ArchiveOpenCallback openCallback) - { - if (!_opened) - { - if (OpenArchiveInner(archiveStream, openCallback) != OperationResult.Ok) - { - if (!ThrowException(null, new SevenZipArchiveException())) - { - return false; - } - } - _volumeFileNames = new ReadOnlyCollection(openCallback.VolumeFileNames); - _opened = true; - } - return true; - } - - /// - /// Retrieves all information about the archive. - /// - /// - private void GetArchiveInfo(bool disposeStream) - { - if (_archive == null) - { - if (!ThrowException(null, new SevenZipArchiveException())) - { - return; - } - } - else - { - IInStream archiveStream; - using ((archiveStream = GetArchiveStream(disposeStream)) as IDisposable) - { - var openCallback = GetArchiveOpenCallback(); - if (!_opened) - { - if (!OpenArchive(archiveStream, openCallback)) - { - return; - } - _opened = !disposeStream; - } - _filesCount = _archive.GetNumberOfItems(); - _archiveFileData = new List((int)_filesCount); - if (_filesCount != 0) - { - var data = new PropVariant(); - try - { - #region Getting archive items data - - for (uint i = 0; i < _filesCount; i++) - { - try - { - var fileInfo = new ArchiveFileInfo { Index = (int)i }; - _archive.GetProperty(i, ItemPropId.Path, ref data); - fileInfo.FileName = NativeMethods.SafeCast(data, "[no name]"); - _archive.GetProperty(i, ItemPropId.LastWriteTime, ref data); - fileInfo.LastWriteTime = NativeMethods.SafeCast(data, DateTime.Now); - _archive.GetProperty(i, ItemPropId.CreationTime, ref data); - fileInfo.CreationTime = NativeMethods.SafeCast(data, DateTime.Now); - _archive.GetProperty(i, ItemPropId.LastAccessTime, ref data); - fileInfo.LastAccessTime = NativeMethods.SafeCast(data, DateTime.Now); - _archive.GetProperty(i, ItemPropId.Size, ref data); - fileInfo.Size = NativeMethods.SafeCast(data, 0); - if (fileInfo.Size == 0) - { - fileInfo.Size = NativeMethods.SafeCast(data, 0); - } - _archive.GetProperty(i, ItemPropId.Attributes, ref data); - fileInfo.Attributes = NativeMethods.SafeCast(data, 0); - _archive.GetProperty(i, ItemPropId.IsDirectory, ref data); - fileInfo.IsDirectory = NativeMethods.SafeCast(data, false); - _archive.GetProperty(i, ItemPropId.Encrypted, ref data); - fileInfo.Encrypted = NativeMethods.SafeCast(data, false); - _archive.GetProperty(i, ItemPropId.Crc, ref data); - fileInfo.Crc = NativeMethods.SafeCast(data, 0); - _archive.GetProperty(i, ItemPropId.Comment, ref data); - fileInfo.Comment = NativeMethods.SafeCast(data, ""); - _archiveFileData.Add(fileInfo); - } - catch (InvalidCastException) - { - ThrowException(null, new SevenZipArchiveException("probably archive is corrupted.")); - } - } - - #endregion - - #region Getting archive properties - - uint numProps = _archive.GetNumberOfArchiveProperties(); - var archProps = new List((int)numProps); - for (uint i = 0; i < numProps; i++) - { - string propName; - ItemPropId propId; - ushort varType; - _archive.GetArchivePropertyInfo(i, out propName, out propId, out varType); - _archive.GetArchiveProperty(propId, ref data); - if (propId == ItemPropId.Solid) - { - _isSolid = NativeMethods.SafeCast(data, true); - } - // TODO Add more archive properties - if (PropIdToName.PropIdNames.ContainsKey(propId)) - { - archProps.Add(new ArchiveProperty - { - Name = PropIdToName.PropIdNames[propId], - Value = data.Object - }); - } - else - { - Debug.WriteLine( - "An unknown archive property encountered (code " + - ((int)propId).ToString(CultureInfo.InvariantCulture) + ')'); - } - } - _archiveProperties = new ReadOnlyCollection(archProps); - if (!_isSolid.HasValue && _format == InArchiveFormat.Zip) - { - _isSolid = false; - } - if (!_isSolid.HasValue) - { - _isSolid = true; - } - - #endregion - } - catch (Exception) - { - if (openCallback.ThrowException()) - { - throw; - } - } - } - } - if (disposeStream) - { - _archive.Close(); - _archiveStream = null; - } - _archiveFileInfoCollection = new ReadOnlyCollection(_archiveFileData); - } - } - - /// - /// Ensure that _archiveFileData is loaded. - /// - /// Dispose the archive stream after this operation. - private void InitArchiveFileData(bool disposeStream) - { - if (_archiveFileData == null) - { - GetArchiveInfo(disposeStream); - } - } - - /// - /// Produces an array of indexes from 0 to the maximum value in the specified array - /// - /// The source array - /// The array of indexes from 0 to the maximum value in the specified array - private static uint[] SolidIndexes(uint[] indexes) - { -#if CS4 - int max = indexes.Aggregate(0, (current, i) => Math.Max(current, (int) i)); -#else - int max = 0; - foreach (uint i in indexes) - { - max = Math.Max(max, (int)i); - } -#endif - if (max > 0) - { - max++; - var res = new uint[max]; - for (int i = 0; i < max; i++) - { - res[i] = (uint)i; - } - return res; - } - return indexes; - } - - /// - /// Checkes whether all the indexes are valid. - /// - /// The indexes to check. - /// True is valid; otherwise, false. - private static bool CheckIndexes(params int[] indexes) - { -#if CS4 // Wow, C# 4 is great! - return indexes.All(i => i >= 0); -#else - bool res = true; - foreach (int i in indexes) - { - if (i < 0) - { - res = false; - break; - } - } - return res; -#endif - } - - private void ArchiveExtractCallbackCommonInit(ArchiveExtractCallback aec) - { - aec.Open += ((s, e) => { _unpackedSize = (long)e.TotalSize; }); - aec.FileExtractionStarted += FileExtractionStartedEventProxy; - aec.FileExtractionFinished += FileExtractionFinishedEventProxy; - aec.Extracting += ExtractingEventProxy; - aec.FileExists += FileExistsEventProxy; - } - - /// - /// Gets the IArchiveExtractCallback callback - /// - /// The directory where extract the files - /// The number of files to be extracted - /// The list of actual indexes (solid archives support) - /// The ArchiveExtractCallback callback - private ArchiveExtractCallback GetArchiveExtractCallback(string directory, int filesCount, - List actualIndexes) - { - var aec = String.IsNullOrEmpty(Password) - ? new ArchiveExtractCallback(_archive, directory, filesCount, PreserveDirectoryStructure, actualIndexes, this) - : new ArchiveExtractCallback(_archive, directory, filesCount, PreserveDirectoryStructure, actualIndexes, Password, this); - ArchiveExtractCallbackCommonInit(aec); - return aec; - } - - /// - /// Gets the IArchiveExtractCallback callback - /// - /// The stream where extract the file - /// The file index - /// The number of files to be extracted - /// The ArchiveExtractCallback callback - private ArchiveExtractCallback GetArchiveExtractCallback(Stream stream, uint index, int filesCount) - { - var aec = String.IsNullOrEmpty(Password) - ? new ArchiveExtractCallback(_archive, stream, filesCount, index, this) - : new ArchiveExtractCallback(_archive, stream, filesCount, index, Password, this); - ArchiveExtractCallbackCommonInit(aec); - return aec; - } - - private void FreeArchiveExtractCallback(ArchiveExtractCallback callback) - { - callback.Open -= ((s, e) => { _unpackedSize = (long)e.TotalSize; }); - callback.FileExtractionStarted -= FileExtractionStartedEventProxy; - callback.FileExtractionFinished -= FileExtractionFinishedEventProxy; - callback.Extracting -= ExtractingEventProxy; - callback.FileExists -= FileExistsEventProxy; - } - #endregion -#endif - - /// - /// Checks if the specified stream supports extraction. - /// - /// The stream to check. - private static void ValidateStream(Stream stream) - { - if (stream == null) - { - throw new ArgumentNullException("stream"); - } - if (!stream.CanSeek || !stream.CanRead) - { - throw new ArgumentException("The specified stream can not seek or read.", "stream"); - } - if (stream.Length == 0) - { - throw new ArgumentException("The specified stream has zero length.", "stream"); - } - } - -#if UNMANAGED - - #region IDisposable Members - - private void CommonDispose() - { - if (_opened) - { - try - { - if (_archive != null) - { - _archive.Close(); - } - } - catch (Exception) { } - } - _archive = null; - _archiveFileData = null; - _archiveProperties = null; - _archiveFileInfoCollection = null; - _inStream = null; - if (_openCallback != null) - { - try - { - _openCallback.Dispose(); - } - catch (ObjectDisposedException) { } - _openCallback = null; - } - if (_archiveStream != null) - { - if (_archiveStream is IDisposable) - { - try - { - if (_archiveStream is DisposeVariableWrapper) - { - (_archiveStream as DisposeVariableWrapper).DisposeStream = true; - } - (_archiveStream as IDisposable).Dispose(); - } - catch (ObjectDisposedException) { } - _archiveStream = null; - } - } - SevenZipLibraryManager.FreeLibrary(this, _format); - } - - /// - /// Releases the unmanaged resources used by SevenZipExtractor. - /// - public void Dispose() - { - if (!_disposed) - { - CommonDispose(); - } - _disposed = true; - GC.SuppressFinalize(this); - } - - #endregion - - #region Core public Members - - #region Events - - /// - /// Occurs when a new file is going to be unpacked. - /// - /// Occurs when 7-zip engine requests for an output stream for a new file to unpack in. - public event EventHandler FileExtractionStarted; - - /// - /// Occurs when a file has been successfully unpacked. - /// - public event EventHandler FileExtractionFinished; - - /// - /// Occurs when the archive has been unpacked. - /// - public event EventHandler ExtractionFinished; - - /// - /// Occurs when data are being extracted. - /// - /// Use this event for accurate progress handling and various ProgressBar.StepBy(e.PercentDelta) routines. - public event EventHandler Extracting; - - /// - /// Occurs during the extraction when a file already exists. - /// - public event EventHandler FileExists; - - #region Event proxies - /// - /// Event proxy for FileExtractionStarted. - /// - /// The sender of the event. - /// The event arguments. - private void FileExtractionStartedEventProxy(object sender, FileInfoEventArgs e) - { - OnEvent(FileExtractionStarted, e, true); - } - - /// - /// Event proxy for FileExtractionFinished. - /// - /// The sender of the event. - /// The event arguments. - private void FileExtractionFinishedEventProxy(object sender, FileInfoEventArgs e) - { - OnEvent(FileExtractionFinished, e, true); - } - - /// - /// Event proxy for Extractng. - /// - /// The sender of the event. - /// The event arguments. - private void ExtractingEventProxy(object sender, ProgressEventArgs e) - { - OnEvent(Extracting, e, false); - } - - /// - /// Event proxy for FileExists. - /// - /// The sender of the event. - /// The event arguments. - private void FileExistsEventProxy(object sender, FileOverwriteEventArgs e) - { - OnEvent(FileExists, e, true); - } - #endregion - #endregion - - #region Properties - /// - /// Gets the collection of ArchiveFileInfo with all information about files in the archive - /// - public ReadOnlyCollection ArchiveFileData - { - get - { - DisposedCheck(); - InitArchiveFileData(true); - return _archiveFileInfoCollection; - } - } - - /// - /// Gets the properties for the current archive - /// - public ReadOnlyCollection ArchiveProperties - { - get - { - DisposedCheck(); - InitArchiveFileData(true); - return _archiveProperties; - } - } - - /// - /// Gets the collection of all file names contained in the archive. - /// - /// - /// Each get recreates the collection - /// - public ReadOnlyCollection ArchiveFileNames - { - get - { - DisposedCheck(); - InitArchiveFileData(true); - var fileNames = new List(_archiveFileData.Count); -#if CS4 - fileNames.AddRange(_archiveFileData.Select(afi => afi.FileName)); -#else - foreach (var afi in _archiveFileData) - { - fileNames.Add(afi.FileName); - } -#endif - return new ReadOnlyCollection(fileNames); - } - } - - /// - /// Gets the list of archive volume file names. - /// - public ReadOnlyCollection VolumeFileNames - { - get - { - DisposedCheck(); - InitArchiveFileData(true); - return _volumeFileNames; - } - } - #endregion - - /// - /// Performs the archive integrity test. - /// - /// True is the archive is ok; otherwise, false. - public bool Check() - { - DisposedCheck(); - try - { - InitArchiveFileData(false); - var archiveStream = GetArchiveStream(true); - var openCallback = GetArchiveOpenCallback(); - if (!OpenArchive(archiveStream, openCallback)) - { - return false; - } - using (var aec = GetArchiveExtractCallback("", (int)_filesCount, null)) - { - try - { - CheckedExecute( - _archive.Extract(null, UInt32.MaxValue, 1, aec), - SevenZipExtractionFailedException.DEFAULT_MESSAGE, aec); - } - finally - { - FreeArchiveExtractCallback(aec); - } - } - } - catch (Exception) - { - return false; - } - finally - { - if (_archive != null) - { - _archive.Close(); - } - _archiveStream = null; - _opened = false; - } - return true; - } - - #region ExtractFile overloads - /// - /// Unpacks the file by its name to the specified stream. - /// - /// The file full name in the archive file table. - /// The stream where the file is to be unpacked. - public void ExtractFile(string fileName, Stream stream) - { - DisposedCheck(); - InitArchiveFileData(false); - int index = -1; - foreach (ArchiveFileInfo afi in _archiveFileData) - { - if (afi.FileName == fileName && !afi.IsDirectory) - { - index = afi.Index; - break; - } - } - if (index == -1) - { - if (!ThrowException(null, new ArgumentOutOfRangeException( - "fileName", - "The specified file name was not found in the archive file table."))) - { - return; - } - } - else - { - ExtractFile(index, stream); - } - } - - /// - /// Unpacks the file by its index to the specified stream. - /// - /// Index in the archive file table. - /// The stream where the file is to be unpacked. - public void ExtractFile(int index, Stream stream) - { - DisposedCheck(); - ClearExceptions(); - if (!CheckIndexes(index)) - { - if (!ThrowException(null, new ArgumentException("The index must be more or equal to zero.", "index"))) - { - return; - } - } - if (!stream.CanWrite) - { - if (!ThrowException(null, new ArgumentException("The specified stream can not be written.", "stream"))) - { - return; - } - } - InitArchiveFileData(false); - if (index > _filesCount - 1) - { - if (!ThrowException(null, new ArgumentOutOfRangeException( - "index", "The specified index is greater than the archive files count."))) - { - return; - } - } - var indexes = new[] {(uint) index}; - if (_isSolid.Value) - { - indexes = SolidIndexes(indexes); - } - var archiveStream = GetArchiveStream(false); - var openCallback = GetArchiveOpenCallback(); - if (!OpenArchive(archiveStream, openCallback)) - { - return; - } - try - { - using (var aec = GetArchiveExtractCallback(stream, (uint) index, indexes.Length)) - { - try - { - CheckedExecute( - _archive.Extract(indexes, (uint) indexes.Length, 0, aec), - SevenZipExtractionFailedException.DEFAULT_MESSAGE, aec); - } - finally - { - FreeArchiveExtractCallback(aec); - } - } - } - catch (Exception) - { - if (openCallback.ThrowException()) - { - throw; - } - } - OnEvent(ExtractionFinished, EventArgs.Empty, false); - ThrowUserException(); - } - #endregion - - #region ExtractFiles overloads - /// - /// Unpacks files by their indices to the specified directory. - /// - /// indexes of the files in the archive file table. - /// Directory where the files are to be unpacked. - public void ExtractFiles(string directory, params int[] indexes) - { - DisposedCheck(); - ClearExceptions(); - if (!CheckIndexes(indexes)) - { - if ( - !ThrowException(null, new ArgumentException("The indexes must be more or equal to zero.", "indexes"))) - { - return; - } - } - InitArchiveFileData(false); - - #region Indexes stuff - - var uindexes = new uint[indexes.Length]; - for (int i = 0; i < indexes.Length; i++) - { - uindexes[i] = (uint) indexes[i]; - } -#if CS4 - if (uindexes.Where(i => i >= _filesCount).Any( - i => !ThrowException(null, - new ArgumentOutOfRangeException("indexes", - "Index must be less than " + - _filesCount.Value.ToString( - CultureInfo.InvariantCulture) + "!")))) - { - return; - } -#else - foreach (uint i in uindexes) - { - if (i >= _filesCount) - { - if (!ThrowException(null, - new ArgumentOutOfRangeException("indexes", - "Index must be less than " + - _filesCount.Value.ToString( - CultureInfo.InvariantCulture) + "!"))) - { - return; - } - } - } -#endif - var origIndexes = new List(uindexes); - origIndexes.Sort(); - uindexes = origIndexes.ToArray(); - if (_isSolid.Value) - { - uindexes = SolidIndexes(uindexes); - } - - #endregion - - try - { - IInStream archiveStream; - using ((archiveStream = GetArchiveStream(origIndexes.Count != 1)) as IDisposable) - { - var openCallback = GetArchiveOpenCallback(); - if (!OpenArchive(archiveStream, openCallback)) - { - return; - } - try - { - using (var aec = GetArchiveExtractCallback(directory, (int) _filesCount, origIndexes)) - { - try - { - CheckedExecute( - _archive.Extract(uindexes, (uint) uindexes.Length, 0, aec), - SevenZipExtractionFailedException.DEFAULT_MESSAGE, aec); - } - finally - { - FreeArchiveExtractCallback(aec); - } - } - } - catch (Exception) - { - if (openCallback.ThrowException()) - { - throw; - } - } - } - OnEvent(ExtractionFinished, EventArgs.Empty, false); - } - finally - { - if (origIndexes.Count > 1) - { - if (_archive != null) - { - _archive.Close(); - } - _archiveStream = null; - _opened = false; - } - } - ThrowUserException(); - } - - /// - /// Unpacks files by their full names to the specified directory. - /// - /// Full file names in the archive file table. - /// Directory where the files are to be unpacked. - public void ExtractFiles(string directory, params string[] fileNames) - { - DisposedCheck(); - InitArchiveFileData(false); - var indexes = new List(fileNames.Length); - var archiveFileNames = new List(ArchiveFileNames); - foreach (string fn in fileNames) - { - if (!archiveFileNames.Contains(fn)) - { - if ( - !ThrowException(null, - new ArgumentOutOfRangeException("fileNames", - "File \"" + fn + - "\" was not found in the archive file table."))) - { - return; - } - } - else - { - foreach (ArchiveFileInfo afi in _archiveFileData) - { - if (afi.FileName == fn && !afi.IsDirectory) - { - indexes.Add(afi.Index); - break; - } - } - } - } - ExtractFiles(directory, indexes.ToArray()); - } - - /// - /// Extracts files from the archive, giving a callback the choice what - /// to do with each file. The order of the files is given by the archive. - /// 7-Zip (and any other solid) archives are NOT supported. - /// - /// The callback to call for each file in the archive. - public void ExtractFiles(ExtractFileCallback extractFileCallback) - { - DisposedCheck(); - InitArchiveFileData(false); - if (IsSolid) - { - // solid strategy - } - else - { - foreach (ArchiveFileInfo archiveFileInfo in ArchiveFileData) - { - var extractFileCallbackArgs = new ExtractFileCallbackArgs(archiveFileInfo); - extractFileCallback(extractFileCallbackArgs); - if (extractFileCallbackArgs.CancelExtraction) - { - break; - } - if (extractFileCallbackArgs.ExtractToStream != null || extractFileCallbackArgs.ExtractToFile != null) - { - bool callDone = false; - try - { - if (extractFileCallbackArgs.ExtractToStream != null) - { - ExtractFile(archiveFileInfo.Index, extractFileCallbackArgs.ExtractToStream); - } - else - { - using (var file = new FileStream(extractFileCallbackArgs.ExtractToFile, FileMode.CreateNew, - FileAccess.Write, FileShare.None, 8192)) - { - ExtractFile(archiveFileInfo.Index, file); - } - } - callDone = true; - } - catch (Exception ex) - { - extractFileCallbackArgs.Exception = ex; - extractFileCallbackArgs.Reason = ExtractFileCallbackReason.Failure; - extractFileCallback(extractFileCallbackArgs); - if (!ThrowException(null, ex)) - { - return; - } - } - if (callDone) - { - extractFileCallbackArgs.Reason = ExtractFileCallbackReason.Done; - extractFileCallback(extractFileCallbackArgs); - } - } - } - } - } - #endregion - - /// - /// Unpacks the whole archive to the specified directory. - /// - /// The directory where the files are to be unpacked. - public void ExtractArchive(string directory) - { - DisposedCheck(); - ClearExceptions(); - InitArchiveFileData(false); - try - { - IInStream archiveStream; - using ((archiveStream = GetArchiveStream(true)) as IDisposable) - { - var openCallback = GetArchiveOpenCallback(); - if (!OpenArchive(archiveStream, openCallback)) - { - return; - } - try - { - using (var aec = GetArchiveExtractCallback(directory, (int) _filesCount, null)) - { - try - { - CheckedExecute( - _archive.Extract(null, UInt32.MaxValue, 0, aec), - SevenZipExtractionFailedException.DEFAULT_MESSAGE, aec); - OnEvent(ExtractionFinished, EventArgs.Empty, false); - } - finally - { - FreeArchiveExtractCallback(aec); - } - } - } - catch (Exception) - { - if (openCallback.ThrowException()) - { - throw; - } - } - } - } - finally - { - if (_archive != null) - { - _archive.Close(); - } - _archiveStream = null; - _opened = false; - } - ThrowUserException(); - } - #endregion - -#endif - - #region LZMA SDK functions - - internal static byte[] GetLzmaProperties(Stream inStream, out long outSize) - { - var lzmAproperties = new byte[5]; - if (inStream.Read(lzmAproperties, 0, 5) != 5) - { - throw new LzmaException(); - } - outSize = 0; - for (int i = 0; i < 8; i++) - { - int b = inStream.ReadByte(); - if (b < 0) - { - throw new LzmaException(); - } - outSize |= ((long) (byte) b) << (i << 3); - } - return lzmAproperties; - } - - /// - /// Decompress the specified stream (C# inside) - /// - /// The source compressed stream - /// The destination uncompressed stream - /// The length of compressed data (null for inStream.Length) - /// The event for handling the code progress - public static void DecompressStream(Stream inStream, Stream outStream, int? inLength, - EventHandler codeProgressEvent) - { - if (!inStream.CanRead || !outStream.CanWrite) - { - throw new ArgumentException("The specified streams are invalid."); - } - var decoder = new Decoder(); - long outSize, inSize = (inLength.HasValue ? inLength.Value : inStream.Length) - inStream.Position; - decoder.SetDecoderProperties(GetLzmaProperties(inStream, out outSize)); - decoder.Code( - inStream, outStream, inSize, outSize, - new LzmaProgressCallback(inSize, codeProgressEvent)); - } - - /// - /// Decompress byte array compressed with LZMA algorithm (C# inside) - /// - /// Byte array to decompress - /// Decompressed byte array - public static byte[] ExtractBytes(byte[] data) - { - using (var inStream = new MemoryStream(data)) - { - var decoder = new Decoder(); - inStream.Seek(0, 0); - using (var outStream = new MemoryStream()) - { - long outSize; - decoder.SetDecoderProperties(GetLzmaProperties(inStream, out outSize)); - decoder.Code(inStream, outStream, inStream.Length - inStream.Position, outSize, null); - return outStream.ToArray(); - } - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BizHawk.Util/7z/SevenZipExtractorAsynchronous.cs b/BizHawk.Util/7z/SevenZipExtractorAsynchronous.cs deleted file mode 100644 index bffc19cc5e..0000000000 --- a/BizHawk.Util/7z/SevenZipExtractorAsynchronous.cs +++ /dev/null @@ -1,294 +0,0 @@ -namespace SevenZip -{ - using System; - using System.IO; -#if DOTNET20 - using System.Threading; -#else - using System.Windows.Threading; -#endif - - partial class SevenZipExtractor - { - #region Asynchronous core methods - - /// - /// Recreates the instance of the SevenZipExtractor class. - /// Used in asynchronous methods. - /// - private void RecreateInstanceIfNeeded() - { - if (NeedsToBeRecreated) - { - NeedsToBeRecreated = false; - Stream backupStream = null; - string backupFileName = null; - if (String.IsNullOrEmpty(_fileName)) - { - backupStream = _inStream; - } - else - { - backupFileName = _fileName; - } - CommonDispose(); - if (backupStream == null) - { - Init(backupFileName); - } - else - { - Init(backupStream); - } - } - } - - internal override void SaveContext( -#if !DOTNET20 - DispatcherPriority eventPriority -#if CS4 - = DispatcherPriority.Normal -#endif -#endif -) - { - DisposedCheck(); - base.SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - - } - - #endregion - - #region Delegates - /// - /// The delegate to use in BeginExtractArchive. - /// - /// The directory where the files are to be unpacked. - private delegate void ExtractArchiveDelegate(string directory); - - /// - /// The delegate to use in BeginExtractFile (by file name). - /// - /// The file full name in the archive file table. - /// The stream where the file is to be unpacked. - private delegate void ExtractFileByFileNameDelegate(string fileName, Stream stream); - - /// - /// The delegate to use in BeginExtractFile (by index). - /// - /// Index in the archive file table. - /// The stream where the file is to be unpacked. - private delegate void ExtractFileByIndexDelegate(int index, Stream stream); - - /// - /// The delegate to use in BeginExtractFiles(string directory, params int[] indexes). - /// - /// indexes of the files in the archive file table. - /// Directory where the files are to be unpacked. - private delegate void ExtractFiles1Delegate(string directory, int[] indexes); - - /// - /// The delegate to use in BeginExtractFiles(string directory, params string[] fileNames). - /// - /// Full file names in the archive file table. - /// Directory where the files are to be unpacked. - private delegate void ExtractFiles2Delegate(string directory, string[] fileNames); - - /// - /// The delegate to use in BeginExtractFiles(ExtractFileCallback extractFileCallback). - /// - /// The callback to call for each file in the archive. - private delegate void ExtractFiles3Delegate(ExtractFileCallback extractFileCallback); - #endregion - -#if !DOTNET20 - /// - /// Unpacks the whole archive asynchronously to the specified directory name at the specified priority. - /// - /// The directory where the files are to be unpacked. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Unpacks the whole archive asynchronously to the specified directory name at the specified priority. - /// - /// The directory where the files are to be unpacked. -#endif - public void BeginExtractArchive(string directory -#if !DOTNET20 - , DispatcherPriority eventPriority -#if CS4 - = DispatcherPriority.Normal -#endif -#endif -) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new ExtractArchiveDelegate(ExtractArchive)).BeginInvoke(directory, AsyncCallbackImplementation, this); - } - -#if !DOTNET20 - /// - /// Unpacks the file asynchronously by its name to the specified stream. - /// - /// The file full name in the archive file table. - /// The stream where the file is to be unpacked. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Unpacks the file asynchronously by its name to the specified stream. - /// - /// The file full name in the archive file table. - /// The stream where the file is to be unpacked. -#endif - public void BeginExtractFile(string fileName, Stream stream -#if !DOTNET20 - , DispatcherPriority eventPriority -#if CS4 - = DispatcherPriority.Normal -#endif -#endif -) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new ExtractFileByFileNameDelegate(ExtractFile)).BeginInvoke(fileName, stream, AsyncCallbackImplementation, this); - } - -#if !DOTNET20 - /// - /// Unpacks the file asynchronously by its index to the specified stream. - /// - /// Index in the archive file table. - /// The stream where the file is to be unpacked. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Unpacks the file asynchronously by its index to the specified stream. - /// - /// Index in the archive file table. - /// The stream where the file is to be unpacked. -#endif - public void BeginExtractFile(int index, Stream stream -#if !DOTNET20 - , DispatcherPriority eventPriority -#if CS4 - = DispatcherPriority.Normal -#endif -#endif -) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new ExtractFileByIndexDelegate(ExtractFile)).BeginInvoke(index, stream, AsyncCallbackImplementation, this); - } - -#if !DOTNET20 - /// - /// Unpacks files asynchronously by their indices to the specified directory. - /// - /// indexes of the files in the archive file table. - /// Directory where the files are to be unpacked. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Unpacks files asynchronously by their indices to the specified directory. - /// - /// indexes of the files in the archive file table. - /// Directory where the files are to be unpacked. -#endif - public void BeginExtractFiles(string directory -#if !DOTNET20 - , DispatcherPriority eventPriority -#if CS4 - = DispatcherPriority.Normal -#endif -#endif - , params int[] indexes) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new ExtractFiles1Delegate(ExtractFiles)).BeginInvoke(directory, indexes, AsyncCallbackImplementation, this); - } - -#if !DOTNET20 - /// - /// Unpacks files asynchronously by their full names to the specified directory. - /// - /// Full file names in the archive file table. - /// Directory where the files are to be unpacked. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Unpacks files asynchronously by their full names to the specified directory. - /// - /// Full file names in the archive file table. - /// Directory where the files are to be unpacked. -#endif - public void BeginExtractFiles(string directory -#if !DOTNET20 - , DispatcherPriority eventPriority -#if CS4 - = DispatcherPriority.Normal -#endif -#endif - , params string[] fileNames) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new ExtractFiles2Delegate(ExtractFiles)).BeginInvoke(directory, fileNames, AsyncCallbackImplementation, this); - } - -#if !DOTNET20 - /// - /// Extracts files from the archive asynchronously, giving a callback the choice what - /// to do with each file. The order of the files is given by the archive. - /// 7-Zip (and any other solid) archives are NOT supported. - /// - /// The callback to call for each file in the archive. - /// The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked. -#else - /// - /// Extracts files from the archive asynchronously, giving a callback the choice what - /// to do with each file. The order of the files is given by the archive. - /// 7-Zip (and any other solid) archives are NOT supported. - /// - /// The callback to call for each file in the archive. -#endif - public void BeginExtractFiles(ExtractFileCallback extractFileCallback -#if !DOTNET20 - , DispatcherPriority eventPriority -#if CS4 - = DispatcherPriority.Normal -#endif -#endif -) - { - SaveContext( -#if !DOTNET20 - eventPriority -#endif - ); - (new ExtractFiles3Delegate(ExtractFiles)).BeginInvoke(extractFileCallback, AsyncCallbackImplementation, this); - } - } -} diff --git a/BizHawk.Util/7z/SevenZipSfx.cs b/BizHawk.Util/7z/SevenZipSfx.cs deleted file mode 100644 index c02d279fd9..0000000000 --- a/BizHawk.Util/7z/SevenZipSfx.cs +++ /dev/null @@ -1,499 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Reflection; -using System.Text; -using System.Xml; -using System.Xml.Schema; - -namespace SevenZip -{ -#if SFX - using SfxSettings = Dictionary; - - /// - /// Sfx module choice enumeration - /// - public enum SfxModule - { - /// - /// Default module (leave this if unsure) - /// - Default, - /// - /// The simple sfx module by Igor Pavlov with no adjustable parameters - /// - Simple, - /// - /// The installer sfx module by Igor Pavlov - /// - Installer, - /// - /// The extended installer sfx module by Oleg Scherbakov - /// - Extended, - /// - /// The custom sfx module. First you must specify the module file name. - /// - Custom - } - - /// - /// The class for making 7-zip based self-extracting archives. - /// - public class SevenZipSfx - { - private static readonly Dictionary> SfxSupportedModuleNames = - new Dictionary>(3) - { - {SfxModule.Default, new List(1) {"7zxSD_All.sfx"}}, - {SfxModule.Simple, new List(2) {"7z.sfx", "7zCon.sfx"}}, - {SfxModule.Installer, new List(2) {"7zS.sfx", "7zSD.sfx"}}, - { - SfxModule.Extended, - new List(4) {"7zxSD_All.sfx", "7zxSD_Deflate", "7zxSD_LZMA", "7zxSD_PPMd"} - } - }; - - private SfxModule _module = SfxModule.Default; - private string _moduleFileName; - private Dictionary> _sfxCommands; - - /// - /// Initializes a new instance of the SevenZipSfx class. - /// - public SevenZipSfx() - { - _module = SfxModule.Default; - CommonInit(); - } - - /// - /// Initializes a new instance of the SevenZipSfx class. - /// - /// The sfx module to use as a front-end. - public SevenZipSfx(SfxModule module) - { - if (module == SfxModule.Custom) - { - throw new ArgumentException("You must specify the custom module executable.", "module"); - } - _module = module; - CommonInit(); - } - - /// - /// Initializes a new instance of the SevenZipSfx class. - /// - /// - public SevenZipSfx(string moduleFileName) - { - _module = SfxModule.Custom; - ModuleFileName = moduleFileName; - CommonInit(); - } - - /// - /// Gets the sfx module type. - /// - public SfxModule SfxModule - { - get - { - return _module; - } - } - - /// - /// Gets or sets the custom sfx module file name - /// - public string ModuleFileName - { - get - { - return _moduleFileName; - } - - set - { - if (!File.Exists(value)) - { - throw new ArgumentException("The specified file does not exist."); - } - _moduleFileName = value; - _module = SfxModule.Custom; - string sfxName = Path.GetFileName(value); - foreach (SfxModule mod in SfxSupportedModuleNames.Keys) - { - if (SfxSupportedModuleNames[mod].Contains(sfxName)) - { - _module = mod; - } - } - } - } - - private void CommonInit() - { - LoadCommandsFromResource("Configs"); - } - - private static string GetResourceString(string str) - { -#if !WINCE - return "SevenZip.sfx." + str; -#else - return "SevenZipSharpMobile.sfx." + str; -#endif - } - - /// - /// Gets the sfx module enum by the list of supported modules - /// - /// - /// - private static SfxModule GetModuleByName(string name) - { - if (name.IndexOf("7z.sfx", StringComparison.Ordinal) > -1) - { - return SfxModule.Simple; - } - if (name.IndexOf("7zS.sfx", StringComparison.Ordinal) > -1) - { - return SfxModule.Installer; - } - if (name.IndexOf("7zxSD_All.sfx", StringComparison.Ordinal) > -1) - { - return SfxModule.Extended; - } - throw new SevenZipSfxValidationException("The specified configuration is unsupported."); - } - - /// - /// Loads the commands for each supported sfx module configuration - /// - /// The resource name for xml definitions - private void LoadCommandsFromResource(string xmlDefinitions) - { - using (Stream cfg = Assembly.GetExecutingAssembly().GetManifestResourceStream( - GetResourceString(xmlDefinitions + ".xml"))) - { - if (cfg == null) - { - throw new SevenZipSfxValidationException("The configuration \"" + xmlDefinitions + - "\" does not exist."); - } - using (Stream schm = Assembly.GetExecutingAssembly().GetManifestResourceStream( - GetResourceString(xmlDefinitions + ".xsd"))) - { - if (schm == null) - { - throw new SevenZipSfxValidationException("The configuration schema \"" + xmlDefinitions + - "\" does not exist."); - } - var sc = new XmlSchemaSet(); - using (XmlReader scr = XmlReader.Create(schm)) - { - sc.Add(null, scr); - var settings = new XmlReaderSettings {ValidationType = ValidationType.Schema, Schemas = sc}; - string validationErrors = ""; - settings.ValidationEventHandler += - ((s, t) => - { - validationErrors += String.Format(CultureInfo.InvariantCulture, "[{0}]: {1}\n", - t.Severity.ToString(), t.Message); - }); - using (XmlReader rdr = XmlReader.Create(cfg, settings)) - { - _sfxCommands = new Dictionary>(); - rdr.Read(); - rdr.Read(); - rdr.Read(); - rdr.Read(); - rdr.Read(); - rdr.ReadStartElement("sfxConfigs"); - rdr.Read(); - do - { - SfxModule mod = GetModuleByName(rdr["modules"]); - rdr.ReadStartElement("config"); - rdr.Read(); - if (rdr.Name == "id") - { - var cmds = new List(); - _sfxCommands.Add(mod, cmds); - do - { - cmds.Add(rdr["command"]); - rdr.Read(); - rdr.Read(); - } while (rdr.Name == "id"); - rdr.ReadEndElement(); - rdr.Read(); - } - else - { - _sfxCommands.Add(mod, null); - } - } while (rdr.Name == "config"); - } - if (!String.IsNullOrEmpty(validationErrors)) - { - throw new SevenZipSfxValidationException( - "\n" + validationErrors.Substring(0, validationErrors.Length - 1)); - } - _sfxCommands.Add(SfxModule.Default, _sfxCommands[SfxModule.Extended]); - } - } - } - } - - /// - /// Validates the sfx scenario commands. - /// - /// The sfx settings dictionary to validate. - private void ValidateSettings(SfxSettings settings) - { - if (_module == SfxModule.Custom) - { - return; - } - List commands = _sfxCommands[_module]; - if (commands == null) - { - return; - } - var invalidCommands = new List(); - foreach (string command in settings.Keys) - { - if (!commands.Contains(command)) - { - invalidCommands.Add(command); - } - } - if (invalidCommands.Count > 0) - { - var invalidText = new StringBuilder("\nInvalid commands:\n"); - foreach (string str in invalidCommands) - { - invalidText.Append(str); - } - throw new SevenZipSfxValidationException(invalidText.ToString()); - } - } - - /// - /// Gets the stream containing the sfx settings. - /// - /// The sfx settings dictionary. - /// - private static Stream GetSettingsStream(SfxSettings settings) - { - var ms = new MemoryStream(); - byte[] buf = Encoding.UTF8.GetBytes(@";!@Install@!UTF-8!" + '\n'); - ms.Write(buf, 0, buf.Length); - foreach (string command in settings.Keys) - { - buf = - Encoding.UTF8.GetBytes(String.Format(CultureInfo.InvariantCulture, "{0}=\"{1}\"\n", command, - settings[command])); - ms.Write(buf, 0, buf.Length); - } - buf = Encoding.UTF8.GetBytes(@";!@InstallEnd@!"); - ms.Write(buf, 0, buf.Length); - return ms; - } - - private SfxSettings GetDefaultSettings() - { - switch (_module) - { - default: - return null; - case SfxModule.Installer: - var settings = new Dictionary {{"Title", "7-Zip self-extracting archive"}}; - return settings; - case SfxModule.Default: - case SfxModule.Extended: - settings = new Dictionary - { - {"GUIMode", "0"}, - {"InstallPath", "."}, - {"GUIFlags", "128+8"}, - {"ExtractPathTitle", "7-Zip self-extracting archive"}, - {"ExtractPathText", "Specify the path where to extract the files:"} - }; - return settings; - } - } - - /// - /// Writes the whole to the other one. - /// - /// The source stream to read from. - /// The destination stream to wrie to. - private static void WriteStream(Stream src, Stream dest) - { - src.Seek(0, SeekOrigin.Begin); - var buf = new byte[32768]; - int bytesRead; - while ((bytesRead = src.Read(buf, 0, buf.Length)) > 0) - { - dest.Write(buf, 0, bytesRead); - } - } - - /// - /// Makes the self-extracting archive. - /// - /// The archive stream. - /// The name of the self-extracting executable. - public void MakeSfx(Stream archive, string sfxFileName) - { - using (Stream sfxStream = File.Create(sfxFileName)) - { - MakeSfx(archive, GetDefaultSettings(), sfxStream); - } - } - - /// - /// Makes the self-extracting archive. - /// - /// The archive stream. - /// The stream to write the self-extracting executable to. - public void MakeSfx(Stream archive, Stream sfxStream) - { - MakeSfx(archive, GetDefaultSettings(), sfxStream); - } - - /// - /// Makes the self-extracting archive. - /// - /// The archive stream. - /// The sfx settings. - /// The name of the self-extracting executable. - public void MakeSfx(Stream archive, SfxSettings settings, string sfxFileName) - { - using (Stream sfxStream = File.Create(sfxFileName)) - { - MakeSfx(archive, settings, sfxStream); - } - } - - /// - /// Makes the self-extracting archive. - /// - /// The archive stream. - /// The sfx settings. - /// The stream to write the self-extracting executable to. - public void MakeSfx(Stream archive, SfxSettings settings, Stream sfxStream) - { - if (!sfxStream.CanWrite) - { - throw new ArgumentException("The specified output stream can not write.", "sfxStream"); - } - ValidateSettings(settings); - using (Stream sfx = _module == SfxModule.Default - ? Assembly.GetExecutingAssembly().GetManifestResourceStream( - GetResourceString(SfxSupportedModuleNames[_module][0])) - : new FileStream(_moduleFileName, FileMode.Open, FileAccess.Read, - FileShare.ReadWrite)) - { - WriteStream(sfx, sfxStream); - } - if (_module == SfxModule.Custom || _sfxCommands[_module] != null) - { - using (Stream set = GetSettingsStream(settings)) - { - WriteStream(set, sfxStream); - } - } - WriteStream(archive, sfxStream); - } - - /// - /// Makes the self-extracting archive. - /// - /// The archive file name. - /// The name of the self-extracting executable. - public void MakeSfx(string archiveFileName, string sfxFileName) - { - using (Stream sfxStream = File.Create(sfxFileName)) - { - using ( - Stream archive = new FileStream(archiveFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) - ) - { - MakeSfx(archive, GetDefaultSettings(), sfxStream); - } - } - } - - /// - /// Makes the self-extracting archive. - /// - /// The archive file name. - /// The stream to write the self-extracting executable to. - public void MakeSfx(string archiveFileName, Stream sfxStream) - { - using (Stream archive = new FileStream(archiveFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) - ) - { - MakeSfx(archive, GetDefaultSettings(), sfxStream); - } - } - - /// - /// Makes the self-extracting archive. - /// - /// The archive file name. - /// The sfx settings. - /// The name of the self-extracting executable. - public void MakeSfx(string archiveFileName, SfxSettings settings, string sfxFileName) - { - using (Stream sfxStream = File.Create(sfxFileName)) - { - using ( - Stream archive = new FileStream(archiveFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) - ) - { - MakeSfx(archive, settings, sfxStream); - } - } - } - - /// - /// Makes the self-extracting archive. - /// - /// The archive file name. - /// The sfx settings. - /// The stream to write the self-extracting executable to. - public void MakeSfx(string archiveFileName, SfxSettings settings, Stream sfxStream) - { - using (Stream archive = new FileStream(archiveFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) - ) - { - MakeSfx(archive, settings, sfxStream); - } - } - } -#endif -} \ No newline at end of file diff --git a/BizHawk.Util/7z/StreamWrappers.cs b/BizHawk.Util/7z/StreamWrappers.cs deleted file mode 100644 index 55821d3e17..0000000000 --- a/BizHawk.Util/7z/StreamWrappers.cs +++ /dev/null @@ -1,545 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Runtime.InteropServices; -#if MONO -using SevenZip.Mono.COM; -#endif - -namespace SevenZip -{ -#if UNMANAGED - - /// - /// A class that has DisposeStream property. - /// - internal class DisposeVariableWrapper - { - public bool DisposeStream { protected get; set; } - - protected DisposeVariableWrapper(bool disposeStream) { DisposeStream = disposeStream; } - } - - /// - /// Stream wrapper used in InStreamWrapper - /// - internal class StreamWrapper : DisposeVariableWrapper, IDisposable - { - /// - /// File name associated with the stream (for date fix) - /// - private readonly string _fileName; - - private readonly DateTime _fileTime; - - /// - /// Worker stream for reading, writing and seeking. - /// - private Stream _baseStream; - - /// - /// Initializes a new instance of the StreamWrapper class - /// - /// Worker stream for reading, writing and seeking - /// File name associated with the stream (for attributes fix) - /// File last write time (for attributes fix) - /// Indicates whether to dispose the baseStream - protected StreamWrapper(Stream baseStream, string fileName, DateTime time, bool disposeStream) - : base(disposeStream) - { - _baseStream = baseStream; - _fileName = fileName; - _fileTime = time; - } - - /// - /// Initializes a new instance of the StreamWrapper class - /// - /// Worker stream for reading, writing and seeking - /// Indicates whether to dispose the baseStream - protected StreamWrapper(Stream baseStream, bool disposeStream) - : base(disposeStream) - { - _baseStream = baseStream; - } - - /// - /// Gets the worker stream for reading, writing and seeking. - /// - protected Stream BaseStream - { - get - { - return _baseStream; - } - } - - #region IDisposable Members - - /// - /// Cleans up any resources used and fixes file attributes. - /// - public void Dispose() - { - if (_baseStream != null && DisposeStream) - { - try - { - _baseStream.Dispose(); - } - catch (ObjectDisposedException) { } - _baseStream = null; - } - if (!String.IsNullOrEmpty(_fileName) && File.Exists(_fileName)) - { - try - { -#if !WINCE - - File.SetLastWriteTime(_fileName, _fileTime); - File.SetLastAccessTime(_fileName, _fileTime); - File.SetCreationTime(_fileName, _fileTime); -#elif WINCE - OpenNETCF.IO.FileHelper.SetLastWriteTime(_fileName, _fileTime); - OpenNETCF.IO.FileHelper.SetLastAccessTime(_fileName, _fileTime); - OpenNETCF.IO.FileHelper.SetCreationTime(_fileName, _fileTime); -#endif - //TODO: time support for Windows Phone - } - catch (ArgumentOutOfRangeException) {} - } - GC.SuppressFinalize(this); - } - - #endregion - - public virtual void Seek(long offset, SeekOrigin seekOrigin, IntPtr newPosition) - { - if (BaseStream != null) - { - long position = BaseStream.Seek(offset, seekOrigin); - if (newPosition != IntPtr.Zero) - { - Marshal.WriteInt64(newPosition, position); - } - } - } - } - - /// - /// IInStream wrapper used in stream read operations. - /// - internal sealed class InStreamWrapper : StreamWrapper, ISequentialInStream, IInStream - { - /// - /// Initializes a new instance of the InStreamWrapper class. - /// - /// Stream for writing data - /// Indicates whether to dispose the baseStream - public InStreamWrapper(Stream baseStream, bool disposeStream) : base(baseStream, disposeStream) { } - - #region ISequentialInStream Members - - /// - /// Reads data from the stream. - /// - /// A data array. - /// The array size. - /// The read bytes count. - public int Read(byte[] data, uint size) - { - int readCount = 0; - if (BaseStream != null) - { - readCount = BaseStream.Read(data, 0, (int) size); - if (readCount > 0) - { - OnBytesRead(new IntEventArgs(readCount)); - } - } - return readCount; - } - - #endregion - - /// - /// Occurs when IntEventArgs.Value bytes were read from the source. - /// - public event EventHandler BytesRead; - - private void OnBytesRead(IntEventArgs e) - { - if (BytesRead != null) - { - BytesRead(this, e); - } - } - } - - /// - /// IOutStream wrapper used in stream write operations. - /// - internal sealed class OutStreamWrapper : StreamWrapper, ISequentialOutStream, IOutStream - { - /// - /// Initializes a new instance of the OutStreamWrapper class - /// - /// Stream for writing data - /// File name (for attributes fix) - /// Time of the file creation (for attributes fix) - /// Indicates whether to dispose the baseStream - public OutStreamWrapper(Stream baseStream, string fileName, DateTime time, bool disposeStream) : - base(baseStream, fileName, time, disposeStream) {} - - /// - /// Initializes a new instance of the OutStreamWrapper class - /// - /// Stream for writing data - /// Indicates whether to dispose the baseStream - public OutStreamWrapper(Stream baseStream, bool disposeStream) : - base(baseStream, disposeStream) {} - - #region IOutStream Members - - public int SetSize(long newSize) - { - BaseStream.SetLength(newSize); - return 0; - } - - #endregion - - #region ISequentialOutStream Members - - /// - /// Writes data to the stream - /// - /// Data array - /// Array size - /// Count of written bytes - /// Zero if Ok - public int Write(byte[] data, uint size, IntPtr processedSize) - { - BaseStream.Write(data, 0, (int) size); - if (processedSize != IntPtr.Zero) - { - Marshal.WriteInt32(processedSize, (int) size); - } - OnBytesWritten(new IntEventArgs((int) size)); - return 0; - } - - #endregion - - /// - /// Occurs when IntEventArgs.Value bytes were written. - /// - public event EventHandler BytesWritten; - - private void OnBytesWritten(IntEventArgs e) - { - if (BytesWritten != null) - { - BytesWritten(this, e); - } - } - } - - /// - /// Base multi volume stream wrapper class. - /// - internal class MultiStreamWrapper : DisposeVariableWrapper, IDisposable - { - protected readonly Dictionary> StreamOffsets = - new Dictionary>(); - - protected readonly List Streams = new List(); - protected int CurrentStream; - protected long Position; - protected long StreamLength; - - /// - /// Initializes a new instance of the MultiStreamWrapper class. - /// - /// Perform Dispose() if requested to. - protected MultiStreamWrapper(bool dispose) : base(dispose) {} - - /// - /// Gets the total length of input data. - /// - public long Length - { - get - { - return StreamLength; - } - } - - #region IDisposable Members - - /// - /// Cleans up any resources used and fixes file attributes. - /// - public virtual void Dispose() - { - if (DisposeStream) - { - foreach (Stream stream in Streams) - { - try - { - stream.Dispose(); - } - catch (ObjectDisposedException) {} - } - Streams.Clear(); - } - GC.SuppressFinalize(this); - } - - #endregion - - protected static string VolumeNumber(int num) - { - if (num < 10) - { - return ".00" + num.ToString(CultureInfo.InvariantCulture); - } - if (num > 9 && num < 100) - { - return ".0" + num.ToString(CultureInfo.InvariantCulture); - } - if (num > 99 && num < 1000) - { - return "." + num.ToString(CultureInfo.InvariantCulture); - } - return String.Empty; - } - - private int StreamNumberByOffset(long offset) - { - foreach (int number in StreamOffsets.Keys) - { - if (StreamOffsets[number].Key <= offset && - StreamOffsets[number].Value >= offset) - { - return number; - } - } - return -1; - } - - public void Seek(long offset, SeekOrigin seekOrigin, IntPtr newPosition) - { - long absolutePosition = (seekOrigin == SeekOrigin.Current) - ? Position + offset - : offset; - CurrentStream = StreamNumberByOffset(absolutePosition); - long delta = Streams[CurrentStream].Seek( - absolutePosition - StreamOffsets[CurrentStream].Key, SeekOrigin.Begin); - Position = StreamOffsets[CurrentStream].Key + delta; - if (newPosition != IntPtr.Zero) - { - Marshal.WriteInt64(newPosition, Position); - } - } - } - - /// - /// IInStream wrapper used in stream multi volume read operations. - /// - internal sealed class InMultiStreamWrapper : MultiStreamWrapper, ISequentialInStream, IInStream - { - /// - /// Initializes a new instance of the InMultiStreamWrapper class. - /// - /// The archive file name. - /// Perform Dispose() if requested to. - public InMultiStreamWrapper(string fileName, bool dispose) : - base(dispose) - { - string baseName = fileName.Substring(0, fileName.Length - 4); - int i = 0; - while (File.Exists(fileName)) - { - Streams.Add(new FileStream(fileName, FileMode.Open)); - long length = Streams[i].Length; - StreamOffsets.Add(i++, new KeyValuePair(StreamLength, StreamLength + length)); - StreamLength += length; - fileName = baseName + VolumeNumber(i + 1); - } - } - - #region ISequentialInStream Members - - /// - /// Reads data from the stream. - /// - /// A data array. - /// The array size. - /// The read bytes count. - public int Read(byte[] data, uint size) - { - var readSize = (int) size; - int readCount = Streams[CurrentStream].Read(data, 0, readSize); - readSize -= readCount; - Position += readCount; - while (readCount < (int) size) - { - if (CurrentStream == Streams.Count - 1) - { - return readCount; - } - CurrentStream++; - Streams[CurrentStream].Seek(0, SeekOrigin.Begin); - int count = Streams[CurrentStream].Read(data, readCount, readSize); - readCount += count; - readSize -= count; - Position += count; - } - return readCount; - } - - #endregion - } - -#if COMPRESS - /// - /// IOutStream wrapper used in multi volume stream write operations. - /// - internal sealed class OutMultiStreamWrapper : MultiStreamWrapper, ISequentialOutStream, IOutStream - { - private readonly string _archiveName; - private readonly int _volumeSize; - private long _overallLength; - - /// - /// Initializes a new instance of the OutMultiStreamWrapper class. - /// - /// The archive name. - /// The volume size. - public OutMultiStreamWrapper(string archiveName, int volumeSize) : - base(true) - { - _archiveName = archiveName; - _volumeSize = volumeSize; - CurrentStream = -1; - NewVolumeStream(); - } - - #region IOutStream Members - - public int SetSize(long newSize) - { - return 0; - } - - #endregion - - #region ISequentialOutStream Members - - public int Write(byte[] data, uint size, IntPtr processedSize) - { - int offset = 0; - var originalSize = (int) size; - Position += size; - _overallLength = Math.Max(Position + 1, _overallLength); - while (size > _volumeSize - Streams[CurrentStream].Position) - { - var count = (int) (_volumeSize - Streams[CurrentStream].Position); - Streams[CurrentStream].Write(data, offset, count); - size -= (uint) count; - offset += count; - NewVolumeStream(); - } - Streams[CurrentStream].Write(data, offset, (int) size); - if (processedSize != IntPtr.Zero) - { - Marshal.WriteInt32(processedSize, originalSize); - } - return 0; - } - - #endregion - - public override void Dispose() - { - int lastIndex = Streams.Count - 1; - Streams[lastIndex].SetLength(lastIndex > 0? Streams[lastIndex].Position : _overallLength); - base.Dispose(); - } - - private void NewVolumeStream() - { - CurrentStream++; - Streams.Add(File.Create(_archiveName + VolumeNumber(CurrentStream + 1))); - Streams[CurrentStream].SetLength(_volumeSize); - StreamOffsets.Add(CurrentStream, new KeyValuePair(0, _volumeSize - 1)); - } - } -#endif - - internal sealed class FakeOutStreamWrapper : ISequentialOutStream, IDisposable - { - #region IDisposable Members - - public void Dispose() - { - GC.SuppressFinalize(this); - } - - #endregion - - #region ISequentialOutStream Members - - /// - /// Does nothing except calling the BytesWritten event - /// - /// Data array - /// Array size - /// Count of written bytes - /// Zero if Ok - public int Write(byte[] data, uint size, IntPtr processedSize) - { - OnBytesWritten(new IntEventArgs((int) size)); - if (processedSize != IntPtr.Zero) - { - Marshal.WriteInt32(processedSize, (int) size); - } - return 0; - } - - #endregion - - /// - /// Occurs when IntEventArgs.Value bytes were written - /// - public event EventHandler BytesWritten; - - private void OnBytesWritten(IntEventArgs e) - { - if (BytesWritten != null) - { - BytesWritten(this, e); - } - } - } -#endif -} \ No newline at end of file diff --git a/BizHawk.Util/7z/arch/Test.bzip2.7z b/BizHawk.Util/7z/arch/Test.bzip2.7z deleted file mode 100644 index cb39ab1b4c..0000000000 Binary files a/BizHawk.Util/7z/arch/Test.bzip2.7z and /dev/null differ diff --git a/BizHawk.Util/7z/arch/Test.lzma.7z b/BizHawk.Util/7z/arch/Test.lzma.7z deleted file mode 100644 index e214c75cc6..0000000000 Binary files a/BizHawk.Util/7z/arch/Test.lzma.7z and /dev/null differ diff --git a/BizHawk.Util/7z/arch/Test.lzma2.7z b/BizHawk.Util/7z/arch/Test.lzma2.7z deleted file mode 100644 index caf8c94f1e..0000000000 Binary files a/BizHawk.Util/7z/arch/Test.lzma2.7z and /dev/null differ diff --git a/BizHawk.Util/7z/arch/Test.ppmd.7z b/BizHawk.Util/7z/arch/Test.ppmd.7z deleted file mode 100644 index 25ee308a6f..0000000000 Binary files a/BizHawk.Util/7z/arch/Test.ppmd.7z and /dev/null differ diff --git a/BizHawk.Util/7z/arch/Test.rar b/BizHawk.Util/7z/arch/Test.rar deleted file mode 100644 index 7d48b8a402..0000000000 Binary files a/BizHawk.Util/7z/arch/Test.rar and /dev/null differ diff --git a/BizHawk.Util/7z/arch/Test.tar b/BizHawk.Util/7z/arch/Test.tar deleted file mode 100644 index b61b52eab4..0000000000 Binary files a/BizHawk.Util/7z/arch/Test.tar and /dev/null differ diff --git a/BizHawk.Util/7z/arch/Test.txt b/BizHawk.Util/7z/arch/Test.txt deleted file mode 100644 index 8318c86b35..0000000000 --- a/BizHawk.Util/7z/arch/Test.txt +++ /dev/null @@ -1 +0,0 @@ -Test \ No newline at end of file diff --git a/BizHawk.Util/7z/arch/Test.txt.bz2 b/BizHawk.Util/7z/arch/Test.txt.bz2 deleted file mode 100644 index 142ed3f74e..0000000000 Binary files a/BizHawk.Util/7z/arch/Test.txt.bz2 and /dev/null differ diff --git a/BizHawk.Util/7z/arch/Test.txt.gz b/BizHawk.Util/7z/arch/Test.txt.gz deleted file mode 100644 index f6f5f33460..0000000000 Binary files a/BizHawk.Util/7z/arch/Test.txt.gz and /dev/null differ diff --git a/BizHawk.Util/7z/arch/Test.txt.xz b/BizHawk.Util/7z/arch/Test.txt.xz deleted file mode 100644 index f928831802..0000000000 Binary files a/BizHawk.Util/7z/arch/Test.txt.xz and /dev/null differ diff --git a/BizHawk.Util/7z/arch/Test.zip b/BizHawk.Util/7z/arch/Test.zip deleted file mode 100644 index e0a9363804..0000000000 Binary files a/BizHawk.Util/7z/arch/Test.zip and /dev/null differ diff --git a/BizHawk.Util/7z/sdk/Common/CRC.cs b/BizHawk.Util/7z/sdk/Common/CRC.cs deleted file mode 100644 index 7ef7958604..0000000000 --- a/BizHawk.Util/7z/sdk/Common/CRC.cs +++ /dev/null @@ -1,75 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -namespace SevenZip.Sdk -{ - internal class CRC - { - public static readonly uint[] Table; - - private uint _value = 0xFFFFFFFF; - - static CRC() - { - Table = new uint[256]; - const uint kPoly = 0xEDB88320; - for (uint i = 0; i < 256; i++) - { - uint r = i; - for (int j = 0; j < 8; j++) - if ((r & 1) != 0) - r = (r >> 1) ^ kPoly; - else - r >>= 1; - Table[i] = r; - } - } - - public void Init() - { - _value = 0xFFFFFFFF; - } - - public void UpdateByte(byte b) - { - _value = Table[(((byte) (_value)) ^ b)] ^ (_value >> 8); - } - - public void Update(byte[] data, uint offset, uint size) - { - for (uint i = 0; i < size; i++) - _value = Table[(((byte) (_value)) ^ data[offset + i])] ^ (_value >> 8); - } - - public uint GetDigest() - { - return _value ^ 0xFFFFFFFF; - } - - private static uint CalculateDigest(byte[] data, uint offset, uint size) - { - var crc = new CRC(); - // crc.Init(); - crc.Update(data, offset, size); - return crc.GetDigest(); - } - - private static bool VerifyDigest(uint digest, byte[] data, uint offset, uint size) - { - return (CalculateDigest(data, offset, size) == digest); - } - } -} \ No newline at end of file diff --git a/BizHawk.Util/7z/sdk/Common/InBuffer.cs b/BizHawk.Util/7z/sdk/Common/InBuffer.cs deleted file mode 100644 index 26f3ae4104..0000000000 --- a/BizHawk.Util/7z/sdk/Common/InBuffer.cs +++ /dev/null @@ -1,119 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System.IO; - -namespace SevenZip.Sdk.Buffer -{ - /// - /// Implements the input buffer work - /// - internal class InBuffer - { - private readonly byte[] m_Buffer; - private readonly uint m_BufferSize; - private uint m_Limit; - private uint m_Pos; - private ulong m_ProcessedSize; - private Stream m_Stream; - private bool m_StreamWasExhausted; - - /// - /// Initializes the input buffer - /// - /// - private InBuffer(uint bufferSize) - { - m_Buffer = new byte[bufferSize]; - m_BufferSize = bufferSize; - } - - /// - /// Initializes the class - /// - /// - private void Init(Stream stream) - { - m_Stream = stream; - m_ProcessedSize = 0; - m_Limit = 0; - m_Pos = 0; - m_StreamWasExhausted = false; - } - - /// - /// Reads the whole block - /// - /// - private bool ReadBlock() - { - if (m_StreamWasExhausted) - return false; - m_ProcessedSize += m_Pos; - int aNumProcessedBytes = m_Stream.Read(m_Buffer, 0, (int) m_BufferSize); - m_Pos = 0; - m_Limit = (uint) aNumProcessedBytes; - m_StreamWasExhausted = (aNumProcessedBytes == 0); - return (!m_StreamWasExhausted); - } - - /// - /// Releases the stream - /// - private void ReleaseStream() - { - // m_Stream.Close(); - m_Stream = null; - } - - /// - /// Reads the byte to check it - /// - /// - /// - private bool ReadByte(out byte b) - { - b = 0; - if (m_Pos >= m_Limit) - if (!ReadBlock()) - return false; - b = m_Buffer[m_Pos++]; - return true; - } - - /// - /// Reads the next byte - /// - /// - private byte ReadByte() - { - // return (byte)m_Stream.ReadByte(); - if (m_Pos >= m_Limit) - if (!ReadBlock()) - return 0xFF; - return m_Buffer[m_Pos++]; - } - - /// - /// Gets processed size - /// - /// - private ulong GetProcessedSize() - { - return m_ProcessedSize + m_Pos; - } - } -} \ No newline at end of file diff --git a/BizHawk.Util/7z/sdk/Common/OutBuffer.cs b/BizHawk.Util/7z/sdk/Common/OutBuffer.cs deleted file mode 100644 index 85117e038d..0000000000 --- a/BizHawk.Util/7z/sdk/Common/OutBuffer.cs +++ /dev/null @@ -1,85 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System.IO; - -namespace SevenZip.Sdk.Buffer -{ - internal class OutBuffer - { - private readonly byte[] m_Buffer; - private readonly uint m_BufferSize; - private uint m_Pos; - private ulong m_ProcessedSize; - private Stream m_Stream; - - /// - /// Initializes a new instance of the OutBuffer class - /// - /// - public OutBuffer(uint bufferSize) - { - m_Buffer = new byte[bufferSize]; - m_BufferSize = bufferSize; - } - - public void SetStream(Stream stream) - { - m_Stream = stream; - } - - public void FlushStream() - { - m_Stream.Flush(); - } - - public void CloseStream() - { - m_Stream.Close(); - } - - public void ReleaseStream() - { - m_Stream = null; - } - - public void Init() - { - m_ProcessedSize = 0; - m_Pos = 0; - } - - public void WriteByte(byte b) - { - m_Buffer[m_Pos++] = b; - if (m_Pos >= m_BufferSize) - FlushData(); - } - - public void FlushData() - { - if (m_Pos == 0) - return; - m_Stream.Write(m_Buffer, 0, (int) m_Pos); - m_Pos = 0; - } - - public ulong GetProcessedSize() - { - return m_ProcessedSize + m_Pos; - } - } -} \ No newline at end of file diff --git a/BizHawk.Util/7z/sdk/Compress/LZ/IMatchFinder.cs b/BizHawk.Util/7z/sdk/Compress/LZ/IMatchFinder.cs deleted file mode 100644 index d7a792c91e..0000000000 --- a/BizHawk.Util/7z/sdk/Compress/LZ/IMatchFinder.cs +++ /dev/null @@ -1,40 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.IO; - -namespace SevenZip.Sdk.Compression.LZ -{ - internal interface IInWindowStream - { - void SetStream(Stream inStream); - void Init(); - void ReleaseStream(); - Byte GetIndexByte(Int32 index); - UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit); - UInt32 GetNumAvailableBytes(); - } - - internal interface IMatchFinder : IInWindowStream - { - void Create(UInt32 historySize, UInt32 keepAddBufferBefore, - UInt32 matchMaxLen, UInt32 keepAddBufferAfter); - - UInt32 GetMatches(UInt32[] distances); - void Skip(UInt32 num); - } -} \ No newline at end of file diff --git a/BizHawk.Util/7z/sdk/Compress/LZ/LzBinTree.cs b/BizHawk.Util/7z/sdk/Compress/LZ/LzBinTree.cs deleted file mode 100644 index 6669a5b2d5..0000000000 --- a/BizHawk.Util/7z/sdk/Compress/LZ/LzBinTree.cs +++ /dev/null @@ -1,405 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.IO; - -namespace SevenZip.Sdk.Compression.LZ -{ - internal class BinTree : InWindow, IMatchFinder - { - private const UInt32 kBT2HashSize = 1 << 16; - private const UInt32 kEmptyHashValue = 0; - private const UInt32 kHash2Size = 1 << 10; - private const UInt32 kHash3Offset = kHash2Size; - private const UInt32 kHash3Size = 1 << 16; - private const UInt32 kMaxValForNormalize = ((UInt32) 1 << 31) - 1; - private const UInt32 kStartMaxLen = 1; - private UInt32 _cutValue = 0xFF; - private UInt32 _cyclicBufferPos; - private UInt32 _cyclicBufferSize; - private UInt32[] _hash; - - private UInt32 _hashMask; - private UInt32 _hashSizeSum; - private UInt32 _matchMaxLen; - - private UInt32[] _son; - - private bool HASH_ARRAY = true; - - private UInt32 kFixHashSize = kHash2Size + kHash3Size; - private UInt32 kMinMatchCheck = 4; - private UInt32 kNumHashDirectBytes; - - #region IMatchFinder Members - - public new void SetStream(Stream stream) - { - base.SetStream(stream); - } - - public new void ReleaseStream() - { - base.ReleaseStream(); - } - - public new void Init() - { - base.Init(); - for (UInt32 i = 0; i < _hashSizeSum; i++) - _hash[i] = kEmptyHashValue; - _cyclicBufferPos = 0; - ReduceOffsets(-1); - } - - public new Byte GetIndexByte(Int32 index) - { - return base.GetIndexByte(index); - } - - public new UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit) - { - return base.GetMatchLen(index, distance, limit); - } - - public new UInt32 GetNumAvailableBytes() - { - return base.GetNumAvailableBytes(); - } - - public void Create(UInt32 historySize, UInt32 keepAddBufferBefore, - UInt32 matchMaxLen, UInt32 keepAddBufferAfter) - { - if (historySize + 256 > kMaxValForNormalize) - { - throw new ArgumentException("historySize + 256 > kMaxValForNormalize", "historySize"); - } - _cutValue = 16 + (matchMaxLen >> 1); - - UInt32 windowReservSize = (historySize + keepAddBufferBefore + - matchMaxLen + keepAddBufferAfter)/2 + 256; - - base.Create(historySize + keepAddBufferBefore, matchMaxLen + keepAddBufferAfter, windowReservSize); - - _matchMaxLen = matchMaxLen; - - UInt32 cyclicBufferSize = historySize + 1; - if (_cyclicBufferSize != cyclicBufferSize) - _son = new UInt32[(_cyclicBufferSize = cyclicBufferSize)*2]; - - UInt32 hs = kBT2HashSize; - - if (HASH_ARRAY) - { - hs = historySize - 1; - hs |= (hs >> 1); - hs |= (hs >> 2); - hs |= (hs >> 4); - hs |= (hs >> 8); - hs >>= 1; - hs |= 0xFFFF; - if (hs > (1 << 24)) - hs >>= 1; - _hashMask = hs; - hs++; - hs += kFixHashSize; - } - if (hs != _hashSizeSum) - _hash = new UInt32[_hashSizeSum = hs]; - } - - public UInt32 GetMatches(UInt32[] distances) - { - UInt32 lenLimit; - if (_pos + _matchMaxLen <= _streamPos) - lenLimit = _matchMaxLen; - else - { - lenLimit = _streamPos - _pos; - if (lenLimit < kMinMatchCheck) - { - MovePos(); - return 0; - } - } - - UInt32 offset = 0; - UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; - UInt32 cur = _bufferOffset + _pos; - UInt32 maxLen = kStartMaxLen; // to avoid items for len < hashSize; - UInt32 hashValue, hash2Value = 0, hash3Value = 0; - - if (HASH_ARRAY) - { - UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1]; - hash2Value = (temp & (((int) kHash2Size) - 1)); - temp ^= (uint) ((_bufferBase[cur + 2]) << 8); - hash3Value = (temp & (((int) kHash3Size) - 1)); - hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask; - } - else - hashValue = _bufferBase[cur] ^ ((UInt32) (_bufferBase[cur + 1]) << 8); - - UInt32 curMatch = _hash[kFixHashSize + hashValue]; - if (HASH_ARRAY) - { - UInt32 curMatch2 = _hash[hash2Value]; - UInt32 curMatch3 = _hash[kHash3Offset + hash3Value]; - _hash[hash2Value] = _pos; - _hash[kHash3Offset + hash3Value] = _pos; - if (curMatch2 > matchMinPos) - if (_bufferBase[_bufferOffset + curMatch2] == _bufferBase[cur]) - { - distances[offset++] = maxLen = 2; - distances[offset++] = _pos - curMatch2 - 1; - } - if (curMatch3 > matchMinPos) - if (_bufferBase[_bufferOffset + curMatch3] == _bufferBase[cur]) - { - if (curMatch3 == curMatch2) - offset -= 2; - distances[offset++] = maxLen = 3; - distances[offset++] = _pos - curMatch3 - 1; - curMatch2 = curMatch3; - } - if (offset != 0 && curMatch2 == curMatch) - { - offset -= 2; - maxLen = kStartMaxLen; - } - } - - _hash[kFixHashSize + hashValue] = _pos; - - UInt32 ptr0 = (_cyclicBufferPos << 1) + 1; - UInt32 ptr1 = (_cyclicBufferPos << 1); - - UInt32 len0, len1; - len0 = len1 = kNumHashDirectBytes; - - if (kNumHashDirectBytes != 0) - { - if (curMatch > matchMinPos) - { - if (_bufferBase[_bufferOffset + curMatch + kNumHashDirectBytes] != - _bufferBase[cur + kNumHashDirectBytes]) - { - distances[offset++] = maxLen = kNumHashDirectBytes; - distances[offset++] = _pos - curMatch - 1; - } - } - } - - UInt32 count = _cutValue; - - while (true) - { - if (curMatch <= matchMinPos || count-- == 0) - { - _son[ptr0] = _son[ptr1] = kEmptyHashValue; - break; - } - UInt32 delta = _pos - curMatch; - UInt32 cyclicPos = ((delta <= _cyclicBufferPos) - ? - (_cyclicBufferPos - delta) - : - (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; - - UInt32 pby1 = _bufferOffset + curMatch; - UInt32 len = Math.Min(len0, len1); - if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) - { - while (++len != lenLimit) - if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) - break; - if (maxLen < len) - { - distances[offset++] = maxLen = len; - distances[offset++] = delta - 1; - if (len == lenLimit) - { - _son[ptr1] = _son[cyclicPos]; - _son[ptr0] = _son[cyclicPos + 1]; - break; - } - } - } - if (_bufferBase[pby1 + len] < _bufferBase[cur + len]) - { - _son[ptr1] = curMatch; - ptr1 = cyclicPos + 1; - curMatch = _son[ptr1]; - len1 = len; - } - else - { - _son[ptr0] = curMatch; - ptr0 = cyclicPos; - curMatch = _son[ptr0]; - len0 = len; - } - } - MovePos(); - return offset; - } - - public void Skip(UInt32 num) - { - do - { - UInt32 lenLimit; - if (_pos + _matchMaxLen <= _streamPos) - lenLimit = _matchMaxLen; - else - { - lenLimit = _streamPos - _pos; - if (lenLimit < kMinMatchCheck) - { - MovePos(); - continue; - } - } - - UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; - UInt32 cur = _bufferOffset + _pos; - - UInt32 hashValue; - - if (HASH_ARRAY) - { - UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1]; - UInt32 hash2Value = (temp & (((int) kHash2Size) - 1)); - _hash[hash2Value] = _pos; - temp ^= ((UInt32) (_bufferBase[cur + 2]) << 8); - UInt32 hash3Value = (temp & (((int) kHash3Size) - 1)); - _hash[kHash3Offset + hash3Value] = _pos; - hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask; - } - else - hashValue = _bufferBase[cur] ^ ((UInt32) (_bufferBase[cur + 1]) << 8); - - UInt32 curMatch = _hash[kFixHashSize + hashValue]; - _hash[kFixHashSize + hashValue] = _pos; - - UInt32 ptr0 = (_cyclicBufferPos << 1) + 1; - UInt32 ptr1 = (_cyclicBufferPos << 1); - - UInt32 len0, len1; - len0 = len1 = kNumHashDirectBytes; - - UInt32 count = _cutValue; - while (true) - { - if (curMatch <= matchMinPos || count-- == 0) - { - _son[ptr0] = _son[ptr1] = kEmptyHashValue; - break; - } - - UInt32 delta = _pos - curMatch; - UInt32 cyclicPos = ((delta <= _cyclicBufferPos) - ? - (_cyclicBufferPos - delta) - : - (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; - - UInt32 pby1 = _bufferOffset + curMatch; - UInt32 len = Math.Min(len0, len1); - if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) - { - while (++len != lenLimit) - if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) - break; - if (len == lenLimit) - { - _son[ptr1] = _son[cyclicPos]; - _son[ptr0] = _son[cyclicPos + 1]; - break; - } - } - if (_bufferBase[pby1 + len] < _bufferBase[cur + len]) - { - _son[ptr1] = curMatch; - ptr1 = cyclicPos + 1; - curMatch = _son[ptr1]; - len1 = len; - } - else - { - _son[ptr0] = curMatch; - ptr0 = cyclicPos; - curMatch = _son[ptr0]; - len0 = len; - } - } - MovePos(); - } while (--num != 0); - } - - #endregion - - public void SetType(int numHashBytes) - { - HASH_ARRAY = (numHashBytes > 2); - if (HASH_ARRAY) - { - kNumHashDirectBytes = 0; - kMinMatchCheck = 4; - kFixHashSize = kHash2Size + kHash3Size; - } - else - { - kNumHashDirectBytes = 2; - kMinMatchCheck = 2 + 1; - kFixHashSize = 0; - } - } - - public new void MovePos() - { - if (++_cyclicBufferPos >= _cyclicBufferSize) - _cyclicBufferPos = 0; - base.MovePos(); - if (_pos == kMaxValForNormalize) - Normalize(); - } - - private static void NormalizeLinks(UInt32[] items, UInt32 numItems, UInt32 subValue) - { - for (UInt32 i = 0; i < numItems; i++) - { - UInt32 value = items[i]; - if (value <= subValue) - value = kEmptyHashValue; - else - value -= subValue; - items[i] = value; - } - } - - private void Normalize() - { - UInt32 subValue = _pos - _cyclicBufferSize; - NormalizeLinks(_son, _cyclicBufferSize*2, subValue); - NormalizeLinks(_hash, _hashSizeSum, subValue); - ReduceOffsets((Int32) subValue); - } - - //public void SetCutValue(UInt32 cutValue) { _cutValue = cutValue; } - } -} \ No newline at end of file diff --git a/BizHawk.Util/7z/sdk/Compress/LZ/LzInWindow.cs b/BizHawk.Util/7z/sdk/Compress/LZ/LzInWindow.cs deleted file mode 100644 index 8cb05038da..0000000000 --- a/BizHawk.Util/7z/sdk/Compress/LZ/LzInWindow.cs +++ /dev/null @@ -1,197 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ -using System; -using System.IO; - -namespace SevenZip.Sdk.Compression.LZ -{ - /// - /// Input window class - /// - internal class InWindow - { - /// - /// Size of Allocated memory block - /// - public UInt32 _blockSize; - - /// - /// The pointer to buffer with data - /// - public Byte[] _bufferBase; - - /// - /// Buffer offset value - /// - public UInt32 _bufferOffset; - - /// - /// How many BYTEs must be kept buffer after _pos - /// - private UInt32 _keepSizeAfter; - - /// - /// How many BYTEs must be kept in buffer before _pos - /// - private UInt32 _keepSizeBefore; - - private UInt32 _pointerToLastSafePosition; - - /// - /// Offset (from _buffer) of curent byte - /// - public UInt32 _pos; - - private UInt32 _posLimit; // offset (from _buffer) of first byte when new block reading must be done - private Stream _stream; - private bool _streamEndWasReached; // if (true) then _streamPos shows real end of stream - - /// - /// Offset (from _buffer) of first not read byte from Stream - /// - public UInt32 _streamPos; - - public void MoveBlock() - { - UInt32 offset = (_bufferOffset) + _pos - _keepSizeBefore; - // we need one additional byte, since MovePos moves on 1 byte. - if (offset > 0) - offset--; - - UInt32 numBytes = (_bufferOffset) + _streamPos - offset; - - // check negative offset ???? - for (UInt32 i = 0; i < numBytes; i++) - _bufferBase[i] = _bufferBase[offset + i]; - _bufferOffset -= offset; - } - - public virtual void ReadBlock() - { - if (_streamEndWasReached) - return; - while (true) - { - var size = (int) ((0 - _bufferOffset) + _blockSize - _streamPos); - if (size == 0) - return; - int numReadBytes = _stream.Read(_bufferBase, (int) (_bufferOffset + _streamPos), size); - if (numReadBytes == 0) - { - _posLimit = _streamPos; - UInt32 pointerToPostion = _bufferOffset + _posLimit; - if (pointerToPostion > _pointerToLastSafePosition) - _posLimit = (_pointerToLastSafePosition - _bufferOffset); - - _streamEndWasReached = true; - return; - } - _streamPos += (UInt32) numReadBytes; - if (_streamPos >= _pos + _keepSizeAfter) - _posLimit = _streamPos - _keepSizeAfter; - } - } - - private void Free() - { - _bufferBase = null; - } - - public void Create(UInt32 keepSizeBefore, UInt32 keepSizeAfter, UInt32 keepSizeReserv) - { - _keepSizeBefore = keepSizeBefore; - _keepSizeAfter = keepSizeAfter; - UInt32 blockSize = keepSizeBefore + keepSizeAfter + keepSizeReserv; - if (_bufferBase == null || _blockSize != blockSize) - { - Free(); - _blockSize = blockSize; - _bufferBase = new Byte[_blockSize]; - } - _pointerToLastSafePosition = _blockSize - keepSizeAfter; - } - - public void SetStream(Stream stream) - { - _stream = stream; - } - - public void ReleaseStream() - { - _stream = null; - } - - public void Init() - { - _bufferOffset = 0; - _pos = 0; - _streamPos = 0; - _streamEndWasReached = false; - ReadBlock(); - } - - public void MovePos() - { - _pos++; - if (_pos > _posLimit) - { - UInt32 pointerToPostion = _bufferOffset + _pos; - if (pointerToPostion > _pointerToLastSafePosition) - MoveBlock(); - ReadBlock(); - } - } - - public Byte GetIndexByte(Int32 index) - { - return _bufferBase[_bufferOffset + _pos + index]; - } - - /// - /// index + limit have not to exceed _keepSizeAfter - /// - /// - /// - /// - /// - public UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit) - { - if (_streamEndWasReached) - if ((_pos + index) + limit > _streamPos) - limit = _streamPos - (UInt32) (_pos + index); - distance++; - // Byte *pby = _buffer + (size_t)_pos + index; - UInt32 pby = _bufferOffset + _pos + (UInt32) index; - - UInt32 i; - for (i = 0; i < limit && _bufferBase[pby + i] == _bufferBase[pby + i - distance]; i++) ; - return i; - } - - public UInt32 GetNumAvailableBytes() - { - return _streamPos - _pos; - } - - public void ReduceOffsets(Int32 subValue) - { - _bufferOffset += (UInt32) subValue; - _posLimit -= (UInt32) subValue; - _pos -= (UInt32) subValue; - _streamPos -= (UInt32) subValue; - } - } -} \ No newline at end of file diff --git a/BizHawk.Util/7z/sdk/Compress/LZ/LzOutWindow.cs b/BizHawk.Util/7z/sdk/Compress/LZ/LzOutWindow.cs deleted file mode 100644 index 6cf788ad06..0000000000 --- a/BizHawk.Util/7z/sdk/Compress/LZ/LzOutWindow.cs +++ /dev/null @@ -1,125 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System.IO; - -namespace SevenZip.Sdk.Compression.LZ -{ - internal class OutWindow - { - private byte[] _buffer; - private uint _pos; - private Stream _stream; - private uint _streamPos; - private uint _windowSize; - public uint TrainSize; - - public void Create(uint windowSize) - { - if (_windowSize != windowSize) - { - // System.GC.Collect(); - _buffer = new byte[windowSize]; - } - _windowSize = windowSize; - _pos = 0; - _streamPos = 0; - } - - public void Init(Stream stream, bool solid) - { - ReleaseStream(); - _stream = stream; - if (!solid) - { - _streamPos = 0; - _pos = 0; - TrainSize = 0; - } - } - - public bool Train(Stream stream) - { - long len = stream.Length; - uint size = (len < _windowSize) ? (uint) len : _windowSize; - TrainSize = size; - stream.Position = len - size; - _streamPos = _pos = 0; - while (size > 0) - { - uint curSize = _windowSize - _pos; - if (size < curSize) - curSize = size; - int numReadBytes = stream.Read(_buffer, (int) _pos, (int) curSize); - if (numReadBytes == 0) - return false; - size -= (uint) numReadBytes; - _pos += (uint) numReadBytes; - _streamPos += (uint) numReadBytes; - if (_pos == _windowSize) - _streamPos = _pos = 0; - } - return true; - } - - public void ReleaseStream() - { - Flush(); - _stream = null; - } - - public void Flush() - { - uint size = _pos - _streamPos; - if (size == 0) - return; - _stream.Write(_buffer, (int) _streamPos, (int) size); - if (_pos >= _windowSize) - _pos = 0; - _streamPos = _pos; - } - - public void CopyBlock(uint distance, uint len) - { - uint pos = _pos - distance - 1; - if (pos >= _windowSize) - pos += _windowSize; - for (; len > 0; len--) - { - if (pos >= _windowSize) - pos = 0; - _buffer[_pos++] = _buffer[pos++]; - if (_pos >= _windowSize) - Flush(); - } - } - - public void PutByte(byte b) - { - _buffer[_pos++] = b; - if (_pos >= _windowSize) - Flush(); - } - - public byte GetByte(uint distance) - { - uint pos = _pos - distance - 1; - if (pos >= _windowSize) - pos += _windowSize; - return _buffer[pos]; - } - } -} \ No newline at end of file diff --git a/BizHawk.Util/7z/sdk/Compress/LZMA/LzmaBase.cs b/BizHawk.Util/7z/sdk/Compress/LZMA/LzmaBase.cs deleted file mode 100644 index cba427c016..0000000000 --- a/BizHawk.Util/7z/sdk/Compress/LZMA/LzmaBase.cs +++ /dev/null @@ -1,108 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -namespace SevenZip.Sdk.Compression.Lzma -{ - internal abstract class Base - { - public const uint kAlignMask = (kAlignTableSize - 1); - public const uint kAlignTableSize = 1 << kNumAlignBits; - public const int kDicLogSizeMin = 0; - public const uint kEndPosModelIndex = 14; - public const uint kMatchMaxLen = kMatchMinLen + kNumLenSymbols - 1; - // public const int kDicLogSizeMax = 30; - // public const uint kDistTableSizeMax = kDicLogSizeMax * 2; - - public const uint kMatchMinLen = 2; - - public const int kNumAlignBits = 4; - - public const uint kNumFullDistances = 1 << ((int) kEndPosModelIndex/2); - public const int kNumHighLenBits = 8; - - public const uint kNumLenSymbols = kNumLowLenSymbols + kNumMidLenSymbols + - (1 << kNumHighLenBits); - - public const uint kNumLenToPosStates = 1 << kNumLenToPosStatesBits; - public const int kNumLenToPosStatesBits = 2; // it's for speed optimization - - public const uint kNumLitContextBitsMax = 8; - public const uint kNumLitPosStatesBitsEncodingMax = 4; - - public const int kNumLowLenBits = 3; - public const uint kNumLowLenSymbols = 1 << kNumLowLenBits; - public const int kNumMidLenBits = 3; - public const uint kNumMidLenSymbols = 1 << kNumMidLenBits; - public const uint kNumPosModels = kEndPosModelIndex - kStartPosModelIndex; - public const int kNumPosSlotBits = 6; - public const int kNumPosStatesBitsEncodingMax = 4; - public const int kNumPosStatesBitsMax = 4; - public const uint kNumPosStatesEncodingMax = (1 << kNumPosStatesBitsEncodingMax); - public const uint kNumPosStatesMax = (1 << kNumPosStatesBitsMax); - public const uint kNumRepDistances = 4; - public const uint kNumStates = 12; - public const uint kStartPosModelIndex = 4; - - public static uint GetLenToPosState(uint len) - { - len -= kMatchMinLen; - if (len < kNumLenToPosStates) - return len; - return (kNumLenToPosStates - 1); - } - - #region Nested type: State - - public struct State - { - public uint Index; - - public void Init() - { - Index = 0; - } - - public void UpdateChar() - { - if (Index < 4) Index = 0; - else if (Index < 10) Index -= 3; - else Index -= 6; - } - - public void UpdateMatch() - { - Index = (uint) (Index < 7 ? 7 : 10); - } - - public void UpdateRep() - { - Index = (uint) (Index < 7 ? 8 : 11); - } - - public void UpdateShortRep() - { - Index = (uint) (Index < 7 ? 9 : 11); - } - - public bool IsCharState() - { - return Index < 7; - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BizHawk.Util/7z/sdk/Compress/LZMA/LzmaDecoder.cs b/BizHawk.Util/7z/sdk/Compress/LZMA/LzmaDecoder.cs deleted file mode 100644 index f3f993d488..0000000000 --- a/BizHawk.Util/7z/sdk/Compress/LZMA/LzmaDecoder.cs +++ /dev/null @@ -1,480 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.IO; -using SevenZip.Sdk.Compression.LZ; -using SevenZip.Sdk.Compression.RangeCoder; - -namespace SevenZip.Sdk.Compression.Lzma -{ - /// - /// The LZMA decoder class - /// - public class Decoder : ICoder, ISetDecoderProperties // ,System.IO.Stream - { - private readonly BitDecoder[] m_IsMatchDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; - - private readonly BitDecoder[] m_IsRep0LongDecoders = - new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; - - private readonly BitDecoder[] m_IsRepDecoders = new BitDecoder[Base.kNumStates]; - private readonly BitDecoder[] m_IsRepG0Decoders = new BitDecoder[Base.kNumStates]; - private readonly BitDecoder[] m_IsRepG1Decoders = new BitDecoder[Base.kNumStates]; - private readonly BitDecoder[] m_IsRepG2Decoders = new BitDecoder[Base.kNumStates]; - - private readonly LenDecoder m_LenDecoder = new LenDecoder(); - - private readonly LiteralDecoder m_LiteralDecoder = new LiteralDecoder(); - private readonly OutWindow m_OutWindow = new OutWindow(); - private readonly BitDecoder[] m_PosDecoders = new BitDecoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; - private readonly BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[Base.kNumLenToPosStates]; - private readonly RangeCoder.Decoder m_RangeDecoder = new RangeCoder.Decoder(); - private readonly LenDecoder m_RepLenDecoder = new LenDecoder(); - private bool _solid; - - private uint m_DictionarySize; - private uint m_DictionarySizeCheck; - private BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(Base.kNumAlignBits); - - private uint m_PosStateMask; - - /// - /// Initializes the Lzma Decoder class. - /// - public Decoder() - { - m_DictionarySize = 0xFFFFFFFF; - for (int i = 0; i < Base.kNumLenToPosStates; i++) - m_PosSlotDecoder[i] = new BitTreeDecoder(Base.kNumPosSlotBits); - } - - #region ICoder Members - - /// - /// Codes a stream with LZMA algorithm to an output stream - /// - /// The input stream - /// The input size - /// The output size - /// The output stream - /// Progress interface - public void Code(Stream inStream, Stream outStream, - Int64 inSize, Int64 outSize, ICodeProgress progress) - { - Init(inStream, outStream); - - var state = new Base.State(); - state.Init(); - uint rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0; - - UInt64 nowPos64 = 0; - var outSize64 = (UInt64) outSize; - if (nowPos64 < outSize64) - { - if (m_IsMatchDecoders[state.Index << Base.kNumPosStatesBitsMax].Decode(m_RangeDecoder) != 0) - throw new DataErrorException(); - state.UpdateChar(); - byte b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, 0, 0); - m_OutWindow.PutByte(b); - nowPos64++; - } - while (nowPos64 < outSize64) - { - // UInt64 next = Math.Min(nowPos64 + (1 << 18), outSize64); - // while(nowPos64 < next) - { - uint posState = (uint) nowPos64 & m_PosStateMask; - if ( - m_IsMatchDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == - 0) - { - byte b; - byte prevByte = m_OutWindow.GetByte(0); - if (!state.IsCharState()) - b = m_LiteralDecoder.DecodeWithMatchByte(m_RangeDecoder, - (uint) nowPos64, prevByte, - m_OutWindow.GetByte(rep0)); - else - b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, (uint) nowPos64, prevByte); - m_OutWindow.PutByte(b); - state.UpdateChar(); - nowPos64++; - } - else - { - uint len; - if (m_IsRepDecoders[state.Index].Decode(m_RangeDecoder) == 1) - { - if (m_IsRepG0Decoders[state.Index].Decode(m_RangeDecoder) == 0) - { - if ( - m_IsRep0LongDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode( - m_RangeDecoder) == 0) - { - state.UpdateShortRep(); - m_OutWindow.PutByte(m_OutWindow.GetByte(rep0)); - nowPos64++; - continue; - } - } - else - { - UInt32 distance; - if (m_IsRepG1Decoders[state.Index].Decode(m_RangeDecoder) == 0) - { - distance = rep1; - } - else - { - if (m_IsRepG2Decoders[state.Index].Decode(m_RangeDecoder) == 0) - distance = rep2; - else - { - distance = rep3; - rep3 = rep2; - } - rep2 = rep1; - } - rep1 = rep0; - rep0 = distance; - } - len = m_RepLenDecoder.Decode(m_RangeDecoder, posState) + Base.kMatchMinLen; - state.UpdateRep(); - } - else - { - rep3 = rep2; - rep2 = rep1; - rep1 = rep0; - len = Base.kMatchMinLen + m_LenDecoder.Decode(m_RangeDecoder, posState); - state.UpdateMatch(); - uint posSlot = m_PosSlotDecoder[Base.GetLenToPosState(len)].Decode(m_RangeDecoder); - if (posSlot >= Base.kStartPosModelIndex) - { - var numDirectBits = (int) ((posSlot >> 1) - 1); - rep0 = ((2 | (posSlot & 1)) << numDirectBits); - if (posSlot < Base.kEndPosModelIndex) - rep0 += BitTreeDecoder.ReverseDecode(m_PosDecoders, - rep0 - posSlot - 1, m_RangeDecoder, - numDirectBits); - else - { - rep0 += (m_RangeDecoder.DecodeDirectBits( - numDirectBits - Base.kNumAlignBits) << Base.kNumAlignBits); - rep0 += m_PosAlignDecoder.ReverseDecode(m_RangeDecoder); - } - } - else - rep0 = posSlot; - } - if (rep0 >= m_OutWindow.TrainSize + nowPos64 || rep0 >= m_DictionarySizeCheck) - { - if (rep0 == 0xFFFFFFFF) - break; - throw new DataErrorException(); - } - m_OutWindow.CopyBlock(rep0, len); - nowPos64 += len; - } - } - } - m_OutWindow.Flush(); - m_OutWindow.ReleaseStream(); - m_RangeDecoder.ReleaseStream(); - } - - #endregion - - #region ISetDecoderProperties Members - - /// - /// Sets decoder properties - /// - /// Array of byte properties - public void SetDecoderProperties(byte[] properties) - { - if (properties.Length < 5) - throw new InvalidParamException(); - int lc = properties[0]%9; - int remainder = properties[0]/9; - int lp = remainder%5; - int pb = remainder/5; - if (pb > Base.kNumPosStatesBitsMax) - throw new InvalidParamException(); - UInt32 dictionarySize = 0; - for (int i = 0; i < 4; i++) - dictionarySize += ((UInt32) (properties[1 + i])) << (i*8); - SetDictionarySize(dictionarySize); - SetLiteralProperties(lp, lc); - SetPosBitsProperties(pb); - } - - #endregion - - private void SetDictionarySize(uint dictionarySize) - { - if (m_DictionarySize != dictionarySize) - { - m_DictionarySize = dictionarySize; - m_DictionarySizeCheck = Math.Max(m_DictionarySize, 1); - uint blockSize = Math.Max(m_DictionarySizeCheck, (1 << 12)); - m_OutWindow.Create(blockSize); - } - } - - private void SetLiteralProperties(int lp, int lc) - { - if (lp > 8) - throw new InvalidParamException(); - if (lc > 8) - throw new InvalidParamException(); - m_LiteralDecoder.Create(lp, lc); - } - - private void SetPosBitsProperties(int pb) - { - if (pb > Base.kNumPosStatesBitsMax) - throw new InvalidParamException(); - uint numPosStates = (uint) 1 << pb; - m_LenDecoder.Create(numPosStates); - m_RepLenDecoder.Create(numPosStates); - m_PosStateMask = numPosStates - 1; - } - - private void Init(Stream inStream, Stream outStream) - { - m_RangeDecoder.Init(inStream); - m_OutWindow.Init(outStream, _solid); - - uint i; - for (i = 0; i < Base.kNumStates; i++) - { - for (uint j = 0; j <= m_PosStateMask; j++) - { - uint index = (i << Base.kNumPosStatesBitsMax) + j; - m_IsMatchDecoders[index].Init(); - m_IsRep0LongDecoders[index].Init(); - } - m_IsRepDecoders[i].Init(); - m_IsRepG0Decoders[i].Init(); - m_IsRepG1Decoders[i].Init(); - m_IsRepG2Decoders[i].Init(); - } - - m_LiteralDecoder.Init(); - for (i = 0; i < Base.kNumLenToPosStates; i++) - m_PosSlotDecoder[i].Init(); - // m_PosSpecDecoder.Init(); - for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++) - m_PosDecoders[i].Init(); - - m_LenDecoder.Init(); - m_RepLenDecoder.Init(); - m_PosAlignDecoder.Init(); - } - - /// - /// Trains a stream - /// - /// The stream to train. - /// true if Ok; otherwise, false. - public bool Train(Stream stream) - { - _solid = true; - return m_OutWindow.Train(stream); - } - - #region Nested type: LenDecoder - - private class LenDecoder - { - private readonly BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; - private readonly BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; - private BitDecoder m_Choice; - private BitDecoder m_Choice2; - private BitTreeDecoder m_HighCoder = new BitTreeDecoder(Base.kNumHighLenBits); - private uint m_NumPosStates; - - internal void Create(uint numPosStates) - { - for (uint posState = m_NumPosStates; posState < numPosStates; posState++) - { - m_LowCoder[posState] = new BitTreeDecoder(Base.kNumLowLenBits); - m_MidCoder[posState] = new BitTreeDecoder(Base.kNumMidLenBits); - } - m_NumPosStates = numPosStates; - } - - internal void Init() - { - m_Choice.Init(); - for (uint posState = 0; posState < m_NumPosStates; posState++) - { - m_LowCoder[posState].Init(); - m_MidCoder[posState].Init(); - } - m_Choice2.Init(); - m_HighCoder.Init(); - } - - /// - /// Decodes the stream - /// - /// The specified RangeCoder - /// The position state - /// - public uint Decode(RangeCoder.Decoder rangeDecoder, uint posState) - { - if (m_Choice.Decode(rangeDecoder) == 0) - return m_LowCoder[posState].Decode(rangeDecoder); - else - { - uint symbol = Base.kNumLowLenSymbols; - if (m_Choice2.Decode(rangeDecoder) == 0) - symbol += m_MidCoder[posState].Decode(rangeDecoder); - else - { - symbol += Base.kNumMidLenSymbols; - symbol += m_HighCoder.Decode(rangeDecoder); - } - return symbol; - } - } - } - - #endregion - - #region Nested type: LiteralDecoder - - private class LiteralDecoder - { - private Decoder2[] m_Coders; - private int m_NumPosBits; - private int m_NumPrevBits; - private uint m_PosMask; - - public void Create(int numPosBits, int numPrevBits) - { - if (m_Coders != null && m_NumPrevBits == numPrevBits && - m_NumPosBits == numPosBits) - return; - m_NumPosBits = numPosBits; - m_PosMask = ((uint) 1 << numPosBits) - 1; - m_NumPrevBits = numPrevBits; - uint numStates = (uint) 1 << (m_NumPrevBits + m_NumPosBits); - m_Coders = new Decoder2[numStates]; - for (uint i = 0; i < numStates; i++) - m_Coders[i].Create(); - } - - public void Init() - { - uint numStates = (uint) 1 << (m_NumPrevBits + m_NumPosBits); - for (uint i = 0; i < numStates; i++) - m_Coders[i].Init(); - } - - private uint GetState(uint pos, byte prevByte) - { - return ((pos & m_PosMask) << m_NumPrevBits) + (uint) (prevByte >> (8 - m_NumPrevBits)); - } - - public byte DecodeNormal(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte) - { - return m_Coders[GetState(pos, prevByte)].DecodeNormal(rangeDecoder); - } - - public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte, byte matchByte) - { - return m_Coders[GetState(pos, prevByte)].DecodeWithMatchByte(rangeDecoder, matchByte); - } - - #region Nested type: Decoder2 - - private struct Decoder2 - { - private BitDecoder[] m_Decoders; - - public void Create() - { - m_Decoders = new BitDecoder[0x300]; - } - - public void Init() - { - for (int i = 0; i < 0x300; i++) m_Decoders[i].Init(); - } - - public byte DecodeNormal(RangeCoder.Decoder rangeDecoder) - { - uint symbol = 1; - do - symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); while (symbol < 0x100); - return (byte) symbol; - } - - public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, byte matchByte) - { - uint symbol = 1; - do - { - uint matchBit = (uint) (matchByte >> 7) & 1; - matchByte <<= 1; - uint bit = m_Decoders[((1 + matchBit) << 8) + symbol].Decode(rangeDecoder); - symbol = (symbol << 1) | bit; - if (matchBit != bit) - { - while (symbol < 0x100) - symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); - break; - } - } while (symbol < 0x100); - return (byte) symbol; - } - } - - #endregion - } ; - - #endregion - - /* - public override bool CanRead { get { return true; }} - public override bool CanWrite { get { return true; }} - public override bool CanSeek { get { return true; }} - public override long Length { get { return 0; }} - public override long Position - { - get { return 0; } - set { } - } - public override void Flush() { } - public override int Read(byte[] buffer, int offset, int count) - { - return 0; - } - public override void Write(byte[] buffer, int offset, int count) - { - } - public override long Seek(long offset, System.IO.SeekOrigin origin) - { - return 0; - } - public override void SetLength(long value) {} - */ - } -} \ No newline at end of file diff --git a/BizHawk.Util/7z/sdk/Compress/LZMA/LzmaEncoder.cs b/BizHawk.Util/7z/sdk/Compress/LZMA/LzmaEncoder.cs deleted file mode 100644 index cf3e528e91..0000000000 --- a/BizHawk.Util/7z/sdk/Compress/LZMA/LzmaEncoder.cs +++ /dev/null @@ -1,1587 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.Globalization; -using System.IO; -using SevenZip.Sdk.Compression.LZ; -using SevenZip.Sdk.Compression.RangeCoder; - -namespace SevenZip.Sdk.Compression.Lzma -{ - /// - /// The LZMA encoder class - /// - public class Encoder : ICoder, ISetCoderProperties, IWriteCoderProperties - { - private const int kDefaultDictionaryLogSize = 22; - private const UInt32 kIfinityPrice = 0xFFFFFFF; - private const UInt32 kNumFastBytesDefault = 0x20; - - private const UInt32 kNumLenSpecSymbols = Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; - - private const UInt32 kNumOpts = 1 << 12; - private const int kPropSize = 5; - private static readonly Byte[] g_FastPos = new Byte[1 << 11]; - - private static readonly string[] kMatchFinderIDs = - { - "BT2", - "BT4", - }; - - private readonly UInt32[] _alignPrices = new UInt32[Base.kAlignTableSize]; - private readonly UInt32[] _distancesPrices = new UInt32[Base.kNumFullDistances << Base.kNumLenToPosStatesBits]; - - private readonly BitEncoder[] _isMatch = new BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; - private readonly BitEncoder[] _isRep = new BitEncoder[Base.kNumStates]; - private readonly BitEncoder[] _isRep0Long = new BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; - private readonly BitEncoder[] _isRepG0 = new BitEncoder[Base.kNumStates]; - private readonly BitEncoder[] _isRepG1 = new BitEncoder[Base.kNumStates]; - private readonly BitEncoder[] _isRepG2 = new BitEncoder[Base.kNumStates]; - - private readonly LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder(); - - private readonly LiteralEncoder _literalEncoder = new LiteralEncoder(); - - private readonly UInt32[] _matchDistances = new UInt32[Base.kMatchMaxLen*2 + 2]; - private readonly Optimal[] _optimum = new Optimal[kNumOpts]; - private readonly BitEncoder[] _posEncoders = new BitEncoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; - private readonly BitTreeEncoder[] _posSlotEncoder = new BitTreeEncoder[Base.kNumLenToPosStates]; - - private readonly UInt32[] _posSlotPrices = new UInt32[1 << (Base.kNumPosSlotBits + Base.kNumLenToPosStatesBits)]; - private readonly RangeCoder.Encoder _rangeEncoder = new RangeCoder.Encoder(); - private readonly UInt32[] _repDistances = new UInt32[Base.kNumRepDistances]; - private readonly LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder(); - private readonly Byte[] properties = new Byte[kPropSize]; - private readonly UInt32[] repLens = new UInt32[Base.kNumRepDistances]; - private readonly UInt32[] reps = new UInt32[Base.kNumRepDistances]; - private readonly UInt32[] tempPrices = new UInt32[Base.kNumFullDistances]; - private UInt32 _additionalOffset; - private UInt32 _alignPriceCount; - - private UInt32 _dictionarySize = (1 << kDefaultDictionaryLogSize); - private UInt32 _dictionarySizePrev = 0xFFFFFFFF; - private UInt32 _distTableSize = (kDefaultDictionaryLogSize*2); - private bool _finished; - private Stream _inStream; - private UInt32 _longestMatchLength; - private bool _longestMatchWasFound; - private IMatchFinder _matchFinder; - - private EMatchFinderType _matchFinderType = EMatchFinderType.BT4; - private UInt32 _matchPriceCount; - - private bool _needReleaseMFStream; - private UInt32 _numDistancePairs; - private UInt32 _numFastBytes = kNumFastBytesDefault; - private UInt32 _numFastBytesPrev = 0xFFFFFFFF; - private int _numLiteralContextBits = 3; - private int _numLiteralPosStateBits; - private UInt32 _optimumCurrentIndex; - private UInt32 _optimumEndIndex; - private BitTreeEncoder _posAlignEncoder = new BitTreeEncoder(Base.kNumAlignBits); - private int _posStateBits = 2; - private UInt32 _posStateMask = (4 - 1); - private Byte _previousByte; - private Base.State _state; - private uint _trainSize; - private bool _writeEndMark; - private Int64 nowPos64; - - static Encoder() - { - const Byte kFastSlots = 22; - int c = 2; - g_FastPos[0] = 0; - g_FastPos[1] = 1; - for (Byte slotFast = 2; slotFast < kFastSlots; slotFast++) - { - UInt32 k = ((UInt32) 1 << ((slotFast >> 1) - 1)); - for (UInt32 j = 0; j < k; j++, c++) - g_FastPos[c] = slotFast; - } - } - - /// - /// Initializes a new instance of the Encoder class - /// - public Encoder() - { - for (int i = 0; i < kNumOpts; i++) - _optimum[i] = new Optimal(); - for (int i = 0; i < Base.kNumLenToPosStates; i++) - _posSlotEncoder[i] = new BitTreeEncoder(Base.kNumPosSlotBits); - } - - #region ICoder Members - - /// - /// Codes the specified stream - /// - /// The input stream - /// The input size - /// The output size - /// The output stream - /// The progress callback - public void Code(Stream inStream, Stream outStream, - Int64 inSize, Int64 outSize, ICodeProgress progress) - { - _needReleaseMFStream = false; - try - { - SetStreams(inStream, outStream /*, inSize, outSize*/); - while (true) - { - Int64 processedInSize; - Int64 processedOutSize; - bool finished; - CodeOneBlock(out processedInSize, out processedOutSize, out finished); - if (finished) - return; - if (progress != null) - { - progress.SetProgress(processedInSize, processedOutSize); - } - } - } - finally - { - ReleaseStreams(); - } - } - - #endregion - - #region ISetCoderProperties Members - - /// - /// Sets the coder properties - /// - /// The property identificators - /// The array of properties - public void SetCoderProperties(CoderPropId[] propIDs, object[] properties) - { - for (UInt32 i = 0; i < properties.Length; i++) - { - object prop = properties[i]; - switch (propIDs[i]) - { - case CoderPropId.NumFastBytes: - { - if (!(prop is Int32)) - throw new InvalidParamException(); - var numFastBytes = (Int32) prop; - if (numFastBytes < 5 || numFastBytes > Base.kMatchMaxLen) - throw new InvalidParamException(); - _numFastBytes = (UInt32) numFastBytes; - break; - } - case CoderPropId.Algorithm: - { - /* - if (!(prop is Int32)) - throw new InvalidParamException(); - Int32 maximize = (Int32)prop; - _fastMode = (maximize == 0); - _maxMode = (maximize >= 2); - */ - break; - } - case CoderPropId.MatchFinder: - { - if (!(prop is String)) - throw new InvalidParamException(); - EMatchFinderType matchFinderIndexPrev = _matchFinderType; - int m = FindMatchFinder(((string) prop).ToUpper(CultureInfo.CurrentCulture)); - if (m < 0) - throw new InvalidParamException(); - _matchFinderType = (EMatchFinderType) m; - if (_matchFinder != null && matchFinderIndexPrev != _matchFinderType) - { - _dictionarySizePrev = 0xFFFFFFFF; - _matchFinder = null; - } - break; - } - case CoderPropId.DictionarySize: - { - const int kDicLogSizeMaxCompress = 30; - if (!(prop is Int32)) - throw new InvalidParamException(); - ; - var dictionarySize = (Int32) prop; - if (dictionarySize < (UInt32) (1 << Base.kDicLogSizeMin) || - dictionarySize > (UInt32) (1 << kDicLogSizeMaxCompress)) - throw new InvalidParamException(); - _dictionarySize = (UInt32) dictionarySize; - int dicLogSize; - for (dicLogSize = 0; dicLogSize < (UInt32) kDicLogSizeMaxCompress; dicLogSize++) - if (dictionarySize <= ((UInt32) (1) << dicLogSize)) - break; - _distTableSize = (UInt32) dicLogSize*2; - break; - } - case CoderPropId.PosStateBits: - { - if (!(prop is Int32)) - throw new InvalidParamException(); - var v = (Int32) prop; - if (v < 0 || v > (UInt32) Base.kNumPosStatesBitsEncodingMax) - throw new InvalidParamException(); - _posStateBits = v; - _posStateMask = (((UInt32) 1) << _posStateBits) - 1; - break; - } - case CoderPropId.LitPosBits: - { - if (!(prop is Int32)) - throw new InvalidParamException(); - var v = (Int32) prop; - if (v < 0 || v > Base.kNumLitPosStatesBitsEncodingMax) - throw new InvalidParamException(); - _numLiteralPosStateBits = v; - break; - } - case CoderPropId.LitContextBits: - { - if (!(prop is Int32)) - throw new InvalidParamException(); - var v = (Int32) prop; - if (v < 0 || v > Base.kNumLitContextBitsMax) - throw new InvalidParamException(); - ; - _numLiteralContextBits = v; - break; - } - case CoderPropId.EndMarker: - { - if (!(prop is Boolean)) - throw new InvalidParamException(); - SetWriteEndMarkerMode((Boolean) prop); - break; - } - default: - throw new InvalidParamException(); - } - } - } - - #endregion - - #region IWriteCoderProperties Members - - /// - /// Writes the coder properties - /// - /// The output stream to write the properties to. - public void WriteCoderProperties(Stream outStream) - { - properties[0] = (Byte) ((_posStateBits*5 + _numLiteralPosStateBits)*9 + _numLiteralContextBits); - for (int i = 0; i < 4; i++) - properties[1 + i] = (Byte) (_dictionarySize >> (8*i)); - outStream.Write(properties, 0, kPropSize); - } - - #endregion - - private static UInt32 GetPosSlot(UInt32 pos) - { - if (pos < (1 << 11)) - return g_FastPos[pos]; - if (pos < (1 << 21)) - return (UInt32) (g_FastPos[pos >> 10] + 20); - return (UInt32) (g_FastPos[pos >> 20] + 40); - } - - private static UInt32 GetPosSlot2(UInt32 pos) - { - if (pos < (1 << 17)) - return (UInt32) (g_FastPos[pos >> 6] + 12); - if (pos < (1 << 27)) - return (UInt32) (g_FastPos[pos >> 16] + 32); - return (UInt32) (g_FastPos[pos >> 26] + 52); - } - - private void BaseInit() - { - _state.Init(); - _previousByte = 0; - for (UInt32 i = 0; i < Base.kNumRepDistances; i++) - _repDistances[i] = 0; - } - - private void Create() - { - if (_matchFinder == null) - { - var bt = new BinTree(); - int numHashBytes = 4; - if (_matchFinderType == EMatchFinderType.BT2) - numHashBytes = 2; - bt.SetType(numHashBytes); - _matchFinder = bt; - } - _literalEncoder.Create(_numLiteralPosStateBits, _numLiteralContextBits); - - if (_dictionarySize == _dictionarySizePrev && _numFastBytesPrev == _numFastBytes) - return; - _matchFinder.Create(_dictionarySize, kNumOpts, _numFastBytes, Base.kMatchMaxLen + 1); - _dictionarySizePrev = _dictionarySize; - _numFastBytesPrev = _numFastBytes; - } - - private void SetWriteEndMarkerMode(bool writeEndMarker) - { - _writeEndMark = writeEndMarker; - } - - private void Init() - { - BaseInit(); - _rangeEncoder.Init(); - - uint i; - for (i = 0; i < Base.kNumStates; i++) - { - for (uint j = 0; j <= _posStateMask; j++) - { - uint complexState = (i << Base.kNumPosStatesBitsMax) + j; - _isMatch[complexState].Init(); - _isRep0Long[complexState].Init(); - } - _isRep[i].Init(); - _isRepG0[i].Init(); - _isRepG1[i].Init(); - _isRepG2[i].Init(); - } - _literalEncoder.Init(); - for (i = 0; i < Base.kNumLenToPosStates; i++) - _posSlotEncoder[i].Init(); - for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++) - _posEncoders[i].Init(); - - _lenEncoder.Init((UInt32) 1 << _posStateBits); - _repMatchLenEncoder.Init((UInt32) 1 << _posStateBits); - - _posAlignEncoder.Init(); - - _longestMatchWasFound = false; - _optimumEndIndex = 0; - _optimumCurrentIndex = 0; - _additionalOffset = 0; - } - - private void ReadMatchDistances(out UInt32 lenRes, out UInt32 numDistancePairs) - { - lenRes = 0; - numDistancePairs = _matchFinder.GetMatches(_matchDistances); - if (numDistancePairs > 0) - { - lenRes = _matchDistances[numDistancePairs - 2]; - if (lenRes == _numFastBytes) - lenRes += _matchFinder.GetMatchLen((int) lenRes - 1, _matchDistances[numDistancePairs - 1], - Base.kMatchMaxLen - lenRes); - } - _additionalOffset++; - } - - - private void MovePos(UInt32 num) - { - if (num > 0) - { - _matchFinder.Skip(num); - _additionalOffset += num; - } - } - - private UInt32 GetRepLen1Price(Base.State state, UInt32 posState) - { - return _isRepG0[state.Index].GetPrice0() + - _isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0(); - } - - private UInt32 GetPureRepPrice(UInt32 repIndex, Base.State state, UInt32 posState) - { - UInt32 price; - if (repIndex == 0) - { - price = _isRepG0[state.Index].GetPrice0(); - price += _isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1(); - } - else - { - price = _isRepG0[state.Index].GetPrice1(); - if (repIndex == 1) - price += _isRepG1[state.Index].GetPrice0(); - else - { - price += _isRepG1[state.Index].GetPrice1(); - price += _isRepG2[state.Index].GetPrice(repIndex - 2); - } - } - return price; - } - - private UInt32 GetRepPrice(UInt32 repIndex, UInt32 len, Base.State state, UInt32 posState) - { - UInt32 price = _repMatchLenEncoder.GetPrice(len - Base.kMatchMinLen, posState); - return price + GetPureRepPrice(repIndex, state, posState); - } - - private UInt32 GetPosLenPrice(UInt32 pos, UInt32 len, UInt32 posState) - { - UInt32 price; - UInt32 lenToPosState = Base.GetLenToPosState(len); - if (pos < Base.kNumFullDistances) - price = _distancesPrices[(lenToPosState*Base.kNumFullDistances) + pos]; - else - price = _posSlotPrices[(lenToPosState << Base.kNumPosSlotBits) + GetPosSlot2(pos)] + - _alignPrices[pos & Base.kAlignMask]; - return price + _lenEncoder.GetPrice(len - Base.kMatchMinLen, posState); - } - - private UInt32 Backward(out UInt32 backRes, UInt32 cur) - { - _optimumEndIndex = cur; - UInt32 posMem = _optimum[cur].PosPrev; - UInt32 backMem = _optimum[cur].BackPrev; - do - { - if (_optimum[cur].Prev1IsChar) - { - _optimum[posMem].MakeAsChar(); - _optimum[posMem].PosPrev = posMem - 1; - if (_optimum[cur].Prev2) - { - _optimum[posMem - 1].Prev1IsChar = false; - _optimum[posMem - 1].PosPrev = _optimum[cur].PosPrev2; - _optimum[posMem - 1].BackPrev = _optimum[cur].BackPrev2; - } - } - UInt32 posPrev = posMem; - UInt32 backCur = backMem; - - backMem = _optimum[posPrev].BackPrev; - posMem = _optimum[posPrev].PosPrev; - - _optimum[posPrev].BackPrev = backCur; - _optimum[posPrev].PosPrev = cur; - cur = posPrev; - } while (cur > 0); - backRes = _optimum[0].BackPrev; - _optimumCurrentIndex = _optimum[0].PosPrev; - return _optimumCurrentIndex; - } - - - private UInt32 GetOptimum(UInt32 position, out UInt32 backRes) - { - if (_optimumEndIndex != _optimumCurrentIndex) - { - UInt32 lenRes = _optimum[_optimumCurrentIndex].PosPrev - _optimumCurrentIndex; - backRes = _optimum[_optimumCurrentIndex].BackPrev; - _optimumCurrentIndex = _optimum[_optimumCurrentIndex].PosPrev; - return lenRes; - } - _optimumCurrentIndex = _optimumEndIndex = 0; - - UInt32 lenMain, numDistancePairs; - if (!_longestMatchWasFound) - { - ReadMatchDistances(out lenMain, out numDistancePairs); - } - else - { - lenMain = _longestMatchLength; - numDistancePairs = _numDistancePairs; - _longestMatchWasFound = false; - } - - UInt32 numAvailableBytes = _matchFinder.GetNumAvailableBytes() + 1; - if (numAvailableBytes < 2) - { - backRes = 0xFFFFFFFF; - return 1; - } - if (numAvailableBytes > Base.kMatchMaxLen) - numAvailableBytes = Base.kMatchMaxLen; - - UInt32 repMaxIndex = 0; - - for (UInt32 i = 0; i < Base.kNumRepDistances; i++) - { - reps[i] = _repDistances[i]; - repLens[i] = _matchFinder.GetMatchLen(0 - 1, reps[i], Base.kMatchMaxLen); - if (repLens[i] > repLens[repMaxIndex]) - repMaxIndex = i; - } - if (repLens[repMaxIndex] >= _numFastBytes) - { - backRes = repMaxIndex; - UInt32 lenRes = repLens[repMaxIndex]; - MovePos(lenRes - 1); - return lenRes; - } - - if (lenMain >= _numFastBytes) - { - backRes = _matchDistances[numDistancePairs - 1] + Base.kNumRepDistances; - MovePos(lenMain - 1); - return lenMain; - } - - Byte currentByte = _matchFinder.GetIndexByte(0 - 1); - Byte matchByte = _matchFinder.GetIndexByte((Int32) (0 - _repDistances[0] - 1 - 1)); - - if (lenMain < 2 && currentByte != matchByte && repLens[repMaxIndex] < 2) - { - backRes = 0xFFFFFFFF; - return 1; - } - - _optimum[0].State = _state; - - UInt32 posState = (position & _posStateMask); - - _optimum[1].Price = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() + - _literalEncoder.GetSubCoder(position, _previousByte).GetPrice(!_state.IsCharState(), - matchByte, currentByte); - _optimum[1].MakeAsChar(); - - UInt32 matchPrice = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1(); - UInt32 repMatchPrice = matchPrice + _isRep[_state.Index].GetPrice1(); - - if (matchByte == currentByte) - { - UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(_state, posState); - if (shortRepPrice < _optimum[1].Price) - { - _optimum[1].Price = shortRepPrice; - _optimum[1].MakeAsShortRep(); - } - } - - UInt32 lenEnd = ((lenMain >= repLens[repMaxIndex]) ? lenMain : repLens[repMaxIndex]); - - if (lenEnd < 2) - { - backRes = _optimum[1].BackPrev; - return 1; - } - - _optimum[1].PosPrev = 0; - - _optimum[0].Backs0 = reps[0]; - _optimum[0].Backs1 = reps[1]; - _optimum[0].Backs2 = reps[2]; - _optimum[0].Backs3 = reps[3]; - - UInt32 len = lenEnd; - do - _optimum[len--].Price = kIfinityPrice; while (len >= 2); - - for (UInt32 i = 0; i < Base.kNumRepDistances; i++) - { - UInt32 repLen = repLens[i]; - if (repLen < 2) - continue; - UInt32 price = repMatchPrice + GetPureRepPrice(i, _state, posState); - do - { - UInt32 curAndLenPrice = price + _repMatchLenEncoder.GetPrice(repLen - 2, posState); - Optimal optimum = _optimum[repLen]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = 0; - optimum.BackPrev = i; - optimum.Prev1IsChar = false; - } - } while (--repLen >= 2); - } - - UInt32 normalMatchPrice = matchPrice + _isRep[_state.Index].GetPrice0(); - - len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2); - if (len <= lenMain) - { - UInt32 offs = 0; - while (len > _matchDistances[offs]) - offs += 2; - for (;; len++) - { - UInt32 distance = _matchDistances[offs + 1]; - UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(distance, len, posState); - Optimal optimum = _optimum[len]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = 0; - optimum.BackPrev = distance + Base.kNumRepDistances; - optimum.Prev1IsChar = false; - } - if (len == _matchDistances[offs]) - { - offs += 2; - if (offs == numDistancePairs) - break; - } - } - } - - UInt32 cur = 0; - - while (true) - { - cur++; - if (cur == lenEnd) - return Backward(out backRes, cur); - UInt32 newLen; - ReadMatchDistances(out newLen, out numDistancePairs); - if (newLen >= _numFastBytes) - { - _numDistancePairs = numDistancePairs; - _longestMatchLength = newLen; - _longestMatchWasFound = true; - return Backward(out backRes, cur); - } - position++; - UInt32 posPrev = _optimum[cur].PosPrev; - Base.State state; - if (_optimum[cur].Prev1IsChar) - { - posPrev--; - if (_optimum[cur].Prev2) - { - state = _optimum[_optimum[cur].PosPrev2].State; - if (_optimum[cur].BackPrev2 < Base.kNumRepDistances) - state.UpdateRep(); - else - state.UpdateMatch(); - } - else - state = _optimum[posPrev].State; - state.UpdateChar(); - } - else - state = _optimum[posPrev].State; - if (posPrev == cur - 1) - { - if (_optimum[cur].IsShortRep()) - state.UpdateShortRep(); - else - state.UpdateChar(); - } - else - { - UInt32 pos; - if (_optimum[cur].Prev1IsChar && _optimum[cur].Prev2) - { - posPrev = _optimum[cur].PosPrev2; - pos = _optimum[cur].BackPrev2; - state.UpdateRep(); - } - else - { - pos = _optimum[cur].BackPrev; - if (pos < Base.kNumRepDistances) - state.UpdateRep(); - else - state.UpdateMatch(); - } - Optimal opt = _optimum[posPrev]; - if (pos < Base.kNumRepDistances) - { - if (pos == 0) - { - reps[0] = opt.Backs0; - reps[1] = opt.Backs1; - reps[2] = opt.Backs2; - reps[3] = opt.Backs3; - } - else if (pos == 1) - { - reps[0] = opt.Backs1; - reps[1] = opt.Backs0; - reps[2] = opt.Backs2; - reps[3] = opt.Backs3; - } - else if (pos == 2) - { - reps[0] = opt.Backs2; - reps[1] = opt.Backs0; - reps[2] = opt.Backs1; - reps[3] = opt.Backs3; - } - else - { - reps[0] = opt.Backs3; - reps[1] = opt.Backs0; - reps[2] = opt.Backs1; - reps[3] = opt.Backs2; - } - } - else - { - reps[0] = (pos - Base.kNumRepDistances); - reps[1] = opt.Backs0; - reps[2] = opt.Backs1; - reps[3] = opt.Backs2; - } - } - _optimum[cur].State = state; - _optimum[cur].Backs0 = reps[0]; - _optimum[cur].Backs1 = reps[1]; - _optimum[cur].Backs2 = reps[2]; - _optimum[cur].Backs3 = reps[3]; - UInt32 curPrice = _optimum[cur].Price; - - currentByte = _matchFinder.GetIndexByte(0 - 1); - matchByte = _matchFinder.GetIndexByte((Int32) (0 - reps[0] - 1 - 1)); - - posState = (position & _posStateMask); - - UInt32 curAnd1Price = curPrice + - _isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() + - _literalEncoder.GetSubCoder(position, _matchFinder.GetIndexByte(0 - 2)). - GetPrice(!state.IsCharState(), matchByte, currentByte); - - Optimal nextOptimum = _optimum[cur + 1]; - - bool nextIsChar = false; - if (curAnd1Price < nextOptimum.Price) - { - nextOptimum.Price = curAnd1Price; - nextOptimum.PosPrev = cur; - nextOptimum.MakeAsChar(); - nextIsChar = true; - } - - matchPrice = curPrice + _isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1(); - repMatchPrice = matchPrice + _isRep[state.Index].GetPrice1(); - - if (matchByte == currentByte && - !(nextOptimum.PosPrev < cur && nextOptimum.BackPrev == 0)) - { - UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(state, posState); - if (shortRepPrice <= nextOptimum.Price) - { - nextOptimum.Price = shortRepPrice; - nextOptimum.PosPrev = cur; - nextOptimum.MakeAsShortRep(); - nextIsChar = true; - } - } - - UInt32 numAvailableBytesFull = _matchFinder.GetNumAvailableBytes() + 1; - numAvailableBytesFull = Math.Min(((int) kNumOpts) - 1 - cur, numAvailableBytesFull); - numAvailableBytes = numAvailableBytesFull; - - if (numAvailableBytes < 2) - continue; - if (numAvailableBytes > _numFastBytes) - numAvailableBytes = _numFastBytes; - if (!nextIsChar && matchByte != currentByte) - { - // try Literal + rep0 - UInt32 t = Math.Min(numAvailableBytesFull - 1, _numFastBytes); - UInt32 lenTest2 = _matchFinder.GetMatchLen(0, reps[0], t); - if (lenTest2 >= 2) - { - Base.State state2 = state; - state2.UpdateChar(); - UInt32 posStateNext = (position + 1) & _posStateMask; - UInt32 nextRepMatchPrice = curAnd1Price + - _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext]. - GetPrice1() + - _isRep[state2.Index].GetPrice1(); - { - UInt32 offset = cur + 1 + lenTest2; - while (lenEnd < offset) - _optimum[++lenEnd].Price = kIfinityPrice; - UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice( - 0, lenTest2, state2, posStateNext); - Optimal optimum = _optimum[offset]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = cur + 1; - optimum.BackPrev = 0; - optimum.Prev1IsChar = true; - optimum.Prev2 = false; - } - } - } - } - - UInt32 startLen = 2; // speed optimization - - for (UInt32 repIndex = 0; repIndex < Base.kNumRepDistances; repIndex++) - { - UInt32 lenTest = _matchFinder.GetMatchLen(0 - 1, reps[repIndex], numAvailableBytes); - if (lenTest < 2) - continue; - UInt32 lenTestTemp = lenTest; - do - { - while (lenEnd < cur + lenTest) - _optimum[++lenEnd].Price = kIfinityPrice; - UInt32 curAndLenPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState); - Optimal optimum = _optimum[cur + lenTest]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = cur; - optimum.BackPrev = repIndex; - optimum.Prev1IsChar = false; - } - } while (--lenTest >= 2); - lenTest = lenTestTemp; - - if (repIndex == 0) - startLen = lenTest + 1; - - // if (_maxMode) - if (lenTest < numAvailableBytesFull) - { - UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes); - UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32) lenTest, reps[repIndex], t); - if (lenTest2 >= 2) - { - Base.State state2 = state; - state2.UpdateRep(); - UInt32 posStateNext = (position + lenTest) & _posStateMask; - UInt32 curAndLenCharPrice = - repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState) + - _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() + - _literalEncoder.GetSubCoder(position + lenTest, - _matchFinder.GetIndexByte((Int32) lenTest - 1 - 1)).GetPrice - (true, - _matchFinder.GetIndexByte(((Int32) lenTest - 1 - (Int32) (reps[repIndex] + 1))), - _matchFinder.GetIndexByte((Int32) lenTest - 1)); - state2.UpdateChar(); - posStateNext = (position + lenTest + 1) & _posStateMask; - UInt32 nextMatchPrice = curAndLenCharPrice + - _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext] - .GetPrice1(); - UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1(); - - // for(; lenTest2 >= 2; lenTest2--) - { - UInt32 offset = lenTest + 1 + lenTest2; - while (lenEnd < cur + offset) - _optimum[++lenEnd].Price = kIfinityPrice; - UInt32 curAndLenPrice = nextRepMatchPrice + - GetRepPrice(0, lenTest2, state2, posStateNext); - Optimal optimum = _optimum[cur + offset]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = cur + lenTest + 1; - optimum.BackPrev = 0; - optimum.Prev1IsChar = true; - optimum.Prev2 = true; - optimum.PosPrev2 = cur; - optimum.BackPrev2 = repIndex; - } - } - } - } - } - - if (newLen > numAvailableBytes) - { - newLen = numAvailableBytes; - for (numDistancePairs = 0; newLen > _matchDistances[numDistancePairs]; numDistancePairs += 2) ; - _matchDistances[numDistancePairs] = newLen; - numDistancePairs += 2; - } - if (newLen >= startLen) - { - normalMatchPrice = matchPrice + _isRep[state.Index].GetPrice0(); - while (lenEnd < cur + newLen) - _optimum[++lenEnd].Price = kIfinityPrice; - - UInt32 offs = 0; - while (startLen > _matchDistances[offs]) - offs += 2; - - for (UInt32 lenTest = startLen;; lenTest++) - { - UInt32 curBack = _matchDistances[offs + 1]; - UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(curBack, lenTest, posState); - Optimal optimum = _optimum[cur + lenTest]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = cur; - optimum.BackPrev = curBack + Base.kNumRepDistances; - optimum.Prev1IsChar = false; - } - - if (lenTest == _matchDistances[offs]) - { - if (lenTest < numAvailableBytesFull) - { - UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes); - UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32) lenTest, curBack, t); - if (lenTest2 >= 2) - { - Base.State state2 = state; - state2.UpdateMatch(); - UInt32 posStateNext = (position + lenTest) & _posStateMask; - UInt32 curAndLenCharPrice = curAndLenPrice + - _isMatch[ - (state2.Index << Base.kNumPosStatesBitsMax) + - posStateNext].GetPrice0() + - _literalEncoder.GetSubCoder(position + lenTest, - _matchFinder.GetIndexByte( - (Int32) lenTest - 1 - 1)) - . - GetPrice(true, - _matchFinder.GetIndexByte((Int32) lenTest - - (Int32) - (curBack + 1) - 1), - _matchFinder.GetIndexByte((Int32) lenTest - - 1)); - state2.UpdateChar(); - posStateNext = (position + lenTest + 1) & _posStateMask; - UInt32 nextMatchPrice = curAndLenCharPrice + - _isMatch[ - (state2.Index << Base.kNumPosStatesBitsMax) + - posStateNext].GetPrice1(); - UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1(); - - UInt32 offset = lenTest + 1 + lenTest2; - while (lenEnd < cur + offset) - _optimum[++lenEnd].Price = kIfinityPrice; - curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext); - optimum = _optimum[cur + offset]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = cur + lenTest + 1; - optimum.BackPrev = 0; - optimum.Prev1IsChar = true; - optimum.Prev2 = true; - optimum.PosPrev2 = cur; - optimum.BackPrev2 = curBack + Base.kNumRepDistances; - } - } - } - offs += 2; - if (offs == numDistancePairs) - break; - } - } - } - } - } - - /*static bool ChangePair(UInt32 smallDist, UInt32 bigDist) - { - const int kDif = 7; - return (smallDist < ((UInt32)(1) << (32 - kDif)) && bigDist >= (smallDist << kDif)); - }*/ - - private void WriteEndMarker(UInt32 posState) - { - if (!_writeEndMark) - return; - - _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 1); - _isRep[_state.Index].Encode(_rangeEncoder, 0); - _state.UpdateMatch(); - UInt32 len = Base.kMatchMinLen; - _lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); - UInt32 posSlot = (1 << Base.kNumPosSlotBits) - 1; - UInt32 lenToPosState = Base.GetLenToPosState(len); - _posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot); - int footerBits = 30; - UInt32 posReduced = (((UInt32) 1) << footerBits) - 1; - _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits); - _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); - } - - private void Flush(UInt32 nowPos) - { - ReleaseMFStream(); - WriteEndMarker(nowPos & _posStateMask); - _rangeEncoder.FlushData(); - _rangeEncoder.FlushStream(); - } - - internal void CodeOneBlock(out Int64 inSize, out Int64 outSize, out bool finished) - { - inSize = 0; - outSize = 0; - finished = true; - - if (_inStream != null) - { - _matchFinder.SetStream(_inStream); - _matchFinder.Init(); - _needReleaseMFStream = true; - _inStream = null; - if (_trainSize > 0) - _matchFinder.Skip(_trainSize); - } - - if (_finished) - return; - _finished = true; - - - Int64 progressPosValuePrev = nowPos64; - if (nowPos64 == 0) - { - if (_matchFinder.GetNumAvailableBytes() == 0) - { - Flush((UInt32) nowPos64); - return; - } - UInt32 len, numDistancePairs; // it's not used - ReadMatchDistances(out len, out numDistancePairs); - UInt32 posState = (UInt32) (nowPos64) & _posStateMask; - _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 0); - _state.UpdateChar(); - Byte curByte = _matchFinder.GetIndexByte((Int32) (0 - _additionalOffset)); - _literalEncoder.GetSubCoder((UInt32) (nowPos64), _previousByte).Encode(_rangeEncoder, curByte); - _previousByte = curByte; - _additionalOffset--; - nowPos64++; - } - if (_matchFinder.GetNumAvailableBytes() == 0) - { - Flush((UInt32) nowPos64); - return; - } - while (true) - { - UInt32 pos; - UInt32 len = GetOptimum((UInt32) nowPos64, out pos); - - UInt32 posState = ((UInt32) nowPos64) & _posStateMask; - UInt32 complexState = (_state.Index << Base.kNumPosStatesBitsMax) + posState; - if (len == 1 && pos == 0xFFFFFFFF) - { - _isMatch[complexState].Encode(_rangeEncoder, 0); - Byte curByte = _matchFinder.GetIndexByte((Int32) (0 - _additionalOffset)); - LiteralEncoder.Encoder2 subCoder = _literalEncoder.GetSubCoder((UInt32) nowPos64, _previousByte); - if (!_state.IsCharState()) - { - Byte matchByte = - _matchFinder.GetIndexByte((Int32) (0 - _repDistances[0] - 1 - _additionalOffset)); - subCoder.EncodeMatched(_rangeEncoder, matchByte, curByte); - } - else - subCoder.Encode(_rangeEncoder, curByte); - _previousByte = curByte; - _state.UpdateChar(); - } - else - { - _isMatch[complexState].Encode(_rangeEncoder, 1); - if (pos < Base.kNumRepDistances) - { - _isRep[_state.Index].Encode(_rangeEncoder, 1); - if (pos == 0) - { - _isRepG0[_state.Index].Encode(_rangeEncoder, 0); - if (len == 1) - _isRep0Long[complexState].Encode(_rangeEncoder, 0); - else - _isRep0Long[complexState].Encode(_rangeEncoder, 1); - } - else - { - _isRepG0[_state.Index].Encode(_rangeEncoder, 1); - if (pos == 1) - _isRepG1[_state.Index].Encode(_rangeEncoder, 0); - else - { - _isRepG1[_state.Index].Encode(_rangeEncoder, 1); - _isRepG2[_state.Index].Encode(_rangeEncoder, pos - 2); - } - } - if (len == 1) - _state.UpdateShortRep(); - else - { - _repMatchLenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); - _state.UpdateRep(); - } - UInt32 distance = _repDistances[pos]; - if (pos != 0) - { - for (UInt32 i = pos; i >= 1; i--) - _repDistances[i] = _repDistances[i - 1]; - _repDistances[0] = distance; - } - } - else - { - _isRep[_state.Index].Encode(_rangeEncoder, 0); - _state.UpdateMatch(); - _lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); - pos -= Base.kNumRepDistances; - UInt32 posSlot = GetPosSlot(pos); - UInt32 lenToPosState = Base.GetLenToPosState(len); - _posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot); - - if (posSlot >= Base.kStartPosModelIndex) - { - var footerBits = (int) ((posSlot >> 1) - 1); - UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits); - UInt32 posReduced = pos - baseVal; - - if (posSlot < Base.kEndPosModelIndex) - BitTreeEncoder.ReverseEncode(_posEncoders, - baseVal - posSlot - 1, _rangeEncoder, footerBits, - posReduced); - else - { - _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, - footerBits - Base.kNumAlignBits); - _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); - _alignPriceCount++; - } - } - UInt32 distance = pos; - for (Int32 i = ((int) Base.kNumRepDistances) - 1; i >= 1; i--) - _repDistances[i] = _repDistances[i - 1]; - _repDistances[0] = distance; - _matchPriceCount++; - } - _previousByte = _matchFinder.GetIndexByte((Int32) (len - 1 - _additionalOffset)); - } - _additionalOffset -= len; - nowPos64 += len; - if (_additionalOffset == 0) - { - // if (!_fastMode) - if (_matchPriceCount >= (1 << 7)) - FillDistancesPrices(); - if (_alignPriceCount >= Base.kAlignTableSize) - FillAlignPrices(); - inSize = nowPos64; - outSize = _rangeEncoder.GetProcessedSizeAdd(); - if (_matchFinder.GetNumAvailableBytes() == 0) - { - Flush((UInt32) nowPos64); - return; - } - - if (nowPos64 - progressPosValuePrev >= (1 << 12)) - { - _finished = false; - finished = false; - return; - } - } - } - } - - private void ReleaseMFStream() - { - if (_matchFinder != null && _needReleaseMFStream) - { - _matchFinder.ReleaseStream(); - _needReleaseMFStream = false; - } - } - - private void SetOutStream(Stream outStream) - { - _rangeEncoder.SetStream(outStream); - } - - private void ReleaseOutStream() - { - _rangeEncoder.ReleaseStream(); - } - - private void ReleaseStreams() - { - ReleaseMFStream(); - ReleaseOutStream(); - } - - private void SetStreams(Stream inStream, Stream outStream /*, - Int64 inSize, Int64 outSize*/) - { - _inStream = inStream; - _finished = false; - Create(); - SetOutStream(outStream); - Init(); - - // if (!_fastMode) - { - FillDistancesPrices(); - FillAlignPrices(); - } - - _lenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen); - _lenEncoder.UpdateTables((UInt32) 1 << _posStateBits); - _repMatchLenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen); - _repMatchLenEncoder.UpdateTables((UInt32) 1 << _posStateBits); - - nowPos64 = 0; - } - - private void FillDistancesPrices() - { - for (UInt32 i = Base.kStartPosModelIndex; i < Base.kNumFullDistances; i++) - { - UInt32 posSlot = GetPosSlot(i); - var footerBits = (int) ((posSlot >> 1) - 1); - UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits); - tempPrices[i] = BitTreeEncoder.ReverseGetPrice(_posEncoders, - baseVal - posSlot - 1, footerBits, i - baseVal); - } - - for (UInt32 lenToPosState = 0; lenToPosState < Base.kNumLenToPosStates; lenToPosState++) - { - UInt32 posSlot; - BitTreeEncoder encoder = _posSlotEncoder[lenToPosState]; - - UInt32 st = (lenToPosState << Base.kNumPosSlotBits); - for (posSlot = 0; posSlot < _distTableSize; posSlot++) - _posSlotPrices[st + posSlot] = encoder.GetPrice(posSlot); - for (posSlot = Base.kEndPosModelIndex; posSlot < _distTableSize; posSlot++) - _posSlotPrices[st + posSlot] += ((((posSlot >> 1) - 1) - Base.kNumAlignBits) << - BitEncoder.kNumBitPriceShiftBits); - - UInt32 st2 = lenToPosState*Base.kNumFullDistances; - UInt32 i; - for (i = 0; i < Base.kStartPosModelIndex; i++) - _distancesPrices[st2 + i] = _posSlotPrices[st + i]; - for (; i < Base.kNumFullDistances; i++) - _distancesPrices[st2 + i] = _posSlotPrices[st + GetPosSlot(i)] + tempPrices[i]; - } - _matchPriceCount = 0; - } - - private void FillAlignPrices() - { - for (UInt32 i = 0; i < Base.kAlignTableSize; i++) - _alignPrices[i] = _posAlignEncoder.ReverseGetPrice(i); - _alignPriceCount = 0; - } - - - private static int FindMatchFinder(string s) - { - for (int m = 0; m < kMatchFinderIDs.Length; m++) - if (s == kMatchFinderIDs[m]) - return m; - return -1; - } - - #region Nested type: EMatchFinderType - - private enum EMatchFinderType - { - BT2, - BT4, - } ; - - #endregion - - #region Nested type: LenEncoder - - private class LenEncoder - { - private readonly BitTreeEncoder[] _lowCoder = new BitTreeEncoder[Base.kNumPosStatesEncodingMax]; - private readonly BitTreeEncoder[] _midCoder = new BitTreeEncoder[Base.kNumPosStatesEncodingMax]; - private BitEncoder _choice; - private BitEncoder _choice2; - private BitTreeEncoder _highCoder = new BitTreeEncoder(Base.kNumHighLenBits); - - public LenEncoder() - { - for (UInt32 posState = 0; posState < Base.kNumPosStatesEncodingMax; posState++) - { - _lowCoder[posState] = new BitTreeEncoder(Base.kNumLowLenBits); - _midCoder[posState] = new BitTreeEncoder(Base.kNumMidLenBits); - } - } - - public void Init(UInt32 numPosStates) - { - _choice.Init(); - _choice2.Init(); - for (UInt32 posState = 0; posState < numPosStates; posState++) - { - _lowCoder[posState].Init(); - _midCoder[posState].Init(); - } - _highCoder.Init(); - } - - public void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState) - { - if (symbol < Base.kNumLowLenSymbols) - { - _choice.Encode(rangeEncoder, 0); - _lowCoder[posState].Encode(rangeEncoder, symbol); - } - else - { - symbol -= Base.kNumLowLenSymbols; - _choice.Encode(rangeEncoder, 1); - if (symbol < Base.kNumMidLenSymbols) - { - _choice2.Encode(rangeEncoder, 0); - _midCoder[posState].Encode(rangeEncoder, symbol); - } - else - { - _choice2.Encode(rangeEncoder, 1); - _highCoder.Encode(rangeEncoder, symbol - Base.kNumMidLenSymbols); - } - } - } - - public void SetPrices(UInt32 posState, UInt32 numSymbols, UInt32[] prices, UInt32 st) - { - UInt32 a0 = _choice.GetPrice0(); - UInt32 a1 = _choice.GetPrice1(); - UInt32 b0 = a1 + _choice2.GetPrice0(); - UInt32 b1 = a1 + _choice2.GetPrice1(); - UInt32 i = 0; - for (i = 0; i < Base.kNumLowLenSymbols; i++) - { - if (i >= numSymbols) - return; - prices[st + i] = a0 + _lowCoder[posState].GetPrice(i); - } - for (; i < Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; i++) - { - if (i >= numSymbols) - return; - prices[st + i] = b0 + _midCoder[posState].GetPrice(i - Base.kNumLowLenSymbols); - } - for (; i < numSymbols; i++) - prices[st + i] = b1 + _highCoder.GetPrice(i - Base.kNumLowLenSymbols - Base.kNumMidLenSymbols); - } - } ; - - #endregion - - #region Nested type: LenPriceTableEncoder - - private class LenPriceTableEncoder : LenEncoder - { - private readonly UInt32[] _counters = new UInt32[Base.kNumPosStatesEncodingMax]; - private readonly UInt32[] _prices = new UInt32[Base.kNumLenSymbols << Base.kNumPosStatesBitsEncodingMax]; - private UInt32 _tableSize; - - public void SetTableSize(UInt32 tableSize) - { - _tableSize = tableSize; - } - - public UInt32 GetPrice(UInt32 symbol, UInt32 posState) - { - return _prices[posState*Base.kNumLenSymbols + symbol]; - } - - private void UpdateTable(UInt32 posState) - { - SetPrices(posState, _tableSize, _prices, posState*Base.kNumLenSymbols); - _counters[posState] = _tableSize; - } - - public void UpdateTables(UInt32 numPosStates) - { - for (UInt32 posState = 0; posState < numPosStates; posState++) - UpdateTable(posState); - } - - public new void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState) - { - base.Encode(rangeEncoder, symbol, posState); - if (--_counters[posState] == 0) - UpdateTable(posState); - } - } - - #endregion - - #region Nested type: LiteralEncoder - - private class LiteralEncoder - { - private Encoder2[] m_Coders; - private int m_NumPosBits; - private int m_NumPrevBits; - private uint m_PosMask; - - internal void Create(int numPosBits, int numPrevBits) - { - if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits) - return; - m_NumPosBits = numPosBits; - m_PosMask = ((uint) 1 << numPosBits) - 1; - m_NumPrevBits = numPrevBits; - uint numStates = (uint) 1 << (m_NumPrevBits + m_NumPosBits); - m_Coders = new Encoder2[numStates]; - for (uint i = 0; i < numStates; i++) - m_Coders[i].Create(); - } - - internal void Init() - { - uint numStates = (uint) 1 << (m_NumPrevBits + m_NumPosBits); - for (uint i = 0; i < numStates; i++) - m_Coders[i].Init(); - } - - internal Encoder2 GetSubCoder(UInt32 pos, Byte prevByte) - { - return m_Coders[((pos & m_PosMask) << m_NumPrevBits) + (uint) (prevByte >> (8 - m_NumPrevBits))]; - } - - #region Nested type: Encoder2 - - public struct Encoder2 - { - private BitEncoder[] m_Encoders; - - public void Create() - { - m_Encoders = new BitEncoder[0x300]; - } - - public void Init() - { - for (int i = 0; i < 0x300; i++) m_Encoders[i].Init(); - } - - public void Encode(RangeCoder.Encoder rangeEncoder, byte symbol) - { - uint context = 1; - for (int i = 7; i >= 0; i--) - { - var bit = (uint) ((symbol >> i) & 1); - m_Encoders[context].Encode(rangeEncoder, bit); - context = (context << 1) | bit; - } - } - - public void EncodeMatched(RangeCoder.Encoder rangeEncoder, byte matchByte, byte symbol) - { - uint context = 1; - bool same = true; - for (int i = 7; i >= 0; i--) - { - var bit = (uint) ((symbol >> i) & 1); - uint state = context; - if (same) - { - var matchBit = (uint) ((matchByte >> i) & 1); - state += ((1 + matchBit) << 8); - same = (matchBit == bit); - } - m_Encoders[state].Encode(rangeEncoder, bit); - context = (context << 1) | bit; - } - } - - public uint GetPrice(bool matchMode, byte matchByte, byte symbol) - { - uint price = 0; - uint context = 1; - int i = 7; - if (matchMode) - { - for (; i >= 0; i--) - { - uint matchBit = (uint) (matchByte >> i) & 1; - uint bit = (uint) (symbol >> i) & 1; - price += m_Encoders[((1 + matchBit) << 8) + context].GetPrice(bit); - context = (context << 1) | bit; - if (matchBit != bit) - { - i--; - break; - } - } - } - for (; i >= 0; i--) - { - uint bit = (uint) (symbol >> i) & 1; - price += m_Encoders[context].GetPrice(bit); - context = (context << 1) | bit; - } - return price; - } - } - - #endregion - } - - #endregion - - #region Nested type: Optimal - - private class Optimal - { - public UInt32 BackPrev; - public UInt32 BackPrev2; - - public UInt32 Backs0; - public UInt32 Backs1; - public UInt32 Backs2; - public UInt32 Backs3; - public UInt32 PosPrev; - public UInt32 PosPrev2; - public bool Prev1IsChar; - public bool Prev2; - public UInt32 Price; - public Base.State State; - - public void MakeAsChar() - { - BackPrev = 0xFFFFFFFF; - Prev1IsChar = false; - } - - public void MakeAsShortRep() - { - BackPrev = 0; - ; - Prev1IsChar = false; - } - - public bool IsShortRep() - { - return (BackPrev == 0); - } - } ; - - #endregion - - internal void SetTrainSize(uint trainSize) - { - _trainSize = trainSize; - } - } -} \ No newline at end of file diff --git a/BizHawk.Util/7z/sdk/Compress/RangeCoder/RangeCoder.cs b/BizHawk.Util/7z/sdk/Compress/RangeCoder/RangeCoder.cs deleted file mode 100644 index b371fe34ce..0000000000 --- a/BizHawk.Util/7z/sdk/Compress/RangeCoder/RangeCoder.cs +++ /dev/null @@ -1,249 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.IO; - -namespace SevenZip.Sdk.Compression.RangeCoder -{ - internal class Encoder - { - public const uint kTopValue = (1 << 24); - private byte _cache; - private uint _cacheSize; - - public UInt64 Low; - public uint Range; - - private long StartPosition; - private Stream Stream; - - public void SetStream(Stream stream) - { - Stream = stream; - } - - public void ReleaseStream() - { - Stream = null; - } - - public void Init() - { - StartPosition = Stream.Position; - - Low = 0; - Range = 0xFFFFFFFF; - _cacheSize = 1; - _cache = 0; - } - - public void FlushData() - { - for (int i = 0; i < 5; i++) - ShiftLow(); - } - - public void FlushStream() - { - Stream.Flush(); - } - - /*public void CloseStream() - { - Stream.Close(); - }*/ - - /*public void Encode(uint start, uint size, uint total) - { - Low += start * (Range /= total); - Range *= size; - while (Range < kTopValue) - { - Range <<= 8; - ShiftLow(); - } - }*/ - - public void ShiftLow() - { - if ((uint) Low < 0xFF000000 || (uint) (Low >> 32) == 1) - { - byte temp = _cache; - do - { - Stream.WriteByte((byte) (temp + (Low >> 32))); - temp = 0xFF; - } while (--_cacheSize != 0); - _cache = (byte) (((uint) Low) >> 24); - } - _cacheSize++; - Low = ((uint) Low) << 8; - } - - public void EncodeDirectBits(uint v, int numTotalBits) - { - for (int i = numTotalBits - 1; i >= 0; i--) - { - Range >>= 1; - if (((v >> i) & 1) == 1) - Low += Range; - if (Range < kTopValue) - { - Range <<= 8; - ShiftLow(); - } - } - } - - /*public void EncodeBit(uint size0, int numTotalBits, uint symbol) - { - uint newBound = (Range >> numTotalBits) * size0; - if (symbol == 0) - Range = newBound; - else - { - Low += newBound; - Range -= newBound; - } - while (Range < kTopValue) - { - Range <<= 8; - ShiftLow(); - } - }*/ - - public long GetProcessedSizeAdd() - { - return _cacheSize + - Stream.Position - StartPosition + 4; - // (long)Stream.GetProcessedSize(); - } - } - - internal class Decoder - { - public const uint kTopValue = (1 << 24); - public uint Code; - public uint Range; - // public Buffer.InBuffer Stream = new Buffer.InBuffer(1 << 16); - public Stream Stream; - - public void Init(Stream stream) - { - // Stream.Init(stream); - Stream = stream; - - Code = 0; - Range = 0xFFFFFFFF; - for (int i = 0; i < 5; i++) - Code = (Code << 8) | (byte) Stream.ReadByte(); - } - - public void ReleaseStream() - { - // Stream.ReleaseStream(); - Stream = null; - } - - /*public void CloseStream() - { - Stream.Close(); - }*/ - - /*public void Normalize() - { - while (Range < kTopValue) - { - Code = (Code << 8) | (byte)Stream.ReadByte(); - Range <<= 8; - } - }*/ - - /*public void Normalize2() - { - if (Range < kTopValue) - { - Code = (Code << 8) | (byte)Stream.ReadByte(); - Range <<= 8; - } - }*/ - - /*public uint GetThreshold(uint total) - { - return Code / (Range /= total); - }*/ - - /*public void Decode(uint start, uint size, uint total) - { - Code -= start * Range; - Range *= size; - Normalize(); - }*/ - - public uint DecodeDirectBits(int numTotalBits) - { - uint range = Range; - uint code = Code; - uint result = 0; - for (int i = numTotalBits; i > 0; i--) - { - range >>= 1; - /* - result <<= 1; - if (code >= range) - { - code -= range; - result |= 1; - } - */ - uint t = (code - range) >> 31; - code -= range & (t - 1); - result = (result << 1) | (1 - t); - - if (range < kTopValue) - { - code = (code << 8) | (byte) Stream.ReadByte(); - range <<= 8; - } - } - Range = range; - Code = code; - return result; - } - - /*public uint DecodeBit(uint size0, int numTotalBits) - { - uint newBound = (Range >> numTotalBits) * size0; - uint symbol; - if (Code < newBound) - { - symbol = 0; - Range = newBound; - } - else - { - symbol = 1; - Code -= newBound; - Range -= newBound; - } - Normalize(); - return symbol; - }*/ - - // ulong GetProcessedSize() {return Stream.GetProcessedSize(); } - } -} \ No newline at end of file diff --git a/BizHawk.Util/7z/sdk/Compress/RangeCoder/RangeCoderBit.cs b/BizHawk.Util/7z/sdk/Compress/RangeCoder/RangeCoderBit.cs deleted file mode 100644 index 48fa6db98f..0000000000 --- a/BizHawk.Util/7z/sdk/Compress/RangeCoder/RangeCoderBit.cs +++ /dev/null @@ -1,146 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; - -namespace SevenZip.Sdk.Compression.RangeCoder -{ - internal struct BitEncoder - { - public const uint kBitModelTotal = (1 << kNumBitModelTotalBits); - public const int kNumBitModelTotalBits = 11; - public const int kNumBitPriceShiftBits = 6; - private const int kNumMoveBits = 5; - private const int kNumMoveReducingBits = 2; - private static readonly UInt32[] ProbPrices = new UInt32[kBitModelTotal >> kNumMoveReducingBits]; - - private uint Prob; - - static BitEncoder() - { - const int kNumBits = (kNumBitModelTotalBits - kNumMoveReducingBits); - for (int i = kNumBits - 1; i >= 0; i--) - { - UInt32 start = (UInt32) 1 << (kNumBits - i - 1); - UInt32 end = (UInt32) 1 << (kNumBits - i); - for (UInt32 j = start; j < end; j++) - ProbPrices[j] = ((UInt32) i << kNumBitPriceShiftBits) + - (((end - j) << kNumBitPriceShiftBits) >> (kNumBits - i - 1)); - } - } - - public void Init() - { - Prob = kBitModelTotal >> 1; - } - - /*public void UpdateModel(uint symbol) - { - if (symbol == 0) - Prob += (kBitModelTotal - Prob) >> kNumMoveBits; - else - Prob -= (Prob) >> kNumMoveBits; - }*/ - - public void Encode(Encoder encoder, uint symbol) - { - // encoder.EncodeBit(Prob, kNumBitModelTotalBits, symbol); - // UpdateModel(symbol); - uint newBound = (encoder.Range >> kNumBitModelTotalBits)*Prob; - if (symbol == 0) - { - encoder.Range = newBound; - Prob += (kBitModelTotal - Prob) >> kNumMoveBits; - } - else - { - encoder.Low += newBound; - encoder.Range -= newBound; - Prob -= (Prob) >> kNumMoveBits; - } - if (encoder.Range < Encoder.kTopValue) - { - encoder.Range <<= 8; - encoder.ShiftLow(); - } - } - - public uint GetPrice(uint symbol) - { - return ProbPrices[(((Prob - symbol) ^ ((-(int) symbol))) & (kBitModelTotal - 1)) >> kNumMoveReducingBits]; - } - - public uint GetPrice0() - { - return ProbPrices[Prob >> kNumMoveReducingBits]; - } - - public uint GetPrice1() - { - return ProbPrices[(kBitModelTotal - Prob) >> kNumMoveReducingBits]; - } - } - - internal struct BitDecoder - { - public const uint kBitModelTotal = (1 << kNumBitModelTotalBits); - public const int kNumBitModelTotalBits = 11; - private const int kNumMoveBits = 5; - - private uint Prob; - - /*public void UpdateModel(int numMoveBits, uint symbol) - { - if (symbol == 0) - Prob += (kBitModelTotal - Prob) >> numMoveBits; - else - Prob -= (Prob) >> numMoveBits; - }*/ - - public void Init() - { - Prob = kBitModelTotal >> 1; - } - - public uint Decode(Decoder rangeDecoder) - { - uint newBound = (rangeDecoder.Range >> kNumBitModelTotalBits)*Prob; - if (rangeDecoder.Code < newBound) - { - rangeDecoder.Range = newBound; - Prob += (kBitModelTotal - Prob) >> kNumMoveBits; - if (rangeDecoder.Range < Decoder.kTopValue) - { - rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte) rangeDecoder.Stream.ReadByte(); - rangeDecoder.Range <<= 8; - } - return 0; - } - else - { - rangeDecoder.Range -= newBound; - rangeDecoder.Code -= newBound; - Prob -= (Prob) >> kNumMoveBits; - if (rangeDecoder.Range < Decoder.kTopValue) - { - rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte) rangeDecoder.Stream.ReadByte(); - rangeDecoder.Range <<= 8; - } - return 1; - } - } - } -} \ No newline at end of file diff --git a/BizHawk.Util/7z/sdk/Compress/RangeCoder/RangeCoderBitTree.cs b/BizHawk.Util/7z/sdk/Compress/RangeCoder/RangeCoderBitTree.cs deleted file mode 100644 index 2e3bd4d18b..0000000000 --- a/BizHawk.Util/7z/sdk/Compress/RangeCoder/RangeCoderBitTree.cs +++ /dev/null @@ -1,173 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; - -namespace SevenZip.Sdk.Compression.RangeCoder -{ - internal struct BitTreeEncoder - { - private readonly BitEncoder[] Models; - private readonly int NumBitLevels; - - public BitTreeEncoder(int numBitLevels) - { - NumBitLevels = numBitLevels; - Models = new BitEncoder[1 << numBitLevels]; - } - - public void Init() - { - for (uint i = 1; i < (1 << NumBitLevels); i++) - Models[i].Init(); - } - - public void Encode(Encoder rangeEncoder, UInt32 symbol) - { - UInt32 m = 1; - for (int bitIndex = NumBitLevels; bitIndex > 0;) - { - bitIndex--; - UInt32 bit = (symbol >> bitIndex) & 1; - Models[m].Encode(rangeEncoder, bit); - m = (m << 1) | bit; - } - } - - public void ReverseEncode(Encoder rangeEncoder, UInt32 symbol) - { - UInt32 m = 1; - for (UInt32 i = 0; i < NumBitLevels; i++) - { - UInt32 bit = symbol & 1; - Models[m].Encode(rangeEncoder, bit); - m = (m << 1) | bit; - symbol >>= 1; - } - } - - public UInt32 GetPrice(UInt32 symbol) - { - UInt32 price = 0; - UInt32 m = 1; - for (int bitIndex = NumBitLevels; bitIndex > 0;) - { - bitIndex--; - UInt32 bit = (symbol >> bitIndex) & 1; - price += Models[m].GetPrice(bit); - m = (m << 1) + bit; - } - return price; - } - - public UInt32 ReverseGetPrice(UInt32 symbol) - { - UInt32 price = 0; - UInt32 m = 1; - for (int i = NumBitLevels; i > 0; i--) - { - UInt32 bit = symbol & 1; - symbol >>= 1; - price += Models[m].GetPrice(bit); - m = (m << 1) | bit; - } - return price; - } - - public static UInt32 ReverseGetPrice(BitEncoder[] Models, UInt32 startIndex, - int NumBitLevels, UInt32 symbol) - { - UInt32 price = 0; - UInt32 m = 1; - for (int i = NumBitLevels; i > 0; i--) - { - UInt32 bit = symbol & 1; - symbol >>= 1; - price += Models[startIndex + m].GetPrice(bit); - m = (m << 1) | bit; - } - return price; - } - - public static void ReverseEncode(BitEncoder[] Models, UInt32 startIndex, - Encoder rangeEncoder, int NumBitLevels, UInt32 symbol) - { - UInt32 m = 1; - for (int i = 0; i < NumBitLevels; i++) - { - UInt32 bit = symbol & 1; - Models[startIndex + m].Encode(rangeEncoder, bit); - m = (m << 1) | bit; - symbol >>= 1; - } - } - } - - internal struct BitTreeDecoder - { - private readonly BitDecoder[] Models; - private readonly int NumBitLevels; - - public BitTreeDecoder(int numBitLevels) - { - NumBitLevels = numBitLevels; - Models = new BitDecoder[1 << numBitLevels]; - } - - public void Init() - { - for (uint i = 1; i < (1 << NumBitLevels); i++) - Models[i].Init(); - } - - public uint Decode(Decoder rangeDecoder) - { - uint m = 1; - for (int bitIndex = NumBitLevels; bitIndex > 0; bitIndex--) - m = (m << 1) + Models[m].Decode(rangeDecoder); - return m - ((uint) 1 << NumBitLevels); - } - - public uint ReverseDecode(Decoder rangeDecoder) - { - uint m = 1; - uint symbol = 0; - for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++) - { - uint bit = Models[m].Decode(rangeDecoder); - m <<= 1; - m += bit; - symbol |= (bit << bitIndex); - } - return symbol; - } - - public static uint ReverseDecode(BitDecoder[] Models, UInt32 startIndex, - Decoder rangeDecoder, int NumBitLevels) - { - uint m = 1; - uint symbol = 0; - for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++) - { - uint bit = Models[startIndex + m].Decode(rangeDecoder); - m <<= 1; - m += bit; - symbol |= (bit << bitIndex); - } - return symbol; - } - } -} \ No newline at end of file diff --git a/BizHawk.Util/7z/sdk/ICoder.cs b/BizHawk.Util/7z/sdk/ICoder.cs deleted file mode 100644 index a87019e2df..0000000000 --- a/BizHawk.Util/7z/sdk/ICoder.cs +++ /dev/null @@ -1,191 +0,0 @@ -/* This file is part of SevenZipSharp. - - SevenZipSharp is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - SevenZipSharp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with SevenZipSharp. If not, see . -*/ - -using System; -using System.IO; - -namespace SevenZip.Sdk -{ - /// - /// The exception that is thrown when an error in input stream occurs during decoding. - /// - [Serializable] - internal class DataErrorException : ApplicationException - { - public DataErrorException() : base("Data Error") {} - } - - /// - /// The exception that is thrown when the value of an argument is outside the allowable range. - /// - internal class InvalidParamException : ApplicationException - { - public InvalidParamException() : base("Invalid Parameter") {} - } - - /// - /// Callback progress interface. - /// - public interface ICodeProgress - { - /// - /// Callback progress. - /// - /// - /// Processed input size. -1 if unknown. - /// - /// - /// Processed output size. -1 if unknown. - /// - void SetProgress(Int64 inSize, Int64 outSize); - } ; - - /// - /// Stream coder interface - /// - public interface ICoder - { - /// - /// Codes streams. - /// - /// - /// input Stream. - /// - /// - /// output Stream. - /// - /// - /// input Size. -1 if unknown. - /// - /// - /// output Size. -1 if unknown. - /// - /// - /// callback progress reference. - /// - /// - /// if input stream is not valid - /// - void Code(Stream inStream, Stream outStream, - Int64 inSize, Int64 outSize, ICodeProgress progress); - } ; - - /* - public interface ICoder2 - { - void Code(ISequentialInStream []inStreams, - const UInt64 []inSizes, - ISequentialOutStream []outStreams, - UInt64 []outSizes, - ICodeProgress progress); - }; - */ - - /// - /// Provides the fields that represent properties idenitifiers for compressing. - /// - public enum CoderPropId - { - /// - /// Specifies default property. - /// - DefaultProp = 0, - /// - /// Specifies size of dictionary. - /// - DictionarySize, - /// - /// Specifies size of memory for PPM*. - /// - UsedMemorySize, - /// - /// Specifies order for PPM methods. - /// - Order, - /// - /// Specifies Block Size. - /// - BlockSize, - /// - /// Specifies number of postion state bits for LZMA (0 <= x <= 4). - /// - PosStateBits, - /// - /// Specifies number of literal context bits for LZMA (0 <= x <= 8). - /// - LitContextBits, - /// - /// Specifies number of literal position bits for LZMA (0 <= x <= 4). - /// - LitPosBits, - /// - /// Specifies number of fast bytes for LZ*. - /// - NumFastBytes, - /// - /// Specifies match finder. LZMA: "BT2", "BT4" or "BT4B". - /// - MatchFinder, - /// - /// Specifies the number of match finder cyckes. - /// - MatchFinderCycles, - /// - /// Specifies number of passes. - /// - NumPasses, - /// - /// Specifies number of algorithm. - /// - Algorithm, - /// - /// Specifies the number of threads. - /// - NumThreads, - /// - /// Specifies mode with end marker. - /// - EndMarker = 0x490 - } ; - - /// - /// The ISetCoderProperties interface - /// - internal interface ISetCoderProperties - { - void SetCoderProperties(CoderPropId[] propIDs, object[] properties); - } ; - - /// - /// The IWriteCoderProperties interface - /// - internal interface IWriteCoderProperties - { - void WriteCoderProperties(Stream outStream); - } - - /// - /// The ISetDecoderPropertiesinterface - /// - internal interface ISetDecoderProperties - { - /// - /// Sets decoder properties - /// - /// Array of byte properties - void SetDecoderProperties(byte[] properties); - } -} \ No newline at end of file diff --git a/BizHawk.Util/FolderBrowserDialogEx.cs b/BizHawk.Util/FolderBrowserDialogEx.cs deleted file mode 100644 index bbd6179fff..0000000000 --- a/BizHawk.Util/FolderBrowserDialogEx.cs +++ /dev/null @@ -1,307 +0,0 @@ -using System.Runtime.InteropServices; -using System.Text; -using System; -using System.Windows.Forms; -using System.ComponentModel; -using System.Security.Permissions; - - -namespace BizHawk -{ - - /// - /// Component wrapping access to the Browse For Folder common dialog box. - /// Call the ShowDialog() method to bring the dialog box up. - /// - public sealed class FolderBrowserEx : Component - { - private const int MAX_PATH = 260; - - // Root node of the tree view. - private FolderID startLocation = FolderID.Desktop; - - // Browse info options. - private int publicOptions = (int) Win32API.Shell32.BffStyles.RestrictToFilesystem | - (int) Win32API.Shell32.BffStyles.RestrictToDomain; - - private const int privateOptions = (int) (Win32API.Shell32.BffStyles.NewDialogStyle | Win32API.Shell32.BffStyles.ShowTextBox); - - // Description text to show. - public string Description = "Please select a folder below:"; - - /// - /// Enum of CSIDLs identifying standard shell folders. - /// - public enum FolderID - { - Desktop = 0x0000, - Printers = 0x0004, - MyDocuments = 0x0005, - Favorites = 0x0006, - Recent = 0x0008, - SendTo = 0x0009, - StartMenu = 0x000b, - MyComputer = 0x0011, - NetworkNeighborhood = 0x0012, - Templates = 0x0015, - MyPictures = 0x0027, - NetAndDialUpConnections = 0x0031, - } - - /// - /// Helper function that returns the IMalloc interface used by the shell. - /// - private static Win32API.IMalloc GetSHMalloc() - { - Win32API.IMalloc malloc; - Win32API.Shell32.SHGetMalloc(out malloc); - return malloc; - } - - /// - /// Shows the folder browser dialog box. - /// - public DialogResult ShowDialog() - { - return ShowDialog(null); - } - - - private int callback(IntPtr hwnd, uint uMsg, IntPtr lParam, IntPtr lpData) - { - switch (uMsg) - { - case 1: - { - IntPtr str = Marshal.StringToHGlobalUni(SelectedPath); - Win32.SendMessage(hwnd, (0x400 + 103), 1, str.ToInt32()); - Marshal.FreeHGlobal(str); - break; - } - - } - return 0; - } - - - /// - /// Shows the folder browser dialog box with the specified owner window. - /// - public DialogResult ShowDialog(IWin32Window owner) - { - IntPtr pidlRoot = IntPtr.Zero; - - // Get/find an owner HWND for this dialog. - IntPtr hWndOwner; - - if (owner != null) - { - hWndOwner = owner.Handle; - } - else - { - hWndOwner = Win32API.GetActiveWindow(); - } - - // Get the IDL for the specific startLocation. - Win32API.Shell32.SHGetSpecialFolderLocation(hWndOwner, (int) startLocation, out pidlRoot); - - if (pidlRoot == IntPtr.Zero) - { - return DialogResult.Cancel; - } - - int mergedOptions = (int) publicOptions | (int) privateOptions; - - if ((mergedOptions & (int) Win32API.Shell32.BffStyles.NewDialogStyle) != 0) - { - if (System.Threading.ApartmentState.MTA == Application.OleRequired()) - mergedOptions = mergedOptions & (~(int) Win32API.Shell32.BffStyles.NewDialogStyle); - } - - IntPtr pidlRet = IntPtr.Zero; - - try - { - // Construct a BROWSEINFO. - Win32API.Shell32.BROWSEINFO bi = new Win32API.Shell32.BROWSEINFO(); - IntPtr buffer = Marshal.AllocHGlobal(MAX_PATH); - - bi.pidlRoot = pidlRoot; - bi.hwndOwner = hWndOwner; - bi.pszDisplayName = buffer; - bi.lpszTitle = Description; - bi.ulFlags = mergedOptions; - bi.lpfn = new Win32API.Shell32.BFFCALLBACK(callback); - // The rest of the fields are initialized to zero by the constructor. - // bi.lParam = IntPtr.Zero; bi.iImage = 0; - - // Show the dialog. - pidlRet = Win32API.Shell32.SHBrowseForFolder(ref bi); - - // Free the buffer you've allocated on the global heap. - Marshal.FreeHGlobal(buffer); - - if (pidlRet == IntPtr.Zero) - { - // User clicked Cancel. - return DialogResult.Cancel; - } - - // Then retrieve the path from the IDList. - StringBuilder sb = new StringBuilder(MAX_PATH); - if (0 == Win32API.Shell32.SHGetPathFromIDList(pidlRet, sb)) - { - return DialogResult.Cancel; - } - - // Convert to a string. - } - finally - { - Win32API.IMalloc malloc = GetSHMalloc(); - malloc.Free(pidlRoot); - - if (pidlRet != IntPtr.Zero) - { - malloc.Free(pidlRet); - } - } - - return DialogResult.OK; - } - - /// - /// Helper function used to set and reset bits in the publicOptions bitfield. - /// - private void SetOptionField(int mask, bool turnOn) - { - if (turnOn) - publicOptions |= mask; - else - publicOptions &= ~mask; - } - - /// - /// Only return file system directories. If the user selects folders - /// that are not part of the file system, the OK button is unavailable. - /// - [Category("Navigation")] - [Description("Only return file system directories. If the user selects folders " + - "that are not part of the file system, the OK button is unavailable.")] - [DefaultValue(true)] - public bool OnlyFilesystem - { - get { return (publicOptions & (int) Win32API.Shell32.BffStyles.RestrictToFilesystem) != 0; } - set { SetOptionField((int) Win32API.Shell32.BffStyles.RestrictToFilesystem, value); } - } - - /// - /// Location of the root folder from which to start browsing. Only the specified - /// folder and any folders beneath it in the namespace hierarchy appear - /// in the dialog box. - /// - [Category("Navigation")] - [Description("Location of the root folder from which to start browsing. Only the specified " + - "folder and any folders beneath it in the namespace hierarchy appear " + - "in the dialog box.")] - [DefaultValue(typeof (FolderID), "0")] - public FolderID StartLocation - { - get { return startLocation; } - set - { - new UIPermission(UIPermissionWindow.AllWindows).Demand(); - startLocation = value; - } - } - - public string SelectedPath; - - } - - - - - - internal class Win32API - { - // C# representation of the IMalloc interface. - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown), - Guid("00000002-0000-0000-C000-000000000046")] - public interface IMalloc - { - [PreserveSig] - IntPtr Alloc([In] int cb); - - [PreserveSig] - IntPtr Realloc([In] IntPtr pv, [In] int cb); - - [PreserveSig] - void Free([In] IntPtr pv); - - [PreserveSig] - int GetSize([In] IntPtr pv); - - [PreserveSig] - int DidAlloc(IntPtr pv); - - [PreserveSig] - void HeapMinimize(); - } - - [DllImport("User32.DLL")] - public static extern IntPtr GetActiveWindow(); - - public class Shell32 - { - // Styles used in the BROWSEINFO.ulFlags field. - [Flags] - public enum BffStyles - { - RestrictToFilesystem = 0x0001, // BIF_RETURNONLYFSDIRS - RestrictToDomain = 0x0002, // BIF_DONTGOBELOWDOMAIN - RestrictToSubfolders = 0x0008, // BIF_RETURNFSANCESTORS - ShowTextBox = 0x0010, // BIF_EDITBOX - ValidateSelection = 0x0020, // BIF_VALIDATE - NewDialogStyle = 0x0040, // BIF_NEWDIALOGSTYLE - BrowseForComputer = 0x1000, // BIF_BROWSEFORCOMPUTER - BrowseForPrinter = 0x2000, // BIF_BROWSEFORPRINTER - BrowseForEverything = 0x4000, // BIF_BROWSEINCLUDEFILES - } - - // Delegate type used in BROWSEINFO.lpfn field. - public delegate int BFFCALLBACK(IntPtr hwnd, uint uMsg, IntPtr lParam, IntPtr lpData); - - [StructLayout(LayoutKind.Sequential, Pack = 8)] - public struct BROWSEINFO - { - public IntPtr hwndOwner; - public IntPtr pidlRoot; - public IntPtr pszDisplayName; - [MarshalAs(UnmanagedType.LPTStr)] public string lpszTitle; - public int ulFlags; - [MarshalAs(UnmanagedType.FunctionPtr)] public BFFCALLBACK lpfn; - public IntPtr lParam; - public int iImage; - } - - [DllImport("Shell32.DLL")] - public static extern int SHGetMalloc(out IMalloc ppMalloc); - - [DllImport("Shell32.DLL")] - public static extern int SHGetSpecialFolderLocation( - IntPtr hwndOwner, int nFolder, out IntPtr ppidl); - - [DllImport("Shell32.DLL")] - public static extern int SHGetPathFromIDList( - IntPtr pidl, StringBuilder Path); - - [DllImport("Shell32.DLL", CharSet = CharSet.Auto)] - public static extern IntPtr SHBrowseForFolder(ref BROWSEINFO bi); - } - } - - - -} \ No newline at end of file diff --git a/BizHawk.Util/HexTextBox.cs b/BizHawk.Util/HexTextBox.cs deleted file mode 100644 index 73289e5637..0000000000 --- a/BizHawk.Util/HexTextBox.cs +++ /dev/null @@ -1,243 +0,0 @@ -using System; -using System.Globalization; -using System.Windows.Forms; - -namespace BizHawk -{ - public interface INumberBox - { - int ToRawInt(); - void SetFromRawInt(int rawint); - bool Nullable { get; } - } - - public class HexTextBox : TextBox, INumberBox - { - private string _addressFormatStr = "{0:X4}"; - private int? _maxSize = null; - private bool _nullable = true; - - public bool Nullable { get { return _nullable; } set { _nullable = value; } } - - public void SetHexProperties(int domainSize) - { - _maxSize = domainSize - 1; - MaxLength = IntHelpers.GetNumDigits(_maxSize.Value); - _addressFormatStr = "{0:X" + MaxLength.ToString() + "}"; - - ResetText(); - } - - private uint GetMax() - { - if (_maxSize.HasValue) - { - return (uint)_maxSize.Value; - } - else - { - return IntHelpers.MaxHexValueFromMaxDigits(MaxLength); - } - } - - public override void ResetText() - { - if (_nullable) - { - Text = String.Empty; - } - else - { - Text = String.Format(_addressFormatStr, 0); - } - } - - public HexTextBox() - { - CharacterCasing = CharacterCasing.Upper; - } - - protected override void OnKeyPress(KeyPressEventArgs e) - { - if (e.KeyChar == '\b' || e.KeyChar == 22 || e.KeyChar == 1 || e.KeyChar == 3) - { - return; - } - else if (!InputValidate.IsValidHexNumber(e.KeyChar)) - { - e.Handled = true; - } - } - - protected override void OnKeyDown(KeyEventArgs e) - { - if (e.KeyCode == Keys.Up) - { - if (InputValidate.IsValidHexNumber(Text)) - { - uint val = (uint)ToRawInt(); - - if (val == GetMax()) - { - val = 0; - } - else - { - val++; - } - - Text = String.Format(_addressFormatStr, val); - } - } - else if (e.KeyCode == Keys.Down) - { - if (InputValidate.IsValidHexNumber(Text)) - { - uint val = (uint)ToRawInt(); - if (val == 0) - { - val = GetMax(); - } - else - { - val--; - } - - Text = String.Format(_addressFormatStr, val); - } - } - else - { - base.OnKeyDown(e); - } - } - - protected override void OnTextChanged(EventArgs e) - { - if (String.IsNullOrWhiteSpace(Text)) - { - ResetText(); - } - } - - public int ToRawInt() - { - if (String.IsNullOrWhiteSpace(Text)) - { - return 0; - } - else - { - return int.Parse(Text, NumberStyles.HexNumber); - } - } - - public void SetFromRawInt(int val) - { - Text = String.Format(_addressFormatStr, val); - } - } - - public class UnsignedIntegerBox : TextBox, INumberBox - { - public UnsignedIntegerBox() - { - CharacterCasing = CharacterCasing.Upper; - } - - private bool _nullable = true; - - public bool Nullable { get { return _nullable; } set { _nullable = value; } } - - protected override void OnKeyPress(KeyPressEventArgs e) - { - if (e.KeyChar == '\b' || e.KeyChar == 22 || e.KeyChar == 1 || e.KeyChar == 3) - { - return; - } - else if (!InputValidate.IsValidUnsignedNumber(e.KeyChar)) - { - e.Handled = true; - } - } - - public override void ResetText() - { - if (_nullable) - { - Text = String.Empty; - } - else - { - Text = "0"; - } - } - - protected override void OnKeyDown(KeyEventArgs e) - { - if (e.KeyCode == Keys.Up) - { - if (InputValidate.IsValidUnsignedNumber(Text)) - { - uint val = (uint)ToRawInt(); - if (val == uint.MaxValue) - { - val = 0; - } - else - { - val++; - } - Text = val.ToString(); - } - } - else if (e.KeyCode == Keys.Down) - { - if (InputValidate.IsValidUnsignedNumber(Text)) - { - uint val = (uint)ToRawInt(); - - if (val == 0) - { - val = uint.MaxValue; - } - else - { - val--; - } - - Text = val.ToString(); - } - } - else - { - base.OnKeyDown(e); - } - } - - protected override void OnTextChanged(EventArgs e) - { - if (String.IsNullOrWhiteSpace(Text)) - { - ResetText(); - } - } - - public int ToRawInt() - { - if (String.IsNullOrWhiteSpace(Text)) - { - return 0; - } - else - { - return (int)uint.Parse(Text); - } - } - - public void SetFromRawInt(int val) - { - Text = val.ToString(); - } - } -} diff --git a/BizHawk.Util/InputConfigBase.cs b/BizHawk.Util/InputConfigBase.cs deleted file mode 100644 index d8627a56f7..0000000000 --- a/BizHawk.Util/InputConfigBase.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Collections.Generic; -using System.Windows.Forms; - -namespace BizHawk -{ - public class InputConfigBase : Form - { - public void CheckDups() - { - Dictionary dups = new Dictionary(); - foreach (Control c in Controls) - { - SmartTextBoxControl stbc = c as SmartTextBoxControl; - if (stbc == null) continue; - if (dups.ContainsKey(stbc.Text)) - { - MessageBox.Show("DUP!"); - return; - } - dups[stbc.Text] = true; - } - } - - } -} \ No newline at end of file diff --git a/BizHawk.Util/InputConfigBase.resx b/BizHawk.Util/InputConfigBase.resx deleted file mode 100644 index ff31a6db56..0000000000 --- a/BizHawk.Util/InputConfigBase.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/BizHawk.Util/InputValidate.cs b/BizHawk.Util/InputValidate.cs deleted file mode 100644 index 3252c880d6..0000000000 --- a/BizHawk.Util/InputValidate.cs +++ /dev/null @@ -1,277 +0,0 @@ -using System.Text; - -namespace BizHawk -{ - /// - /// Includes helper functions to validate user input - /// - public static class InputValidate - { - public static bool IsValidUnsignedNumber(string Str) - { - char[] input = (Str.ToCharArray()); - ASCIIEncoding AE = new ASCIIEncoding(); - // Check each character in the new label to determine if it is a number. - for (int x = 0; x < input.Length; x++) - { - // Encode the character from the character array to its ASCII code. - byte[] bc = AE.GetBytes(input[x].ToString()); - - // Determine if the ASCII code is within the valid range of numerical values. - if (bc[0] < 47 || bc[0] > 58) - return false; - } - return true; - } - - public static bool IsValidUnsignedNumber(char c) - { - if (c < 47 || c > 58) - return false; - - return true; - } - - /// - /// Validates all chars are 0-9 or a dash as the first value - /// - /// - /// - public static bool IsValidSignedNumber(string Str) - { - char[] input = (Str.Trim().ToCharArray()); - ASCIIEncoding AE = new ASCIIEncoding(); - // Check each character in the new label to determine if it is a number. - for (int x = 0; x < input.Length; x++) - { - // Encode the character from the character array to its ASCII code. - byte[] bc = AE.GetBytes(input[x].ToString()); - - // Determine if the ASCII code is within the valid range of numerical values. - if (bc[0] > 58) - return false; - - if (bc[0] < 47) - { - if (bc[0] == 45 && x == 0) - continue; - else - return false; - } - - } - return true; - } - - public static bool IsValidSignedNumber(char c) - { - if (c == 45) return true; - - if (c < 47 || c > 58) - return false; - - return true; - } - - /// - /// validates is a Hex number 0-9, A-F (must be capital letters) - /// - /// - public static bool IsValidHexNumber(string Str) - { - char[] input = (Str.ToCharArray()); - ASCIIEncoding AE = new ASCIIEncoding(); - // Check each character in the new label to determine if it is a number. - for (int x = 0; x < input.Length; x++) - { - // Encode the character from the character array to its ASCII code. - byte[] bc = AE.GetBytes(input[x].ToString()); - - // Determine if the ASCII code is within the valid range of numerical values. - if (bc[0] < 47) //0 - return false; - if (bc[0] > 58) //9 - { - if (bc[0] < 65) //A - return false; - - if (bc[0] > 70) //F - { - if (bc[0] < 97 || bc[0] > 102) //a-f - return false; - } - } - } - return true; - } - - public static bool IsValidHexNumber(char c) - { - if (c < 47) return false; //0 - - if (c > 58) //9 - { - if (c < 65) //A - return false; - - if (c > 70) //F - { - if (c < 97 || c > 102) //a-f - return false; - } - } - return true; - } - - /// - /// Takes any string and removes any value that is not a valid hex value (0-9, a-f, A-F), returns the remaining characters in uppercase - /// - /// - /// - public static string DoHexString(string raw) - { - raw = raw.ToUpper(); - StringBuilder output = new StringBuilder(); - foreach (char x in raw) - { - if (x >= 'A' && x <= 'F') - { - output.Append(x); - } - else if (x >= '0' && x <= '9') - { - output.Append(x); - } - } - return output.ToString(); - } - - - public static bool IsValidBinaryNumber(string s) - { - char[] input = (s.ToCharArray()); - ASCIIEncoding AE = new ASCIIEncoding(); - // Check each character in the new label to determine if it is a number. - for (int x = 0; x < input.Length; x++) - { - // Encode the character from the character array to its ASCII code. - byte[] bc = AE.GetBytes(input[x].ToString()); - - // Determine if the ASCII code is within the valid range of numerical values. - if (bc[0] != 48 && bc[0] != 49) //0 or 1 - { - return false; - } - } - return true; - } - - public static bool IsValidBinaryNumber(char c) - { - return (c == 48 || c == 49); - } - - /// - /// Validates all chars are 0-9 or decimal - /// - /// - /// - public static bool IsValidFixedPointNumber(string Str) - { - if (StringHelpers.HowMany(Str, '.') > 1) - { - return false; - } - - char[] input = (Str.Trim().ToCharArray()); - ASCIIEncoding AE = new ASCIIEncoding(); - // Check each character in the new label to determine if it is a number. - - for (int x = 0; x < input.Length; x++) - { - // Encode the character from the character array to its ASCII code. - byte[] bc = AE.GetBytes(input[x].ToString()); - - // Determine if the ASCII code is within the valid range of numerical values. - if (bc[0] > 58) - return false; - - if (bc[0] == 46) - continue; - - if (bc[0] < 48) - { - if (bc[0] == 45 && x == 0) - continue; - else - return false; - } - - } - return true; - } - - public static bool IsValidFixedPointNumber(char c) - { - if (c == 46 || c == 45) return true; - - if (c < 48 || c > 58) - return false; - - return true; - } - - /// - /// Validates all chars are 0-9 or decimal or dash as the first character - /// - /// - /// - public static bool IsValidDecimalNumber(string Str) - { - if (StringHelpers.HowMany(Str, '.') > 1) - { - return false; - } - - char[] input = (Str.Trim().ToCharArray()); - ASCIIEncoding AE = new ASCIIEncoding(); - // Check each character in the new label to determine if it is a number. - for (int x = 0; x < input.Length; x++) - { - // Encode the character from the character array to its ASCII code. - byte[] bc = AE.GetBytes(input[x].ToString()); - - // Determine if the ASCII code is within the valid range of numerical values. - if (bc[0] > 58) - return false; - - if (bc[0] == 46) - continue; - - if (bc[0] < 48) - { - if (bc[0] == 45 && x == 0) - continue; - else - return false; - } - - } - return true; - } - - public static bool IsValidDecimalNumber(char c) - { - if (c == 45 || c == 46) //45 = dash, 46 = dot - { - return true; - } - else if (c < 48 || c > 58) - { - return false; - } - - return true; - } - } -} diff --git a/BizHawk.Util/KeyTurbo.cs b/BizHawk.Util/KeyTurbo.cs deleted file mode 100644 index 6fe6eb6ed6..0000000000 --- a/BizHawk.Util/KeyTurbo.cs +++ /dev/null @@ -1,36 +0,0 @@ -namespace BizHawk -{ - public class TurboKey - { - public void Reset(int downTime, int upTime) - { - Value = false; - _timer = 0; - _upTime = upTime; - _downTime = downTime; - } - - public void Tick(bool down) - { - if (!down) - { - Reset(_downTime, _upTime); - return; - } - - _timer++; - - Value = true; - if (_timer > _downTime) - Value = false; - if(_timer > (_upTime+_downTime)) - { - _timer = 0; - Value = true; - } - } - - public bool Value; - private int _upTime, _downTime, _timer; - } -} \ No newline at end of file diff --git a/BizHawk.Util/MiscControls.cs b/BizHawk.Util/MiscControls.cs deleted file mode 100644 index 4ea75770b7..0000000000 --- a/BizHawk.Util/MiscControls.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System.Drawing; -using System.Windows.Forms; - -namespace BizHawk.Core -{ - public class HorizontalLine : Control - { - protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) - { - base.SetBoundsCore(x, y, width, 2, specified); - } - - protected override void OnPaint(PaintEventArgs e) - { - ControlPaint.DrawBorder3D(e.Graphics, 0, 0, Width, 2, Border3DStyle.Etched); - } - } - - public class CustomCheckBox : CheckBox - { - Color _CheckBackColor = SystemColors.Control; - public Color CheckBackColor - { - get { return _CheckBackColor; } - set { _CheckBackColor = value; Refresh(); } - } - - bool? _ForceChecked; - public bool? ForceChecked - { - get { return _ForceChecked; } - set { _ForceChecked = value; Refresh(); } - } - - protected override void OnPaint(PaintEventArgs pevent) - { - //draw text-label part of the control with something so that it isn't hallofmirrorsy - using(var brush = new SolidBrush(Parent.BackColor)) - pevent.Graphics.FillRectangle(brush, ClientRectangle); - - var r = new Rectangle(ClientRectangle.Location, SystemInformation.MenuCheckSize); - var glyphLoc = ClientRectangle; - glyphLoc.Size = SystemInformation.MenuCheckSize; - - //draw the selectedbackdrop color roughly where the glyph belongs - using (var brush = new SolidBrush(_CheckBackColor)) - pevent.Graphics.FillRectangle(brush, glyphLoc); - - //draw a checkbox menu glyph (we could do this more elegantly with DrawFrameControl) - bool c = CheckState == CheckState.Checked; - if (ForceChecked.HasValue) - { - c = ForceChecked.Value; - } - if (c) - { - glyphLoc.Y--; - glyphLoc.X++; - ControlPaint.DrawMenuGlyph(pevent.Graphics, glyphLoc, MenuGlyph.Checkmark, Color.Black, Color.Transparent); - } - - //draw a border on top of it all - ControlPaint.DrawBorder3D(pevent.Graphics, r, Border3DStyle.Sunken); - - //stuff that didnt work - //CheckBoxRenderer.DrawParentBackground(pevent.Graphics, ClientRectangle, this); - //CheckBoxRenderer.DrawCheckBox(pevent.Graphics, ClientRectangle.Location, System.Windows.Forms.VisualStyles.CheckBoxState.CheckedNormal); - //glyphLoc.Size = new System.Drawing.Size(SystemInformation.MenuCheckSize.Width-1,SystemInformation.MenuCheckSize.Height-1); - } - } - -} \ No newline at end of file diff --git a/BizHawk.Util/QuickProgressPopup.Designer.cs b/BizHawk.Util/QuickProgressPopup.Designer.cs deleted file mode 100644 index 7094caf040..0000000000 --- a/BizHawk.Util/QuickProgressPopup.Designer.cs +++ /dev/null @@ -1,77 +0,0 @@ -namespace BizHawk -{ - partial class QuickProgressPopup - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.progressBar = new System.Windows.Forms.ProgressBar(); - this.lblProgress = new System.Windows.Forms.Label(); - this.SuspendLayout(); - // - // progressBar - // - this.progressBar.Location = new System.Drawing.Point(12, 12); - this.progressBar.Name = "progressBar"; - this.progressBar.Size = new System.Drawing.Size(194, 23); - this.progressBar.TabIndex = 0; - // - // lblProgress - // - this.lblProgress.AutoSize = true; - this.lblProgress.Location = new System.Drawing.Point(12, 41); - this.lblProgress.Margin = new System.Windows.Forms.Padding(3); - this.lblProgress.Name = "lblProgress"; - this.lblProgress.Size = new System.Drawing.Size(35, 13); - this.lblProgress.TabIndex = 1; - this.lblProgress.Text = "label1"; - // - // QuickProgressPopup - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.AutoSize = true; - this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - this.ClientSize = new System.Drawing.Size(229, 63); - this.ControlBox = false; - this.Controls.Add(this.lblProgress); - this.Controls.Add(this.progressBar); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "QuickProgressPopup"; - this.Text = "Please wait..."; - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.ProgressBar progressBar; - private System.Windows.Forms.Label lblProgress; - } -} \ No newline at end of file diff --git a/BizHawk.Util/QuickProgressPopup.cs b/BizHawk.Util/QuickProgressPopup.cs deleted file mode 100644 index c3ac041523..0000000000 --- a/BizHawk.Util/QuickProgressPopup.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Windows.Forms; - -namespace BizHawk -{ - public partial class QuickProgressPopup : Form - { - public QuickProgressPopup() - { - InitializeComponent(); - } - } -} diff --git a/BizHawk.Util/QuickProgressPopup.resx b/BizHawk.Util/QuickProgressPopup.resx deleted file mode 100644 index 29dcb1b3a3..0000000000 --- a/BizHawk.Util/QuickProgressPopup.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/BizHawk.Util/SmartTextBoxControl.cs b/BizHawk.Util/SmartTextBoxControl.cs deleted file mode 100644 index 34d8b7b35a..0000000000 --- a/BizHawk.Util/SmartTextBoxControl.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.Windows.Forms; - -namespace BizHawk -{ - public class SmartTextBoxControl : TextBox - { - public SmartTextBoxControl() - { - ReadOnly = true; - } - protected override void OnKeyDown(KeyEventArgs e) - { - base.Text = e.KeyCode.ToString(); - OnTextChanged(new EventArgs()); - } - - protected override void OnKeyPress(KeyPressEventArgs e) - { - - } - - protected override void OnKeyUp(KeyEventArgs e) - { - } - - public override string Text - { - get { return base.Text; } - set { } - } - - } -} \ No newline at end of file diff --git a/BizHawk.Util/StringHelpers.cs b/BizHawk.Util/StringHelpers.cs deleted file mode 100644 index ef55c81fd9..0000000000 --- a/BizHawk.Util/StringHelpers.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System; -using System.Linq; - -namespace BizHawk -{ - public static class StringHelpers - { - public static int HowMany(string str, char c) - { - if (!String.IsNullOrEmpty(str)) - { - return str.Count(t => t == c); - } - else - { - return 0; - } - } - - public static int HowMany(string str, string s) - { - int count = 0; - for (int x = 0; x < (str.Length - s.Length); x++) - { - if (str.Substring(x, s.Length) == s) - count++; - } - return count; - } - } - - //TODO: put it in its own file - public static class IntHelpers //TODO: a less lame name - { - public static int GetNumDigits(Int32 i) - { - //if (i == 0) return 0; - //if (i < 0x10) return 1; - if (i < 0x100) return 2; - //if (i < 0x1000) return 3; //adelikat: let's only do even numbers - if (i < 0x10000) return 4; - if (i < 0x1000000) return 6; - else return 8; - } - - public static uint MaxHexValueFromMaxDigits(Int32 i) - { - switch (i) - { - case 0: - return 0; - case 1: - return 0xF; - case 2: - return 0xFF; - case 3: - return 0xFFF; - case 4: - return 0xFFFF; - case 5: - return 0xFFFFF; - case 6: - return 0xFFFFFF; - case 7: - return 0xFFFFFFF; - case 8: - return 0xFFFFFFFF; - } - - return int.MaxValue; - } - } -} diff --git a/BizHawk.Util/TextDebugView.cs b/BizHawk.Util/TextDebugView.cs deleted file mode 100644 index 1c061cbe88..0000000000 --- a/BizHawk.Util/TextDebugView.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System.Drawing; -using System.Windows.Forms; - -namespace BizHawk -{ - public class TextDebugView : Control - { - public TextDebugView() - { - SetStyle(ControlStyles.AllPaintingInWmPaint, true); - SetStyle(ControlStyles.Opaque, true); - SetStyle(ControlStyles.OptimizedDoubleBuffer, true); - } - protected override void OnPaint(PaintEventArgs e) - { - base.OnPaint(e); - e.Graphics.Clear(SystemColors.Control); - Font font = new Font(new FontFamily("Courier New"), 8); - e.Graphics.DrawString(Text, font, Brushes.Black,0,0); - font.Dispose(); - } - - public override string Text - { - get - { - return base.Text; - } - set - { - base.Text = value; - Invalidate(); - } - } - } - - public class TextDebugForm : Form - { - public TextDebugView view = new TextDebugView(); - public TextDebugForm() - { - view.Dock = DockStyle.Fill; - Controls.Add(view); - } - - public override string Text - { - get - { - return view.Text; - } - set - { - view.Text = value; - } - } - } -} \ No newline at end of file diff --git a/BizHawk.Util/ToolStripEx.cs b/BizHawk.Util/ToolStripEx.cs deleted file mode 100644 index fe7a40bf41..0000000000 --- a/BizHawk.Util/ToolStripEx.cs +++ /dev/null @@ -1,84 +0,0 @@ -//credit: http://blogs.msdn.com/b/rickbrew/archive/2006/01/09/511003.aspx - -using System; -using System.Windows.Forms; - -/// -/// This class adds on to the functionality provided in System.Windows.Forms.ToolStrip. -/// -public class ToolStripEx : ToolStrip -{ - private bool clickThrough = true; - - /// - /// Gets or sets whether the ToolStripEx honors item clicks when its containing form does - /// not have input focus. - /// - public bool ClickThrough - { - get - { - return clickThrough; - } - set - { - clickThrough = value; - } - } - - protected override void WndProc(ref Message m) - { - base.WndProc(ref m); - if (clickThrough && - m.Msg == NativeConstants.WM_MOUSEACTIVATE && - m.Result == (IntPtr)NativeConstants.MA_ACTIVATEANDEAT) - { - m.Result = (IntPtr)NativeConstants.MA_ACTIVATE; - } - } -} - -/// -/// This class adds on to the functionality provided in System.Windows.Forms.MenuStrip. -/// -public class MenuStripEx : MenuStrip -{ - private bool clickThrough = true; - - /// - /// Gets or sets whether the ToolStripEx honors item clicks when its containing form does - /// not have input focus. - /// - public bool ClickThrough - { - get - { - return clickThrough; - } - set - { - clickThrough = value; - } - } - - protected override void WndProc(ref Message m) - { - base.WndProc(ref m); - if (clickThrough && - m.Msg == NativeConstants.WM_MOUSEACTIVATE && - m.Result == (IntPtr)NativeConstants.MA_ACTIVATEANDEAT) - { - m.Result = (IntPtr)NativeConstants.MA_ACTIVATE; - } - } -} - -internal sealed class NativeConstants -{ - private NativeConstants(){} - internal const uint WM_MOUSEACTIVATE = 0x21; - internal const uint MA_ACTIVATE = 1; - internal const uint MA_ACTIVATEANDEAT = 2; - internal const uint MA_NOACTIVATE = 3; - internal const uint MA_NOACTIVATEANDEAT = 4; -} \ No newline at end of file diff --git a/BizHawk.Util/Util.cs b/BizHawk.Util/Util.cs deleted file mode 100644 index 5ecd9dac91..0000000000 --- a/BizHawk.Util/Util.cs +++ /dev/null @@ -1,139 +0,0 @@ -using System; -using System.Text; -using System.ComponentModel; -using System.Runtime.InteropServices; -using System.Windows.Forms; - -namespace BizHawk -{ - public static class Extensions - { - //extension method to make Control.Invoke easier to use - public static void Invoke(this Control control, Action action) - { - control.Invoke((Delegate)action); - } - } - - - public static class ListViewExtensions - { - [StructLayout(LayoutKind.Sequential)] - public struct HDITEM - { - public Mask mask; - public int cxy; - [MarshalAs(UnmanagedType.LPTStr)] - public string pszText; - public IntPtr hbm; - public int cchTextMax; - public Format fmt; - public IntPtr lParam; - // _WIN32_IE >= 0x0300 - public int iImage; - public int iOrder; - // _WIN32_IE >= 0x0500 - public uint type; - public IntPtr pvFilter; - // _WIN32_WINNT >= 0x0600 - public uint state; - - [Flags] - public enum Mask - { - Format = 0x4, // HDI_FORMAT - }; - - [Flags] - public enum Format - { - SortDown = 0x200, // HDF_SORTDOWN - SortUp = 0x400, // HDF_SORTUP - }; - }; - - public const int LVM_FIRST = 0x1000; - public const int LVM_GETHEADER = LVM_FIRST + 31; - - public const int HDM_FIRST = 0x1200; - public const int HDM_GETITEM = HDM_FIRST + 11; - public const int HDM_SETITEM = HDM_FIRST + 12; - - [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] - static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, IntPtr lParam); - - [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] - static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, ref HDITEM lParam); - - public static string CopyItemsAsText(this ListView listViewControl) - { - ListView.SelectedIndexCollection indexes = listViewControl.SelectedIndices; - if (indexes.Count <= 0) - return ""; - - StringBuilder sb = new StringBuilder(); - - //walk over each selected item and subitem within it to generate a string from it - foreach (int index in indexes) - { - foreach (ListViewItem.ListViewSubItem item in listViewControl.Items[index].SubItems) - { - if (!String.IsNullOrWhiteSpace(item.Text)) - sb.Append(item.Text).Append('\t'); - } - //remove the last tab - sb.Remove(sb.Length - 1, 1); - - sb.Append("\r\n"); - } - - //remove last newline - sb.Length -= 2; - - - return sb.ToString(); - } - - public static void SetSortIcon(this ListView listViewControl, int columnIndex, SortOrder order) - { - IntPtr columnHeader = SendMessage(listViewControl.Handle, LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero); - for (int columnNumber = 0; columnNumber <= listViewControl.Columns.Count - 1; columnNumber++) - { - var columnPtr = new IntPtr(columnNumber); - var item = new HDITEM - { - mask = HDITEM.Mask.Format - }; - - if (SendMessage(columnHeader, HDM_GETITEM, columnPtr, ref item) == IntPtr.Zero) - { - throw new Win32Exception(); - } - - if (order != SortOrder.None && columnNumber == columnIndex) - { - switch (order) - { - case SortOrder.Ascending: - item.fmt &= ~HDITEM.Format.SortDown; - item.fmt |= HDITEM.Format.SortUp; - break; - case SortOrder.Descending: - item.fmt &= ~HDITEM.Format.SortUp; - item.fmt |= HDITEM.Format.SortDown; - break; - } - } - else - { - item.fmt &= ~HDITEM.Format.SortDown & ~HDITEM.Format.SortUp; - } - - if (SendMessage(columnHeader, HDM_SETITEM, columnPtr, ref item) == IntPtr.Zero) - { - throw new Win32Exception(); - } - } - } - } -} \ No newline at end of file diff --git a/BizHawk.Util/ViewportPanel.cs b/BizHawk.Util/ViewportPanel.cs deleted file mode 100644 index 12e47dcbac..0000000000 --- a/BizHawk.Util/ViewportPanel.cs +++ /dev/null @@ -1,239 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading; -using System.Drawing; -using System.Drawing.Imaging; -using System.Drawing.Drawing2D; -using System.Windows.Forms; - -namespace BizHawk.Core -{ - /// - /// A programmatic PictureBox, really, which will paint itself using the last bitmap that was provided - /// - public class RetainedViewportPanel : Control - { - Thread threadPaint; - EventWaitHandle ewh; - volatile bool killSignal; - - public Func ReleaseCallback; - - /// - /// Turns this panel into multi-threaded mode. - /// This will sort of glitch out other gdi things on the system, but at least its fast... - /// - public void ActivateThreaded() - { - ewh = new EventWaitHandle(false, EventResetMode.AutoReset); - threadPaint = new Thread(PaintProc); - threadPaint.IsBackground = true; - threadPaint.Start(); - } - - public RetainedViewportPanel(bool doubleBuffer = false) - { - CreateHandle(); - - SetStyle(ControlStyles.AllPaintingInWmPaint, true); - SetStyle(ControlStyles.UserPaint, true); - SetStyle(ControlStyles.DoubleBuffer, doubleBuffer); - SetStyle(ControlStyles.Opaque, true); - SetStyle(ControlStyles.UserMouse, true); - - SetBitmap(new Bitmap(2, 2)); - } - - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - if (threadPaint != null) - { - killSignal = true; - ewh.Set(); - ewh.WaitOne(); - } - CleanupDisposeQueue(); - } - - public bool ScaleImage = true; - - void DoPaint() - { - if (bmp != null) - { - using (Graphics g = CreateGraphics()) - { - g.PixelOffsetMode = PixelOffsetMode.HighSpeed; - g.InterpolationMode = InterpolationMode.NearestNeighbor; - g.CompositingMode = CompositingMode.SourceCopy; - g.CompositingQuality = CompositingQuality.HighSpeed; - if (ScaleImage) - { - g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; - g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half; - g.DrawImage(bmp, 0, 0, Width, Height); - } - else - { - using (var sb = new SolidBrush(Color.Black)) - { - g.FillRectangle(sb, bmp.Width, 0, Width - bmp.Width, Height); - g.FillRectangle(sb, 0, bmp.Height, bmp.Width, Height - bmp.Height); - } - g.DrawImageUnscaled(bmp, 0, 0); - } - } - } - - CleanupDisposeQueue(); - } - - void PaintProc() - { - for (; ; ) - { - ewh.WaitOne(); - if (killSignal) - { - ewh.Set(); - return; - } - - DoPaint(); - } - } - - void CleanupDisposeQueue() - { - lock (this) - { - while (DisposeQueue.Count > 0) - { - var bmp = DisposeQueue.Dequeue(); - bool dispose = true; - if(ReleaseCallback != null) - dispose = ReleaseCallback(bmp); - if(dispose) bmp.Dispose(); - } - } - } - - Queue DisposeQueue = new Queue(); - - void SignalPaint() - { - if (threadPaint == null) - DoPaint(); - else - ewh.Set(); - } - - //Size logicalSize; - ////int pitch; - //public void SetLogicalSize(int w, int h) - //{ - // if (bmp != null) bmp.Dispose(); - // bmp = new Bitmap(w, h, PixelFormat.Format32bppArgb); - // logicalSize = new Size(w, h); - //} - - /// - /// Takes ownership of the provided bitmap and will use it for future painting - /// - public void SetBitmap(Bitmap newbmp) - { - lock (this) - { - if(bmp != null) DisposeQueue.Enqueue(bmp); - bmp = newbmp; - } - SignalPaint(); - } - - Bitmap bmp; - - /// bit of a hack; use at your own risk - /// you probably shouldn't modify this? - public Bitmap GetBitmap() - { - return bmp; - } - - protected override void OnPaintBackground(PaintEventArgs pevent) - { - - } - - - protected override void OnPaint(PaintEventArgs e) - { - SignalPaint(); - base.OnPaint(e); - } - - } - - /// - /// A dumb panel which functions as a placeholder for framebuffer painting - /// - public class ViewportPanel : Control - { - public ViewportPanel() - { - SetStyle(ControlStyles.AllPaintingInWmPaint, true); - SetStyle(ControlStyles.UserPaint, true); - SetStyle(ControlStyles.DoubleBuffer, true); - SetStyle(ControlStyles.Opaque, true); - SetStyle(ControlStyles.UserMouse, true); - } - } - - /// - /// A ViewportPanel with a vertical scroll bar - /// - public class ScrollableViewportPanel : UserControl - { - TableLayoutPanel table; - ViewportPanel view; - VScrollBar scroll; - - public ViewportPanel View { get { return view; } } - public VScrollBar Scrollbar { get { return scroll; } } - - public int ScrollMax { get { return Scrollbar.Maximum; } set { Scrollbar.Maximum = value; } } - public int ScrollLargeChange { get { return Scrollbar.LargeChange; } set { Scrollbar.LargeChange = value; } } - - public ScrollableViewportPanel() - { - InitializeComponent(); - } - - public void InitializeComponent() - { - table = new TableLayoutPanel(); - view = new ViewportPanel(); - scroll = new VScrollBar(); - - scroll.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom; - view.Dock = DockStyle.Fill; - - table.Dock = DockStyle.Fill; - table.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); - table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); - table.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize, 0)); - table.RowCount = 1; - table.ColumnCount = 2; - table.Controls.Add(view); - table.Controls.Add(scroll); - table.SetColumn(view, 0); - table.SetColumn(scroll, 1); - - scroll.Scroll += (sender, e) => OnScroll(e); - view.Paint += (sender, e) => OnPaint(e); - - Controls.Add(table); - } - } -} \ No newline at end of file diff --git a/BizHawk.Util/VirtualListView.cs b/BizHawk.Util/VirtualListView.cs deleted file mode 100644 index 9cdbb42481..0000000000 --- a/BizHawk.Util/VirtualListView.cs +++ /dev/null @@ -1,695 +0,0 @@ -using System; -using System.Windows.Forms; -using System.ComponentModel; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Drawing; - -namespace BizHawk -{ - - #region win32interop - - [StructLayout(LayoutKind.Sequential)] - internal struct LVDISPINFO { - public NMHDR hdr; - public LVITEM item; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct NMHDR { - public int hwndFrom; - public int idFrom; - public int code; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct NMITEMACTIVATE { - NMHDR hdr; - int iItem; - int iSubItem; - uint uNewState; - uint uOldState; - uint uChanged; - POINT ptAction; - uint lParam; - uint uKeyFlags; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct RECT { - public int left, top, right, bottom; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct NMCUSTOMDRAWINFO { - public NMHDR hdr; - public uint dwDrawStage; - public IntPtr hdc; - public RECT rc; - public int dwItemSpec; - public uint uItemState; - public int lItemlParam; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct NMLVCUSTOMDRAW { - public NMCUSTOMDRAWINFO nmcd; - public int clrText; - public int clrTextBk; - public int iSubItem; - } - - - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal struct LVITEM { - public uint mask; - public int iItem; - public int iSubItem; - public uint state; - public uint stateMask; - public IntPtr pszText; - public int cchTextMax; - public int iImage; - public IntPtr lParam; - //#if (_WIN32_IE >= 0x0300) - public int iIndent; - //#endif - //#if (_WIN32_WINNT >= 0x501) - //public int iGroupId; - //public uint cColumns; - //public IntPtr puColumns; - //#endif - } - - [FlagsAttribute] - enum CUSTOMDRAWRETURNFLAGS { - CDRF_DODEFAULT = 0x00000000, - CDRF_NEWFONT = 0x00000002, - CDRF_SKIPDEFAULT = 0x00000004, - - - CDRF_NOTIFYPOSTPAINT = 0x00000010, - CDRF_NOTIFYITEMDRAW = 0x00000020, - //#if (_WIN32_IE >= 0x0400) - CDRF_NOTIFYSUBITEMDRAW = 0x00000020,//[sic] - //#endif - CDRF_NOTIFYPOSTERASE = 0x00000040, - } - - [FlagsAttribute] - enum CUSTOMDRAWDRAWSTAGEFLAGS { - CDDS_PREPAINT = 0x00000001, - CDDS_POSTPAINT = 0x00000002, - CDDS_PREERASE = 0x00000003, - CDDS_POSTERASE = 0x00000004, - - // the 0x000010000 bit means it's individual item specific - CDDS_ITEM = 0x00010000, - CDDS_ITEMPREPAINT = (CDDS_ITEM | CDDS_PREPAINT), - CDDS_ITEMPOSTPAINT = (CDDS_ITEM | CDDS_POSTPAINT), - CDDS_ITEMPREERASE = (CDDS_ITEM | CDDS_PREERASE), - CDDS_ITEMPOSTERASE = (CDDS_ITEM | CDDS_POSTERASE), - //#if (_WIN32_IE >= 0x0400) - CDDS_SUBITEM = 0x00020000, - CDDS_SUBITEMPREPAINT = (CDDS_SUBITEM | CDDS_ITEMPREPAINT), - CDDS_SUBITEMPOSTPAINT = (CDDS_SUBITEM | CDDS_ITEMPOSTPAINT), - CDDS_SUBITEMPREERASE = (CDDS_SUBITEM | CDDS_ITEMPREERASE), - CDDS_SUBITEMPOSTERASE = (CDDS_SUBITEM | CDDS_ITEMPOSTERASE), - //#endif - } - - [FlagsAttribute] - enum LVHITTESTFLAGS { - LVHT_NOWHERE = 0x0001, - LVHT_ONITEMICON = 0x0002, - LVHT_ONITEMLABEL = 0x0004, - LVHT_ONITEMSTATEICON = 0x0008, - LVHT_ONITEM = (LVHT_ONITEMICON | LVHT_ONITEMLABEL | LVHT_ONITEMSTATEICON), - - LVHT_ABOVE = 0x0008, - LVHT_BELOW = 0x0010, - LVHT_TORIGHT = 0x0020, - LVHT_TOLEFT = 0x0040 - } - - [StructLayout(LayoutKind.Sequential)] - internal struct POINT { - public int x; - public int y; - } - - [StructLayout(LayoutKind.Sequential)] - internal class LVHITTESTINFO { - public POINT pt; - public uint flags; - public int iItem; - public int iSubItem; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct NMLISTVIEW { - public NMHDR hdr; - public int iItem; - public int iSubItem; - public uint uNewState; - public uint uOldState; - public uint uChanged; - public POINT ptAction; - public IntPtr lParam; - } - - - internal enum ListViewItemMask : short { - LVIF_TEXT = 0x0001, - LVIF_IMAGE = 0x0002, - LVIF_PARAM = 0x0004, - LVIF_STATE = 0x0008, - - LVIF_INDENT = 0x0010, - LVIF_NORECOMPUTE = 0x0800, - LVIF_GROUPID = 0x0100, - LVIF_COLUMNS = 0x0200 - } - - internal enum LVNI { - ALL = 0x0000, - FOCUSED = 0x0001, - SELECTED = 0x0002, - CUT = 0x0004, - DROPHILITED = 0x0008, - - ABOVE = 0x0100, - BELOW = 0x0200, - TOLEFT = 0x0400, - TORIGHT = 0x0800 - } - - internal enum ListViewMessages { - LVM_FIRST = 0x1000, - LVM_GETITEMCOUNT = (LVM_FIRST + 4), - LVM_SETCALLBACKMASK = (LVM_FIRST + 11), - LVM_GETNEXTITEM = (LVM_FIRST + 12), - LVM_HITTEST = (LVM_FIRST + 18), - LVM_ENSUREVISIBLE = (LVM_FIRST + 19), - LVM_SETITEMSTATE = (LVM_FIRST + 43), - LVM_GETITEMSTATE = (LVM_FIRST + 44), - LVM_SETITEMCOUNT = (LVM_FIRST + 47), - LVM_GETSUBITEMRECT = (LVM_FIRST + 56) - } - - internal enum ListViewStyles : short { - LVS_OWNERDATA = 0x1000, - LVS_SORTASCENDING = 0x0010, - LVS_SORTDESCENDING = 0x0020, - LVS_SHAREIMAGELISTS = 0x0040, - LVS_NOLABELWRAP = 0x0080, - LVS_AUTOARRANGE = 0x0100 - } - internal enum ListViewStylesICF : uint { - LVSICF_NOINVALIDATEALL = 0x00000001, - LVSICF_NOSCROLL = 0x00000002 - } - - internal enum WindowsMessage : uint { - WM_ERASEBKGND = 0x0014, - WM_SCROLL = 0x115, - WM_LBUTTONDOWN = 0x0201, - WM_LBUTTONUP = 0x0202, - WM_LBUTTONDBLCLK = 0x0203, - WM_RBUTTONDOWN = 0x0204, - WM_RBUTTONUP = 0x0205, - WM_RBUTTONDBLCLK = 0x0206, - WM_SETFOCUS = 0x0007, - WM_NOTIFY = 0x004E, - WM_USER = 0x0400, - WM_REFLECT = WM_USER + 0x1c00 - } - - internal enum Notices : int { - NM_FIRST = 0, - NM_CUSTOMDRAW = NM_FIRST - 12, - NM_CLICK = NM_FIRST - 2, - NM_DBLCLICK = NM_FIRST - 3, - } - - internal enum ListViewNotices : int { - LVN_FIRST = (0 - 100), - LVN_LAST = (0 - 199), - LVN_BEGINDRAG = (int)LVN_FIRST - 9, - LVN_BEGINRDRAG = (int)LVN_FIRST - 11, - LVN_GETDISPINFOA = (int)LVN_FIRST - 50, - LVN_GETDISPINFOW = (int)LVN_FIRST - 77, - LVN_SETDISPINFOA = (int)LVN_FIRST - 51, - LVN_SETDISPINFOW = (int)LVN_FIRST - 78, - LVN_ODCACHEHINT = (int)LVN_FIRST - 13, - LVN_ODFINDITEMW = (int)LVN_FIRST - 79 - } - - [Flags] - internal enum ListViewCallBackMask : uint { - LVIS_FOCUSED = 0x0001, - LVIS_SELECTED = 0x0002, - LVIS_CUT = 0x0004, - LVIS_DROPHILITED = 0x0008, - LVIS_GLOW = 0x0010, - LVIS_ACTIVATING = 0x0020, - - LVIS_OVERLAYMASK = 0x0F00, - LVIS_STATEIMAGEMASK = 0xF000, - } - - - #endregion - - #region VirtualListView Delegates - /// - /// Retrieve the background color for a Listview cell (item and subitem). - /// - /// Listview item (row). - /// Listview subitem (column). - /// Background color to use - public delegate void QueryItemBkColorHandler(int item, int subItem, ref Color color); - - - /// - /// Retrieve the text for a Listview cell (item and subitem). - /// - /// Listview item (row). - /// Listview subitem (column). - /// Text to display. - public delegate void QueryItemTextHandler(int item, int subItem, out string text); - - /// - /// Retrieve the image index for a Listview item. - /// - /// Listview item (row). - /// Listview subitem (column) - should always be zero. - /// Index of associated ImageList. - public delegate void QueryItemImageHandler(int item, int subItem, out int imageIndex); - - /// - /// Retrieve the indent for a Listview item. The indent is always width of an image. - /// For example, 1 indents the Listview item one image width. - /// - /// Listview item (row). - /// The amount to indent the Listview item. - public delegate void QueryItemIndentHandler(int item, out int itemIndent); - - public delegate void QueryItemHandler(int idx, out ListViewItem item); - #endregion - - /// - /// VirtualListView is a virtual Listview which allows for a large number of items(rows) - /// to be displayed. The virtual Listview contains very little actual information - - /// mainly item selection and focus information. - /// - public class VirtualListView : ListView { - // store the item count to prevent the call to SendMessage(LVM_GETITEMCOUNT) - private int itemCount = 0; - - #region Display query callbacks - /// - /// Fire the QueryItemBkColor event which requests the background color for the passed Listview cell - /// - public event QueryItemBkColorHandler QueryItemBkColor; - - /// - /// Fire the QueryItemText event which requests the text for the passed Listview cell. - /// - [Category("Data")] - public event QueryItemTextHandler QueryItemText; - /// - /// Fire the QueryItemImage event which requests the ImageIndex for the passed Listview item. - /// - [Category("Data")] - public event QueryItemImageHandler QueryItemImage; - /// - /// Fire the QueryItemIndent event which requests the indent for the passed Listview item. - /// - [Category("Data")] - public event QueryItemIndentHandler QueryItemIndent; - [Category("Data")] - public event QueryItemHandler QueryItem; - #endregion - - #region Properties - /// - /// Gets/sets the sets the virtual number of items to be displayed. - /// - [Category("Behavior")] - public int ItemCount { - get { - return itemCount; - } - set { - itemCount = value; - // if the virtual item count is set before the handle is created - // then the image lists don't get loaded properly - if(!this.IsHandleCreated) - return; - SetVirtualItemCount(); - } - } - - /// - /// Gets/sets how list items are to be displayed. - /// - /// Hide the ListView.View property. - /// Virtual Listviews only allow Details or List. - /// - public new System.Windows.Forms.View View { - get { - return base.View; - } - set { - if(value == View.LargeIcon || - value == View.SmallIcon) { - throw new ArgumentException("Icon views are invalid for virtual ListViews", "View"); - } - base.View = value; - } - } - - /// - /// Gets the required creation parameters when the control handle is created. - /// - /// Use LVS_OWNERDATA to set this as a virtual Listview. - /// - protected override System.Windows.Forms.CreateParams CreateParams { - get { - CreateParams cp = base.CreateParams; - // LVS_OWNERDATA style must be set when the control is created - cp.Style |= (int)ListViewStyles.LVS_OWNERDATA; - return cp; - } - } - - #endregion - - #region Constructors - /// - /// Create a new instance of this control. - /// - public VirtualListView() { - // virtual listviews must be Details or List view with no sorting - View = View.Details; - Sorting = SortOrder.None; - - ptrlvhti = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LVHITTESTINFO))); - - SetStyle(ControlStyles.OptimizedDoubleBuffer, true); - SetStyle(ControlStyles.Opaque, true); - SetStyle(ControlStyles.AllPaintingInWmPaint, true); - } - - ~VirtualListView() { - Marshal.FreeHGlobal(ptrlvhti); - } - - #endregion - - #region Methods - /// - /// Set the state of the passed Listview item's index. - /// - /// Listview item's index. - /// Select the passed item? - public void SelectItem(int index, bool selected) { - IntPtr ptrItem = IntPtr.Zero; - - try { - // Determine whether selecting or unselecting. - uint select = selected ? (uint)ListViewCallBackMask.LVIS_SELECTED : 0; - - // Fill in the LVITEM structure with state fields. - LVITEM stateItem = new LVITEM(); - stateItem.mask = (uint)ListViewItemMask.LVIF_STATE; - stateItem.iItem = index; - stateItem.iSubItem = 0; - stateItem.state = select; - stateItem.stateMask = (uint)ListViewCallBackMask.LVIS_SELECTED; - - // Copy the structure to unmanaged memory. - ptrItem = Marshal.AllocHGlobal(Marshal.SizeOf(stateItem.GetType())); - Marshal.StructureToPtr(stateItem, ptrItem, true); - - // Send the message to the control window. - int result = Win32.SendMessage( - this.Handle, - (int)ListViewMessages.LVM_SETITEMSTATE, - index, - ptrItem.ToInt32()); - } catch(Exception ex) { - System.Diagnostics.Trace.WriteLine("VirtualListView.SetItemState error=" + ex.Message); - // TODO: should this eat any exceptions? - throw ex; - } finally { - // Always release the unmanaged memory. - if(ptrItem != IntPtr.Zero) { - Marshal.FreeHGlobal(ptrItem); - } - } - } - - private void SetVirtualItemCount() { - int result; - result = Win32.SendMessage( - this.Handle, - (int)ListViewMessages.LVM_SETITEMCOUNT, - itemCount, - 0); - } - - protected void OnDispInfoNotice(ref Message m, bool useAnsi) { - - LVDISPINFO info = (LVDISPINFO)m.GetLParam(typeof(LVDISPINFO)); - string lvtext = null; - - if((info.item.mask & (uint)ListViewItemMask.LVIF_TEXT) > 0) { - if(QueryItemText != null) { - QueryItemText(info.item.iItem, info.item.iSubItem, out lvtext); - if(lvtext != null) { - try { - int maxIndex = Math.Min(info.item.cchTextMax - 1, lvtext.Length); - char[] data = new char[maxIndex + 1]; - lvtext.CopyTo(0, data, 0, lvtext.Length); - data[maxIndex] = '\0'; - System.Runtime.InteropServices.Marshal.Copy(data, 0, info.item.pszText, data.Length); - } catch(Exception e) { - Debug.WriteLine("Failed to copy text name from client: " + e.ToString(), "VirtualListView.OnDispInfoNotice"); - } - } - } - } - - if((info.item.mask & (uint)ListViewItemMask.LVIF_IMAGE) > 0) { - int imageIndex = 0; - if(QueryItemImage != null) { - QueryItemImage(info.item.iItem, info.item.iSubItem, out imageIndex); - } - info.item.iImage = imageIndex; - System.Runtime.InteropServices.Marshal.StructureToPtr(info, m.LParam, false); - } - - if((info.item.mask & (uint)ListViewItemMask.LVIF_INDENT) > 0) { - int itemIndent = 0; - if(QueryItemIndent != null) { - QueryItemIndent(info.item.iItem, out itemIndent); - } - info.item.iIndent = itemIndent; - System.Runtime.InteropServices.Marshal.StructureToPtr(info, m.LParam, false); - } - m.Result = new IntPtr(0); - } - - protected void OnCustomDrawNotice(ref System.Windows.Forms.Message m) { - NMLVCUSTOMDRAW cd = (NMLVCUSTOMDRAW)m.GetLParam(typeof(NMLVCUSTOMDRAW)); - switch(cd.nmcd.dwDrawStage) { - case (int)CUSTOMDRAWDRAWSTAGEFLAGS.CDDS_ITEMPREPAINT: - case (int)CUSTOMDRAWDRAWSTAGEFLAGS.CDDS_PREPAINT: - m.Result = new IntPtr((int)CUSTOMDRAWRETURNFLAGS.CDRF_NOTIFYSUBITEMDRAW); - break; - case (int)CUSTOMDRAWDRAWSTAGEFLAGS.CDDS_SUBITEMPREPAINT: - Color color; - if(QueryItemBkColor != null) { - color = Color.FromArgb(cd.clrTextBk & 0xFF, (cd.clrTextBk >> 8) & 0xFF, (cd.clrTextBk >> 16) & 0xFF); - QueryItemBkColor(cd.nmcd.dwItemSpec, cd.iSubItem, ref color); - cd.clrTextBk = (color.B << 16) | (color.G << 8) | (color.R); - System.Runtime.InteropServices.Marshal.StructureToPtr(cd, m.LParam, false); - } - m.Result = new IntPtr((int)CUSTOMDRAWRETURNFLAGS.CDRF_DODEFAULT); - break; - } - } - - /// - /// Event to be fired whenever the control scrolls - /// - public event ScrollEventHandler Scroll; - protected virtual void OnScroll(ScrollEventArgs e) - { - ScrollEventHandler handler = this.Scroll; - if (handler != null) handler(this, e); - } - - protected override void WndProc(ref System.Windows.Forms.Message m) { - NMHDR nm1; - bool messageProcessed = false; - switch(m.Msg) { - case (int)WindowsMessage.WM_REFLECT + (int)WindowsMessage.WM_NOTIFY: - nm1 = (NMHDR)m.GetLParam(typeof(NMHDR)); - switch(nm1.code) { - case (int)Notices.NM_CUSTOMDRAW: - OnCustomDrawNotice(ref m); - messageProcessed = true; - break; - case (int)ListViewNotices.LVN_GETDISPINFOW: - OnDispInfoNotice(ref m, false); - messageProcessed = true; - break; - case (int)ListViewNotices.LVN_BEGINDRAG: - OnBeginItemDrag(MouseButtons.Left, ref m); - messageProcessed = true; - break; - case (int)ListViewNotices.LVN_BEGINRDRAG: - OnBeginItemDrag(MouseButtons.Right, ref m); - messageProcessed = true; - break; - //case (int)Notices.NM_CLICK: - //case (int)Notices.NM_DBLCLICK: - // { - // NMITEMACTIVATE test = (NMITEMACTIVATE)m.GetLParam(typeof(NMITEMACTIVATE)); - // messageProcessed = true; - // break; - // } - - default: - break; - } - break; - - case (int)WindowsMessage.WM_SCROLL: - //http://stackoverflow.com/questions/1851620/handling-scroll-event-on-listview-in-c-sharp - OnScroll(new ScrollEventArgs((ScrollEventType)(m.WParam.ToInt32() & 0xffff), 0)); - break; - - //obscure message loop flakiness when exceptions are thrown from the message loop... - //THIS BREAKS PROPER LISTVIEW FOCUS SELECTION (blue) - //next time we run into this, debug it better. - //case (int)WindowsMessage.WM_SETFOCUS: - // if (SelectedIndices.Count > 0 && SelectedIndices[0] >= VirtualListSize) - // messageProcessed = true; - // break; - //TRY THIS HACK INSTEAD TO FIX THE EXCEPTION - // (( NOPE, THEY ALL BREAK ONE THING OR ANOTHER. WINFORMS LISTVIEW JUST THROWS EXCEPTIONS, WHAT CAN WE DO? )) - //case 0x100C: - // { - // base.WndProc(ref m); - // int num = m.Result.ToInt32(); - // messageProcessed = true; - // m.Result = new IntPtr(-1); - // break; - // } - //case 0x1012: - // { - // base.WndProc(ref m); - // int num = m.Result.ToInt32(); - // messageProcessed = true; - // m.Result = new IntPtr(-1); - // break; - // } - - case (int)WindowsMessage.WM_ERASEBKGND: - if (BlazingFast) - { - messageProcessed = true; - m.Result = new IntPtr(1); - } - break; - - default: - break; - } - if(!messageProcessed) { - try { - base.WndProc(ref m); - } catch(Exception ex) { - Trace.WriteLine(string.Format("Message {0} caused an exception: {1}", m, ex.Message)); - } - } - } - - public bool BlazingFast = false; - - protected ListViewItem GetItem(int idx) { - ListViewItem item = null; - if(QueryItem != null) { - QueryItem(idx, out item); - } - if(item == null) { - throw new ArgumentException("cannot find item " + idx.ToString() + " via QueryItem event"); - } - return item; - } - - protected void OnBeginItemDrag(MouseButtons mouseButton, ref System.Windows.Forms.Message m) { - NMLISTVIEW info = (NMLISTVIEW)m.GetLParam(typeof(NMLISTVIEW)); - ListViewItem item = null; - if(QueryItem != null) { - QueryItem(info.iItem, out item); - } - OnItemDrag(new ItemDragEventArgs(mouseButton, item)); - } - - protected override void OnHandleCreated(System.EventArgs e) { - base.OnHandleCreated(e); - // ensure the value for ItemCount is sent to the control properly if the user set it - // before the handle was created - SetVirtualItemCount(); - } - - protected override void OnHandleDestroyed(System.EventArgs e) { - // the ListView OnHandleDestroyed accesses the Items list for all selected items - ItemCount = 0; - base.OnHandleDestroyed(e); - } - #endregion - - LVHITTESTINFO lvhti = new LVHITTESTINFO(); - IntPtr ptrlvhti; - int selection = -1; - - public int hitTest(int x, int y) { - lvhti.pt.x = x; - lvhti.pt.y = y; - Marshal.StructureToPtr(lvhti, ptrlvhti, true); - int z = Win32.SendMessage(this.Handle, (int)ListViewMessages.LVM_HITTEST, 0, ptrlvhti.ToInt32()); - Marshal.PtrToStructure(ptrlvhti, lvhti); - return z; - } - - public void ensureVisible(int index) { - Win32.SendMessage(Handle, (int)ListViewMessages.LVM_ENSUREVISIBLE, index, 1); - } - - public void ensureVisible() { - ensureVisible(selectedItem); - } - - public void setSelection(int index) { - clearSelection(); - selection = index; - SelectItem(selection, true); - } - - public int selectedItem { get { if(SelectedIndices.Count == 0) return -1; else return SelectedIndices[0]; } set { setSelection(value); } } - - public void clearSelection() { - if(selection != -1) - SelectItem(selection, false); - selection = -1; - } - } -} diff --git a/BizHawk.Util/Win32.cs b/BizHawk.Util/Win32.cs deleted file mode 100644 index ccefefb97a..0000000000 --- a/BizHawk.Util/Win32.cs +++ /dev/null @@ -1,574 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Windows.Forms; -using System.Drawing; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -namespace BizHawk -{ - public static class Win32 - { - - public static bool Is64BitProcess { get { return (IntPtr.Size == 8); } } - public static bool Is64BitOperatingSystem { get { return Is64BitProcess || InternalCheckIsWow64(); } } - - [DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool IsWow64Process( - [In] IntPtr hProcess, - [Out] out bool wow64Process - ); - - static bool InternalCheckIsWow64() - { - if ((Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1) || - Environment.OSVersion.Version.Major >= 6) - { - using (var p = System.Diagnostics.Process.GetCurrentProcess()) - { - bool retVal; - if (!IsWow64Process(p.Handle, out retVal)) - { - return false; - } - return retVal; - } - } - else - { - return false; - } - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct RECT - { - private int _Left; - private int _Top; - private int _Right; - private int _Bottom; - - public RECT(RECT Rectangle) - : this(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom) - { - } - public RECT(int Left, int Top, int Right, int Bottom) - { - _Left = Left; - _Top = Top; - _Right = Right; - _Bottom = Bottom; - } - - public int X - { - get { return _Left; } - set { _Left = value; } - } - public int Y - { - get { return _Top; } - set { _Top = value; } - } - public int Left - { - get { return _Left; } - set { _Left = value; } - } - public int Top - { - get { return _Top; } - set { _Top = value; } - } - public int Right - { - get { return _Right; } - set { _Right = value; } - } - public int Bottom - { - get { return _Bottom; } - set { _Bottom = value; } - } - public int Height - { - get { return _Bottom - _Top; } - set { _Bottom = value - _Top; } - } - public int Width - { - get { return _Right - _Left; } - set { _Right = value + _Left; } - } - public Point Location - { - get { return new Point(Left, Top); } - set - { - _Left = value.X; - _Top = value.Y; - } - } - public Size Size - { - get { return new Size(Width, Height); } - set - { - _Right = value.Width + _Left; - _Bottom = value.Height + _Top; - } - } - - public static implicit operator Rectangle(RECT Rectangle) - { - return new Rectangle(Rectangle.Left, Rectangle.Top, Rectangle.Width, Rectangle.Height); - } - public static implicit operator RECT(Rectangle Rectangle) - { - return new RECT(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom); - } - public static bool operator ==(RECT Rectangle1, RECT Rectangle2) - { - return Rectangle1.Equals(Rectangle2); - } - public static bool operator !=(RECT Rectangle1, RECT Rectangle2) - { - return !Rectangle1.Equals(Rectangle2); - } - - public override string ToString() - { - return "{Left: " + _Left + "; " + "Top: " + _Top + "; Right: " + _Right + "; Bottom: " + _Bottom + "}"; - } - - public override int GetHashCode() - { - return ToString().GetHashCode(); - } - - public bool Equals(RECT Rectangle) - { - return Rectangle.Left == _Left && Rectangle.Top == _Top && Rectangle.Right == _Right && Rectangle.Bottom == _Bottom; - } - - public override bool Equals(object Object) - { - if (Object is RECT) - { - return Equals((RECT)Object); - } - else if (Object is Rectangle) - { - return Equals(new RECT((Rectangle)Object)); - } - - return false; - } - } - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct AVISTREAMINFOW - { - public Int32 fccType; - public Int32 fccHandler; - public Int32 dwFlags; - public Int32 dwCaps; - public Int16 wPriority; - public Int16 wLanguage; - public Int32 dwScale; - public Int32 dwRate; - public Int32 dwStart; - public Int32 dwLength; - public Int32 dwInitialFrames; - public Int32 dwSuggestedBufferSize; - public Int32 dwQuality; - public Int32 dwSampleSize; - public RECT rcFrame; - public Int32 dwEditCount; - public Int32 dwFormatChangeCount; - [MarshalAs(UnmanagedType.LPWStr, SizeConst=64)] - public string szName; - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct BITMAPINFOHEADER - { - public uint biSize; - public int biWidth; - public int biHeight; - public ushort biPlanes; - public ushort biBitCount; - public uint biCompression; - public uint biSizeImage; - public int biXPelsPerMeter; - public int biYPelsPerMeter; - public uint biClrUsed; - public uint biClrImportant; - - public void Init() - { - biSize = (uint)Marshal.SizeOf(this); - } - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct WAVEFORMATEX - { - public ushort wFormatTag; - public ushort nChannels; - public uint nSamplesPerSec; - public uint nAvgBytesPerSec; - public ushort nBlockAlign; - public ushort wBitsPerSample; - public ushort cbSize; - - public void Init() - { - cbSize = (ushort)Marshal.SizeOf(this); - } - } - - public const int WAVE_FORMAT_PCM = 1; - public const int AVIIF_KEYFRAME = 0x00000010; - - - [Flags] - public enum OpenFileStyle : uint - { - OF_CANCEL = 0x00000800, // Ignored. For a dialog box with a Cancel button, use OF_PROMPT. - OF_CREATE = 0x00001000, // Creates a new file. If file exists, it is truncated to zero (0) length. - OF_DELETE = 0x00000200, // Deletes a file. - OF_EXIST = 0x00004000, // Opens a file and then closes it. Used to test that a file exists - OF_PARSE = 0x00000100, // Fills the OFSTRUCT structure, but does not do anything else. - OF_PROMPT = 0x00002000, // Displays a dialog box if a requested file does not exist - OF_READ = 0x00000000, // Opens a file for reading only. - OF_READWRITE = 0x00000002, // Opens a file with read/write permissions. - OF_REOPEN = 0x00008000, // Opens a file by using information in the reopen buffer. - - // For MS-DOS–based file systems, opens a file with compatibility mode, allows any process on a - // specified computer to open the file any number of times. - // Other efforts to open a file with other sharing modes fail. This flag is mapped to the - // FILE_SHARE_READ|FILE_SHARE_WRITE flags of the CreateFile function. - OF_SHARE_COMPAT = 0x00000000, - - // Opens a file without denying read or write access to other processes. - // On MS-DOS-based file systems, if the file has been opened in compatibility mode - // by any other process, the function fails. - // This flag is mapped to the FILE_SHARE_READ|FILE_SHARE_WRITE flags of the CreateFile function. - OF_SHARE_DENY_NONE = 0x00000040, - - // Opens a file and denies read access to other processes. - // On MS-DOS-based file systems, if the file has been opened in compatibility mode, - // or for read access by any other process, the function fails. - // This flag is mapped to the FILE_SHARE_WRITE flag of the CreateFile function. - OF_SHARE_DENY_READ = 0x00000030, - - // Opens a file and denies write access to other processes. - // On MS-DOS-based file systems, if a file has been opened in compatibility mode, - // or for write access by any other process, the function fails. - // This flag is mapped to the FILE_SHARE_READ flag of the CreateFile function. - OF_SHARE_DENY_WRITE = 0x00000020, - - // Opens a file with exclusive mode, and denies both read/write access to other processes. - // If a file has been opened in any other mode for read/write access, even by the current process, - // the function fails. - OF_SHARE_EXCLUSIVE = 0x00000010, - - // Verifies that the date and time of a file are the same as when it was opened previously. - // This is useful as an extra check for read-only files. - OF_VERIFY = 0x00000400, - - // Opens a file for write access only. - OF_WRITE = 0x00000001 - } - - [DllImport("avifil32.dll", SetLastError = true)] - public static extern int AVIFileOpenW(ref IntPtr pAviFile, [MarshalAs(UnmanagedType.LPWStr)] string szFile, OpenFileStyle uMode, int lpHandler); - - [DllImport("avifil32.dll", SetLastError = true)] - public static extern void AVIFileInit(); - - // Create a new stream in an existing file and creates an interface to the new stream - [DllImport("avifil32.dll")] - public static extern int AVIFileCreateStreamW( - IntPtr pfile, - out IntPtr ppavi, - ref AVISTREAMINFOW psi); - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct AVICOMPRESSOPTIONS - { - public int fccType; - public int fccHandler; - public int dwKeyFrameEvery; - public int dwQuality; - public int dwBytesPerSecond; - public int dwFlags; - public int lpFormat; - public int cbFormat; - public int lpParms; - public int cbParms; - public int dwInterleaveEvery; - } - - [DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - public static extern SafeFileHandle CreateFile( - string lpFileName, - uint dwDesiredAccess, - uint dwShareMode, - IntPtr SecurityAttributes, - uint dwCreationDisposition, - uint dwFlagsAndAttributes, - IntPtr hTemplateFile - ); - - [DllImport("kernel32.dll")] - public static extern FileType GetFileType(IntPtr hFile); - - [DllImport("kernel32.dll", CharSet = CharSet.Auto)] - public static extern System.IntPtr GetCommandLine(); - - public enum FileType : uint - { - FileTypeChar = 0x0002, - FileTypeDisk = 0x0001, - FileTypePipe = 0x0003, - FileTypeRemote = 0x8000, - FileTypeUnknown = 0x0000, - } - - [DllImport("kernel32.dll", SetLastError = true)] - public static extern IntPtr GetConsoleWindow(); - - [DllImport("user32.dll", SetLastError = true)] - public static extern bool SetForegroundWindow(IntPtr hWnd); - - [DllImport("user32.dll", SetLastError = true)] - public static extern IntPtr SetActiveWindow(IntPtr hWnd); - - [DllImport("kernel32.dll", SetLastError = true)] - public static extern bool AttachConsole(int dwProcessId); - - [DllImport("kernel32.dll", SetLastError = true)] - public static extern bool AllocConsole(); - - [DllImport("kernel32.dll", SetLastError = false)] - public static extern bool FreeConsole(); - - [DllImport("kernel32.dll", SetLastError = true)] - public static extern IntPtr GetStdHandle(int nStdHandle); - - [DllImport("kernel32.dll", SetLastError = true)] - public static extern bool SetStdHandle(int nStdHandle, IntPtr hConsoleOutput); - - [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] - public static extern IntPtr CreateFile( - string fileName, - int desiredAccess, - int shareMode, - IntPtr securityAttributes, - int creationDisposition, - int flagsAndAttributes, - IntPtr templateFile); - - [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)] - public static extern bool CloseHandle(IntPtr handle); - - [DllImport("user32.dll", SetLastError = false)] - public static extern IntPtr GetDesktopWindow(); - - // Retrieve the save options for a file and returns them in a buffer - [DllImport("avifil32.dll")] - public static extern int AVISaveOptions( - IntPtr hwnd, - int flags, - int streams, - [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] IntPtr[] ppavi, - [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] IntPtr[] plpOptions); - - // Free the resources allocated by the AVISaveOptions function - [DllImport("avifil32.dll")] - public static extern int AVISaveOptionsFree( - int streams, - [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] IntPtr[] plpOptions); - - // Create a compressed stream from an uncompressed stream and a - // compression filter, and returns the address of a pointer to - // the compressed stream - [DllImport("avifil32.dll")] - public static extern int AVIMakeCompressedStream( - out IntPtr ppsCompressed, - IntPtr psSource, - ref AVICOMPRESSOPTIONS lpOptions, - IntPtr pclsidHandler); - - // Set the format of a stream at the specified position - [DllImport("avifil32.dll")] - public static extern int AVIStreamSetFormat( - IntPtr pavi, - int lPos, - ref BITMAPINFOHEADER lpFormat, - int cbFormat); - - // Set the format of a stream at the specified position - [DllImport("avifil32.dll")] - public static extern int AVIStreamSetFormat( - IntPtr pavi, - int lPos, - ref WAVEFORMATEX lpFormat, - int cbFormat); - - // Write data to a stream - [DllImport("avifil32.dll")] - public static extern int AVIStreamWrite( - IntPtr pavi, - int lStart, - int lSamples, - IntPtr lpBuffer, - int cbBuffer, - int dwFlags, - IntPtr plSampWritten, - out int plBytesWritten); - - // Release an open AVI stream - [DllImport("avifil32.dll")] - public static extern int AVIStreamRelease( - IntPtr pavi); - - // Release an open AVI stream - [DllImport("avifil32.dll")] - public static extern int AVIFileRelease( - IntPtr pfile); - - - // Replacement of mmioFOURCC macros - public static int mmioFOURCC(string str) - { - return ( - ((int)(byte)(str[0])) | - ((int)(byte)(str[1]) << 8) | - ((int)(byte)(str[2]) << 16) | - ((int)(byte)(str[3]) << 24)); - } - - public static bool FAILED(int hr) { return hr < 0; } - - - - // Inverse of mmioFOURCC - public static string decode_mmioFOURCC(int code) - { - char[] chs = new char[4]; - - for (int i = 0; i < 4; i++) - { - chs[i] = (char)(byte)((code >> (i << 3)) & 0xFF); - if (!char.IsLetterOrDigit(chs[i])) - chs[i] = ' '; - } - return new string(chs); - } - - [DllImport("user32.dll", CharSet = CharSet.Auto)] - public static extern int SendMessage(IntPtr hWnd, int msg, int wParam, int lParam); - - [DllImport("Kernel32.dll", EntryPoint = "RtlZeroMemory", SetLastError = false)] - public static extern void ZeroMemory(IntPtr dest, uint size); - - [DllImport("msvcrt.dll", EntryPoint = "memset", CallingConvention = CallingConvention.Cdecl, SetLastError = false)] - public static extern IntPtr MemSet(IntPtr dest, int c, uint count); - - [DllImport("shlwapi.dll", CharSet = CharSet.Auto)] - public static extern bool PathRelativePathTo( - [Out] System.Text.StringBuilder pszPath, - [In] string pszFrom, - [In] FileAttributes dwAttrFrom, - [In] string pszTo, - [In] FileAttributes dwAttrTo - ); - - /// - /// File attributes are metadata values stored by the file system on disk and are used by the system and are available to developers via various file I/O APIs. - /// - [Flags] - [CLSCompliant(false)] - public enum FileAttributes : uint - { - /// - /// A file that is read-only. Applications can read the file, but cannot write to it or delete it. This attribute is not honored on directories. For more information, see "You cannot view or change the Read-only or the System attributes of folders in Windows Server 2003, in Windows XP, or in Windows Vista". - /// - Readonly = 0x00000001, - - /// - /// The file or directory is hidden. It is not included in an ordinary directory listing. - /// - Hidden = 0x00000002, - - /// - /// A file or directory that the operating system uses a part of, or uses exclusively. - /// - System = 0x00000004, - - /// - /// The handle that identifies a directory. - /// - Directory = 0x00000010, - - /// - /// A file or directory that is an archive file or directory. Applications typically use this attribute to mark files for backup or removal. - /// - Archive = 0x00000020, - - /// - /// This value is reserved for system use. - /// - Device = 0x00000040, - - /// - /// A file that does not have other attributes set. This attribute is valid only when used alone. - /// - Normal = 0x00000080, - - /// - /// A file that is being used for temporary storage. File systems avoid writing data back to mass storage if sufficient cache memory is available, because typically, an application deletes a temporary file after the handle is closed. In that scenario, the system can entirely avoid writing the data. Otherwise, the data is written after the handle is closed. - /// - Temporary = 0x00000100, - - /// - /// A file that is a sparse file. - /// - SparseFile = 0x00000200, - - /// - /// A file or directory that has an associated reparse point, or a file that is a symbolic link. - /// - ReparsePoint = 0x00000400, - - /// - /// A file or directory that is compressed. For a file, all of the data in the file is compressed. For a directory, compression is the default for newly created files and subdirectories. - /// - Compressed = 0x00000800, - - /// - /// The data of a file is not available immediately. This attribute indicates that the file data is physically moved to offline storage. This attribute is used by Remote Storage, which is the hierarchical storage management software. Applications should not arbitrarily change this attribute. - /// - Offline = 0x00001000, - - /// - /// The file or directory is not to be indexed by the content indexing service. - /// - NotContentIndexed = 0x00002000, - - /// - /// A file or directory that is encrypted. For a file, all data streams in the file are encrypted. For a directory, encryption is the default for newly created files and subdirectories. - /// - Encrypted = 0x00004000, - - /// - /// This value is reserved for system use. - /// - Virtual = 0x00010000 - } - } - -} \ No newline at end of file diff --git a/BizHawk.sln b/BizHawk.sln index 6475cf59a6..0355e2d56d 100644 --- a/BizHawk.sln +++ b/BizHawk.sln @@ -3,15 +3,13 @@ Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2010 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BizHawk.Emulation", "BizHawk.Emulation\BizHawk.Emulation.csproj", "{197D4314-8A9F-49BA-977D-54ACEFAEB6BA}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BizHawk.Util", "BizHawk.Util\BizHawk.Util.csproj", "{EE135301-08B3-4EFC-A61C-1C53E1C65CB9}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BizHawk.MultiClient", "BizHawk.MultiClient\BizHawk.MultiClient.csproj", "{DD448B37-BA3F-4544-9754-5406E8094723}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DiscoHawk", "DiscoHawk\DiscoHawk.csproj", "{C4366030-6D03-424B-AE53-F4F43BB217C3}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BizHawk.PCE_Debugger", "BizHawk.PCE_Debugger\BizHawk.PCE_Debugger.csproj", "{2D7F5A4A-C3C4-41CD-839C-C35F3DD58725}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LuaHawk", "LuaHawk\LuaHawk.csproj", "{B7FA7300-52DF-4A3F-84EF-D69E40CF60AF}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BizHawk.Client.Common", "BizHawk.Client.Common\BizHawk.Client.Common.csproj", "{24A0AA3C-B25F-4197-B23D-476D6462DBA0}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -39,20 +37,6 @@ Global {197D4314-8A9F-49BA-977D-54ACEFAEB6BA}.Release|Win32.ActiveCfg = Release|Any CPU {197D4314-8A9F-49BA-977D-54ACEFAEB6BA}.Release|Win32.Build.0 = Release|Any CPU {197D4314-8A9F-49BA-977D-54ACEFAEB6BA}.Release|x86.ActiveCfg = Release|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Debug|Win32.ActiveCfg = Debug|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Debug|Win32.Build.0 = Debug|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Debug|x86.ActiveCfg = Debug|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Release|Any CPU.Build.0 = Release|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Release|Win32.ActiveCfg = Release|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Release|Win32.Build.0 = Release|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Release|x86.ActiveCfg = Release|Any CPU {DD448B37-BA3F-4544-9754-5406E8094723}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DD448B37-BA3F-4544-9754-5406E8094723}.Debug|Any CPU.Build.0 = Debug|Any CPU {DD448B37-BA3F-4544-9754-5406E8094723}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU @@ -93,18 +77,18 @@ Global {2D7F5A4A-C3C4-41CD-839C-C35F3DD58725}.Release|Win32.ActiveCfg = Release|x86 {2D7F5A4A-C3C4-41CD-839C-C35F3DD58725}.Release|x86.ActiveCfg = Release|x86 {2D7F5A4A-C3C4-41CD-839C-C35F3DD58725}.Release|x86.Build.0 = Release|x86 - {B7FA7300-52DF-4A3F-84EF-D69E40CF60AF}.Debug|Any CPU.ActiveCfg = Debug|x86 - {B7FA7300-52DF-4A3F-84EF-D69E40CF60AF}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 - {B7FA7300-52DF-4A3F-84EF-D69E40CF60AF}.Debug|Mixed Platforms.Build.0 = Debug|x86 - {B7FA7300-52DF-4A3F-84EF-D69E40CF60AF}.Debug|Win32.ActiveCfg = Debug|x86 - {B7FA7300-52DF-4A3F-84EF-D69E40CF60AF}.Debug|x86.ActiveCfg = Debug|x86 - {B7FA7300-52DF-4A3F-84EF-D69E40CF60AF}.Debug|x86.Build.0 = Debug|x86 - {B7FA7300-52DF-4A3F-84EF-D69E40CF60AF}.Release|Any CPU.ActiveCfg = Release|x86 - {B7FA7300-52DF-4A3F-84EF-D69E40CF60AF}.Release|Mixed Platforms.ActiveCfg = Release|x86 - {B7FA7300-52DF-4A3F-84EF-D69E40CF60AF}.Release|Mixed Platforms.Build.0 = Release|x86 - {B7FA7300-52DF-4A3F-84EF-D69E40CF60AF}.Release|Win32.ActiveCfg = Release|x86 - {B7FA7300-52DF-4A3F-84EF-D69E40CF60AF}.Release|x86.ActiveCfg = Release|x86 - {B7FA7300-52DF-4A3F-84EF-D69E40CF60AF}.Release|x86.Build.0 = Release|x86 + {24A0AA3C-B25F-4197-B23D-476D6462DBA0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {24A0AA3C-B25F-4197-B23D-476D6462DBA0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {24A0AA3C-B25F-4197-B23D-476D6462DBA0}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {24A0AA3C-B25F-4197-B23D-476D6462DBA0}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {24A0AA3C-B25F-4197-B23D-476D6462DBA0}.Debug|Win32.ActiveCfg = Debug|Any CPU + {24A0AA3C-B25F-4197-B23D-476D6462DBA0}.Debug|x86.ActiveCfg = Debug|Any CPU + {24A0AA3C-B25F-4197-B23D-476D6462DBA0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {24A0AA3C-B25F-4197-B23D-476D6462DBA0}.Release|Any CPU.Build.0 = Release|Any CPU + {24A0AA3C-B25F-4197-B23D-476D6462DBA0}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {24A0AA3C-B25F-4197-B23D-476D6462DBA0}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {24A0AA3C-B25F-4197-B23D-476D6462DBA0}.Release|Win32.ActiveCfg = Release|Any CPU + {24A0AA3C-B25F-4197-B23D-476D6462DBA0}.Release|x86.ActiveCfg = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/BizHawk_2012.sln b/BizHawk_2012.sln deleted file mode 100644 index 96a7eac34d..0000000000 --- a/BizHawk_2012.sln +++ /dev/null @@ -1,87 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2012 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BizHawk.Emulation_v4.5", "BizHawk.Emulation\BizHawk.Emulation_v4.5.csproj", "{197D4314-8A9F-49BA-977D-54ACEFAEB6BA}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BizHawk.Util_v4.5", "BizHawk.Util\BizHawk.Util_v4.5.csproj", "{EE135301-08B3-4EFC-A61C-1C53E1C65CB9}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BizHawk.MultiClient_v4.5", "BizHawk.MultiClient\BizHawk.MultiClient_v4.5.csproj", "{DD448B37-BA3F-4544-9754-5406E8094723}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DiscoHawk_4.5", "DiscoHawk\DiscoHawk_4.5.csproj", "{C4366030-6D03-424B-AE53-F4F43BB217C3}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|Mixed Platforms = Debug|Mixed Platforms - Debug|Win32 = Debug|Win32 - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|Mixed Platforms = Release|Mixed Platforms - Release|Win32 = Release|Win32 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {197D4314-8A9F-49BA-977D-54ACEFAEB6BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {197D4314-8A9F-49BA-977D-54ACEFAEB6BA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {197D4314-8A9F-49BA-977D-54ACEFAEB6BA}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {197D4314-8A9F-49BA-977D-54ACEFAEB6BA}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {197D4314-8A9F-49BA-977D-54ACEFAEB6BA}.Debug|Win32.ActiveCfg = Debug|Any CPU - {197D4314-8A9F-49BA-977D-54ACEFAEB6BA}.Debug|Win32.Build.0 = Debug|Any CPU - {197D4314-8A9F-49BA-977D-54ACEFAEB6BA}.Debug|x86.ActiveCfg = Debug|Any CPU - {197D4314-8A9F-49BA-977D-54ACEFAEB6BA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {197D4314-8A9F-49BA-977D-54ACEFAEB6BA}.Release|Any CPU.Build.0 = Release|Any CPU - {197D4314-8A9F-49BA-977D-54ACEFAEB6BA}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {197D4314-8A9F-49BA-977D-54ACEFAEB6BA}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {197D4314-8A9F-49BA-977D-54ACEFAEB6BA}.Release|Win32.ActiveCfg = Release|Any CPU - {197D4314-8A9F-49BA-977D-54ACEFAEB6BA}.Release|Win32.Build.0 = Release|Any CPU - {197D4314-8A9F-49BA-977D-54ACEFAEB6BA}.Release|x86.ActiveCfg = Release|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Debug|Win32.ActiveCfg = Debug|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Debug|Win32.Build.0 = Debug|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Debug|x86.ActiveCfg = Debug|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Release|Any CPU.Build.0 = Release|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Release|Win32.ActiveCfg = Release|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Release|Win32.Build.0 = Release|Any CPU - {EE135301-08B3-4EFC-A61C-1C53E1C65CB9}.Release|x86.ActiveCfg = Release|Any CPU - {DD448B37-BA3F-4544-9754-5406E8094723}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DD448B37-BA3F-4544-9754-5406E8094723}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DD448B37-BA3F-4544-9754-5406E8094723}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {DD448B37-BA3F-4544-9754-5406E8094723}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {DD448B37-BA3F-4544-9754-5406E8094723}.Debug|Win32.ActiveCfg = Debug|Any CPU - {DD448B37-BA3F-4544-9754-5406E8094723}.Debug|Win32.Build.0 = Debug|Any CPU - {DD448B37-BA3F-4544-9754-5406E8094723}.Debug|x86.ActiveCfg = Debug|Any CPU - {DD448B37-BA3F-4544-9754-5406E8094723}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DD448B37-BA3F-4544-9754-5406E8094723}.Release|Any CPU.Build.0 = Release|Any CPU - {DD448B37-BA3F-4544-9754-5406E8094723}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {DD448B37-BA3F-4544-9754-5406E8094723}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {DD448B37-BA3F-4544-9754-5406E8094723}.Release|Win32.ActiveCfg = Release|Any CPU - {DD448B37-BA3F-4544-9754-5406E8094723}.Release|Win32.Build.0 = Release|Any CPU - {DD448B37-BA3F-4544-9754-5406E8094723}.Release|x86.ActiveCfg = Release|Any CPU - {C4366030-6D03-424B-AE53-F4F43BB217C3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C4366030-6D03-424B-AE53-F4F43BB217C3}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C4366030-6D03-424B-AE53-F4F43BB217C3}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {C4366030-6D03-424B-AE53-F4F43BB217C3}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {C4366030-6D03-424B-AE53-F4F43BB217C3}.Debug|Win32.ActiveCfg = Debug|Any CPU - {C4366030-6D03-424B-AE53-F4F43BB217C3}.Debug|Win32.Build.0 = Debug|Any CPU - {C4366030-6D03-424B-AE53-F4F43BB217C3}.Debug|x86.ActiveCfg = Debug|Any CPU - {C4366030-6D03-424B-AE53-F4F43BB217C3}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C4366030-6D03-424B-AE53-F4F43BB217C3}.Release|Any CPU.Build.0 = Release|Any CPU - {C4366030-6D03-424B-AE53-F4F43BB217C3}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {C4366030-6D03-424B-AE53-F4F43BB217C3}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {C4366030-6D03-424B-AE53-F4F43BB217C3}.Release|Win32.ActiveCfg = Release|Any CPU - {C4366030-6D03-424B-AE53-F4F43BB217C3}.Release|Win32.Build.0 = Release|Any CPU - {C4366030-6D03-424B-AE53-F4F43BB217C3}.Release|x86.ActiveCfg = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(MonoDevelopProperties) = preSolution - StartupItem = BizHawk.MultiClient\BizHawk.MultiClient.csproj - EndGlobalSection -EndGlobal