Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/ClusterM/hakchi2.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlexey 'Cluster' Avdyukhin <clusterrr@clusterrr.com>2017-01-23 02:24:43 +0300
committerAlexey 'Cluster' Avdyukhin <clusterrr@clusterrr.com>2017-01-23 02:24:43 +0300
commitfb6b8383c27560c30e7a3076c67b925a7f8ff363 (patch)
treed30a5008e0fb39bdbac6e275689c2b776c4dee66 /SevenZip
parenta6328fb50012c128e41d23d2de81241aeab14de2 (diff)
Archives support
Diffstat (limited to 'SevenZip')
-rw-r--r--SevenZip/ArchiveEmulationStreamProxy.cs101
-rw-r--r--SevenZip/ArchiveExtractCallback.cs602
-rw-r--r--SevenZip/ArchiveOpenCallback.cs217
-rw-r--r--SevenZip/ArchiveUpdateCallback.cs806
-rw-r--r--SevenZip/COM.cs1244
-rw-r--r--SevenZip/Common.cs847
-rw-r--r--SevenZip/EventArgs.cs401
-rw-r--r--SevenZip/Exceptions.cs464
-rw-r--r--SevenZip/FileSignatureChecker.cs240
-rw-r--r--SevenZip/Formats.cs529
-rw-r--r--SevenZip/LibraryFeature.cs113
-rw-r--r--SevenZip/LibraryManager.cs581
-rw-r--r--SevenZip/LzmaDecodeStream.cs240
-rw-r--r--SevenZip/LzmaProgressCallback.cs72
-rw-r--r--SevenZip/NativeMethods.cs77
-rw-r--r--SevenZip/SevenZipExtractor.cs1449
-rw-r--r--SevenZip/SevenZipExtractorAsynchronous.cs317
-rw-r--r--SevenZip/StreamWrappers.cs545
-rw-r--r--SevenZip/gpl.txt674
-rw-r--r--SevenZip/lgpl.txt165
-rw-r--r--SevenZip/sdk/Common/CRC.cs75
-rw-r--r--SevenZip/sdk/Common/InBuffer.cs119
-rw-r--r--SevenZip/sdk/Common/OutBuffer.cs85
-rw-r--r--SevenZip/sdk/Compress/LZ/IMatchFinder.cs40
-rw-r--r--SevenZip/sdk/Compress/LZ/LzBinTree.cs405
-rw-r--r--SevenZip/sdk/Compress/LZ/LzInWindow.cs197
-rw-r--r--SevenZip/sdk/Compress/LZ/LzOutWindow.cs125
-rw-r--r--SevenZip/sdk/Compress/LZMA/LzmaBase.cs108
-rw-r--r--SevenZip/sdk/Compress/LZMA/LzmaDecoder.cs480
-rw-r--r--SevenZip/sdk/Compress/LZMA/LzmaEncoder.cs1587
-rw-r--r--SevenZip/sdk/Compress/RangeCoder/RangeCoder.cs249
-rw-r--r--SevenZip/sdk/Compress/RangeCoder/RangeCoderBit.cs146
-rw-r--r--SevenZip/sdk/Compress/RangeCoder/RangeCoderBitTree.cs173
-rw-r--r--SevenZip/sdk/ICoder.cs192
34 files changed, 13665 insertions, 0 deletions
diff --git a/SevenZip/ArchiveEmulationStreamProxy.cs b/SevenZip/ArchiveEmulationStreamProxy.cs
new file mode 100644
index 00000000..c0bdaed2
--- /dev/null
+++ b/SevenZip/ArchiveEmulationStreamProxy.cs
@@ -0,0 +1,101 @@
+using System.IO;
+using System;
+
+namespace SevenZip
+{
+ /// <summary>
+ /// The Stream extension class to emulate the archive part of a stream.
+ /// </summary>
+ internal class ArchiveEmulationStreamProxy : Stream, IDisposable
+ {
+ /// <summary>
+ /// Gets the file offset.
+ /// </summary>
+ public int Offset { get; private set; }
+
+ /// <summary>
+ /// The source wrapped stream.
+ /// </summary>
+ public Stream Source { get; private set; }
+
+ /// <summary>
+ /// Initializes a new instance of the ArchiveEmulationStream class.
+ /// </summary>
+ /// <param name="stream">The stream to wrap.</param>
+ /// <param name="offset">The stream offset.</param>
+ 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/SevenZip/ArchiveExtractCallback.cs b/SevenZip/ArchiveExtractCallback.cs
new file mode 100644
index 00000000..d9aedc0f
--- /dev/null
+++ b/SevenZip/ArchiveExtractCallback.cs
@@ -0,0 +1,602 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+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
+ /// <summary>
+ /// Archive extraction callback to handle the process of unpacking files
+ /// </summary>
+ internal sealed class ArchiveExtractCallback : CallbackBase, IArchiveExtractCallback, ICryptoGetTextPassword,
+ IDisposable
+ {
+ private List<uint> _actualIndexes;
+ private IInArchive _archive;
+
+ /// <summary>
+ /// For Compressing event.
+ /// </summary>
+ private long _bytesCount;
+
+ private long _bytesWritten;
+ private long _bytesWrittenOld;
+ private string _directory;
+
+ /// <summary>
+ /// Rate of the done work from [0, 1].
+ /// </summary>
+ 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
+
+ /// <summary>
+ /// Initializes a new instance of the ArchiveExtractCallback class
+ /// </summary>
+ /// <param name="archive">IInArchive interface for the archive</param>
+ /// <param name="directory">Directory where files are to be unpacked to</param>
+ /// <param name="filesCount">The archive files count</param>'
+ /// <param name="extractor">The owner of the callback</param>
+ /// <param name="actualIndexes">The list of actual indexes (solid archives support)</param>
+ /// <param name="directoryStructure">The value indicating whether to preserve directory structure of extracted files.</param>
+ public ArchiveExtractCallback(IInArchive archive, string directory, int filesCount, bool directoryStructure,
+ List<uint> actualIndexes, SevenZipExtractor extractor)
+ {
+ Init(archive, directory, filesCount, directoryStructure, actualIndexes, extractor);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the ArchiveExtractCallback class
+ /// </summary>
+ /// <param name="archive">IInArchive interface for the archive</param>
+ /// <param name="directory">Directory where files are to be unpacked to</param>
+ /// <param name="filesCount">The archive files count</param>
+ /// <param name="password">Password for the archive</param>
+ /// <param name="extractor">The owner of the callback</param>
+ /// <param name="actualIndexes">The list of actual indexes (solid archives support)</param>
+ /// <param name="directoryStructure">The value indicating whether to preserve directory structure of extracted files.</param>
+ public ArchiveExtractCallback(IInArchive archive, string directory, int filesCount, bool directoryStructure,
+ List<uint> actualIndexes, string password, SevenZipExtractor extractor)
+ : base(password)
+ {
+ Init(archive, directory, filesCount, directoryStructure, actualIndexes, extractor);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the ArchiveExtractCallback class
+ /// </summary>
+ /// <param name="archive">IInArchive interface for the archive</param>
+ /// <param name="stream">The stream where files are to be unpacked to</param>
+ /// <param name="filesCount">The archive files count</param>
+ /// <param name="fileIndex">The file index for the stream</param>
+ /// <param name="extractor">The owner of the callback</param>
+ public ArchiveExtractCallback(IInArchive archive, Stream stream, int filesCount, uint fileIndex,
+ SevenZipExtractor extractor)
+ {
+ Init(archive, stream, filesCount, fileIndex, extractor);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the ArchiveExtractCallback class
+ /// </summary>
+ /// <param name="archive">IInArchive interface for the archive</param>
+ /// <param name="stream">The stream where files are to be unpacked to</param>
+ /// <param name="filesCount">The archive files count</param>
+ /// <param name="fileIndex">The file index for the stream</param>
+ /// <param name="password">Password for the archive</param>
+ /// <param name="extractor">The owner of the callback</param>
+ 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<uint> 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
+
+ /// <summary>
+ /// Occurs when a new file is going to be unpacked
+ /// </summary>
+ /// <remarks>Occurs when 7-zip engine requests for an output stream for a new file to unpack in</remarks>
+ public event EventHandler<FileInfoEventArgs> FileExtractionStarted;
+
+ /// <summary>
+ /// Occurs when a file has been successfully unpacked
+ /// </summary>
+ public event EventHandler<FileInfoEventArgs> FileExtractionFinished;
+
+ /// <summary>
+ /// Occurs when the archive is opened and 7-zip sends the size of unpacked data
+ /// </summary>
+ public event EventHandler<OpenEventArgs> Open;
+
+ /// <summary>
+ /// Occurs when the extraction is performed
+ /// </summary>
+ public event EventHandler<ProgressEventArgs> Extracting;
+
+ /// <summary>
+ /// Occurs during the extraction when a file already exists
+ /// </summary>
+ public event EventHandler<FileOverwriteEventArgs> 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
+
+ /// <summary>
+ /// Gives the size of the unpacked archive files
+ /// </summary>
+ /// <param name="total">Size of the unpacked archive files (in bytes)</param>
+ public void SetTotal(ulong total)
+ {
+ _bytesCount = (long)total;
+ OnOpen(new OpenEventArgs(total));
+ }
+
+ public void SetCompleted(ref ulong completeValue) { }
+
+ /// <summary>
+ /// Sets output stream for writing unpacked data
+ /// </summary>
+ /// <param name="index">Current file index</param>
+ /// <param name="outStream">Output stream pointer</param>
+ /// <param name="askExtractMode">Extraction mode</param>
+ /// <returns>0 if OK</returns>
+ 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) { }
+
+ /// <summary>
+ /// Called when the archive was extracted
+ /// </summary>
+ /// <param name="operationResult"></param>
+ 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
+
+ /// <summary>
+ /// Sets password for the archive
+ /// </summary>
+ /// <param name="password">Password for the archive</param>
+ /// <returns>Zero if everything is OK</returns>
+ 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
+
+ /// <summary>
+ /// Validates the file name and ensures that the directory to the file name is valid and creates intermediate directories if necessary
+ /// </summary>
+ /// <param name="fileName">File name</param>
+ /// <returns>The valid file name</returns>
+ private static string ValidateFileName(string fileName)
+ {
+ if (String.IsNullOrEmpty(fileName))
+ {
+ throw new SevenZipArchiveException("some archive name is null or empty.");
+ }
+ var splittedFileName = new List<string>(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/SevenZip/ArchiveOpenCallback.cs b/SevenZip/ArchiveOpenCallback.cs
new file mode 100644
index 00000000..080ce8c6
--- /dev/null
+++ b/SevenZip/ArchiveOpenCallback.cs
@@ -0,0 +1,217 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+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
+ /// <summary>
+ /// Callback to handle the archive opening
+ /// </summary>
+ internal sealed class ArchiveOpenCallback : CallbackBase, IArchiveOpenCallback, IArchiveOpenVolumeCallback,
+ ICryptoGetTextPassword, IDisposable
+ {
+ private FileInfo _fileInfo;
+ private Dictionary<string, InStreamWrapper> _wrappers =
+ new Dictionary<string, InStreamWrapper>();
+ private readonly List<string> _volumeFileNames = new List<string>();
+
+ /// <summary>
+ /// Gets the list of volume file names.
+ /// </summary>
+ public IList<string> VolumeFileNames
+ {
+ get
+ {
+ return _volumeFileNames;
+ }
+ }
+
+ /// <summary>
+ /// Performs the common initialization.
+ /// </summary>
+ /// <param name="fileName">Volume file name.</param>
+ private void Init(string fileName)
+ {
+ if (!String.IsNullOrEmpty(fileName))
+ {
+ _fileInfo = new FileInfo(fileName);
+ _volumeFileNames.Add(fileName);
+ if (fileName.EndsWith("001"))
+ {
+ int index = 2;
+ var baseName = fileName.Substring(0, fileName.Length - 3);
+ var volName = baseName + (index > 99 ? index.ToString() :
+ index > 9 ? "0" + index : "00" + index);
+ while (File.Exists(volName))
+ {
+ _volumeFileNames.Add(volName);
+ index++;
+ volName = baseName + (index > 99 ? index.ToString() :
+ index > 9 ? "0" + index : "00" + index);
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the ArchiveOpenCallback class.
+ /// </summary>
+ /// <param name="fileName">The archive file name.</param>
+ public ArchiveOpenCallback(string fileName)
+ {
+ Init(fileName);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the ArchiveOpenCallback class.
+ /// </summary>
+ /// <param name="fileName">The archive file name.</param>
+ /// <param name="password">Password for the archive.</param>
+ 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
+
+ /// <summary>
+ /// Sets password for the archive
+ /// </summary>
+ /// <param name="password">Password for the archive</param>
+ /// <returns>Zero if everything is OK</returns>
+ 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/SevenZip/ArchiveUpdateCallback.cs b/SevenZip/ArchiveUpdateCallback.cs
new file mode 100644
index 00000000..a9f838e7
--- /dev/null
+++ b/SevenZip/ArchiveUpdateCallback.cs
@@ -0,0 +1,806 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+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
+ /// <summary>
+ /// Archive update callback to handle the process of packing files
+ /// </summary>
+ internal sealed class ArchiveUpdateCallback : CallbackBase, IArchiveUpdateCallback, ICryptoGetTextPassword2,
+ IDisposable
+ {
+ #region Fields
+ /// <summary>
+ /// _files.Count if do not count directories
+ /// </summary>
+ private int _actualFilesCount;
+
+ /// <summary>
+ /// For Compressing event.
+ /// </summary>
+ private long _bytesCount;
+
+ private long _bytesWritten;
+ private long _bytesWrittenOld;
+ private SevenZipCompressor _compressor;
+
+ /// <summary>
+ /// No directories.
+ /// </summary>
+ private bool _directoryStructure;
+
+ /// <summary>
+ /// Rate of the done work from [0, 1]
+ /// </summary>
+ private float _doneRate;
+
+ /// <summary>
+ /// The names of the archive entries
+ /// </summary>
+ private string[] _entries;
+
+ /// <summary>
+ /// Array of files to pack
+ /// </summary>
+ private FileInfo[] _files;
+
+ private InStreamWrapper _fileStream;
+
+ private uint _indexInArchive;
+ private uint _indexOffset;
+
+ /// <summary>
+ /// Common root of file names length.
+ /// </summary>
+ private int _rootLength;
+
+ /// <summary>
+ /// Input streams to be compressed.
+ /// </summary>
+ private Stream[] _streams;
+
+ private UpdateData _updateData;
+ private List<InStreamWrapper> _wrappersToDispose;
+
+ /// <summary>
+ /// Gets or sets the default item name used in MemoryStream compression.
+ /// </summary>
+ public string DefaultItemName { private get; set; }
+
+ /// <summary>
+ /// Gets or sets the value indicating whether to compress as fast as possible, without calling events.
+ /// </summary>
+ public bool FastCompression { private get; set; }
+#if !WINCE
+ private int _memoryPressure;
+#endif
+ #endregion
+
+ #region Constructors
+
+ /// <summary>
+ /// Initializes a new instance of the ArchiveUpdateCallback class
+ /// </summary>
+ /// <param name="files">Array of files to pack</param>
+ /// <param name="rootLength">Common file names root length</param>
+ /// <param name="compressor">The owner of the callback</param>
+ /// <param name="updateData">The compression parameters.</param>
+ /// <param name="directoryStructure">Preserve directory structure.</param>
+ public ArchiveUpdateCallback(
+ FileInfo[] files, int rootLength,
+ SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure)
+ {
+ Init(files, rootLength, compressor, updateData, directoryStructure);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the ArchiveUpdateCallback class
+ /// </summary>
+ /// <param name="files">Array of files to pack</param>
+ /// <param name="rootLength">Common file names root length</param>
+ /// <param name="password">The archive password</param>
+ /// <param name="compressor">The owner of the callback</param>
+ /// <param name="updateData">The compression parameters.</param>
+ /// <param name="directoryStructure">Preserve directory structure.</param>
+ public ArchiveUpdateCallback(
+ FileInfo[] files, int rootLength, string password,
+ SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure)
+ : base(password)
+ {
+ Init(files, rootLength, compressor, updateData, directoryStructure);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the ArchiveUpdateCallback class
+ /// </summary>
+ /// <param name="stream">The input stream</param>
+ /// <param name="compressor">The owner of the callback</param>
+ /// <param name="updateData">The compression parameters.</param>
+ /// <param name="directoryStructure">Preserve directory structure.</param>
+ public ArchiveUpdateCallback(
+ Stream stream, SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure)
+ {
+ Init(stream, compressor, updateData, directoryStructure);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the ArchiveUpdateCallback class
+ /// </summary>
+ /// <param name="stream">The input stream</param>
+ /// <param name="password">The archive password</param>
+ /// <param name="compressor">The owner of the callback</param>
+ /// <param name="updateData">The compression parameters.</param>
+ /// <param name="directoryStructure">Preserve directory structure.</param>
+ public ArchiveUpdateCallback(
+ Stream stream, string password, SevenZipCompressor compressor, UpdateData updateData,
+ bool directoryStructure)
+ : base(password)
+ {
+ Init(stream, compressor, updateData, directoryStructure);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the ArchiveUpdateCallback class
+ /// </summary>
+ /// <param name="streamDict">Dictionary&lt;file stream, name of the archive entry&gt;</param>
+ /// <param name="compressor">The owner of the callback</param>
+ /// <param name="updateData">The compression parameters.</param>
+ /// <param name="directoryStructure">Preserve directory structure.</param>
+ public ArchiveUpdateCallback(
+ Dictionary<string, Stream> streamDict,
+ SevenZipCompressor compressor, UpdateData updateData, bool directoryStructure)
+ {
+ Init(streamDict, compressor, updateData, directoryStructure);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the ArchiveUpdateCallback class
+ /// </summary>
+ /// <param name="streamDict">Dictionary&lt;file stream, name of the archive entry&gt;</param>
+ /// <param name="password">The archive password</param>
+ /// <param name="compressor">The owner of the callback</param>
+ /// <param name="updateData">The compression parameters.</param>
+ /// <param name="directoryStructure">Preserve directory structure.</param>
+ public ArchiveUpdateCallback(
+ Dictionary<string, Stream> 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<InStreamWrapper>();
+ }
+ _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<string, Stream> 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
+
+ /// <summary>
+ /// Gets or sets the dictionary size.
+ /// </summary>
+ public float DictionarySize
+ {
+ set
+ {
+#if !WINCE
+ _memoryPressure = (int)(value * 1024 * 1024);
+ GC.AddMemoryPressure(_memoryPressure);
+#endif
+ }
+ }
+
+ /// <summary>
+ /// Raises events for the GetStream method.
+ /// </summary>
+ /// <param name="index">The current item index.</param>
+ /// <returns>True if not cancelled; otherwise, false.</returns>
+ 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
+
+ /// <summary>
+ /// Occurs when the next file is going to be packed.
+ /// </summary>
+ /// <remarks>Occurs when 7-zip engine requests for an input stream for the next file to pack it</remarks>
+ public event EventHandler<FileNameEventArgs> FileCompressionStarted;
+
+ /// <summary>
+ /// Occurs when data are being compressed.
+ /// </summary>
+ public event EventHandler<ProgressEventArgs> Compressing;
+
+ /// <summary>
+ /// Occurs when the current file was compressed.
+ /// </summary>
+ 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<Int32, string> 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;
+ }
+
+ /// <summary>
+ /// Gets the stream for 7-zip library.
+ /// </summary>
+ /// <param name="index">File index</param>
+ /// <param name="inStream">Input file stream</param>
+ /// <returns>Zero if Ok</returns>
+ 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 (_files)
+ {
+ 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/SevenZip/COM.cs b/SevenZip/COM.cs
new file mode 100644
index 00000000..31d2a4d8
--- /dev/null
+++ b/SevenZip/COM.cs
@@ -0,0 +1,1244 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+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
+
+ /// <summary>
+ /// The structure to fix x64 and x32 variant size mismatch.
+ /// </summary>
+ [StructLayout(LayoutKind.Sequential)]
+ internal struct PropArray
+ {
+ uint _cElems;
+ IntPtr _pElems;
+ }
+
+ /// <summary>
+ /// COM VARIANT structure with special interface routines.
+ /// </summary>
+ [StructLayout(LayoutKind.Explicit)]
+ internal struct PropVariant
+ {
+ [FieldOffset(0)] private ushort _vt;
+
+ /// <summary>
+ /// IntPtr variant value.
+ /// </summary>
+ [FieldOffset(8)] private IntPtr _value;
+
+ /*/// <summary>
+ /// Byte variant value.
+ /// </summary>
+ [FieldOffset(8)]
+ private byte _ByteValue;*/
+
+ /// <summary>
+ /// Signed int variant value.
+ /// </summary>
+ [FieldOffset(8)]
+ private Int32 _int32Value;
+
+ /// <summary>
+ /// Unsigned int variant value.
+ /// </summary>
+ [FieldOffset(8)] private UInt32 _uInt32Value;
+
+ /// <summary>
+ /// Long variant value.
+ /// </summary>
+ [FieldOffset(8)] private Int64 _int64Value;
+
+ /// <summary>
+ /// Unsigned long variant value.
+ /// </summary>
+ [FieldOffset(8)] private UInt64 _uInt64Value;
+
+ /// <summary>
+ /// FILETIME variant value.
+ /// </summary>
+ [FieldOffset(8)] private FILETIME _fileTime;
+
+ /// <summary>
+ /// The PropArray instance to fix the variant size on x64 bit systems.
+ /// </summary>
+ [FieldOffset(8)]
+ private PropArray _propArray;
+
+ /// <summary>
+ /// Gets or sets variant type.
+ /// </summary>
+ public VarEnum VarType
+ {
+ private get
+ {
+ return (VarEnum) _vt;
+ }
+
+ set
+ {
+ _vt = (ushort) value;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the pointer value of the COM variant
+ /// </summary>
+ public IntPtr Value
+ {
+ private get
+ {
+ return _value;
+ }
+
+ set
+ {
+ _value = value;
+ }
+ }
+
+ /*
+ /// <summary>
+ /// Gets or sets the byte value of the COM variant
+ /// </summary>
+ public byte ByteValue
+ {
+ get
+ {
+ return _ByteValue;
+ }
+
+ set
+ {
+ _ByteValue = value;
+ }
+ }
+*/
+
+ /// <summary>
+ /// Gets or sets the UInt32 value of the COM variant.
+ /// </summary>
+ public UInt32 UInt32Value
+ {
+ private get
+ {
+ return _uInt32Value;
+ }
+ set
+ {
+ _uInt32Value = value;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the UInt32 value of the COM variant.
+ /// </summary>
+ public Int32 Int32Value
+ {
+ private get
+ {
+ return _int32Value;
+ }
+ set
+ {
+ _int32Value = value;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the Int64 value of the COM variant
+ /// </summary>
+ public Int64 Int64Value
+ {
+ private get
+ {
+ return _int64Value;
+ }
+
+ set
+ {
+ _int64Value = value;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the UInt64 value of the COM variant
+ /// </summary>
+ public UInt64 UInt64Value
+ {
+ private get
+ {
+ return _uInt64Value;
+ }
+ set
+ {
+ _uInt64Value = value;
+ }
+ }
+
+ /*
+ /// <summary>
+ /// Gets or sets the FILETIME value of the COM variant
+ /// </summary>
+ public System.Runtime.InteropServices.ComTypes.FILETIME FileTime
+ {
+ get
+ {
+ return _fileTime;
+ }
+
+ set
+ {
+ _fileTime = value;
+ }
+ }
+*/
+
+ /*/// <summary>
+ /// Gets or sets variant type (ushort).
+ /// </summary>
+ public ushort VarTypeNative
+ {
+ get
+ {
+ return _vt;
+ }
+
+ set
+ {
+ _vt = value;
+ }
+ }*/
+
+ /*/// <summary>
+ /// Clears variant
+ /// </summary>
+ 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;
+ }
+ }*/
+
+ /// <summary>
+ /// Gets the object for this PropVariant.
+ /// </summary>
+ /// <returns></returns>
+ 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();
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Determines whether the specified System.Object is equal to the current PropVariant.
+ /// </summary>
+ /// <param name="obj">The System.Object to compare with the current PropVariant.</param>
+ /// <returns>true if the specified System.Object is equal to the current PropVariant; otherwise, false.</returns>
+ public override bool Equals(object obj)
+ {
+ return (obj is PropVariant) ? Equals((PropVariant) obj) : false;
+ }
+
+ /// <summary>
+ /// Determines whether the specified PropVariant is equal to the current PropVariant.
+ /// </summary>
+ /// <param name="afi">The PropVariant to compare with the current PropVariant.</param>
+ /// <returns>true if the specified PropVariant is equal to the current PropVariant; otherwise, false.</returns>
+ private bool Equals(PropVariant afi)
+ {
+ if (afi.VarType != VarType)
+ {
+ return false;
+ }
+ if (VarType != VarEnum.VT_BSTR)
+ {
+ return afi.Int64Value == Int64Value;
+ }
+ return afi.Value == Value;
+ }
+
+ /// <summary>
+ /// Serves as a hash function for a particular type.
+ /// </summary>
+ /// <returns> A hash code for the current PropVariant.</returns>
+ public override int GetHashCode()
+ {
+ return Value.GetHashCode();
+ }
+
+ /// <summary>
+ /// Returns a System.String that represents the current PropVariant.
+ /// </summary>
+ /// <returns>A System.String that represents the current PropVariant.</returns>
+ public override string ToString()
+ {
+ return "[" + Value + "] " + Int64Value.ToString(CultureInfo.CurrentCulture);
+ }
+
+ /// <summary>
+ /// Determines whether the specified PropVariant instances are considered equal.
+ /// </summary>
+ /// <param name="afi1">The first PropVariant to compare.</param>
+ /// <param name="afi2">The second PropVariant to compare.</param>
+ /// <returns>true if the specified PropVariant instances are considered equal; otherwise, false.</returns>
+ public static bool operator ==(PropVariant afi1, PropVariant afi2)
+ {
+ return afi1.Equals(afi2);
+ }
+
+ /// <summary>
+ /// Determines whether the specified PropVariant instances are not considered equal.
+ /// </summary>
+ /// <param name="afi1">The first PropVariant to compare.</param>
+ /// <param name="afi2">The second PropVariant to compare.</param>
+ /// <returns>true if the specified PropVariant instances are not considered equal; otherwise, false.</returns>
+ public static bool operator !=(PropVariant afi1, PropVariant afi2)
+ {
+ return !afi1.Equals(afi2);
+ }
+ }
+
+ /// <summary>
+ /// Stores file extraction modes.
+ /// </summary>
+ internal enum AskMode
+ {
+ /// <summary>
+ /// Extraction mode
+ /// </summary>
+ Extract = 0,
+ /// <summary>
+ /// Test mode
+ /// </summary>
+ Test,
+ /// <summary>
+ /// Skip mode
+ /// </summary>
+ Skip
+ }
+
+ /// <summary>
+ /// Stores operation result values
+ /// </summary>
+ public enum OperationResult
+ {
+ /// <summary>
+ /// Success
+ /// </summary>
+ Ok = 0,
+ /// <summary>
+ /// Method is unsupported
+ /// </summary>
+ UnsupportedMethod,
+ /// <summary>
+ /// Data error has occured
+ /// </summary>
+ DataError,
+ /// <summary>
+ /// CrcError has occured
+ /// </summary>
+ CrcError
+ }
+
+ /// <summary>
+ /// Codes of item properities
+ /// </summary>
+ internal enum ItemPropId : uint
+ {
+ /// <summary>
+ /// No property
+ /// </summary>
+ NoProperty = 0,
+ /// <summary>
+ /// Handler item index
+ /// </summary>
+ HandlerItemIndex = 2,
+ /// <summary>
+ /// Item path
+ /// </summary>
+ Path,
+ /// <summary>
+ /// Item name
+ /// </summary>
+ Name,
+ /// <summary>
+ /// Item extension
+ /// </summary>
+ Extension,
+ /// <summary>
+ /// true if the item is a folder; otherwise, false
+ /// </summary>
+ IsDirectory,
+ /// <summary>
+ /// Item size
+ /// </summary>
+ Size,
+ /// <summary>
+ /// Item packed sise; usually absent
+ /// </summary>
+ PackedSize,
+ /// <summary>
+ /// Item attributes; usually absent
+ /// </summary>
+ Attributes,
+ /// <summary>
+ /// Item creation time; usually absent
+ /// </summary>
+ CreationTime,
+ /// <summary>
+ /// Item last access time; usually absent
+ /// </summary>
+ LastAccessTime,
+ /// <summary>
+ /// Item last write time
+ /// </summary>
+ LastWriteTime,
+ /// <summary>
+ /// true if the item is solid; otherwise, false
+ /// </summary>
+ Solid,
+ /// <summary>
+ /// true if the item is commented; otherwise, false
+ /// </summary>
+ Commented,
+ /// <summary>
+ /// true if the item is encrypted; otherwise, false
+ /// </summary>
+ Encrypted,
+ /// <summary>
+ /// (?)
+ /// </summary>
+ SplitBefore,
+ /// <summary>
+ /// (?)
+ /// </summary>
+ SplitAfter,
+ /// <summary>
+ /// Dictionary size(?)
+ /// </summary>
+ DictionarySize,
+ /// <summary>
+ /// Item CRC checksum
+ /// </summary>
+ Crc,
+ /// <summary>
+ /// Item type(?)
+ /// </summary>
+ Type,
+ /// <summary>
+ /// (?)
+ /// </summary>
+ IsAnti,
+ /// <summary>
+ /// Compression method
+ /// </summary>
+ Method,
+ /// <summary>
+ /// (?); usually absent
+ /// </summary>
+ HostOS,
+ /// <summary>
+ /// Item file system; usually absent
+ /// </summary>
+ FileSystem,
+ /// <summary>
+ /// Item user(?); usually absent
+ /// </summary>
+ User,
+ /// <summary>
+ /// Item group(?); usually absent
+ /// </summary>
+ Group,
+ /// <summary>
+ /// Bloack size(?)
+ /// </summary>
+ Block,
+ /// <summary>
+ /// Item comment; usually absent
+ /// </summary>
+ Comment,
+ /// <summary>
+ /// Item position
+ /// </summary>
+ Position,
+ /// <summary>
+ /// Item prefix(?)
+ /// </summary>
+ Prefix,
+ /// <summary>
+ /// Number of subdirectories
+ /// </summary>
+ NumSubDirs,
+ /// <summary>
+ /// Numbers of subfiles
+ /// </summary>
+ NumSubFiles,
+ /// <summary>
+ /// The archive legacy unpacker version
+ /// </summary>
+ UnpackVersion,
+ /// <summary>
+ /// Volume(?)
+ /// </summary>
+ Volume,
+ /// <summary>
+ /// Is a volume
+ /// </summary>
+ IsVolume,
+ /// <summary>
+ /// Offset value(?)
+ /// </summary>
+ Offset,
+ /// <summary>
+ /// Links(?)
+ /// </summary>
+ Links,
+ /// <summary>
+ /// Number of blocks
+ /// </summary>
+ NumBlocks,
+ /// <summary>
+ /// Number of volumes(?)
+ /// </summary>
+ NumVolumes,
+ /// <summary>
+ /// Time type(?)
+ /// </summary>
+ TimeType,
+ /// <summary>
+ /// 64-bit(?)
+ /// </summary>
+ Bit64,
+ /// <summary>
+ /// BigEndian
+ /// </summary>
+ BigEndian,
+ /// <summary>
+ /// Cpu(?)
+ /// </summary>
+ Cpu,
+ /// <summary>
+ /// Physical archive size
+ /// </summary>
+ PhysicalSize,
+ /// <summary>
+ /// Headers size
+ /// </summary>
+ HeadersSize,
+ /// <summary>
+ /// Archive checksum
+ /// </summary>
+ Checksum,
+ /// <summary>
+ /// (?)
+ /// </summary>
+ TotalSize = 0x1100,
+ /// <summary>
+ /// (?)
+ /// </summary>
+ FreeSpace,
+ /// <summary>
+ /// Cluster size(?)
+ /// </summary>
+ ClusterSize,
+ /// <summary>
+ /// Volume name(?)
+ /// </summary>
+ VolumeName,
+ /// <summary>
+ /// Local item name(?); usually absent
+ /// </summary>
+ LocalName = 0x1200,
+ /// <summary>
+ /// (?)
+ /// </summary>
+ Provider,
+ /// <summary>
+ /// User defined property; usually absent
+ /// </summary>
+ UserDefined = 0x10000
+ }
+
+ /*/// <summary>
+ /// Codes of archive properties or modes.
+ /// </summary>
+ internal enum ArchivePropId : uint
+ {
+ Name = 0,
+ ClassID,
+ Extension,
+ AddExtension,
+ Update,
+ KeepName,
+ StartSignature,
+ FinishSignature,
+ Associate
+ }*/
+
+ /// <summary>
+ /// PropId string names dictionary wrapper.
+ /// </summary>
+ internal static class PropIdToName
+ {
+ /// <summary>
+ /// PropId string names
+ /// </summary>
+ public static readonly Dictionary<ItemPropId, string> PropIdNames =
+ #region Initialization
+ new Dictionary<ItemPropId, string>(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
+ }
+
+ /// <summary>
+ /// 7-zip IArchiveOpenCallback imported interface to handle the opening of an archive.
+ /// </summary>
+ [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
+ /// <summary>
+ /// Sets total data size
+ /// </summary>
+ /// <param name="files">Files pointer</param>
+ /// <param name="bytes">Total size in bytes</param>
+ void SetTotal(
+ IntPtr files,
+ IntPtr bytes);
+
+ /// <summary>
+ /// Sets completed size
+ /// </summary>
+ /// <param name="files">Files pointer</param>
+ /// <param name="bytes">Completed size in bytes</param>
+ void SetCompleted(
+ IntPtr files,
+ IntPtr bytes);
+ }
+
+ /// <summary>
+ /// 7-zip ICryptoGetTextPassword imported interface to get the archive password.
+ /// </summary>
+ [ComImport]
+ [Guid("23170F69-40C1-278A-0000-000500100000")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ internal interface ICryptoGetTextPassword
+ {
+ /// <summary>
+ /// Gets password for the archive
+ /// </summary>
+ /// <param name="password">Password for the archive</param>
+ /// <returns>Zero if everything is OK</returns>
+ [PreserveSig]
+ int CryptoGetTextPassword(
+ [MarshalAs(UnmanagedType.BStr)] out string password);
+ }
+
+ /// <summary>
+ /// 7-zip ICryptoGetTextPassword2 imported interface for setting the archive password.
+ /// </summary>
+ [ComImport]
+ [Guid("23170F69-40C1-278A-0000-000500110000")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ internal interface ICryptoGetTextPassword2
+ {
+ /// <summary>
+ /// Sets password for the archive
+ /// </summary>
+ /// <param name="passwordIsDefined">Specifies whether archive has a password or not (0 if not)</param>
+ /// <param name="password">Password for the archive</param>
+ /// <returns>Zero if everything is OK</returns>
+ [PreserveSig]
+ int CryptoGetTextPassword2(
+ ref int passwordIsDefined,
+ [MarshalAs(UnmanagedType.BStr)] out string password);
+ }
+
+ /// <summary>
+ /// 7-zip IArchiveExtractCallback imported interface.
+ /// </summary>
+ [ComImport]
+ [Guid("23170F69-40C1-278A-0000-000600200000")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ internal interface IArchiveExtractCallback
+ {
+ /// <summary>
+ /// Gives the size of the unpacked archive files
+ /// </summary>
+ /// <param name="total">Size of the unpacked archive files (in bytes)</param>
+ void SetTotal(ulong total);
+
+ /// <summary>
+ /// SetCompleted 7-zip function
+ /// </summary>
+ /// <param name="completeValue"></param>
+ void SetCompleted([In] ref ulong completeValue);
+
+ /// <summary>
+ /// Gets the stream for file extraction
+ /// </summary>
+ /// <param name="index">File index in the archive file table</param>
+ /// <param name="outStream">Pointer to the stream</param>
+ /// <param name="askExtractMode">Extraction mode</param>
+ /// <returns>S_OK - OK, S_FALSE - skip this file</returns>
+ [PreserveSig]
+ int GetStream(
+ uint index,
+ [Out, MarshalAs(UnmanagedType.Interface)] out ISequentialOutStream outStream,
+ AskMode askExtractMode);
+
+ /// <summary>
+ /// PrepareOperation 7-zip function
+ /// </summary>
+ /// <param name="askExtractMode">Ask mode</param>
+ void PrepareOperation(AskMode askExtractMode);
+
+ /// <summary>
+ /// Sets the operaton result
+ /// </summary>
+ /// <param name="operationResult">The operation result</param>
+ void SetOperationResult(OperationResult operationResult);
+ }
+
+ /// <summary>
+ /// 7-zip IArchiveUpdateCallback imported interface.
+ /// </summary>
+ [ComImport]
+ [Guid("23170F69-40C1-278A-0000-000600800000")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ internal interface IArchiveUpdateCallback
+ {
+ /// <summary>
+ /// Gives the size of the unpacked archive files.
+ /// </summary>
+ /// <param name="total">Size of the unpacked archive files (in bytes)</param>
+ void SetTotal(ulong total);
+
+ /// <summary>
+ /// SetCompleted 7-zip internal function.
+ /// </summary>
+ /// <param name="completeValue"></param>
+ void SetCompleted([In] ref ulong completeValue);
+
+ /// <summary>
+ /// Gets archive update mode.
+ /// </summary>
+ /// <param name="index">File index</param>
+ /// <param name="newData">1 if new, 0 if not</param>
+ /// <param name="newProperties">1 if new, 0 if not</param>
+ /// <param name="indexInArchive">-1 if doesn't matter</param>
+ /// <returns></returns>
+ [PreserveSig]
+ int GetUpdateItemInfo(
+ uint index, ref int newData,
+ ref int newProperties, ref uint indexInArchive);
+
+ /// <summary>
+ /// Gets the archive item property data.
+ /// </summary>
+ /// <param name="index">Item index</param>
+ /// <param name="propId">Property identificator</param>
+ /// <param name="value">Property value</param>
+ /// <returns>Zero if Ok</returns>
+ [PreserveSig]
+ int GetProperty(uint index, ItemPropId propId, ref PropVariant value);
+
+ /// <summary>
+ /// Gets the stream for reading.
+ /// </summary>
+ /// <param name="index">The item index.</param>
+ /// <param name="inStream">The ISequentialInStream pointer for reading.</param>
+ /// <returns>Zero if Ok</returns>
+ [PreserveSig]
+ int GetStream(
+ uint index,
+ [Out, MarshalAs(UnmanagedType.Interface)] out ISequentialInStream inStream);
+
+ /// <summary>
+ /// Sets the result for currently performed operation.
+ /// </summary>
+ /// <param name="operationResult">The result value.</param>
+ void SetOperationResult(OperationResult operationResult);
+
+ /// <summary>
+ /// EnumProperties 7-zip internal function.
+ /// </summary>
+ /// <param name="enumerator">The enumerator pointer.</param>
+ /// <returns></returns>
+ long EnumProperties(IntPtr enumerator);
+ }
+
+ /// <summary>
+ /// 7-zip IArchiveOpenVolumeCallback imported interface to handle archive volumes.
+ /// </summary>
+ [ComImport]
+ [Guid("23170F69-40C1-278A-0000-000600300000")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ internal interface IArchiveOpenVolumeCallback
+ {
+ /// <summary>
+ /// Gets the archive property data.
+ /// </summary>
+ /// <param name="propId">The property identificator.</param>
+ /// <param name="value">The property value.</param>
+ [PreserveSig]
+ int GetProperty(
+ ItemPropId propId, ref PropVariant value);
+
+ /// <summary>
+ /// Gets the stream for reading the volume.
+ /// </summary>
+ /// <param name="name">The volume file name.</param>
+ /// <param name="inStream">The IInStream pointer for reading.</param>
+ /// <returns>Zero if Ok</returns>
+ [PreserveSig]
+ int GetStream(
+ [MarshalAs(UnmanagedType.LPWStr)] string name,
+ [Out, MarshalAs(UnmanagedType.Interface)] out IInStream inStream);
+ }
+
+ /// <summary>
+ /// 7-zip ISequentialInStream imported interface
+ /// </summary>
+ [ComImport]
+ [Guid("23170F69-40C1-278A-0000-000300010000")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ internal interface ISequentialInStream
+ {
+ /// <summary>
+ /// Writes data to 7-zip packer
+ /// </summary>
+ /// <param name="data">Array of bytes available for writing</param>
+ /// <param name="size">Array size</param>
+ /// <returns>S_OK if success</returns>
+ /// <remarks>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.
+ /// </remarks>
+ int Read(
+ [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data,
+ uint size);
+ }
+
+ /// <summary>
+ /// 7-zip ISequentialOutStream imported interface
+ /// </summary>
+ [ComImport]
+ [Guid("23170F69-40C1-278A-0000-000300020000")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ internal interface ISequentialOutStream
+ {
+ /// <summary>
+ /// Writes data to unpacked file stream
+ /// </summary>
+ /// <param name="data">Array of bytes available for reading</param>
+ /// <param name="size">Array size</param>
+ /// <param name="processedSize">Processed data size</param>
+ /// <returns>S_OK if success</returns>
+ /// <remarks>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.
+ /// </remarks>
+ [PreserveSig]
+ int Write(
+ [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data,
+ uint size, IntPtr processedSize);
+ }
+
+ /// <summary>
+ /// 7-zip IInStream imported interface
+ /// </summary>
+ [ComImport]
+ [Guid("23170F69-40C1-278A-0000-000300030000")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ internal interface IInStream
+ {
+ /// <summary>
+ /// Read routine
+ /// </summary>
+ /// <param name="data">Array of bytes to set</param>
+ /// <param name="size">Array size</param>
+ /// <returns>Zero if Ok</returns>
+ int Read(
+ [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data,
+ uint size);
+
+ /// <summary>
+ /// Seek routine
+ /// </summary>
+ /// <param name="offset">Offset value</param>
+ /// <param name="seekOrigin">Seek origin value</param>
+ /// <param name="newPosition">New position pointer</param>
+ void Seek(
+ long offset, SeekOrigin seekOrigin, IntPtr newPosition);
+ }
+
+ /// <summary>
+ /// 7-zip IOutStream imported interface
+ /// </summary>
+ [ComImport]
+ [Guid("23170F69-40C1-278A-0000-000300040000")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ internal interface IOutStream
+ {
+ /// <summary>
+ /// Write routine
+ /// </summary>
+ /// <param name="data">Array of bytes to get</param>
+ /// <param name="size">Array size</param>
+ /// <param name="processedSize">Processed size</param>
+ /// <returns>Zero if Ok</returns>
+ [PreserveSig]
+ int Write(
+ [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data,
+ uint size,
+ IntPtr processedSize);
+
+ /// <summary>
+ /// Seek routine
+ /// </summary>
+ /// <param name="offset">Offset value</param>
+ /// <param name="seekOrigin">Seek origin value</param>
+ /// <param name="newPosition">New position pointer</param>
+ void Seek(
+ long offset, SeekOrigin seekOrigin, IntPtr newPosition);
+
+ /// <summary>
+ /// Set size routine
+ /// </summary>
+ /// <param name="newSize">New size value</param>
+ /// <returns>Zero if Ok</returns>
+ [PreserveSig]
+ int SetSize(long newSize);
+ }
+
+ /// <summary>
+ /// 7-zip essential in archive interface
+ /// </summary>
+ [ComImport]
+ [Guid("23170F69-40C1-278A-0000-000600600000")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ internal interface IInArchive
+ {
+ /// <summary>
+ /// Opens archive for reading.
+ /// </summary>
+ /// <param name="stream">Archive file stream</param>
+ /// <param name="maxCheckStartPosition">Maximum start position for checking</param>
+ /// <param name="openArchiveCallback">Callback for opening archive</param>
+ /// <returns></returns>
+ [PreserveSig]
+ int Open(
+ IInStream stream,
+ [In] ref ulong maxCheckStartPosition,
+ [MarshalAs(UnmanagedType.Interface)] IArchiveOpenCallback openArchiveCallback);
+
+ /// <summary>
+ /// Closes the archive.
+ /// </summary>
+ void Close();
+
+ /// <summary>
+ /// Gets the number of files in the archive file table .
+ /// </summary>
+ /// <returns>The number of files in the archive</returns>
+ uint GetNumberOfItems();
+
+ /// <summary>
+ /// Retrieves specific property data.
+ /// </summary>
+ /// <param name="index">File index in the archive file table</param>
+ /// <param name="propId">Property code</param>
+ /// <param name="value">Property variant value</param>
+ void GetProperty(
+ uint index,
+ ItemPropId propId,
+ ref PropVariant value); // PropVariant
+
+ /// <summary>
+ /// Extracts files from the opened archive.
+ /// </summary>
+ /// <param name="indexes">indexes of files to be extracted (must be sorted)</param>
+ /// <param name="numItems">0xFFFFFFFF means all files</param>
+ /// <param name="testMode">testMode != 0 means "test files operation"</param>
+ /// <param name="extractCallback">IArchiveExtractCallback for operations handling</param>
+ /// <returns>0 if success</returns>
+ [PreserveSig]
+ int Extract(
+ [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] uint[] indexes,
+ uint numItems,
+ int testMode,
+ [MarshalAs(UnmanagedType.Interface)] IArchiveExtractCallback extractCallback);
+
+ /// <summary>
+ /// Gets archive property data
+ /// </summary>
+ /// <param name="propId">Archive property identificator</param>
+ /// <param name="value">Archive property value</param>
+ void GetArchiveProperty(
+ ItemPropId propId, // PROPID
+ ref PropVariant value); // PropVariant
+
+ /// <summary>
+ /// Gets the number of properties
+ /// </summary>
+ /// <returns>The number of properties</returns>
+ uint GetNumberOfProperties();
+
+ /// <summary>
+ /// Gets property information
+ /// </summary>
+ /// <param name="index">Item index</param>
+ /// <param name="name">Name</param>
+ /// <param name="propId">Property identificator</param>
+ /// <param name="varType">Variant type</param>
+ void GetPropertyInfo(
+ uint index,
+ [MarshalAs(UnmanagedType.BStr)] out string name,
+ out ItemPropId propId, // PROPID
+ out ushort varType); //VARTYPE
+
+ /// <summary>
+ /// Gets the number of archive properties
+ /// </summary>
+ /// <returns>The number of archive properties</returns>
+ uint GetNumberOfArchiveProperties();
+
+ /// <summary>
+ /// Gets the archive property information
+ /// </summary>
+ /// <param name="index">Item index</param>
+ /// <param name="name">Name</param>
+ /// <param name="propId">Property identificator</param>
+ /// <param name="varType">Variant type</param>
+ void GetArchivePropertyInfo(
+ uint index,
+ [MarshalAs(UnmanagedType.BStr)] out string name,
+ out ItemPropId propId, // PROPID
+ out ushort varType); //VARTYPE
+ }
+
+ /// <summary>
+ /// 7-zip essential out archive interface
+ /// </summary>
+ [ComImport]
+ [Guid("23170F69-40C1-278A-0000-000600A00000")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ internal interface IOutArchive
+ {
+ /// <summary>
+ /// Updates archive items
+ /// </summary>
+ /// <param name="outStream">The ISequentialOutStream pointer for writing the archive data</param>
+ /// <param name="numItems">Number of archive items</param>
+ /// <param name="updateCallback">The IArchiveUpdateCallback pointer</param>
+ /// <returns>Zero if Ok</returns>
+ [PreserveSig]
+ int UpdateItems(
+ [MarshalAs(UnmanagedType.Interface)] ISequentialOutStream outStream,
+ uint numItems,
+ [MarshalAs(UnmanagedType.Interface)] IArchiveUpdateCallback updateCallback);
+
+ /// <summary>
+ /// Gets file time type(?)
+ /// </summary>
+ /// <param name="type">Type pointer</param>
+ void GetFileTimeType(IntPtr type);
+ }
+
+ /// <summary>
+ /// 7-zip ISetProperties interface for setting various archive properties
+ /// </summary>
+ [ComImport]
+ [Guid("23170F69-40C1-278A-0000-000600030000")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ internal interface ISetProperties
+ {
+ /// <summary>
+ /// Sets the archive properties
+ /// </summary>
+ /// <param name="names">The names of the properties</param>
+ /// <param name="values">The values of the properties</param>
+ /// <param name="numProperties">The properties count</param>
+ /// <returns></returns>
+ int SetProperties(IntPtr names, IntPtr values, int numProperties);
+ }
+#endif
+} \ No newline at end of file
diff --git a/SevenZip/Common.cs b/SevenZip/Common.cs
new file mode 100644
index 00000000..c79c8699
--- /dev/null
+++ b/SevenZip/Common.cs
@@ -0,0 +1,847 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+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
+
+ /// <summary>
+ /// The way of the event synchronization.
+ /// </summary>
+ public enum EventSynchronizationStrategy
+ {
+ /// <summary>
+ /// Events are called synchronously if user can do some action; that is, cancel the execution process for example.
+ /// </summary>
+ Default,
+ /// <summary>
+ /// Always call events asynchronously.
+ /// </summary>
+ AlwaysAsynchronous,
+ /// <summary>
+ /// Always call events synchronously.
+ /// </summary>
+ AlwaysSynchronous
+ }
+
+ /// <summary>
+ /// SevenZip Extractor/Compressor base class. Implements Password string, ReportErrors flag.
+ /// </summary>
+ public abstract class SevenZipBase : MarshalByRefObject
+ {
+ private readonly string _password;
+ private readonly bool _reportErrors;
+ private readonly int _uniqueID;
+ private static readonly List<int> Identificators = new List<int>();
+#if !WINCE
+ internal static readonly AsyncCallback AsyncCallbackImplementation = AsyncCallbackMethod;
+
+ /// <summary>
+ /// True if the instance of the class needs to be recreated in new thread context; otherwise, false.
+ /// </summary>
+ protected internal bool NeedsToBeRecreated;
+
+ /// <summary>
+ /// AsyncCallback implementation used in asynchronous invocations.
+ /// </summary>
+ /// <param name="ar">IAsyncResult instance.</param>
+ 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;
+ }
+
+ virtual internal void ReleaseContext()
+ {
+#if !DOTNET20
+ Dispatcher = null;
+#else
+ Context = null;
+#endif
+ NeedsToBeRecreated = true;
+ GC.SuppressFinalize(this);
+ }
+
+ private delegate void EventHandlerDelegate<T>(EventHandler<T> handler, T e) where T : EventArgs;
+
+ internal void OnEvent<T>(EventHandler<T> 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<T>((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<T>)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
+ /// <summary>
+ /// Gets or sets the Dispatcher object for this instance.
+ /// It will be used to fire events in the user context.
+ /// </summary>
+ internal Dispatcher Dispatcher { get; set; }
+
+ /// <summary>
+ /// Gets or sets the Dispatcher priority of calling user events.
+ /// </summary>
+ internal DispatcherPriority Priority { get; set; }
+#else
+ internal SynchronizationContext Context { get; set; }
+#endif
+ /// <summary>
+ /// Gets or sets the event synchronization strategy.
+ /// </summary>
+ public EventSynchronizationStrategy EventSynchronization { get; set; }
+#else // WINCE
+ internal void OnEvent<T>(EventHandler<T> handler, T e, bool synchronous) where T : System.EventArgs
+ {
+ try
+ {
+ handler(this, e);
+ }
+ catch (Exception ex)
+ {
+ AddException(ex);
+ }
+ }
+#endif
+ /// <summary>
+ /// Gets the unique identificator of this SevenZipBase instance.
+ /// </summary>
+ public int UniqueID
+ {
+ get
+ {
+ return _uniqueID;
+ }
+ }
+
+ /// <summary>
+ /// User exceptions thrown during the requested operations, for example, in events.
+ /// </summary>
+ private readonly List<Exception> _exceptions = new List<Exception>();
+
+ private static int GetUniqueID()
+ {
+ lock(Identificators)
+ {
+
+ 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
+ /// <summary>
+ /// Initializes a new instance of the SevenZipBase class.
+ /// </summary>
+ protected SevenZipBase()
+ {
+ _password = "";
+ _reportErrors = true;
+ _uniqueID = GetUniqueID();
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipBase class
+ /// </summary>
+ /// <param name="password">The archive password.</param>
+ protected SevenZipBase(string password)
+ {
+ if (String.IsNullOrEmpty(password))
+ {
+ throw new SevenZipException("Empty password was specified.");
+ }
+ _password = password;
+ _reportErrors = true;
+ _uniqueID = GetUniqueID();
+ }
+ #endregion
+
+ /// <summary>
+ /// Removes the UniqueID from the list.
+ /// </summary>
+ ~SevenZipBase()
+ {
+ // This lock probably isn't necessary but just in case...
+ lock (Identificators)
+ {
+ Identificators.Remove(_uniqueID);
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the archive password
+ /// </summary>
+ public string Password
+ {
+ get
+ {
+ return _password;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets throw exceptions on archive errors flag
+ /// </summary>
+ internal bool ReportErrors
+ {
+ get
+ {
+ return _reportErrors;
+ }
+ }
+
+ /// <summary>
+ /// Gets the user exceptions thrown during the requested operations, for example, in events.
+ /// </summary>
+ internal ReadOnlyCollection<Exception> Exceptions
+ {
+ get
+ {
+ return new ReadOnlyCollection<Exception>(_exceptions);
+ }
+ }
+
+ internal void AddException(Exception e)
+ {
+ _exceptions.Add(e);
+ }
+
+ internal void ClearExceptions()
+ {
+ _exceptions.Clear();
+ }
+
+ internal bool HasExceptions
+ {
+ get
+ {
+ return _exceptions.Count > 0;
+ }
+ }
+
+ /// <summary>
+ /// Throws the specified exception when is able to.
+ /// </summary>
+ /// <param name="e">The exception to throw.</param>
+ /// <param name="handler">The handler responsible for the exception.</param>
+ 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);
+ }
+ }
+
+ /// <summary>
+ /// Throws exception if HRESULT != 0.
+ /// </summary>
+ /// <param name="hresult">Result code to check.</param>
+ /// <param name="message">Exception message.</param>
+ /// <param name="handler">The class responsible for the callback.</param>
+ 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
+ /// <summary>
+ /// Changes the path to the 7-zip native library.
+ /// </summary>
+ /// <param name="libraryPath">The path to the 7-zip native library.</param>
+ public static void SetLibraryPath(string libraryPath)
+ {
+ SevenZipLibraryManager.SetLibraryPath(libraryPath);
+ }
+#endif
+ /// <summary>
+ /// Gets the current library features.
+ /// </summary>
+ [CLSCompliant(false)]
+ public static LibraryFeature CurrentLibraryFeatures
+ {
+ get
+ {
+ return SevenZipLibraryManager.CurrentLibraryFeatures;
+ }
+ }
+
+ /// <summary>
+ /// Determines whether the specified System.Object is equal to the current SevenZipBase.
+ /// </summary>
+ /// <param name="obj">The System.Object to compare with the current SevenZipBase.</param>
+ /// <returns>true if the specified System.Object is equal to the current SevenZipBase; otherwise, false.</returns>
+ public override bool Equals(object obj)
+ {
+ var inst = obj as SevenZipBase;
+ if (inst == null)
+ {
+ return false;
+ }
+ return _uniqueID == inst._uniqueID;
+ }
+
+ /// <summary>
+ /// Serves as a hash function for a particular type.
+ /// </summary>
+ /// <returns> A hash code for the current SevenZipBase.</returns>
+ public override int GetHashCode()
+ {
+ return _uniqueID;
+ }
+
+ /// <summary>
+ /// Returns a System.String that represents the current SevenZipBase.
+ /// </summary>
+ /// <returns>A System.String that represents the current SevenZipBase.</returns>
+ 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;
+ /// <summary>
+ /// User exceptions thrown during the requested operations, for example, in events.
+ /// </summary>
+ private readonly List<Exception> _exceptions = new List<Exception>();
+
+ #region Constructors
+ /// <summary>
+ /// Initializes a new instance of the CallbackBase class.
+ /// </summary>
+ protected CallbackBase()
+ {
+ _password = "";
+ _reportErrors = true;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the CallbackBase class.
+ /// </summary>
+ /// <param name="password">The archive password.</param>
+ protected CallbackBase(string password)
+ {
+ if (String.IsNullOrEmpty(password))
+ {
+ throw new SevenZipException("Empty password was specified.");
+ }
+ _password = password;
+ _reportErrors = true;
+ }
+ #endregion
+
+ /// <summary>
+ /// Gets or sets the archive password
+ /// </summary>
+ public string Password
+ {
+ get
+ {
+ return _password;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the value indicating whether the current procedure was cancelled.
+ /// </summary>
+ public bool Canceled { get; set; }
+
+ /// <summary>
+ /// Gets or sets throw exceptions on archive errors flag
+ /// </summary>
+ public bool ReportErrors
+ {
+ get
+ {
+ return _reportErrors;
+ }
+ }
+
+ /// <summary>
+ /// Gets the user exceptions thrown during the requested operations, for example, in events.
+ /// </summary>
+ public ReadOnlyCollection<Exception> Exceptions
+ {
+ get
+ {
+ return new ReadOnlyCollection<Exception>(_exceptions);
+ }
+ }
+
+ public void AddException(Exception e)
+ {
+ _exceptions.Add(e);
+ }
+
+ public void ClearExceptions()
+ {
+ _exceptions.Clear();
+ }
+
+ public bool HasExceptions
+ {
+ get
+ {
+ return _exceptions.Count > 0;
+ }
+ }
+
+ /// <summary>
+ /// Throws the specified exception when is able to.
+ /// </summary>
+ /// <param name="e">The exception to throw.</param>
+ /// <param name="handler">The handler responsible for the exception.</param>
+ public bool ThrowException(CallbackBase handler, params Exception[] e)
+ {
+ if (_reportErrors && (handler == null || !handler.Canceled))
+ {
+ throw e[0];
+ }
+ return false;
+ }
+
+ /// <summary>
+ /// Throws the first exception in the list if any exists.
+ /// </summary>
+ /// <returns>True means no exceptions.</returns>
+ public bool ThrowException()
+ {
+ if (HasExceptions && _reportErrors)
+ {
+ throw _exceptions[0];
+ }
+ return true;
+ }
+
+ public void ThrowUserException()
+ {
+ if (HasExceptions)
+ {
+ throw new SevenZipException(SevenZipException.USER_EXCEPTION_MESSAGE);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Struct for storing information about files in the 7-zip archive.
+ /// </summary>
+ public struct ArchiveFileInfo
+ {
+ /// <summary>
+ /// Gets or sets index of the file in the archive file table.
+ /// </summary>
+ [CLSCompliant(false)]
+ public int Index { get; set; }
+
+ /// <summary>
+ /// Gets or sets file name
+ /// </summary>
+ public string FileName { get; set; }
+
+ /// <summary>
+ /// Gets or sets the file last write time.
+ /// </summary>
+ public DateTime LastWriteTime { get; set; }
+
+ /// <summary>
+ /// Gets or sets the file creation time.
+ /// </summary>
+ public DateTime CreationTime { get; set; }
+
+ /// <summary>
+ /// Gets or sets the file creation time.
+ /// </summary>
+ public DateTime LastAccessTime { get; set; }
+
+ /// <summary>
+ /// Gets or sets size of the file (unpacked).
+ /// </summary>
+ [CLSCompliant(false)]
+ public ulong Size { get; set; }
+
+ /// <summary>
+ /// Gets or sets CRC checksum of the file.
+ /// </summary>
+ [CLSCompliant(false)]
+ public uint Crc { get; set; }
+
+ /// <summary>
+ /// Gets or sets file attributes.
+ /// </summary>
+ [CLSCompliant(false)]
+ public uint Attributes { get; set; }
+
+ /// <summary>
+ /// Gets or sets being a directory.
+ /// </summary>
+ public bool IsDirectory { get; set; }
+
+ /// <summary>
+ /// Gets or sets being encrypted.
+ /// </summary>
+ public bool Encrypted { get; set; }
+
+ /// <summary>
+ /// Gets or sets comment for the file.
+ /// </summary>
+ public string Comment { get; set; }
+
+ /// <summary>
+ /// Determines whether the specified System.Object is equal to the current ArchiveFileInfo.
+ /// </summary>
+ /// <param name="obj">The System.Object to compare with the current ArchiveFileInfo.</param>
+ /// <returns>true if the specified System.Object is equal to the current ArchiveFileInfo; otherwise, false.</returns>
+ public override bool Equals(object obj)
+ {
+ return (obj is ArchiveFileInfo) ? Equals((ArchiveFileInfo)obj) : false;
+ }
+
+ /// <summary>
+ /// Determines whether the specified ArchiveFileInfo is equal to the current ArchiveFileInfo.
+ /// </summary>
+ /// <param name="afi">The ArchiveFileInfo to compare with the current ArchiveFileInfo.</param>
+ /// <returns>true if the specified ArchiveFileInfo is equal to the current ArchiveFileInfo; otherwise, false.</returns>
+ public bool Equals(ArchiveFileInfo afi)
+ {
+ return afi.Index == Index && afi.FileName == FileName;
+ }
+
+ /// <summary>
+ /// Serves as a hash function for a particular type.
+ /// </summary>
+ /// <returns> A hash code for the current ArchiveFileInfo.</returns>
+ public override int GetHashCode()
+ {
+ return FileName.GetHashCode() ^ Index;
+ }
+
+ /// <summary>
+ /// Returns a System.String that represents the current ArchiveFileInfo.
+ /// </summary>
+ /// <returns>A System.String that represents the current ArchiveFileInfo.</returns>
+ public override string ToString()
+ {
+ return "[" + Index.ToString(CultureInfo.CurrentCulture) + "] " + FileName;
+ }
+
+ /// <summary>
+ /// Determines whether the specified ArchiveFileInfo instances are considered equal.
+ /// </summary>
+ /// <param name="afi1">The first ArchiveFileInfo to compare.</param>
+ /// <param name="afi2">The second ArchiveFileInfo to compare.</param>
+ /// <returns>true if the specified ArchiveFileInfo instances are considered equal; otherwise, false.</returns>
+ public static bool operator ==(ArchiveFileInfo afi1, ArchiveFileInfo afi2)
+ {
+ return afi1.Equals(afi2);
+ }
+
+ /// <summary>
+ /// Determines whether the specified ArchiveFileInfo instances are not considered equal.
+ /// </summary>
+ /// <param name="afi1">The first ArchiveFileInfo to compare.</param>
+ /// <param name="afi2">The second ArchiveFileInfo to compare.</param>
+ /// <returns>true if the specified ArchiveFileInfo instances are not considered equal; otherwise, false.</returns>
+ public static bool operator !=(ArchiveFileInfo afi1, ArchiveFileInfo afi2)
+ {
+ return !afi1.Equals(afi2);
+ }
+ }
+
+ /// <summary>
+ /// Archive property struct.
+ /// </summary>
+ public struct ArchiveProperty
+ {
+ /// <summary>
+ /// Gets the name of the archive property.
+ /// </summary>
+ public string Name { get; internal set; }
+
+ /// <summary>
+ /// Gets the value of the archive property.
+ /// </summary>
+ public object Value { get; internal set; }
+
+ /// <summary>
+ /// Determines whether the specified System.Object is equal to the current ArchiveProperty.
+ /// </summary>
+ /// <param name="obj">The System.Object to compare with the current ArchiveProperty.</param>
+ /// <returns>true if the specified System.Object is equal to the current ArchiveProperty; otherwise, false.</returns>
+ public override bool Equals(object obj)
+ {
+ return (obj is ArchiveProperty) ? Equals((ArchiveProperty)obj) : false;
+ }
+
+ /// <summary>
+ /// Determines whether the specified ArchiveProperty is equal to the current ArchiveProperty.
+ /// </summary>
+ /// <param name="afi">The ArchiveProperty to compare with the current ArchiveProperty.</param>
+ /// <returns>true if the specified ArchiveProperty is equal to the current ArchiveProperty; otherwise, false.</returns>
+ public bool Equals(ArchiveProperty afi)
+ {
+ return afi.Name == Name && afi.Value == Value;
+ }
+
+ /// <summary>
+ /// Serves as a hash function for a particular type.
+ /// </summary>
+ /// <returns> A hash code for the current ArchiveProperty.</returns>
+ public override int GetHashCode()
+ {
+ return Name.GetHashCode() ^ Value.GetHashCode();
+ }
+
+ /// <summary>
+ /// Returns a System.String that represents the current ArchiveProperty.
+ /// </summary>
+ /// <returns>A System.String that represents the current ArchiveProperty.</returns>
+ public override string ToString()
+ {
+ return Name + " = " + Value;
+ }
+
+ /// <summary>
+ /// Determines whether the specified ArchiveProperty instances are considered equal.
+ /// </summary>
+ /// <param name="afi1">The first ArchiveProperty to compare.</param>
+ /// <param name="afi2">The second ArchiveProperty to compare.</param>
+ /// <returns>true if the specified ArchiveProperty instances are considered equal; otherwise, false.</returns>
+ public static bool operator ==(ArchiveProperty afi1, ArchiveProperty afi2)
+ {
+ return afi1.Equals(afi2);
+ }
+
+ /// <summary>
+ /// Determines whether the specified ArchiveProperty instances are not considered equal.
+ /// </summary>
+ /// <param name="afi1">The first ArchiveProperty to compare.</param>
+ /// <param name="afi2">The second ArchiveProperty to compare.</param>
+ /// <returns>true if the specified ArchiveProperty instances are not considered equal; otherwise, false.</returns>
+ public static bool operator !=(ArchiveProperty afi1, ArchiveProperty afi2)
+ {
+ return !afi1.Equals(afi2);
+ }
+ }
+
+#if COMPRESS
+
+ /// <summary>
+ /// Archive compression mode.
+ /// </summary>
+ public enum CompressionMode
+ {
+ /// <summary>
+ /// Create a new archive; overwrite the existing one.
+ /// </summary>
+ Create,
+ /// <summary>
+ /// Add data to the archive.
+ /// </summary>
+ Append,
+ }
+
+ internal enum InternalCompressionMode
+ {
+ /// <summary>
+ /// Create a new archive; overwrite the existing one.
+ /// </summary>
+ Create,
+ /// <summary>
+ /// Add data to the archive.
+ /// </summary>
+ Append,
+ /// <summary>
+ /// Modify archive data.
+ /// </summary>
+ Modify
+ }
+
+ /// <summary>
+ /// Zip encryption method enum.
+ /// </summary>
+ public enum ZipEncryptionMethod
+ {
+ /// <summary>
+ /// ZipCrypto encryption method.
+ /// </summary>
+ ZipCrypto,
+ /// <summary>
+ /// AES 128 bit encryption method.
+ /// </summary>
+ Aes128,
+ /// <summary>
+ /// AES 192 bit encryption method.
+ /// </summary>
+ Aes192,
+ /// <summary>
+ /// AES 256 bit encryption method.
+ /// </summary>
+ Aes256
+ }
+
+ /// <summary>
+ /// Archive update data for UpdateCallback.
+ /// </summary>
+ internal struct UpdateData
+ {
+ public uint FilesCount;
+ public InternalCompressionMode Mode;
+
+ public Dictionary<int, string> FileNamesToModify { get; set; }
+
+ public List<ArchiveFileInfo> ArchiveFileData { get; set; }
+ }
+#endif
+#endif
+} \ No newline at end of file
diff --git a/SevenZip/EventArgs.cs b/SevenZip/EventArgs.cs
new file mode 100644
index 00000000..82890ee8
--- /dev/null
+++ b/SevenZip/EventArgs.cs
@@ -0,0 +1,401 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+using System;
+using System.IO;
+
+namespace SevenZip
+{
+ /// <summary>
+ /// The definition of the interface which supports the cancellation of a process.
+ /// </summary>
+ public interface ICancellable
+ {
+ /// <summary>
+ /// Gets or sets whether to stop the current archive operation.
+ /// </summary>
+ bool Cancel { get; set; }
+ }
+
+ /// <summary>
+ /// EventArgs for storing PercentDone property.
+ /// </summary>
+ public class PercentDoneEventArgs : EventArgs
+ {
+ private readonly byte _percentDone;
+
+ /// <summary>
+ /// Initializes a new instance of the PercentDoneEventArgs class.
+ /// </summary>
+ /// <param name="percentDone">The percent of finished work.</param>
+ /// <exception cref="System.ArgumentOutOfRangeException"/>
+ 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;
+ }
+
+ /// <summary>
+ /// Gets the percent of finished work.
+ /// </summary>
+ public byte PercentDone
+ {
+ get
+ {
+ return _percentDone;
+ }
+ }
+
+ /// <summary>
+ /// Converts a [0, 1] rate to its percent equivalent.
+ /// </summary>
+ /// <param name="doneRate">The rate of the done work.</param>
+ /// <returns>Percent integer equivalent.</returns>
+ /// <exception cref="System.ArgumentException"/>
+ 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
+ }
+ }
+
+ /// <summary>
+ /// The EventArgs class for accurate progress handling.
+ /// </summary>
+ public sealed class ProgressEventArgs : PercentDoneEventArgs
+ {
+ private readonly byte _delta;
+
+ /// <summary>
+ /// Initializes a new instance of the ProgressEventArgs class.
+ /// </summary>
+ /// <param name="percentDone">The percent of finished work.</param>
+ /// <param name="percentDelta">The percent of work done after the previous event.</param>
+ public ProgressEventArgs(byte percentDone, byte percentDelta)
+ : base(percentDone)
+ {
+ _delta = percentDelta;
+ }
+
+ /// <summary>
+ /// Gets the change in done work percentage.
+ /// </summary>
+ public byte PercentDelta
+ {
+ get
+ {
+ return _delta;
+ }
+ }
+ }
+
+#if UNMANAGED
+ /// <summary>
+ /// EventArgs used to report the file information which is going to be packed.
+ /// </summary>
+ public sealed class FileInfoEventArgs : PercentDoneEventArgs, ICancellable
+ {
+ private readonly ArchiveFileInfo _fileInfo;
+
+ /// <summary>
+ /// Initializes a new instance of the FileInfoEventArgs class.
+ /// </summary>
+ /// <param name="fileInfo">The current ArchiveFileInfo.</param>
+ /// <param name="percentDone">The percent of finished work.</param>
+ public FileInfoEventArgs(ArchiveFileInfo fileInfo, byte percentDone)
+ : base(percentDone)
+ {
+ _fileInfo = fileInfo;
+ }
+
+ /// <summary>
+ /// Gets or sets whether to stop the current archive operation.
+ /// </summary>
+ public bool Cancel { get; set; }
+
+ /// <summary>
+ /// Gets the corresponding FileInfo to the event.
+ /// </summary>
+ public ArchiveFileInfo FileInfo
+ {
+ get
+ {
+ return _fileInfo;
+ }
+ }
+ }
+
+ /// <summary>
+ /// EventArgs used to report the size of unpacked archive data
+ /// </summary>
+ public sealed class OpenEventArgs : EventArgs
+ {
+ private readonly ulong _totalSize;
+
+ /// <summary>
+ /// Initializes a new instance of the OpenEventArgs class
+ /// </summary>
+ /// <param name="totalSize">Size of unpacked archive data</param>
+ [CLSCompliant(false)]
+ public OpenEventArgs(ulong totalSize)
+ {
+ _totalSize = totalSize;
+ }
+
+ /// <summary>
+ /// Gets the size of unpacked archive data
+ /// </summary>
+ [CLSCompliant(false)]
+ public ulong TotalSize
+ {
+ get
+ {
+ return _totalSize;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Stores an int number
+ /// </summary>
+ public sealed class IntEventArgs : EventArgs
+ {
+ private readonly int _value;
+
+ /// <summary>
+ /// Initializes a new instance of the IntEventArgs class
+ /// </summary>
+ /// <param name="value">Useful data carried by the IntEventArgs class</param>
+ public IntEventArgs(int value)
+ {
+ _value = value;
+ }
+
+ /// <summary>
+ /// Gets the value of the IntEventArgs class
+ /// </summary>
+ public int Value
+ {
+ get
+ {
+ return _value;
+ }
+ }
+ }
+
+ /// <summary>
+ /// EventArgs class which stores the file name.
+ /// </summary>
+ public sealed class FileNameEventArgs : PercentDoneEventArgs, ICancellable
+ {
+ private readonly string _fileName;
+
+ /// <summary>
+ /// Initializes a new instance of the FileNameEventArgs class.
+ /// </summary>
+ /// <param name="fileName">The file name.</param>
+ /// <param name="percentDone">The percent of finished work</param>
+ public FileNameEventArgs(string fileName, byte percentDone) :
+ base(percentDone)
+ {
+ _fileName = fileName;
+ }
+
+ /// <summary>
+ /// Gets or sets whether to stop the current archive operation.
+ /// </summary>
+ public bool Cancel { get; set; }
+
+ /// <summary>
+ /// Gets the file name.
+ /// </summary>
+ public string FileName
+ {
+ get
+ {
+ return _fileName;
+ }
+ }
+ }
+
+ /// <summary>
+ /// EventArgs for FileExists event, stores the file name and asks whether to overwrite it in case it already exists.
+ /// </summary>
+ public sealed class FileOverwriteEventArgs : EventArgs
+ {
+ /// <summary>
+ /// Initializes a new instance of the FileOverwriteEventArgs class
+ /// </summary>
+ /// <param name="fileName">The file name.</param>
+ public FileOverwriteEventArgs(string fileName)
+ {
+ FileName = fileName;
+ }
+
+ /// <summary>
+ /// Gets or sets the value indicating whether to cancel the extraction.
+ /// </summary>
+ public bool Cancel { get; set; }
+
+ /// <summary>
+ /// Gets or sets the file name to extract to. Null means skip.
+ /// </summary>
+ public string FileName { get; set; }
+ }
+
+ /// <summary>
+ /// The reason for calling <see cref="ExtractFileCallback"/>.
+ /// </summary>
+ public enum ExtractFileCallbackReason
+ {
+ /// <summary>
+ /// <see cref="ExtractFileCallback"/> is called the first time for a file.
+ /// </summary>
+ Start,
+
+ /// <summary>
+ /// All data has been written to the target without any exceptions.
+ /// </summary>
+ Done,
+
+ /// <summary>
+ /// An exception occured during extraction of the file.
+ /// </summary>
+ Failure
+ }
+
+ /// <summary>
+ /// The arguments passed to <see cref="ExtractFileCallback"/>.
+ /// </summary>
+ /// <remarks>
+ /// For each file, <see cref="ExtractFileCallback"/> is first called with <see cref="Reason"/>
+ /// set to <see cref="ExtractFileCallbackReason.Start"/>. If the callback chooses to extract the
+ /// file data by setting <see cref="ExtractToFile"/> or <see cref="ExtractToStream"/>, the callback
+ /// will be called a second time with <see cref="Reason"/> set to
+ /// <see cref="ExtractFileCallbackReason.Done"/> or <see cref="ExtractFileCallbackReason.Failure"/>
+ /// to allow for any cleanup task like closing the stream.
+ /// </remarks>
+ public class ExtractFileCallbackArgs : EventArgs
+ {
+ private readonly ArchiveFileInfo _archiveFileInfo;
+ private Stream _extractToStream;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExtractFileCallbackArgs"/> class.
+ /// </summary>
+ /// <param name="archiveFileInfo">The information about file in the archive.</param>
+ public ExtractFileCallbackArgs(ArchiveFileInfo archiveFileInfo)
+ {
+ Reason = ExtractFileCallbackReason.Start;
+ _archiveFileInfo = archiveFileInfo;
+ }
+
+ /// <summary>
+ /// Information about file in the archive.
+ /// </summary>
+ /// <value>Information about file in the archive.</value>
+ public ArchiveFileInfo ArchiveFileInfo
+ {
+ get
+ {
+ return _archiveFileInfo;
+ }
+ }
+
+ /// <summary>
+ /// The reason for calling <see cref="ExtractFileCallback"/>.
+ /// </summary>
+ /// <remarks>
+ /// If neither <see cref="ExtractToFile"/> nor <see cref="ExtractToStream"/> is set,
+ /// <see cref="ExtractFileCallback"/> will not be called after <see cref="ExtractFileCallbackReason.Start"/>.
+ /// </remarks>
+ /// <value>The reason.</value>
+ public ExtractFileCallbackReason Reason { get; internal set; }
+
+ /// <summary>
+ /// The exception that occurred during extraction.
+ /// </summary>
+ /// <value>The _Exception.</value>
+ /// <remarks>
+ /// If the callback is called with <see cref="Reason"/> set to <see cref="ExtractFileCallbackReason.Failure"/>,
+ /// 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 <see cref="Exception"/> to <c>null</c> to swallow the _Exception
+ /// and continue extraction with the next file.
+ /// </remarks>
+ public Exception Exception { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to cancel the extraction.
+ /// </summary>
+ /// <value><c>true</c> to cancel the extraction; <c>false</c> to continue. The default is <c>false</c>.</value>
+ public bool CancelExtraction { get; set; }
+
+ /// <summary>
+ /// Gets or sets whether and where to extract the file.
+ /// </summary>
+ /// <value>The path where to extract the file to.</value>
+ /// <remarks>
+ /// If <see cref="ExtractToStream"/> is set, this mmember will be ignored.
+ /// </remarks>
+ public string ExtractToFile { get; set; }
+
+ /// <summary>
+ /// Gets or sets whether and where to extract the file.
+ /// </summary>
+ /// <value>The the extracted data is written to.</value>
+ /// <remarks>
+ /// If both this member and <see cref="ExtractToFile"/> are <c>null</c> (the defualt), the file
+ /// will not be extracted and the callback will be be executed a second time with the <see cref="Reason"/>
+ /// set to <see cref="ExtractFileCallbackReason.Done"/> or <see cref="ExtractFileCallbackReason.Failure"/>.
+ /// </remarks>
+ public Stream ExtractToStream
+ {
+ get
+ {
+ return _extractToStream;
+ }
+ set
+ {
+ if (_extractToStream != null && !_extractToStream.CanWrite)
+ {
+ throw new ExtractionFailedException("The specified stream is not writable!");
+ }
+ _extractToStream = value;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets any data that will be preserved between the <see cref="ExtractFileCallbackReason.Start"/> callback call
+ /// and the <see cref="ExtractFileCallbackReason.Done"/> or <see cref="ExtractFileCallbackReason.Failure"/> calls.
+ /// </summary>
+ /// <value>The data.</value>
+ public object ObjectData { get; set; }
+ }
+
+ /// <summary>
+ /// Callback delegate for <see cref="SevenZipExtractor.ExtractFiles(SevenZip.ExtractFileCallback)"/>.
+ /// </summary>
+ public delegate void ExtractFileCallback(ExtractFileCallbackArgs extractFileCallbackArgs);
+#endif
+} \ No newline at end of file
diff --git a/SevenZip/Exceptions.cs b/SevenZip/Exceptions.cs
new file mode 100644
index 00000000..8a8410e0
--- /dev/null
+++ b/SevenZip/Exceptions.cs
@@ -0,0 +1,464 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+using System;
+#if !WINCE
+using System.Runtime.Serialization;
+#endif
+
+namespace SevenZip
+{
+ /// <summary>
+ /// Base SevenZip exception class.
+ /// </summary>
+ [Serializable]
+ public class SevenZipException : Exception
+ {
+ /// <summary>
+ /// The message for thrown user exceptions.
+ /// </summary>
+ internal const string USER_EXCEPTION_MESSAGE = "The extraction was successful but" +
+ "some exceptions were thrown in your events. Check UserExceptions for details.";
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipException class
+ /// </summary>
+ public SevenZipException() : base("SevenZip unknown exception.") {}
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipException class
+ /// </summary>
+ /// <param name="defaultMessage">Default exception message</param>
+ public SevenZipException(string defaultMessage)
+ : base(defaultMessage) {}
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipException class
+ /// </summary>
+ /// <param name="defaultMessage">Default exception message</param>
+ /// <param name="message">Additional detailed message</param>
+ public SevenZipException(string defaultMessage, string message)
+ : base(defaultMessage + " Message: " + message) {}
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipException class
+ /// </summary>
+ /// <param name="defaultMessage">Default exception message</param>
+ /// <param name="message">Additional detailed message</param>
+ /// <param name="inner">Inner exception occured</param>
+ public SevenZipException(string defaultMessage, string message, Exception inner)
+ : base(
+ defaultMessage + (defaultMessage.EndsWith(" ", StringComparison.CurrentCulture) ? "" : " Message: ") +
+ message, inner) {}
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipException class
+ /// </summary>
+ /// <param name="defaultMessage">Default exception message</param>
+ /// <param name="inner">Inner exception occured</param>
+ public SevenZipException(string defaultMessage, Exception inner)
+ : base(defaultMessage, inner) {}
+#if !WINCE
+ /// <summary>
+ /// Initializes a new instance of the SevenZipException class
+ /// </summary>
+ /// <param name="info">All data needed for serialization or deserialization</param>
+ /// <param name="context">Serialized stream descriptor</param>
+ protected SevenZipException(
+ SerializationInfo info, StreamingContext context)
+ : base(info, context) {}
+#endif
+ }
+
+#if UNMANAGED
+
+ /// <summary>
+ /// Exception class for ArchiveExtractCallback.
+ /// </summary>
+ [Serializable]
+ public class ExtractionFailedException : SevenZipException
+ {
+ /// <summary>
+ /// Exception dafault message which is displayed if no extra information is specified
+ /// </summary>
+ public const string DEFAULT_MESSAGE = "Could not extract files!";
+
+ /// <summary>
+ /// Initializes a new instance of the ExtractionFailedException class
+ /// </summary>
+ public ExtractionFailedException() : base(DEFAULT_MESSAGE) {}
+
+ /// <summary>
+ /// Initializes a new instance of the ExtractionFailedException class
+ /// </summary>
+ /// <param name="message">Additional detailed message</param>
+ public ExtractionFailedException(string message) : base(DEFAULT_MESSAGE, message) {}
+
+ /// <summary>
+ /// Initializes a new instance of the ExtractionFailedException class
+ /// </summary>
+ /// <param name="message">Additional detailed message</param>
+ /// <param name="inner">Inner exception occured</param>
+ public ExtractionFailedException(string message, Exception inner) : base(DEFAULT_MESSAGE, message, inner) {}
+#if !WINCE
+ /// <summary>
+ /// Initializes a new instance of the ExtractionFailedException class
+ /// </summary>
+ /// <param name="info">All data needed for serialization or deserialization</param>
+ /// <param name="context">Serialized stream descriptor</param>
+ protected ExtractionFailedException(
+ SerializationInfo info, StreamingContext context)
+ : base(info, context) {}
+#endif
+ }
+
+#if COMPRESS
+
+ /// <summary>
+ /// Exception class for ArchiveUpdateCallback.
+ /// </summary>
+ [Serializable]
+ public class CompressionFailedException : SevenZipException
+ {
+ /// <summary>
+ /// Exception dafault message which is displayed if no extra information is specified
+ /// </summary>
+ public const string DEFAULT_MESSAGE = "Could not pack files!";
+
+ /// <summary>
+ /// Initializes a new instance of the CompressionFailedException class
+ /// </summary>
+ public CompressionFailedException() : base(DEFAULT_MESSAGE) {}
+
+ /// <summary>
+ /// Initializes a new instance of the CompressionFailedException class
+ /// </summary>
+ /// <param name="message">Additional detailed message</param>
+ public CompressionFailedException(string message) : base(DEFAULT_MESSAGE, message) {}
+
+ /// <summary>
+ /// Initializes a new instance of the CompressionFailedException class
+ /// </summary>
+ /// <param name="message">Additional detailed message</param>
+ /// <param name="inner">Inner exception occured</param>
+ public CompressionFailedException(string message, Exception inner) : base(DEFAULT_MESSAGE, message, inner) {}
+#if !WINCE
+ /// <summary>
+ /// Initializes a new instance of the CompressionFailedException class
+ /// </summary>
+ /// <param name="info">All data needed for serialization or deserialization</param>
+ /// <param name="context">Serialized stream descriptor</param>
+ protected CompressionFailedException(
+ SerializationInfo info, StreamingContext context)
+ : base(info, context) {}
+#endif
+ }
+#endif
+#endif
+
+ /// <summary>
+ /// Exception class for LZMA operations.
+ /// </summary>
+ [Serializable]
+ public class LzmaException : SevenZipException
+ {
+ /// <summary>
+ /// Exception dafault message which is displayed if no extra information is specified
+ /// </summary>
+ public const string DEFAULT_MESSAGE = "Specified stream is not a valid LZMA compressed stream!";
+
+ /// <summary>
+ /// Initializes a new instance of the LzmaException class
+ /// </summary>
+ public LzmaException() : base(DEFAULT_MESSAGE) {}
+
+ /// <summary>
+ /// Initializes a new instance of the LzmaException class
+ /// </summary>
+ /// <param name="message">Additional detailed message</param>
+ public LzmaException(string message) : base(DEFAULT_MESSAGE, message) {}
+
+ /// <summary>
+ /// Initializes a new instance of the LzmaException class
+ /// </summary>
+ /// <param name="message">Additional detailed message</param>
+ /// <param name="inner">Inner exception occured</param>
+ public LzmaException(string message, Exception inner) : base(DEFAULT_MESSAGE, message, inner) {}
+#if !WINCE
+ /// <summary>
+ /// Initializes a new instance of the LzmaException class
+ /// </summary>
+ /// <param name="info">All data needed for serialization or deserialization</param>
+ /// <param name="context">Serialized stream descriptor</param>
+ protected LzmaException(
+ SerializationInfo info, StreamingContext context)
+ : base(info, context) {}
+#endif
+ }
+
+#if UNMANAGED
+
+ /// <summary>
+ /// Exception class for 7-zip archive open or read operations.
+ /// </summary>
+ [Serializable]
+ public class SevenZipArchiveException : SevenZipException
+ {
+ /// <summary>
+ /// Exception dafault message which is displayed if no extra information is specified
+ /// </summary>
+ 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.";
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipArchiveException class
+ /// </summary>
+ public SevenZipArchiveException() : base(DEFAULT_MESSAGE) {}
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipArchiveException class
+ /// </summary>
+ /// <param name="message">Additional detailed message</param>
+ public SevenZipArchiveException(string message) : base(DEFAULT_MESSAGE, message) {}
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipArchiveException class
+ /// </summary>
+ /// <param name="message">Additional detailed message</param>
+ /// <param name="inner">Inner exception occured</param>
+ public SevenZipArchiveException(string message, Exception inner) : base(DEFAULT_MESSAGE, message, inner) {}
+#if !WINCE
+ /// <summary>
+ /// Initializes a new instance of the SevenZipArchiveException class
+ /// </summary>
+ /// <param name="info">All data needed for serialization or deserialization</param>
+ /// <param name="context">Serialized stream descriptor</param>
+ protected SevenZipArchiveException(
+ SerializationInfo info, StreamingContext context)
+ : base(info, context) {}
+#endif
+ }
+
+ /// <summary>
+ /// Exception class for empty common root if file name array in SevenZipCompressor.
+ /// </summary>
+ [Serializable]
+ public class SevenZipInvalidFileNamesException : SevenZipException
+ {
+ /// <summary>
+ /// Exception dafault message which is displayed if no extra information is specified
+ /// </summary>
+ public const string DEFAULT_MESSAGE = "Invalid file names have been specified: ";
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipInvalidFileNamesException class
+ /// </summary>
+ public SevenZipInvalidFileNamesException() : base(DEFAULT_MESSAGE) {}
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipInvalidFileNamesException class
+ /// </summary>
+ /// <param name="message">Additional detailed message</param>
+ public SevenZipInvalidFileNamesException(string message) : base(DEFAULT_MESSAGE, message) {}
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipInvalidFileNamesException class
+ /// </summary>
+ /// <param name="message">Additional detailed message</param>
+ /// <param name="inner">Inner exception occured</param>
+ public SevenZipInvalidFileNamesException(string message, Exception inner) : base(DEFAULT_MESSAGE, message, inner) {}
+#if !WINCE
+ /// <summary>
+ /// Initializes a new instance of the SevenZipInvalidFileNamesException class
+ /// </summary>
+ /// <param name="info">All data needed for serialization or deserialization</param>
+ /// <param name="context">Serialized stream descriptor</param>
+ protected SevenZipInvalidFileNamesException(
+ SerializationInfo info, StreamingContext context)
+ : base(info, context) {}
+#endif
+ }
+
+#if COMPRESS
+
+ /// <summary>
+ /// Exception class for fail to create an archive in SevenZipCompressor.
+ /// </summary>
+ [Serializable]
+ public class SevenZipCompressionFailedException : SevenZipException
+ {
+ /// <summary>
+ /// Exception dafault message which is displayed if no extra information is specified
+ /// </summary>
+ public const string DEFAULT_MESSAGE = "The compression has failed for an unknown reason with code ";
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipCompressionFailedException class
+ /// </summary>
+ public SevenZipCompressionFailedException() : base(DEFAULT_MESSAGE) {}
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipCompressionFailedException class
+ /// </summary>
+ /// <param name="message">Additional detailed message</param>
+ public SevenZipCompressionFailedException(string message) : base(DEFAULT_MESSAGE, message) {}
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipCompressionFailedException class
+ /// </summary>
+ /// <param name="message">Additional detailed message</param>
+ /// <param name="inner">Inner exception occured</param>
+ public SevenZipCompressionFailedException(string message, Exception inner)
+ : base(DEFAULT_MESSAGE, message, inner) {}
+#if !WINCE
+ /// <summary>
+ /// Initializes a new instance of the SevenZipCompressionFailedException class
+ /// </summary>
+ /// <param name="info">All data needed for serialization or deserialization</param>
+ /// <param name="context">Serialized stream descriptor</param>
+ protected SevenZipCompressionFailedException(
+ SerializationInfo info, StreamingContext context)
+ : base(info, context) {}
+#endif
+ }
+#endif
+
+ /// <summary>
+ /// Exception class for fail to extract an archive in SevenZipExtractor.
+ /// </summary>
+ [Serializable]
+ public class SevenZipExtractionFailedException : SevenZipException
+ {
+ /// <summary>
+ /// Exception dafault message which is displayed if no extra information is specified
+ /// </summary>
+ public const string DEFAULT_MESSAGE = "The extraction has failed for an unknown reason with code ";
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipExtractionFailedException class
+ /// </summary>
+ public SevenZipExtractionFailedException() : base(DEFAULT_MESSAGE) {}
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipExtractionFailedException class
+ /// </summary>
+ /// <param name="message">Additional detailed message</param>
+ public SevenZipExtractionFailedException(string message) : base(DEFAULT_MESSAGE, message) {}
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipExtractionFailedException class
+ /// </summary>
+ /// <param name="message">Additional detailed message</param>
+ /// <param name="inner">Inner exception occured</param>
+ public SevenZipExtractionFailedException(string message, Exception inner) : base(DEFAULT_MESSAGE, message, inner) {}
+#if !WINCE
+ /// <summary>
+ /// Initializes a new instance of the SevenZipExtractionFailedException class
+ /// </summary>
+ /// <param name="info">All data needed for serialization or deserialization</param>
+ /// <param name="context">Serialized stream descriptor</param>
+ protected SevenZipExtractionFailedException(
+ SerializationInfo info, StreamingContext context)
+ : base(info, context) {}
+#endif
+ }
+
+ /// <summary>
+ /// Exception class for 7-zip library operations.
+ /// </summary>
+ [Serializable]
+ public class SevenZipLibraryException : SevenZipException
+ {
+ /// <summary>
+ /// Exception dafault message which is displayed if no extra information is specified
+ /// </summary>
+ public const string DEFAULT_MESSAGE = "Can not load 7-zip library or internal COM error!";
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipLibraryException class
+ /// </summary>
+ public SevenZipLibraryException() : base(DEFAULT_MESSAGE) {}
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipLibraryException class
+ /// </summary>
+ /// <param name="message">Additional detailed message</param>
+ public SevenZipLibraryException(string message) : base(DEFAULT_MESSAGE, message) {}
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipLibraryException class
+ /// </summary>
+ /// <param name="message">Additional detailed message</param>
+ /// <param name="inner">Inner exception occured</param>
+ public SevenZipLibraryException(string message, Exception inner) : base(DEFAULT_MESSAGE, message, inner) {}
+#if !WINCE
+ /// <summary>
+ /// Initializes a new instance of the SevenZipLibraryException class
+ /// </summary>
+ /// <param name="info">All data needed for serialization or deserialization</param>
+ /// <param name="context">Serialized stream descriptor</param>
+ protected SevenZipLibraryException(
+ SerializationInfo info, StreamingContext context)
+ : base(info, context) {}
+#endif
+ }
+#endif
+
+#if SFX
+
+ /// <summary>
+ /// Exception class for 7-zip sfx settings validation.
+ /// </summary>
+ [Serializable]
+ public class SevenZipSfxValidationException : SevenZipException
+ {
+ /// <summary>
+ /// Exception dafault message which is displayed if no extra information is specified
+ /// </summary>
+ public static readonly string DefaultMessage = "Sfx settings validation failed.";
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipSfxValidationException class
+ /// </summary>
+ public SevenZipSfxValidationException() : base(DefaultMessage) {}
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipSfxValidationException class
+ /// </summary>
+ /// <param name="message">Additional detailed message</param>
+ public SevenZipSfxValidationException(string message) : base(DefaultMessage, message) {}
+
+ /// <summary>
+ /// Initializes a new instance of the SevenZipSfxValidationException class
+ /// </summary>
+ /// <param name="message">Additional detailed message</param>
+ /// <param name="inner">Inner exception occured</param>
+ public SevenZipSfxValidationException(string message, Exception inner) : base(DefaultMessage, message, inner) {}
+#if !WINCE
+ /// <summary>
+ /// Initializes a new instance of the SevenZipSfxValidationException class
+ /// </summary>
+ /// <param name="info">All data needed for serialization or deserialization</param>
+ /// <param name="context">Serialized stream descriptor</param>
+ protected SevenZipSfxValidationException(
+ SerializationInfo info, StreamingContext context)
+ : base(info, context) {}
+#endif
+ }
+#endif
+} \ No newline at end of file
diff --git a/SevenZip/FileSignatureChecker.cs b/SevenZip/FileSignatureChecker.cs
new file mode 100644
index 00000000..294cdc95
--- /dev/null
+++ b/SevenZip/FileSignatureChecker.cs
@@ -0,0 +1,240 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+using System;
+using System.IO;
+
+namespace SevenZip
+{
+#if UNMANAGED
+ /// <summary>
+ /// The signature checker class. Original code by Siddharth Uppal, adapted by Markhor.
+ /// </summary>
+ /// <remarks>Based on the code at http://blog.somecreativity.com/2008/04/08/how-to-check-if-a-file-is-compressed-in-c/#</remarks>
+ internal static class FileChecker
+ {
+ 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;
+ }
+
+ /// <summary>
+ /// Gets the InArchiveFormat for a specific extension.
+ /// </summary>
+ /// <param name="stream">The stream to identify.</param>
+ /// <param name="offset">The archive beginning offset.</param>
+ /// <param name="isExecutable">True if the original format of the stream is PE; otherwise, false.</param>
+ /// <returns>Corresponding InArchiveFormat.</returns>
+ public static InArchiveFormat CheckSignature(Stream stream, out int offset, out bool isExecutable)
+ {
+ offset = 0;
+ if (!stream.CanRead)
+ {
+ throw new ArgumentException("The stream must be readable.");
+ }
+ if (stream.Length < SIGNATURE_SIZE)
+ {
+ throw new ArgumentException("The stream is invalid.");
+ }
+
+ #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
+
+ throw new ArgumentException("The stream is invalid or no corresponding signature was found.");
+ }
+
+ /// <summary>
+ /// Gets the InArchiveFormat for a specific file name.
+ /// </summary>
+ /// <param name="fileName">The archive file name.</param>
+ /// <param name="offset">The archive beginning offset.</param>
+ /// <param name="isExecutable">True if the original format of the file is PE; otherwise, false.</param>
+ /// <returns>Corresponding InArchiveFormat.</returns>
+ /// <exception cref="System.ArgumentException"/>
+ 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
+ {
+ return CheckSignature(fs, out offset, out isExecutable);
+ }
+ catch (ArgumentException)
+ {
+ offset = 0;
+ isExecutable = false;
+ return Formats.FormatByFileName(fileName, true);
+ }
+ }
+ }
+ }
+#endif
+} \ No newline at end of file
diff --git a/SevenZip/Formats.cs b/SevenZip/Formats.cs
new file mode 100644
index 00000000..3c7acb85
--- /dev/null
+++ b/SevenZip/Formats.cs
@@ -0,0 +1,529 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+
+namespace SevenZip
+{
+#if UNMANAGED
+ /// <summary>
+ /// Readable archive format enumeration.
+ /// </summary>
+ public enum InArchiveFormat
+ {
+ /// <summary>
+ /// Open 7-zip archive format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/7-zip">Wikipedia information</a></remarks>
+ SevenZip,
+ /// <summary>
+ /// Proprietary Arj archive format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/ARJ">Wikipedia information</a></remarks>
+ Arj,
+ /// <summary>
+ /// Open Bzip2 archive format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Bzip2">Wikipedia information</a></remarks>
+ BZip2,
+ /// <summary>
+ /// Microsoft cabinet archive format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Cabinet_(file_format)">Wikipedia information</a></remarks>
+ Cab,
+ /// <summary>
+ /// Microsoft Compiled HTML Help file format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Microsoft_Compiled_HTML_Help">Wikipedia information</a></remarks>
+ Chm,
+ /// <summary>
+ /// Microsoft Compound file format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Compound_File_Binary_Format">Wikipedia information</a></remarks>
+ Compound,
+ /// <summary>
+ /// Open Cpio archive format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Cpio">Wikipedia information</a></remarks>
+ Cpio,
+ /// <summary>
+ /// Open Debian software package format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Deb_(file_format)">Wikipedia information</a></remarks>
+ Deb,
+ /// <summary>
+ /// Open Gzip archive format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Gzip">Wikipedia information</a></remarks>
+ GZip,
+ /// <summary>
+ /// Open ISO disk image format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/ISO_image">Wikipedia information</a></remarks>
+ Iso,
+ /// <summary>
+ /// Open Lzh archive format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Lzh">Wikipedia information</a></remarks>
+ Lzh,
+ /// <summary>
+ /// Open core 7-zip Lzma raw archive format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Lzma">Wikipedia information</a></remarks>
+ Lzma,
+ /// <summary>
+ /// Nullsoft installation package format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/NSIS">Wikipedia information</a></remarks>
+ Nsis,
+ /// <summary>
+ /// RarLab Rar archive format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Rar">Wikipedia information</a></remarks>
+ Rar,
+ /// <summary>
+ /// Open Rpm software package format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/RPM_Package_Manager">Wikipedia information</a></remarks>
+ Rpm,
+ /// <summary>
+ /// Open split file format.
+ /// </summary>
+ /// <remarks><a href="?">Wikipedia information</a></remarks>
+ Split,
+ /// <summary>
+ /// Open Tar archive format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Tar_(file_format)">Wikipedia information</a></remarks>
+ Tar,
+ /// <summary>
+ /// Microsoft Windows Imaging disk image format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Windows_Imaging_Format">Wikipedia information</a></remarks>
+ Wim,
+ /// <summary>
+ /// Open LZW archive format; implemented in "compress" program; also known as "Z" archive format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Compress">Wikipedia information</a></remarks>
+ Lzw,
+ /// <summary>
+ /// Open Zip archive format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/ZIP_(file_format)">Wikipedia information</a></remarks>
+ Zip,
+ /// <summary>
+ /// Open Udf disk image format.
+ /// </summary>
+ Udf,
+ /// <summary>
+ /// Xar open source archive format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Xar_(archiver)">Wikipedia information</a></remarks>
+ Xar,
+ /// <summary>
+ /// Mub
+ /// </summary>
+ Mub,
+ /// <summary>
+ /// Macintosh Disk Image on CD.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/HFS_Plus">Wikipedia information</a></remarks>
+ Hfs,
+ /// <summary>
+ /// Apple Mac OS X Disk Copy Disk Image format.
+ /// </summary>
+ Dmg,
+ /// <summary>
+ /// Open Xz archive format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Xz">Wikipedia information</a></remarks>
+ XZ,
+ /// <summary>
+ /// MSLZ archive format.
+ /// </summary>
+ Mslz,
+ /// <summary>
+ /// Flash video format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Flv">Wikipedia information</a></remarks>
+ Flv,
+ /// <summary>
+ /// Shockwave Flash format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Swf">Wikipedia information</a></remarks>
+ Swf,
+ /// <summary>
+ /// Windows PE executable format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Portable_Executable">Wikipedia information</a></remarks>
+ PE,
+ /// <summary>
+ /// Linux executable Elf format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Executable_and_Linkable_Format">Wikipedia information</a></remarks>
+ Elf,
+ /// <summary>
+ /// Windows Installer Database.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Windows_Installer">Wikipedia information</a></remarks>
+ Msi,
+ /// <summary>
+ /// Microsoft virtual hard disk file format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/VHD_%28file_format%29">Wikipedia information</a></remarks>
+ Vhd
+ }
+
+#if COMPRESS
+ /// <summary>
+ /// Writable archive format enumeration.
+ /// </summary>
+ public enum OutArchiveFormat
+ {
+ /// <summary>
+ /// Open 7-zip archive format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/7-zip">Wikipedia information</a></remarks>
+ SevenZip,
+ /// <summary>
+ /// Open Zip archive format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/ZIP_(file_format)">Wikipedia information</a></remarks>
+ Zip,
+ /// <summary>
+ /// Open Gzip archive format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Gzip">Wikipedia information</a></remarks>
+ GZip,
+ /// <summary>
+ /// Open Bzip2 archive format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Bzip2">Wikipedia information</a></remarks>
+ BZip2,
+ /// <summary>
+ /// Open Tar archive format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Tar_(file_format)">Wikipedia information</a></remarks>
+ Tar,
+ /// <summary>
+ /// Open Xz archive format.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Xz">Wikipedia information</a></remarks>
+ XZ
+ }
+
+ /// <summary>
+ /// Compression level enumeration
+ /// </summary>
+ public enum CompressionLevel
+ {
+ /// <summary>
+ /// No compression
+ /// </summary>
+ None,
+ /// <summary>
+ /// Very low compression level
+ /// </summary>
+ Fast,
+ /// <summary>
+ /// Low compression level
+ /// </summary>
+ Low,
+ /// <summary>
+ /// Normal compression level (default)
+ /// </summary>
+ Normal,
+ /// <summary>
+ /// High compression level
+ /// </summary>
+ High,
+ /// <summary>
+ /// The best compression level (slow)
+ /// </summary>
+ Ultra
+ }
+
+ /// <summary>
+ /// Compression method enumeration.
+ /// </summary>
+ /// <remarks>Some methods are applicable only to Zip format, some - only to 7-zip.</remarks>
+ public enum CompressionMethod
+ {
+ /// <summary>
+ /// Zip or 7-zip|no compression method.
+ /// </summary>
+ Copy,
+ /// <summary>
+ /// Zip|Deflate method.
+ /// </summary>
+ Deflate,
+ /// <summary>
+ /// Zip|Deflate64 method.
+ /// </summary>
+ Deflate64,
+ /// <summary>
+ /// Zip or 7-zip|Bzip2 method.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Cabinet_(file_format)">Wikipedia information</a></remarks>
+ BZip2,
+ /// <summary>
+ /// Zip or 7-zip|LZMA method based on Lempel-Ziv algorithm, it is default for 7-zip.
+ /// </summary>
+ Lzma,
+ /// <summary>
+ /// 7-zip|LZMA version 2, LZMA with improved multithreading and usually slight archive size decrease.
+ /// </summary>
+ Lzma2,
+ /// <summary>
+ /// Zip or 7-zip|PPMd method based on Dmitry Shkarin's PPMdH source code, very efficient for compressing texts.
+ /// </summary>
+ /// <remarks><a href="http://en.wikipedia.org/wiki/Prediction_by_Partial_Matching">Wikipedia information</a></remarks>
+ Ppmd,
+ /// <summary>
+ /// No method change.
+ /// </summary>
+ Default
+ }
+#endif
+
+ /// <summary>
+ /// Archive format routines
+ /// </summary>
+ public static class Formats
+ {
+ /*/// <summary>
+ /// Gets the max value of the specified enum type.
+ /// </summary>
+ /// <param name="type">Type of the enum</param>
+ /// <returns>Max value</returns>
+ internal static int GetMaxValue(Type type)
+ {
+ List<int> enumList = new List<int>((IEnumerable<int>)Enum.GetValues(type));
+ enumList.Sort();
+ return enumList[enumList.Count - 1];
+ }*/
+
+ /// <summary>
+ /// List of readable archive format interface guids for 7-zip COM interop.
+ /// </summary>
+ internal static readonly Dictionary<InArchiveFormat, Guid> InFormatGuids =
+ new Dictionary<InArchiveFormat, Guid>(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
+ /// <summary>
+ /// List of writable archive format interface guids for 7-zip COM interop.
+ /// </summary>
+ internal static readonly Dictionary<OutArchiveFormat, Guid> OutFormatGuids =
+ new Dictionary<OutArchiveFormat, Guid>(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<CompressionMethod, string> MethodNames =
+ new Dictionary<CompressionMethod, string>(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<OutArchiveFormat, InArchiveFormat> InForOutFormats =
+ new Dictionary<OutArchiveFormat, InArchiveFormat>(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
+
+ /// <summary>
+ /// List of archive formats corresponding to specific extensions
+ /// </summary>
+ private static readonly Dictionary<string, InArchiveFormat> InExtensionFormats =
+ new Dictionary<string, InArchiveFormat>
+ #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
+
+ /// <summary>
+ /// List of archive formats corresponding to specific signatures
+ /// </summary>
+ /// <remarks>Based on the information at <a href="http://www.garykessler.net/library/file_sigs.html">this site.</a></remarks>
+ internal static readonly Dictionary<string, InArchiveFormat> InSignatureFormats =
+ new Dictionary<string, InArchiveFormat>
+ #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}};
+ #endregion
+
+ internal static Dictionary<InArchiveFormat, string> InSignatureFormatsReversed;
+
+ static Formats()
+ {
+ InSignatureFormatsReversed = new Dictionary<InArchiveFormat, string>(InSignatureFormats.Count);
+ foreach (var pair in InSignatureFormats)
+ {
+ InSignatureFormatsReversed.Add(pair.Value, pair.Key);
+ }
+ }
+
+ /// <summary>
+ /// Gets InArchiveFormat for specified archive file name
+ /// </summary>
+ /// <param name="fileName">Archive file name</param>
+ /// <param name="reportErrors">Indicates whether to throw exceptions</param>
+ /// <returns>InArchiveFormat recognized by the file name extension</returns>
+ /// <exception cref="System.ArgumentException"/>
+ 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).Substring(1);
+ if (!InExtensionFormats.ContainsKey(extension) && reportErrors)
+ {
+ throw new ArgumentException("Extension \"" + extension +
+ "\" is not a supported archive file name extension.");
+ }
+ return InExtensionFormats[extension];
+ }
+ }
+#endif
+} \ No newline at end of file
diff --git a/SevenZip/LibraryFeature.cs b/SevenZip/LibraryFeature.cs
new file mode 100644
index 00000000..5085b6b1
--- /dev/null
+++ b/SevenZip/LibraryFeature.cs
@@ -0,0 +1,113 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+using System;
+
+namespace SevenZip
+{
+ /// <summary>
+ /// The set of features supported by the library.
+ /// </summary>
+ [Flags]
+ [CLSCompliant(false)]
+ public enum LibraryFeature : uint
+ {
+ /// <summary>
+ /// Default feature.
+ /// </summary>
+ None = 0,
+ /// <summary>
+ /// The library can extract 7zip archives compressed with LZMA method.
+ /// </summary>
+ Extract7z = 0x1,
+ /// <summary>
+ /// The library can extract 7zip archives compressed with LZMA2 method.
+ /// </summary>
+ Extract7zLZMA2 = 0x2,
+ /// <summary>
+ /// The library can extract 7z archives compressed with all known methods.
+ /// </summary>
+ Extract7zAll = Extract7z|Extract7zLZMA2|0x4,
+ /// <summary>
+ /// The library can extract zip archives.
+ /// </summary>
+ ExtractZip = 0x8,
+ /// <summary>
+ /// The library can extract rar archives.
+ /// </summary>
+ ExtractRar = 0x10,
+ /// <summary>
+ /// The library can extract gzip archives.
+ /// </summary>
+ ExtractGzip = 0x20,
+ /// <summary>
+ /// The library can extract bzip2 archives.
+ /// </summary>
+ ExtractBzip2 = 0x40,
+ /// <summary>
+ /// The library can extract tar archives.
+ /// </summary>
+ ExtractTar = 0x80,
+ /// <summary>
+ /// The library can extract xz archives.
+ /// </summary>
+ ExtractXz = 0x100,
+ /// <summary>
+ /// The library can extract all types of archives supported.
+ /// </summary>
+ ExtractAll = Extract7zAll|ExtractZip|ExtractRar|ExtractGzip|ExtractBzip2|ExtractTar|ExtractXz,
+ /// <summary>
+ /// The library can compress data to 7zip archives with LZMA method.
+ /// </summary>
+ Compress7z = 0x200,
+ /// <summary>
+ /// The library can compress data to 7zip archives with LZMA2 method.
+ /// </summary>
+ Compress7zLZMA2 = 0x400,
+ /// <summary>
+ /// The library can compress data to 7zip archives with all methods known.
+ /// </summary>
+ Compress7zAll = Compress7z|Compress7zLZMA2|0x800,
+ /// <summary>
+ /// The library can compress data to tar archives.
+ /// </summary>
+ CompressTar = 0x1000,
+ /// <summary>
+ /// The library can compress data to gzip archives.
+ /// </summary>
+ CompressGzip = 0x2000,
+ /// <summary>
+ /// The library can compress data to bzip2 archives.
+ /// </summary>
+ CompressBzip2 = 0x4000,
+ /// <summary>
+ /// The library can compress data to xz archives.
+ /// </summary>
+ CompressXz = 0x8000,
+ /// <summary>
+ /// The library can compress data to zip archives.
+ /// </summary>
+ CompressZip = 0x10000,
+ /// <summary>
+ /// The library can compress data to all types of archives supported.
+ /// </summary>
+ CompressAll = Compress7zAll|CompressTar|CompressGzip|CompressBzip2|CompressXz|CompressZip,
+ /// <summary>
+ /// The library can modify archives.
+ /// </summary>
+ Modify = 0x20000
+ }
+}
diff --git a/SevenZip/LibraryManager.cs b/SevenZip/LibraryManager.cs
new file mode 100644
index 00000000..610b7f28
--- /dev/null
+++ b/SevenZip/LibraryManager.cs
@@ -0,0 +1,581 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+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
+ /// <summary>
+ /// 7-zip library low-level wrapper.
+ /// </summary>
+ internal static class SevenZipLibraryManager
+ {
+ /// <summary>
+ /// Synchronization root for all locking.
+ /// </summary>
+ private static readonly object _syncRoot = new object();
+
+#if !WINCE && !MONO
+ /// <summary>
+ /// Path to the 7-zip dll.
+ /// </summary>
+ /// <remarks>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.
+ /// </remarks>
+ private static string _libraryFileName = //ConfigurationManager.AppSettings["7zLocation"] ??
+ Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), IntPtr.Size==8 ? "7z64.dll" : "7z.dll");
+#endif
+#if WINCE
+ private static string _libraryFileName =
+ Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase), "7z.dll");
+#endif
+ /// <summary>
+ /// 7-zip library handle.
+ /// </summary>
+ private static IntPtr _modulePtr;
+
+ /// <summary>
+ /// 7-zip library features.
+ /// </summary>
+ private static LibraryFeature? _features;
+
+ private static Dictionary<object, Dictionary<InArchiveFormat, IInArchive>> _inArchives;
+#if COMPRESS
+ private static Dictionary<object, Dictionary<OutArchiveFormat, IOutArchive>> _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<InArchiveFormat, IInArchive>());
+ }
+ 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<OutArchiveFormat, IOutArchive>());
+ }
+ if (!_outArchives[user].ContainsKey(format))
+ {
+ _outArchives[user].Add(format, null);
+ _totalUsers++;
+ }
+ }
+#endif
+
+ private static void Init()
+ {
+ _inArchives = new Dictionary<object, Dictionary<InArchiveFormat, IInArchive>>();
+#if COMPRESS
+ _outArchives = new Dictionary<object, Dictionary<OutArchiveFormat, IOutArchive>>();
+#endif
+ }
+
+ /// <summary>
+ /// Loads the 7-zip library if necessary and adds user to the reference list
+ /// </summary>
+ /// <param name="user">Caller of the function</param>
+ /// <param name="format">Archive format</param>
+ public static void LoadLibrary(object user, Enum format)
+ {
+ lock (_syncRoot)
+ {
+ if (_inArchives == null
+#if COMPRESS
+ || _outArchives == null
+#endif
+ )
+ {
+ Init();
+ }
+#if !WINCE && !MONO
+ if (_modulePtr == IntPtr.Zero)
+ {
+ if (!File.Exists(_libraryFileName))
+ {
+ throw new SevenZipLibraryException("DLL file does not exist.");
+ }
+ if ((_modulePtr = NativeMethods.LoadLibrary(_libraryFileName)) == 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!");
+ }
+ }
+
+ /*/// <summary>
+ /// Gets the native 7zip library version string.
+ /// </summary>
+ 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;
+ }
+ }*/
+
+ /// <summary>
+ /// Gets the value indicating whether the library supports modifying archives.
+ /// </summary>
+ public static bool ModifyCapable
+ {
+ get
+ {
+ lock (_syncRoot)
+ {
+ 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;
+ }
+
+#if COMPRESS
+ 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;
+ }
+#endif
+
+ public static LibraryFeature CurrentLibraryFeatures
+ {
+ get
+ {
+ lock (_syncRoot)
+ {
+ 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
+#if COMPRESS
+ 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);
+ }
+ }
+#endif
+ #endregion
+ #endregion
+ if (ModifyCapable && (_features.Value & LibraryFeature.Compress7z) != 0)
+ {
+ _features |= LibraryFeature.Modify;
+ }
+ return _features.Value;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Removes user from reference list and frees the 7-zip library if it becomes empty
+ /// </summary>
+ /// <param name="user">Caller of the function</param>
+ /// <param name="format">Archive format</param>
+ public static void FreeLibrary(object user, Enum format)
+ {
+#if !WINCE && !MONO
+ var sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
+ sp.Demand();
+#endif
+ lock (_syncRoot)
+ {
+ 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;
+ }
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Gets IInArchive interface to extract 7-zip archives.
+ /// </summary>
+ /// <param name="format">Archive format.</param>
+ /// <param name="user">Archive format user.</param>
+ public static IInArchive InArchive(InArchiveFormat format, object user)
+ {
+ lock (_syncRoot)
+ {
+ 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<IInArchive>(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;
+ }
+ return _inArchives[user][format];
+#if !WINCE && !MONO
+ }
+#endif
+ }
+
+#if COMPRESS
+ /// <summary>
+ /// Gets IOutArchive interface to pack 7-zip archives.
+ /// </summary>
+ /// <param name="format">Archive format.</param>
+ /// <param name="user">Archive format user.</param>
+ public static IOutArchive OutArchive(OutArchiveFormat format, object user)
+ {
+ lock (_syncRoot)
+ {
+ 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<IOutArchive>(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;
+ }
+ return _outArchives[user][format];
+#if !WINCE && !MONO
+ }
+#endif
+
+ }
+#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/SevenZip/LzmaDecodeStream.cs b/SevenZip/LzmaDecodeStream.cs
new file mode 100644
index 00000000..16946d5a
--- /dev/null
+++ b/SevenZip/LzmaDecodeStream.cs
@@ -0,0 +1,240 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+using System;
+using System.IO;
+using SevenZip.Sdk.Compression.Lzma;
+
+namespace SevenZip
+{
+#if LZMA_STREAM
+ /// <summary>
+ /// The stream which decompresses data with LZMA on the fly.
+ /// </summary>
+ 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;
+
+ /// <summary>
+ /// Initializes a new instance of the LzmaDecodeStream class.
+ /// </summary>
+ /// <param name="encodedStream">A compressed stream.</param>
+ public LzmaDecodeStream(Stream encodedStream)
+ {
+ if (!encodedStream.CanRead)
+ {
+ throw new ArgumentException("The specified stream can not read.", "encodedStream");
+ }
+ _input = encodedStream;
+ }
+
+ /// <summary>
+ /// Gets the chunk size.
+ /// </summary>
+ public int ChunkSize
+ {
+ get
+ {
+ return (int) _buffer.Length;
+ }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the current stream supports reading.
+ /// </summary>
+ public override bool CanRead
+ {
+ get
+ {
+ return true;
+ }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the current stream supports seeking.
+ /// </summary>
+ public override bool CanSeek
+ {
+ get
+ {
+ return false;
+ }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the current stream supports writing.
+ /// </summary>
+ public override bool CanWrite
+ {
+ get
+ {
+ return false;
+ }
+ }
+
+ /// <summary>
+ /// Gets the length in bytes of the output stream.
+ /// </summary>
+ public override long Length
+ {
+ get
+ {
+ if (_input.CanSeek)
+ {
+ return _input.Length;
+ }
+ return _buffer.Length;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the position within the output stream.
+ /// </summary>
+ 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;
+ }
+
+ /// <summary>
+ /// Does nothing.
+ /// </summary>
+ public override void Flush() {}
+
+ /// <summary>
+ /// Reads a sequence of bytes from the current stream and decompresses data if necessary.
+ /// </summary>
+ /// <param name="buffer">An array of bytes.</param>
+ /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
+ /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
+ /// <returns>The total number of bytes read into the buffer.</returns>
+ 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;
+ }
+
+ /// <summary>
+ /// Sets the position within the current stream.
+ /// </summary>
+ /// <param name="offset">A byte offset relative to the origin parameter.</param>
+ /// <param name="origin">A value of type System.IO.SeekOrigin indicating the reference point used to obtain the new position.</param>
+ /// <returns>The new position within the current stream.</returns>
+ public override long Seek(long offset, SeekOrigin origin)
+ {
+ throw new NotSupportedException();
+ }
+
+ /// <summary>
+ /// Sets the length of the current stream.
+ /// </summary>
+ /// <param name="value">The desired length of the current stream in bytes.</param>
+ public override void SetLength(long value)
+ {
+ throw new NotSupportedException();
+ }
+
+ /// <summary>
+ /// Writes a sequence of bytes to the current stream.
+ /// </summary>
+ /// <param name="buffer">An array of bytes.</param>
+ /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
+ /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
+ public override void Write(byte[] buffer, int offset, int count)
+ {
+ throw new NotSupportedException();
+ }
+ }
+#endif
+} \ No newline at end of file
diff --git a/SevenZip/LzmaProgressCallback.cs b/SevenZip/LzmaProgressCallback.cs
new file mode 100644
index 00000000..fee8c7ab
--- /dev/null
+++ b/SevenZip/LzmaProgressCallback.cs
@@ -0,0 +1,72 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+using System;
+using SevenZip.Sdk;
+
+namespace SevenZip
+{
+ /// <summary>
+ /// Callback to implement the ICodeProgress interface
+ /// </summary>
+ internal sealed class LzmaProgressCallback : ICodeProgress
+ {
+ private readonly long _inSize;
+ private float _oldPercentDone;
+
+ /// <summary>
+ /// Initializes a new instance of the LzmaProgressCallback class
+ /// </summary>
+ /// <param name="inSize">The input size</param>
+ /// <param name="working">Progress event handler</param>
+ public LzmaProgressCallback(long inSize, EventHandler<ProgressEventArgs> working)
+ {
+ _inSize = inSize;
+ Working += working;
+ }
+
+ #region ICodeProgress Members
+
+ /// <summary>
+ /// Sets the progress
+ /// </summary>
+ /// <param name="inSize">The processed input size</param>
+ /// <param name="outSize">The processed output size</param>
+ 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<ProgressEventArgs> Working;
+ }
+}
diff --git a/SevenZip/NativeMethods.cs b/SevenZip/NativeMethods.cs
new file mode 100644
index 00000000..02ef5e7e
--- /dev/null
+++ b/SevenZip/NativeMethods.cs
@@ -0,0 +1,77 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+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<T>(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/SevenZip/SevenZipExtractor.cs b/SevenZip/SevenZipExtractor.cs
new file mode 100644
index 00000000..51e3b174
--- /dev/null
+++ b/SevenZip/SevenZipExtractor.cs
@@ -0,0 +1,1449 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+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
+{
+ /// <summary>
+ /// Class to unpack data from archives supported by 7-Zip.
+ /// </summary>
+ /// <example>
+ /// using (var extr = new SevenZipExtractor(@"C:\Test.7z"))
+ /// {
+ /// extr.ExtractArchive(@"C:\TestDirectory");
+ /// }
+ /// </example>
+ public sealed partial class SevenZipExtractor
+#if UNMANAGED
+ : SevenZipBase, IDisposable
+#endif
+ {
+#if UNMANAGED
+ private List<ArchiveFileInfo> _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 = (InArchiveFormat)(-1);
+ private ReadOnlyCollection<ArchiveFileInfo> _archiveFileInfoCollection;
+ private ReadOnlyCollection<ArchiveProperty> _archiveProperties;
+ private ReadOnlyCollection<string> _volumeFileNames;
+ /// <summary>
+ /// This is used to lock possible Dispose() calls.
+ /// </summary>
+ private bool _asynchronousDisposeLock;
+
+ #region Constructors
+ /// <summary>
+ /// General initialization function.
+ /// </summary>
+ /// <param name="archiveFullName">The archive file name.</param>
+ private void Init(string archiveFullName)
+ {
+ _fileName = archiveFullName;
+ bool isExecutable = false;
+ if ((int)_format == -1)
+ {
+ _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;
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// General initialization function.
+ /// </summary>
+ /// <param name="stream">The stream to read the archive from.</param>
+ private void Init(Stream stream)
+ {
+ ValidateStream(stream);
+ bool isExecutable = false;
+ if ((int)_format == -1)
+ {
+ _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;
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Initializes a new instance of SevenZipExtractor class.
+ /// </summary>
+ /// <param name="archiveStream">The stream to read the archive from.
+ /// Use SevenZipExtractor(string) to extract from disk, though it is not necessary.</param>
+ /// <remarks>The archive format is guessed by the signature.</remarks>
+ public SevenZipExtractor(Stream archiveStream)
+ {
+ Init(archiveStream);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of SevenZipExtractor class.
+ /// </summary>
+ /// <param name="archiveStream">The stream to read the archive from.
+ /// Use SevenZipExtractor(string) to extract from disk, though it is not necessary.</param>
+ /// <param name="format">Manual archive format setup. You SHOULD NOT normally specify it this way.
+ /// Instead, use SevenZipExtractor(Stream archiveStream), that constructor
+ /// automatically detects the archive format.</param>
+ public SevenZipExtractor(Stream archiveStream, InArchiveFormat format)
+ {
+ _format = format;
+ Init(archiveStream);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of SevenZipExtractor class.
+ /// </summary>
+ /// <param name="archiveFullName">The archive full file name.</param>
+ public SevenZipExtractor(string archiveFullName)
+ {
+ Init(archiveFullName);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of SevenZipExtractor class.
+ /// </summary>
+ /// <param name="archiveFullName">The archive full file name.</param>
+ /// <param name="format">Manual archive format setup. You SHOULD NOT normally specify it this way.
+ /// Instead, use SevenZipExtractor(string archiveFullName), that constructor
+ /// automatically detects the archive format.</param>
+ public SevenZipExtractor(string archiveFullName, InArchiveFormat format)
+ {
+ _format = format;
+ Init(archiveFullName);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of SevenZipExtractor class.
+ /// </summary>
+ /// <param name="archiveFullName">The archive full file name.</param>
+ /// <param name="password">Password for an encrypted archive.</param>
+ public SevenZipExtractor(string archiveFullName, string password)
+ : base(password)
+ {
+ Init(archiveFullName);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of SevenZipExtractor class.
+ /// </summary>
+ /// <param name="archiveFullName">The archive full file name.</param>
+ /// <param name="password">Password for an encrypted archive.</param>
+ /// <param name="format">Manual archive format setup. You SHOULD NOT normally specify it this way.
+ /// Instead, use SevenZipExtractor(string archiveFullName, string password), that constructor
+ /// automatically detects the archive format.</param>
+ public SevenZipExtractor(string archiveFullName, string password, InArchiveFormat format)
+ : base(password)
+ {
+ _format = format;
+ Init(archiveFullName);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of SevenZipExtractor class.
+ /// </summary>
+ /// <param name="archiveStream">The stream to read the archive from.</param>
+ /// <param name="password">Password for an encrypted archive.</param>
+ /// <remarks>The archive format is guessed by the signature.</remarks>
+ public SevenZipExtractor(Stream archiveStream, string password)
+ : base(password)
+ {
+ Init(archiveStream);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of SevenZipExtractor class.
+ /// </summary>
+ /// <param name="archiveStream">The stream to read the archive from.</param>
+ /// <param name="password">Password for an encrypted archive.</param>
+ /// <param name="format">Manual archive format setup. You SHOULD NOT normally specify it this way.
+ /// Instead, use SevenZipExtractor(Stream archiveStream, string password), that constructor
+ /// automatically detects the archive format.</param>
+ public SevenZipExtractor(Stream archiveStream, string password, InArchiveFormat format)
+ : base(password)
+ {
+ _format = format;
+ Init(archiveStream);
+ }
+
+ #endregion
+
+ #region Properties
+
+ /// <summary>
+ /// Gets or sets archive full file name
+ /// </summary>
+ public string FileName
+ {
+ get
+ {
+ DisposedCheck();
+ return _fileName;
+ }
+ }
+
+ /// <summary>
+ /// Gets the size of the archive file
+ /// </summary>
+ public long PackedSize
+ {
+ get
+ {
+ DisposedCheck();
+ return _packedSize.HasValue
+ ?
+ _packedSize.Value
+ :
+ _fileName != null
+ ?
+ (new FileInfo(_fileName)).Length
+ :
+ -1;
+ }
+ }
+
+ /// <summary>
+ /// Gets the size of unpacked archive data
+ /// </summary>
+ public long UnpackedSize
+ {
+ get
+ {
+ DisposedCheck();
+ if (!_unpackedSize.HasValue)
+ {
+ return -1;
+ }
+ return _unpackedSize.Value;
+ }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the archive is solid
+ /// </summary>
+ public bool IsSolid
+ {
+ get
+ {
+ DisposedCheck();
+ if (!_isSolid.HasValue)
+ {
+ GetArchiveInfo(true);
+ }
+ Debug.Assert(_isSolid != null);
+ return _isSolid.Value;
+ }
+ }
+
+ /// <summary>
+ /// Gets the number of files in the archive
+ /// </summary>
+ [CLSCompliant(false)]
+ public uint FilesCount
+ {
+ get
+ {
+ DisposedCheck();
+ if (!_filesCount.HasValue)
+ {
+ GetArchiveInfo(true);
+ }
+ Debug.Assert(_filesCount != null);
+ return _filesCount.Value;
+ }
+ }
+
+ /// <summary>
+ /// Gets archive format
+ /// </summary>
+ public InArchiveFormat Format
+ {
+ get
+ {
+ DisposedCheck();
+ return _format;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the value indicating whether to preserve the directory structure of extracted files.
+ /// </summary>
+ public bool PreserveDirectoryStructure { get; set; }
+ #endregion
+
+ /// <summary>
+ /// Checked whether the class was disposed.
+ /// </summary>
+ /// <exception cref="System.ObjectDisposedException" />
+ 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));
+ }
+
+ /// <summary>
+ /// Gets the archive input stream.
+ /// </summary>
+ /// <returns>The archive input wrapper stream.</returns>
+ 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)
+ || (_volumeFileNames.Count == 1))
+ {
+ _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;
+ }
+
+ /// <summary>
+ /// Opens the archive and throws exceptions or returns OperationResult.DataError if any error occurs.
+ /// </summary>
+ /// <param name="archiveStream">The IInStream compliant class instance, that is, the input stream.</param>
+ /// <param name="openCallback">The ArchiveOpenCallback instance.</param>
+ /// <returns>OperationResult.Ok if Open() succeeds.</returns>
+ private OperationResult OpenArchiveInner(IInStream archiveStream,
+ IArchiveOpenCallback openCallback)
+ {
+ ulong checkPos = 1 << 15;
+ int res = _archive.Open(archiveStream, ref checkPos, openCallback);
+ return (OperationResult)res;
+ }
+
+ /// <summary>
+ /// Opens the archive and throws exceptions or returns OperationResult.DataError if any error occurs.
+ /// </summary>
+ /// <param name="archiveStream">The IInStream compliant class instance, that is, the input stream.</param>
+ /// <param name="openCallback">The ArchiveOpenCallback instance.</param>
+ /// <returns>True if Open() succeeds; otherwise, false.</returns>
+ 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<string>(openCallback.VolumeFileNames);
+ _opened = true;
+ }
+ return true;
+ }
+
+ /// <summary>
+ /// Retrieves all information about the archive.
+ /// </summary>
+ /// <exception cref="SevenZip.SevenZipArchiveException"/>
+ 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<ArchiveFileInfo>((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<ulong>(data, 0);
+ if (fileInfo.Size == 0)
+ {
+ fileInfo.Size = NativeMethods.SafeCast<uint>(data, 0);
+ }
+ _archive.GetProperty(i, ItemPropId.Attributes, ref data);
+ fileInfo.Attributes = NativeMethods.SafeCast<uint>(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<uint>(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<ArchiveProperty>((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<ArchiveProperty>(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<ArchiveFileInfo>(_archiveFileData);
+ }
+ }
+
+ /// <summary>
+ /// Ensure that _archiveFileData is loaded.
+ /// </summary>
+ /// <param name="disposeStream">Dispose the archive stream after this operation.</param>
+ private void InitArchiveFileData(bool disposeStream)
+ {
+ if (_archiveFileData == null)
+ {
+ GetArchiveInfo(disposeStream);
+ }
+ }
+
+ /// <summary>
+ /// Produces an array of indexes from 0 to the maximum value in the specified array
+ /// </summary>
+ /// <param name="indexes">The source array</param>
+ /// <returns>The array of indexes from 0 to the maximum value in the specified array</returns>
+ 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;
+ }
+
+ /// <summary>
+ /// Checkes whether all the indexes are valid.
+ /// </summary>
+ /// <param name="indexes">The indexes to check.</param>
+ /// <returns>True is valid; otherwise, false.</returns>
+ 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;
+ }
+
+ /// <summary>
+ /// Gets the IArchiveExtractCallback callback
+ /// </summary>
+ /// <param name="directory">The directory where extract the files</param>
+ /// <param name="filesCount">The number of files to be extracted</param>
+ /// <param name="actualIndexes">The list of actual indexes (solid archives support)</param>
+ /// <returns>The ArchiveExtractCallback callback</returns>
+ private ArchiveExtractCallback GetArchiveExtractCallback(string directory, int filesCount,
+ List<uint> 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;
+ }
+
+ /// <summary>
+ /// Gets the IArchiveExtractCallback callback
+ /// </summary>
+ /// <param name="stream">The stream where extract the file</param>
+ /// <param name="index">The file index</param>
+ /// <param name="filesCount">The number of files to be extracted</param>
+ /// <returns>The ArchiveExtractCallback callback</returns>
+ 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
+
+ /// <summary>
+ /// Checks if the specified stream supports extraction.
+ /// </summary>
+ /// <param name="stream">The stream to check.</param>
+ 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.Dispose();
+ _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);
+ }
+
+ /// <summary>
+ /// Releases the unmanaged resources used by SevenZipExtractor.
+ /// </summary>
+ public void Dispose()
+ {
+ if (_asynchronousDisposeLock)
+ {
+ throw new InvalidOperationException("SevenZipExtractor instance must not be disposed " +
+ "while making an asynchronous method call.");
+ }
+ if (!_disposed)
+ {
+ CommonDispose();
+ }
+ _disposed = true;
+ GC.SuppressFinalize(this);
+ }
+
+ #endregion
+
+ #region Core public Members
+
+ #region Events
+
+ /// <summary>
+ /// Occurs when a new file is going to be unpacked.
+ /// </summary>
+ /// <remarks>Occurs when 7-zip engine requests for an output stream for a new file to unpack in.</remarks>
+ public event EventHandler<FileInfoEventArgs> FileExtractionStarted;
+
+ /// <summary>
+ /// Occurs when a file has been successfully unpacked.
+ /// </summary>
+ public event EventHandler<FileInfoEventArgs> FileExtractionFinished;
+
+ /// <summary>
+ /// Occurs when the archive has been unpacked.
+ /// </summary>
+ public event EventHandler<EventArgs> ExtractionFinished;
+
+ /// <summary>
+ /// Occurs when data are being extracted.
+ /// </summary>
+ /// <remarks>Use this event for accurate progress handling and various ProgressBar.StepBy(e.PercentDelta) routines.</remarks>
+ public event EventHandler<ProgressEventArgs> Extracting;
+
+ /// <summary>
+ /// Occurs during the extraction when a file already exists.
+ /// </summary>
+ public event EventHandler<FileOverwriteEventArgs> FileExists;
+
+ #region Event proxies
+ /// <summary>
+ /// Event proxy for FileExtractionStarted.
+ /// </summary>
+ /// <param name="sender">The sender of the event.</param>
+ /// <param name="e">The event arguments.</param>
+ private void FileExtractionStartedEventProxy(object sender, FileInfoEventArgs e)
+ {
+ OnEvent(FileExtractionStarted, e, true);
+ }
+
+ /// <summary>
+ /// Event proxy for FileExtractionFinished.
+ /// </summary>
+ /// <param name="sender">The sender of the event.</param>
+ /// <param name="e">The event arguments.</param>
+ private void FileExtractionFinishedEventProxy(object sender, FileInfoEventArgs e)
+ {
+ OnEvent(FileExtractionFinished, e, true);
+ }
+
+ /// <summary>
+ /// Event proxy for Extractng.
+ /// </summary>
+ /// <param name="sender">The sender of the event.</param>
+ /// <param name="e">The event arguments.</param>
+ private void ExtractingEventProxy(object sender, ProgressEventArgs e)
+ {
+ OnEvent(Extracting, e, false);
+ }
+
+ /// <summary>
+ /// Event proxy for FileExists.
+ /// </summary>
+ /// <param name="sender">The sender of the event.</param>
+ /// <param name="e">The event arguments.</param>
+ private void FileExistsEventProxy(object sender, FileOverwriteEventArgs e)
+ {
+ OnEvent(FileExists, e, true);
+ }
+ #endregion
+ #endregion
+
+ #region Properties
+ /// <summary>
+ /// Gets the collection of ArchiveFileInfo with all information about files in the archive
+ /// </summary>
+ public ReadOnlyCollection<ArchiveFileInfo> ArchiveFileData
+ {
+ get
+ {
+ DisposedCheck();
+ InitArchiveFileData(true);
+ return _archiveFileInfoCollection;
+ }
+ }
+
+ /// <summary>
+ /// Gets the properties for the current archive
+ /// </summary>
+ public ReadOnlyCollection<ArchiveProperty> ArchiveProperties
+ {
+ get
+ {
+ DisposedCheck();
+ InitArchiveFileData(true);
+ return _archiveProperties;
+ }
+ }
+
+ /// <summary>
+ /// Gets the collection of all file names contained in the archive.
+ /// </summary>
+ /// <remarks>
+ /// Each get recreates the collection
+ /// </remarks>
+ public ReadOnlyCollection<string> ArchiveFileNames
+ {
+ get
+ {
+ DisposedCheck();
+ InitArchiveFileData(true);
+ var fileNames = new List<string>(_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<string>(fileNames);
+ }
+ }
+
+ /// <summary>
+ /// Gets the list of archive volume file names.
+ /// </summary>
+ public ReadOnlyCollection<string> VolumeFileNames
+ {
+ get
+ {
+ DisposedCheck();
+ InitArchiveFileData(true);
+ return _volumeFileNames;
+ }
+ }
+ #endregion
+
+ /// <summary>
+ /// Performs the archive integrity test.
+ /// </summary>
+ /// <returns>True is the archive is ok; otherwise, false.</returns>
+ 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();
+ }
+ ((InStreamWrapper)_archiveStream).Dispose();
+ _archiveStream = null;
+ _opened = false;
+ }
+ return true;
+ }
+
+ #region ExtractFile overloads
+ /// <summary>
+ /// Unpacks the file by its name to the specified stream.
+ /// </summary>
+ /// <param name="fileName">The file full name in the archive file table.</param>
+ /// <param name="stream">The stream where the file is to be unpacked.</param>
+ 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);
+ }
+ }
+
+ /// <summary>
+ /// Unpacks the file by its index to the specified stream.
+ /// </summary>
+ /// <param name="index">Index in the archive file table.</param>
+ /// <param name="stream">The stream where the file is to be unpacked.</param>
+ 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
+ /// <summary>
+ /// Unpacks files by their indices to the specified directory.
+ /// </summary>
+ /// <param name="indexes">indexes of the files in the archive file table.</param>
+ /// <param name="directory">Directory where the files are to be unpacked.</param>
+ 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<uint>(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();
+ }
+
+ /// <summary>
+ /// Unpacks files by their full names to the specified directory.
+ /// </summary>
+ /// <param name="fileNames">Full file names in the archive file table.</param>
+ /// <param name="directory">Directory where the files are to be unpacked.</param>
+ public void ExtractFiles(string directory, params string[] fileNames)
+ {
+ DisposedCheck();
+ InitArchiveFileData(false);
+ var indexes = new List<int>(fileNames.Length);
+ var archiveFileNames = new List<string>(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());
+ }
+
+ /// <summary>
+ /// 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.
+ /// </summary>
+ /// <param name="extractFileCallback">The callback to call for each file in the archive.</param>
+ 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
+
+ /// <summary>
+ /// Unpacks the whole archive to the specified directory.
+ /// </summary>
+ /// <param name="directory">The directory where the files are to be unpacked.</param>
+ 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;
+ }
+
+ /// <summary>
+ /// Decompress the specified stream (C# inside)
+ /// </summary>
+ /// <param name="inStream">The source compressed stream</param>
+ /// <param name="outStream">The destination uncompressed stream</param>
+ /// <param name="inLength">The length of compressed data (null for inStream.Length)</param>
+ /// <param name="codeProgressEvent">The event for handling the code progress</param>
+ public static void DecompressStream(Stream inStream, Stream outStream, int? inLength,
+ EventHandler<ProgressEventArgs> 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));
+ }
+
+ /// <summary>
+ /// Decompress byte array compressed with LZMA algorithm (C# inside)
+ /// </summary>
+ /// <param name="data">Byte array to decompress</param>
+ /// <returns>Decompressed byte array</returns>
+ 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/SevenZip/SevenZipExtractorAsynchronous.cs b/SevenZip/SevenZipExtractorAsynchronous.cs
new file mode 100644
index 00000000..4d00ddc4
--- /dev/null
+++ b/SevenZip/SevenZipExtractorAsynchronous.cs
@@ -0,0 +1,317 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+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
+
+ /// <summary>
+ /// Recreates the instance of the SevenZipExtractor class.
+ /// Used in asynchronous methods.
+ /// </summary>
+ 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();
+ _asynchronousDisposeLock = true;
+ base.SaveContext(
+#if !DOTNET20
+ eventPriority
+#endif
+ );
+
+ }
+
+ internal override void ReleaseContext()
+ {
+ base.ReleaseContext();
+ _asynchronousDisposeLock = false;
+ }
+
+ #endregion
+
+ #region Delegates
+ /// <summary>
+ /// The delegate to use in BeginExtractArchive.
+ /// </summary>
+ /// <param name="directory">The directory where the files are to be unpacked.</param>
+ private delegate void ExtractArchiveDelegate(string directory);
+
+ /// <summary>
+ /// The delegate to use in BeginExtractFile (by file name).
+ /// </summary>
+ /// <param name="fileName">The file full name in the archive file table.</param>
+ /// <param name="stream">The stream where the file is to be unpacked.</param>
+ private delegate void ExtractFileByFileNameDelegate(string fileName, Stream stream);
+
+ /// <summary>
+ /// The delegate to use in BeginExtractFile (by index).
+ /// </summary>
+ /// <param name="index">Index in the archive file table.</param>
+ /// <param name="stream">The stream where the file is to be unpacked.</param>
+ private delegate void ExtractFileByIndexDelegate(int index, Stream stream);
+
+ /// <summary>
+ /// The delegate to use in BeginExtractFiles(string directory, params int[] indexes).
+ /// </summary>
+ /// <param name="indexes">indexes of the files in the archive file table.</param>
+ /// <param name="directory">Directory where the files are to be unpacked.</param>
+ private delegate void ExtractFiles1Delegate(string directory, int[] indexes);
+
+ /// <summary>
+ /// The delegate to use in BeginExtractFiles(string directory, params string[] fileNames).
+ /// </summary>
+ /// <param name="fileNames">Full file names in the archive file table.</param>
+ /// <param name="directory">Directory where the files are to be unpacked.</param>
+ private delegate void ExtractFiles2Delegate(string directory, string[] fileNames);
+
+ /// <summary>
+ /// The delegate to use in BeginExtractFiles(ExtractFileCallback extractFileCallback).
+ /// </summary>
+ /// <param name="extractFileCallback">The callback to call for each file in the archive.</param>
+ private delegate void ExtractFiles3Delegate(ExtractFileCallback extractFileCallback);
+ #endregion
+
+#if !DOTNET20
+ /// <summary>
+ /// Unpacks the whole archive asynchronously to the specified directory name at the specified priority.
+ /// </summary>
+ /// <param name="directory">The directory where the files are to be unpacked.</param>
+ /// <param name="eventPriority">The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked.</param>
+#else
+ /// <summary>
+ /// Unpacks the whole archive asynchronously to the specified directory name at the specified priority.
+ /// </summary>
+ /// <param name="directory">The directory where the files are to be unpacked.</param>
+#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
+ /// <summary>
+ /// Unpacks the file asynchronously by its name to the specified stream.
+ /// </summary>
+ /// <param name="fileName">The file full name in the archive file table.</param>
+ /// <param name="stream">The stream where the file is to be unpacked.</param>
+ /// <param name="eventPriority">The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked.</param>
+#else
+ /// <summary>
+ /// Unpacks the file asynchronously by its name to the specified stream.
+ /// </summary>
+ /// <param name="fileName">The file full name in the archive file table.</param>
+ /// <param name="stream">The stream where the file is to be unpacked.</param>
+#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
+ /// <summary>
+ /// Unpacks the file asynchronously by its index to the specified stream.
+ /// </summary>
+ /// <param name="index">Index in the archive file table.</param>
+ /// <param name="stream">The stream where the file is to be unpacked.</param>
+ /// <param name="eventPriority">The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked.</param>
+#else
+ /// <summary>
+ /// Unpacks the file asynchronously by its index to the specified stream.
+ /// </summary>
+ /// <param name="index">Index in the archive file table.</param>
+ /// <param name="stream">The stream where the file is to be unpacked.</param>
+#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
+ /// <summary>
+ /// Unpacks files asynchronously by their indices to the specified directory.
+ /// </summary>
+ /// <param name="indexes">indexes of the files in the archive file table.</param>
+ /// <param name="directory">Directory where the files are to be unpacked.</param>
+ /// <param name="eventPriority">The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked.</param>
+#else
+ /// <summary>
+ /// Unpacks files asynchronously by their indices to the specified directory.
+ /// </summary>
+ /// <param name="indexes">indexes of the files in the archive file table.</param>
+ /// <param name="directory">Directory where the files are to be unpacked.</param>
+#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
+ /// <summary>
+ /// Unpacks files asynchronously by their full names to the specified directory.
+ /// </summary>
+ /// <param name="fileNames">Full file names in the archive file table.</param>
+ /// <param name="directory">Directory where the files are to be unpacked.</param>
+ /// <param name="eventPriority">The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked.</param>
+#else
+ /// <summary>
+ /// Unpacks files asynchronously by their full names to the specified directory.
+ /// </summary>
+ /// <param name="fileNames">Full file names in the archive file table.</param>
+ /// <param name="directory">Directory where the files are to be unpacked.</param>
+#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
+ /// <summary>
+ /// 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.
+ /// </summary>
+ /// <param name="extractFileCallback">The callback to call for each file in the archive.</param>
+ /// <param name="eventPriority">The priority of events, relative to the other pending operations in the System.Windows.Threading.Dispatcher event queue, the specified method is invoked.</param>
+#else
+ /// <summary>
+ /// 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.
+ /// </summary>
+ /// <param name="extractFileCallback">The callback to call for each file in the archive.</param>
+#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/SevenZip/StreamWrappers.cs b/SevenZip/StreamWrappers.cs
new file mode 100644
index 00000000..55821d3e
--- /dev/null
+++ b/SevenZip/StreamWrappers.cs
@@ -0,0 +1,545 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+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
+
+ /// <summary>
+ /// A class that has DisposeStream property.
+ /// </summary>
+ internal class DisposeVariableWrapper
+ {
+ public bool DisposeStream { protected get; set; }
+
+ protected DisposeVariableWrapper(bool disposeStream) { DisposeStream = disposeStream; }
+ }
+
+ /// <summary>
+ /// Stream wrapper used in InStreamWrapper
+ /// </summary>
+ internal class StreamWrapper : DisposeVariableWrapper, IDisposable
+ {
+ /// <summary>
+ /// File name associated with the stream (for date fix)
+ /// </summary>
+ private readonly string _fileName;
+
+ private readonly DateTime _fileTime;
+
+ /// <summary>
+ /// Worker stream for reading, writing and seeking.
+ /// </summary>
+ private Stream _baseStream;
+
+ /// <summary>
+ /// Initializes a new instance of the StreamWrapper class
+ /// </summary>
+ /// <param name="baseStream">Worker stream for reading, writing and seeking</param>
+ /// <param name="fileName">File name associated with the stream (for attributes fix)</param>
+ /// <param name="time">File last write time (for attributes fix)</param>
+ /// <param name="disposeStream">Indicates whether to dispose the baseStream</param>
+ protected StreamWrapper(Stream baseStream, string fileName, DateTime time, bool disposeStream)
+ : base(disposeStream)
+ {
+ _baseStream = baseStream;
+ _fileName = fileName;
+ _fileTime = time;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the StreamWrapper class
+ /// </summary>
+ /// <param name="baseStream">Worker stream for reading, writing and seeking</param>
+ /// <param name="disposeStream">Indicates whether to dispose the baseStream</param>
+ protected StreamWrapper(Stream baseStream, bool disposeStream)
+ : base(disposeStream)
+ {
+ _baseStream = baseStream;
+ }
+
+ /// <summary>
+ /// Gets the worker stream for reading, writing and seeking.
+ /// </summary>
+ protected Stream BaseStream
+ {
+ get
+ {
+ return _baseStream;
+ }
+ }
+
+ #region IDisposable Members
+
+ /// <summary>
+ /// Cleans up any resources used and fixes file attributes.
+ /// </summary>
+ 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);
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// IInStream wrapper used in stream read operations.
+ /// </summary>
+ internal sealed class InStreamWrapper : StreamWrapper, ISequentialInStream, IInStream
+ {
+ /// <summary>
+ /// Initializes a new instance of the InStreamWrapper class.
+ /// </summary>
+ /// <param name="baseStream">Stream for writing data</param>
+ /// <param name="disposeStream">Indicates whether to dispose the baseStream</param>
+ public InStreamWrapper(Stream baseStream, bool disposeStream) : base(baseStream, disposeStream) { }
+
+ #region ISequentialInStream Members
+
+ /// <summary>
+ /// Reads data from the stream.
+ /// </summary>
+ /// <param name="data">A data array.</param>
+ /// <param name="size">The array size.</param>
+ /// <returns>The read bytes count.</returns>
+ 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
+
+ /// <summary>
+ /// Occurs when IntEventArgs.Value bytes were read from the source.
+ /// </summary>
+ public event EventHandler<IntEventArgs> BytesRead;
+
+ private void OnBytesRead(IntEventArgs e)
+ {
+ if (BytesRead != null)
+ {
+ BytesRead(this, e);
+ }
+ }
+ }
+
+ /// <summary>
+ /// IOutStream wrapper used in stream write operations.
+ /// </summary>
+ internal sealed class OutStreamWrapper : StreamWrapper, ISequentialOutStream, IOutStream
+ {
+ /// <summary>
+ /// Initializes a new instance of the OutStreamWrapper class
+ /// </summary>
+ /// <param name="baseStream">Stream for writing data</param>
+ /// <param name="fileName">File name (for attributes fix)</param>
+ /// <param name="time">Time of the file creation (for attributes fix)</param>
+ /// <param name="disposeStream">Indicates whether to dispose the baseStream</param>
+ public OutStreamWrapper(Stream baseStream, string fileName, DateTime time, bool disposeStream) :
+ base(baseStream, fileName, time, disposeStream) {}
+
+ /// <summary>
+ /// Initializes a new instance of the OutStreamWrapper class
+ /// </summary>
+ /// <param name="baseStream">Stream for writing data</param>
+ /// <param name="disposeStream">Indicates whether to dispose the baseStream</param>
+ 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
+
+ /// <summary>
+ /// Writes data to the stream
+ /// </summary>
+ /// <param name="data">Data array</param>
+ /// <param name="size">Array size</param>
+ /// <param name="processedSize">Count of written bytes</param>
+ /// <returns>Zero if Ok</returns>
+ 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
+
+ /// <summary>
+ /// Occurs when IntEventArgs.Value bytes were written.
+ /// </summary>
+ public event EventHandler<IntEventArgs> BytesWritten;
+
+ private void OnBytesWritten(IntEventArgs e)
+ {
+ if (BytesWritten != null)
+ {
+ BytesWritten(this, e);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Base multi volume stream wrapper class.
+ /// </summary>
+ internal class MultiStreamWrapper : DisposeVariableWrapper, IDisposable
+ {
+ protected readonly Dictionary<int, KeyValuePair<long, long>> StreamOffsets =
+ new Dictionary<int, KeyValuePair<long, long>>();
+
+ protected readonly List<Stream> Streams = new List<Stream>();
+ protected int CurrentStream;
+ protected long Position;
+ protected long StreamLength;
+
+ /// <summary>
+ /// Initializes a new instance of the MultiStreamWrapper class.
+ /// </summary>
+ /// <param name="dispose">Perform Dispose() if requested to.</param>
+ protected MultiStreamWrapper(bool dispose) : base(dispose) {}
+
+ /// <summary>
+ /// Gets the total length of input data.
+ /// </summary>
+ public long Length
+ {
+ get
+ {
+ return StreamLength;
+ }
+ }
+
+ #region IDisposable Members
+
+ /// <summary>
+ /// Cleans up any resources used and fixes file attributes.
+ /// </summary>
+ 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);
+ }
+ }
+ }
+
+ /// <summary>
+ /// IInStream wrapper used in stream multi volume read operations.
+ /// </summary>
+ internal sealed class InMultiStreamWrapper : MultiStreamWrapper, ISequentialInStream, IInStream
+ {
+ /// <summary>
+ /// Initializes a new instance of the InMultiStreamWrapper class.
+ /// </summary>
+ /// <param name="fileName">The archive file name.</param>
+ /// <param name="dispose">Perform Dispose() if requested to.</param>
+ 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<long, long>(StreamLength, StreamLength + length));
+ StreamLength += length;
+ fileName = baseName + VolumeNumber(i + 1);
+ }
+ }
+
+ #region ISequentialInStream Members
+
+ /// <summary>
+ /// Reads data from the stream.
+ /// </summary>
+ /// <param name="data">A data array.</param>
+ /// <param name="size">The array size.</param>
+ /// <returns>The read bytes count.</returns>
+ 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
+ /// <summary>
+ /// IOutStream wrapper used in multi volume stream write operations.
+ /// </summary>
+ internal sealed class OutMultiStreamWrapper : MultiStreamWrapper, ISequentialOutStream, IOutStream
+ {
+ private readonly string _archiveName;
+ private readonly int _volumeSize;
+ private long _overallLength;
+
+ /// <summary>
+ /// Initializes a new instance of the OutMultiStreamWrapper class.
+ /// </summary>
+ /// <param name="archiveName">The archive name.</param>
+ /// <param name="volumeSize">The volume size.</param>
+ 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<long, long>(0, _volumeSize - 1));
+ }
+ }
+#endif
+
+ internal sealed class FakeOutStreamWrapper : ISequentialOutStream, IDisposable
+ {
+ #region IDisposable Members
+
+ public void Dispose()
+ {
+ GC.SuppressFinalize(this);
+ }
+
+ #endregion
+
+ #region ISequentialOutStream Members
+
+ /// <summary>
+ /// Does nothing except calling the BytesWritten event
+ /// </summary>
+ /// <param name="data">Data array</param>
+ /// <param name="size">Array size</param>
+ /// <param name="processedSize">Count of written bytes</param>
+ /// <returns>Zero if Ok</returns>
+ 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
+
+ /// <summary>
+ /// Occurs when IntEventArgs.Value bytes were written
+ /// </summary>
+ public event EventHandler<IntEventArgs> BytesWritten;
+
+ private void OnBytesWritten(IntEventArgs e)
+ {
+ if (BytesWritten != null)
+ {
+ BytesWritten(this, e);
+ }
+ }
+ }
+#endif
+} \ No newline at end of file
diff --git a/SevenZip/gpl.txt b/SevenZip/gpl.txt
new file mode 100644
index 00000000..94a9ed02
--- /dev/null
+++ b/SevenZip/gpl.txt
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/SevenZip/lgpl.txt b/SevenZip/lgpl.txt
new file mode 100644
index 00000000..fc8a5de7
--- /dev/null
+++ b/SevenZip/lgpl.txt
@@ -0,0 +1,165 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/SevenZip/sdk/Common/CRC.cs b/SevenZip/sdk/Common/CRC.cs
new file mode 100644
index 00000000..7ef79586
--- /dev/null
+++ b/SevenZip/sdk/Common/CRC.cs
@@ -0,0 +1,75 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+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/SevenZip/sdk/Common/InBuffer.cs b/SevenZip/sdk/Common/InBuffer.cs
new file mode 100644
index 00000000..26f3ae41
--- /dev/null
+++ b/SevenZip/sdk/Common/InBuffer.cs
@@ -0,0 +1,119 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+using System.IO;
+
+namespace SevenZip.Sdk.Buffer
+{
+ /// <summary>
+ /// Implements the input buffer work
+ /// </summary>
+ 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;
+
+ /// <summary>
+ /// Initializes the input buffer
+ /// </summary>
+ /// <param name="bufferSize"></param>
+ private InBuffer(uint bufferSize)
+ {
+ m_Buffer = new byte[bufferSize];
+ m_BufferSize = bufferSize;
+ }
+
+ /// <summary>
+ /// Initializes the class
+ /// </summary>
+ /// <param name="stream"></param>
+ private void Init(Stream stream)
+ {
+ m_Stream = stream;
+ m_ProcessedSize = 0;
+ m_Limit = 0;
+ m_Pos = 0;
+ m_StreamWasExhausted = false;
+ }
+
+ /// <summary>
+ /// Reads the whole block
+ /// </summary>
+ /// <returns></returns>
+ 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);
+ }
+
+ /// <summary>
+ /// Releases the stream
+ /// </summary>
+ private void ReleaseStream()
+ {
+ // m_Stream.Close();
+ m_Stream = null;
+ }
+
+ /// <summary>
+ /// Reads the byte to check it
+ /// </summary>
+ /// <param name="b"></param>
+ /// <returns></returns>
+ private bool ReadByte(out byte b)
+ {
+ b = 0;
+ if (m_Pos >= m_Limit)
+ if (!ReadBlock())
+ return false;
+ b = m_Buffer[m_Pos++];
+ return true;
+ }
+
+ /// <summary>
+ /// Reads the next byte
+ /// </summary>
+ /// <returns></returns>
+ private byte ReadByte()
+ {
+ // return (byte)m_Stream.ReadByte();
+ if (m_Pos >= m_Limit)
+ if (!ReadBlock())
+ return 0xFF;
+ return m_Buffer[m_Pos++];
+ }
+
+ /// <summary>
+ /// Gets processed size
+ /// </summary>
+ /// <returns></returns>
+ private ulong GetProcessedSize()
+ {
+ return m_ProcessedSize + m_Pos;
+ }
+ }
+} \ No newline at end of file
diff --git a/SevenZip/sdk/Common/OutBuffer.cs b/SevenZip/sdk/Common/OutBuffer.cs
new file mode 100644
index 00000000..85117e03
--- /dev/null
+++ b/SevenZip/sdk/Common/OutBuffer.cs
@@ -0,0 +1,85 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+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;
+
+ /// <summary>
+ /// Initializes a new instance of the OutBuffer class
+ /// </summary>
+ /// <param name="bufferSize"></param>
+ 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/SevenZip/sdk/Compress/LZ/IMatchFinder.cs b/SevenZip/sdk/Compress/LZ/IMatchFinder.cs
new file mode 100644
index 00000000..d7a792c9
--- /dev/null
+++ b/SevenZip/sdk/Compress/LZ/IMatchFinder.cs
@@ -0,0 +1,40 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+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/SevenZip/sdk/Compress/LZ/LzBinTree.cs b/SevenZip/sdk/Compress/LZ/LzBinTree.cs
new file mode 100644
index 00000000..6669a5b2
--- /dev/null
+++ b/SevenZip/sdk/Compress/LZ/LzBinTree.cs
@@ -0,0 +1,405 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+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/SevenZip/sdk/Compress/LZ/LzInWindow.cs b/SevenZip/sdk/Compress/LZ/LzInWindow.cs
new file mode 100644
index 00000000..8cb05038
--- /dev/null
+++ b/SevenZip/sdk/Compress/LZ/LzInWindow.cs
@@ -0,0 +1,197 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+using System;
+using System.IO;
+
+namespace SevenZip.Sdk.Compression.LZ
+{
+ /// <summary>
+ /// Input window class
+ /// </summary>
+ internal class InWindow
+ {
+ /// <summary>
+ /// Size of Allocated memory block
+ /// </summary>
+ public UInt32 _blockSize;
+
+ /// <summary>
+ /// The pointer to buffer with data
+ /// </summary>
+ public Byte[] _bufferBase;
+
+ /// <summary>
+ /// Buffer offset value
+ /// </summary>
+ public UInt32 _bufferOffset;
+
+ /// <summary>
+ /// How many BYTEs must be kept buffer after _pos
+ /// </summary>
+ private UInt32 _keepSizeAfter;
+
+ /// <summary>
+ /// How many BYTEs must be kept in buffer before _pos
+ /// </summary>
+ private UInt32 _keepSizeBefore;
+
+ private UInt32 _pointerToLastSafePosition;
+
+ /// <summary>
+ /// Offset (from _buffer) of curent byte
+ /// </summary>
+ 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
+
+ /// <summary>
+ /// Offset (from _buffer) of first not read byte from Stream
+ /// </summary>
+ 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];
+ }
+
+ /// <summary>
+ /// index + limit have not to exceed _keepSizeAfter
+ /// </summary>
+ /// <param name="index"></param>
+ /// <param name="distance"></param>
+ /// <param name="limit"></param>
+ /// <returns></returns>
+ 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/SevenZip/sdk/Compress/LZ/LzOutWindow.cs b/SevenZip/sdk/Compress/LZ/LzOutWindow.cs
new file mode 100644
index 00000000..6cf788ad
--- /dev/null
+++ b/SevenZip/sdk/Compress/LZ/LzOutWindow.cs
@@ -0,0 +1,125 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+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/SevenZip/sdk/Compress/LZMA/LzmaBase.cs b/SevenZip/sdk/Compress/LZMA/LzmaBase.cs
new file mode 100644
index 00000000..cba427c0
--- /dev/null
+++ b/SevenZip/sdk/Compress/LZMA/LzmaBase.cs
@@ -0,0 +1,108 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+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/SevenZip/sdk/Compress/LZMA/LzmaDecoder.cs b/SevenZip/sdk/Compress/LZMA/LzmaDecoder.cs
new file mode 100644
index 00000000..f3f993d4
--- /dev/null
+++ b/SevenZip/sdk/Compress/LZMA/LzmaDecoder.cs
@@ -0,0 +1,480 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+using System;
+using System.IO;
+using SevenZip.Sdk.Compression.LZ;
+using SevenZip.Sdk.Compression.RangeCoder;
+
+namespace SevenZip.Sdk.Compression.Lzma
+{
+ /// <summary>
+ /// The LZMA decoder class
+ /// </summary>
+ 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;
+
+ /// <summary>
+ /// Initializes the Lzma Decoder class.
+ /// </summary>
+ public Decoder()
+ {
+ m_DictionarySize = 0xFFFFFFFF;
+ for (int i = 0; i < Base.kNumLenToPosStates; i++)
+ m_PosSlotDecoder[i] = new BitTreeDecoder(Base.kNumPosSlotBits);
+ }
+
+ #region ICoder Members
+
+ /// <summary>
+ /// Codes a stream with LZMA algorithm to an output stream
+ /// </summary>
+ /// <param name="inStream">The input stream</param>
+ /// <param name="inSize">The input size</param>
+ /// <param name="outSize">The output size</param>
+ /// <param name="outStream">The output stream</param>
+ /// <param name="progress">Progress interface</param>
+ 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
+
+ /// <summary>
+ /// Sets decoder properties
+ /// </summary>
+ /// <param name="properties">Array of byte properties</param>
+ 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();
+ }
+
+ /// <summary>
+ /// Trains a stream
+ /// </summary>
+ /// <param name="stream">The stream to train.</param>
+ /// <returns>true if Ok; otherwise, false.</returns>
+ 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();
+ }
+
+ /// <summary>
+ /// Decodes the stream
+ /// </summary>
+ /// <param name="rangeDecoder">The specified RangeCoder</param>
+ /// <param name="posState">The position state</param>
+ /// <returns></returns>
+ 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/SevenZip/sdk/Compress/LZMA/LzmaEncoder.cs b/SevenZip/sdk/Compress/LZMA/LzmaEncoder.cs
new file mode 100644
index 00000000..cf3e528e
--- /dev/null
+++ b/SevenZip/sdk/Compress/LZMA/LzmaEncoder.cs
@@ -0,0 +1,1587 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+using System;
+using System.Globalization;
+using System.IO;
+using SevenZip.Sdk.Compression.LZ;
+using SevenZip.Sdk.Compression.RangeCoder;
+
+namespace SevenZip.Sdk.Compression.Lzma
+{
+ /// <summary>
+ /// The LZMA encoder class
+ /// </summary>
+ 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;
+ }
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the Encoder class
+ /// </summary>
+ 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
+
+ /// <summary>
+ /// Codes the specified stream
+ /// </summary>
+ /// <param name="inStream">The input stream</param>
+ /// <param name="inSize">The input size</param>
+ /// <param name="outSize">The output size</param>
+ /// <param name="outStream">The output stream</param>
+ /// <param name="progress">The progress callback</param>
+ 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
+
+ /// <summary>
+ /// Sets the coder properties
+ /// </summary>
+ /// <param name="propIDs">The property identificators</param>
+ /// <param name="properties">The array of properties</param>
+ 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
+
+ /// <summary>
+ /// Writes the coder properties
+ /// </summary>
+ /// <param name="outStream">The output stream to write the properties to.</param>
+ 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/SevenZip/sdk/Compress/RangeCoder/RangeCoder.cs b/SevenZip/sdk/Compress/RangeCoder/RangeCoder.cs
new file mode 100644
index 00000000..b371fe34
--- /dev/null
+++ b/SevenZip/sdk/Compress/RangeCoder/RangeCoder.cs
@@ -0,0 +1,249 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+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/SevenZip/sdk/Compress/RangeCoder/RangeCoderBit.cs b/SevenZip/sdk/Compress/RangeCoder/RangeCoderBit.cs
new file mode 100644
index 00000000..48fa6db9
--- /dev/null
+++ b/SevenZip/sdk/Compress/RangeCoder/RangeCoderBit.cs
@@ -0,0 +1,146 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+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/SevenZip/sdk/Compress/RangeCoder/RangeCoderBitTree.cs b/SevenZip/sdk/Compress/RangeCoder/RangeCoderBitTree.cs
new file mode 100644
index 00000000..2e3bd4d1
--- /dev/null
+++ b/SevenZip/sdk/Compress/RangeCoder/RangeCoderBitTree.cs
@@ -0,0 +1,173 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+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/SevenZip/sdk/ICoder.cs b/SevenZip/sdk/ICoder.cs
new file mode 100644
index 00000000..e893cddd
--- /dev/null
+++ b/SevenZip/sdk/ICoder.cs
@@ -0,0 +1,192 @@
+/* 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 <http://www.gnu.org/licenses/>.
+*/
+
+using System;
+using System.IO;
+
+namespace SevenZip.Sdk
+{
+ /// <summary>
+ /// The exception that is thrown when an error in input stream occurs during decoding.
+ /// </summary>
+ [Serializable]
+ internal class DataErrorException : ApplicationException
+ {
+ public DataErrorException() : base("Data Error") {}
+ }
+
+ /// <summary>
+ /// The exception that is thrown when the value of an argument is outside the allowable range.
+ /// </summary>
+ [Serializable]
+ internal class InvalidParamException : ApplicationException
+ {
+ public InvalidParamException() : base("Invalid Parameter") {}
+ }
+
+ /// <summary>
+ /// Callback progress interface.
+ /// </summary>
+ public interface ICodeProgress
+ {
+ /// <summary>
+ /// Callback progress.
+ /// </summary>
+ /// <param name="inSize">
+ /// Processed input size. -1 if unknown.
+ /// </param>
+ /// <param name="outSize">
+ /// Processed output size. -1 if unknown.
+ /// </param>
+ void SetProgress(Int64 inSize, Int64 outSize);
+ } ;
+
+ /// <summary>
+ /// Stream coder interface
+ /// </summary>
+ public interface ICoder
+ {
+ /// <summary>
+ /// Codes streams.
+ /// </summary>
+ /// <param name="inStream">
+ /// input Stream.
+ /// </param>
+ /// <param name="outStream">
+ /// output Stream.
+ /// </param>
+ /// <param name="inSize">
+ /// input Size. -1 if unknown.
+ /// </param>
+ /// <param name="outSize">
+ /// output Size. -1 if unknown.
+ /// </param>
+ /// <param name="progress">
+ /// callback progress reference.
+ /// </param>
+ /// <exception cref="SevenZip.Sdk.DataErrorException">
+ /// if input stream is not valid
+ /// </exception>
+ 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);
+ };
+ */
+
+ /// <summary>
+ /// Provides the fields that represent properties idenitifiers for compressing.
+ /// </summary>
+ public enum CoderPropId
+ {
+ /// <summary>
+ /// Specifies default property.
+ /// </summary>
+ DefaultProp = 0,
+ /// <summary>
+ /// Specifies size of dictionary.
+ /// </summary>
+ DictionarySize,
+ /// <summary>
+ /// Specifies size of memory for PPM*.
+ /// </summary>
+ UsedMemorySize,
+ /// <summary>
+ /// Specifies order for PPM methods.
+ /// </summary>
+ Order,
+ /// <summary>
+ /// Specifies Block Size.
+ /// </summary>
+ BlockSize,
+ /// <summary>
+ /// Specifies number of postion state bits for LZMA (0 &lt;= x &lt;= 4).
+ /// </summary>
+ PosStateBits,
+ /// <summary>
+ /// Specifies number of literal context bits for LZMA (0 &lt;= x &lt;= 8).
+ /// </summary>
+ LitContextBits,
+ /// <summary>
+ /// Specifies number of literal position bits for LZMA (0 &lt;= x &lt;= 4).
+ /// </summary>
+ LitPosBits,
+ /// <summary>
+ /// Specifies number of fast bytes for LZ*.
+ /// </summary>
+ NumFastBytes,
+ /// <summary>
+ /// Specifies match finder. LZMA: "BT2", "BT4" or "BT4B".
+ /// </summary>
+ MatchFinder,
+ /// <summary>
+ /// Specifies the number of match finder cyckes.
+ /// </summary>
+ MatchFinderCycles,
+ /// <summary>
+ /// Specifies number of passes.
+ /// </summary>
+ NumPasses,
+ /// <summary>
+ /// Specifies number of algorithm.
+ /// </summary>
+ Algorithm,
+ /// <summary>
+ /// Specifies the number of threads.
+ /// </summary>
+ NumThreads,
+ /// <summary>
+ /// Specifies mode with end marker.
+ /// </summary>
+ EndMarker = 0x490
+ } ;
+
+ /// <summary>
+ /// The ISetCoderProperties interface
+ /// </summary>
+ internal interface ISetCoderProperties
+ {
+ void SetCoderProperties(CoderPropId[] propIDs, object[] properties);
+ } ;
+
+ /// <summary>
+ /// The IWriteCoderProperties interface
+ /// </summary>
+ internal interface IWriteCoderProperties
+ {
+ void WriteCoderProperties(Stream outStream);
+ }
+
+ /// <summary>
+ /// The ISetDecoderPropertiesinterface
+ /// </summary>
+ internal interface ISetDecoderProperties
+ {
+ /// <summary>
+ /// Sets decoder properties
+ /// </summary>
+ /// <param name="properties">Array of byte properties</param>
+ void SetDecoderProperties(byte[] properties);
+ }
+} \ No newline at end of file