Пример #1
0
        public void Save(bool compressed, IProgress <ProgressInfo> progress)
        {
            _progressActionText = "Saving dsi model";
            CompressedFile <ProgressInfo> modelFile = new CompressedFile <ProgressInfo>(_filename);

            modelFile.WriteFile(WriteDsiXml, progress, compressed);
        }
Пример #2
0
        public void Load(IProgress <ProgressInfo> progress)
        {
            _progressActionText = "Loading dsi model";
            CompressedFile <ProgressInfo> modelFile = new CompressedFile <ProgressInfo>(_filename);

            modelFile.ReadFile(ReadDsiXml, progress);
        }
Пример #3
0
        public void GiveFileIsCompressedWhenIsCompressedIsCalledThenTrueIsReturned()
        {
            CompressedFile <int> file = new CompressedFile <int>(CompressedFilePath);

            Assert.IsTrue(file.FileExists);
            Assert.IsTrue(file.IsCompressed);
        }
Пример #4
0
        /// <summary>
        /// The Disassembler which will disassemble the file and extract it.
        /// </summary>
        /// <param name="filePath">Path pointing to file.</param>
        public Disassembler(string filePath)
        {
            if (filePath != null)
            {
                if (Path.GetExtension(filePath) == ".unity3d")
                {
                    _filePath = filePath;
                    ConsoleIO.Log("File path: " + _filePath);
                    _fileName = Path.GetFileNameWithoutExtension(filePath);
                    ConsoleIO.Log("File name: " + _fileName);
                    _fileExtension = Path.GetExtension(filePath);
                    ConsoleIO.Log("File extension: " + _fileExtension);
                    _fileBytes = ReadFile(filePath);
                    _fileSize  = _fileBytes.LongLength;
                    ConsoleIO.Log("File Size: " + _fileSize);

                    _compressedFile = new CompressedFile(_fileBytes);
                }
                else
                {
                    ConsoleIO.WriteLine("Invalid file type", ConsoleIO.LogType.Error);
                    throw new NotSupportedException("Invalid file type, the file type was not a .unity3d");
                }
            }
            else
            {
                ConsoleIO.WriteLine("Could not reach file", ConsoleIO.LogType.Error);
                throw new ArgumentNullException("filePath", "filePath was null :[");
            }
        }
Пример #5
0
 public void Dispose() //Faily attempt to reduce memory usage. :[
 {
     if (_fileBytes != null)
     {
         _fileBytes = null;
     }
     if (_fileExtension != null)
     {
         _fileExtension = null;
     }
     if (_fileName != null)
     {
         _fileName = null;
     }
     if (_filePath != null)
     {
         _filePath = null;
     }
     if (_compressedFile != null)
     {
         _compressedFile = null;
     }
     if (_decompressedFile != null)
     {
         _decompressedFile = null;
     }
 }
Пример #6
0
        static void Main(string[] args)
        {
            string textPath = "D:\\MyPlex\\MyShows";

            // string textPath = "E:\\ZipTest";

            string[] files =
                Directory.GetFiles(textPath, "*.rar", SearchOption.AllDirectories);

            foreach (string dir in files)
            {
                CompressedFile   compressedFile = new CompressedFile(dir);
                FileDecompresser decompresser   = new FileDecompresser(compressedFile);
                try
                {
                    Console.WriteLine("Writing RAR");
                    decompresser.Decompress();
                    Console.WriteLine("Success");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed: " + e.Message);
                    throw;
                }
                decompresser.Decompress();
            }
        }
Пример #7
0
        private void Decompress()
        {
            var resultFile     = new ResultFile(_outputStorage, _threadHelper, _maxCountEvent, false);
            var compressedFile = new CompressedFile(_inputStorage, resultFile, new Compressor(CompressionMode.Decompress, _maxCountEvent, _threadHelper));

            compressedFile.Decompress();

            resultFile.Wait();
        }
Пример #8
0
        private void FileReceiver_Load(object sender, EventArgs e)
        {
            server = new Server();

            serverThread = new Thread(async() =>
            {
                server.Start();

                while (!server.IsStopped)
                {
                    var context = await server.Listening();
                    var request = context.Request;

                    var setEnabled = new SetButtonSalvarEnabledDelegate(SetButtonSalvarEnabled);
                    buttonSalvar.Invoke(setEnabled, false);

                    if (request.Url.AbsolutePath == "/" && request.HttpMethod == "POST")
                    {
                        var writeStatus = new WriteStatusDelegate(WriteStatus);

                        string body;

                        labelStatus.Invoke(writeStatus, "Status: Lendo corpo da requisição");

                        using (var reader = new StreamReader(request.InputStream,
                                                             request.ContentEncoding))
                        {
                            body = reader.ReadToEnd();
                        }

                        labelStatus.Invoke(writeStatus, "Status: Lido corpo da requisição");

                        file = JsonConvert.DeserializeObject <CompressedFile>(body);

                        if (imageExtensions.Contains(Path.GetExtension(file.Name.ToUpperInvariant())))
                        {
                            var d = new PaintImageDelegate(PaintImage);
                            pictureBoxImage.Invoke(d);
                        }

                        labelStatus.Invoke(writeStatus, "Status: Ações completadas com sucesso");
                        buttonSalvar.Invoke(setEnabled, true);
                    }

                    var response             = context.Response;
                    response.ContentLength64 = 0;
                    response.StatusCode      = 200;
                    response.Close();
                }

                server.Stop();
            });

            serverThread.Start();
        }
Пример #9
0
        public void load()
        {
            //Palettes
            int palCount = ROM.LZ77_GetDecompressedSize(PalFile.getContents(), false) / 512;

            palettes = new Palette[palCount];

            CompressedFile PalFileLz = new CompressedFile(PalFile, CompressedFile.CompressionType.LZ);

            for (int i = 0; i < palCount; i++)
            {
                palettes[i] = new FilePalette(new InlineFile(PalFileLz, i * 512, 512, "Palette " + i));
            }

            //Graphics
            CompressedFile GFXFileLz = new CompressedFile(GFXFile, CompressedFile.CompressionType.LZ);

            graphics = new Image2D(GFXFileLz, 256, false);

            //Map16
            map16       = new Map16Tilemap(Map16File, 32, graphics, palettes, Map16TileOffset, Map16PaletteOffset);
            Overrides   = new short[map16.getMap16TileCount()];
            Map16Buffer = map16.render();

            /*
             * TilemapEditorTest t = new TilemapEditorTest();
             * t.load(map16);
             * t.Show();
             */
            //Tile Behaviors
            loadTileBehaviors();

            //Objects
            loadObjects();

/*            // Finally, load overrides
 *          if (overrideFlag)
 *          {
 *              UseOverrides = true;
 *              OverrideBitmap = Properties.Resources.tileoverrides;
 *
 *              Overrides = new short[Map16.Length];
 *              EditorOverrides = new short[Map16.Length];
 *
 *              for (int idx = 0; idx < Map16.Length; idx++)
 *              {
 *                  Overrides[idx] = -1;
 *                  EditorOverrides[idx] = -1;
 *              }
 *          }*/
        }
Пример #10
0
        private Bitmap RenderBackground(File GFXFile, File PalFile, File LayoutFile, int offs, int palOffs)
        {
            LayoutFile = new CompressedFile(LayoutFile, CompressedFile.CompressionType.LZ);
            PalFile    = new CompressedFile(PalFile, CompressedFile.CompressionType.LZ);

            Image2D i    = new Image2D(GFXFile, 256, false);
            Palette pal1 = new FilePalette(new InlineFile(PalFile, 0, 512, PalFile.name));
            Palette pal2 = new FilePalette(new InlineFile(PalFile, 512, 512, PalFile.name));

            Tilemap t = new Tilemap(LayoutFile, 64, i, new Palette[] { pal1, pal2 }, offs, palOffs);

            t.render();
            return(t.buffer);
        }
Пример #11
0
        public byte[] DecompressFile(CompressedFile compressedFile)
        {
            ICompressor compressor;

            if (compressedFile.Queue != null)
            {
                compressor = new HuffmanCoding();
            }
            else
            {
                compressor = new RunLengthEncodingCompressor();
            }

            return(compressor.Decompress(compressedFile));
        }
Пример #12
0
        public void GiveFileIsCompressedWhenReadFileIsCalledThenTheContentIsReadCorrectly()
        {
            CompressedFile <int> file = new CompressedFile <int>(CompressedFilePath);

            Assert.IsTrue(file.FileExists);

            file.ReadFile(ReadContent, this);

            Assert.AreEqual(4, _progress);
            Assert.AreEqual(4, _lines.Count);
            Assert.AreEqual("line0", _lines[0]);
            Assert.AreEqual("line1", _lines[1]);
            Assert.AreEqual("line2", _lines[2]);
            Assert.AreEqual("line3", _lines[3]);
        }
Пример #13
0
        /// <summary>
        /// Start assembling the files into a .unity3d webarchive.
        /// </summary>
        public void Assemble()
        {
            DecompressedFile.WriteFile();
            byte[] compressedbody = Compression.LZMA.LzmaUtils.Compress(((MemoryStream)DecompressedFile.FileWriter.BaseStream).ToArray());
            CompressedFile.Header.BuildVerison                    = 3;
            CompressedFile.Header.WebPlayerVersion                = "3.x.x";
            CompressedFile.Header.UnityEngineVersion              = "4.5.1f3";
            CompressedFile.Header.CompressedFileSize              = compressedbody.Length;
            CompressedFile.Header.CompressedFileHeaderSize        = 60;
            CompressedFile.Header.CompressedFileSizeWithoutHeader = compressedbody.Length - CompressedFile.Header.CompressedFileHeaderSize;
            CompressedFile.Header.DecompressedFileSize            = ((MemoryStream)DecompressedFile.FileWriter.BaseStream).ToArray().Length;
            CompressedFile.Header.CompressedFileSize2             = compressedbody.Length;
            CompressedFile.Header.DecompressedFileHeaderSize      = DecompressedFile.Header.Files[0].Offset;

            CompressedFile.WriteFile(compressedbody);
        }
Пример #14
0
        private Tilemap getTilemap()
        {
            getFiles();
            if (GFXFile == null)
            {
                return(null);
            }
            if (PalFile == null)
            {
                return(null);
            }
            if (LayoutFile == null)
            {
                return(null);
            }

            LayoutFile = new CompressedFile(LayoutFile, CompressedFile.CompressionType.LZ);

            Image2D        image       = new Image2D(new CompressedFile(GFXFile, CompressedFile.CompressionType.MaybeCompressed), 256, false);
            CompressedFile paletteFile = new CompressedFile(PalFile, CompressedFile.CompressionType.MaybeCompressed);

            int palSize = 256;

            Color[] pal = FilePalette.arrayToPalette(paletteFile.getContents());
            if (pal.Length < 256)
            {
                palSize = 16;
            }
            List <Palette> palettes = new List <Palette>();

            for (int i = 0; i + palSize <= pal.Length; i += palSize)
            {
                int palOffs = i;
                int palLen  = palSize;
                if (palOffs + palLen > pal.Length)
                {
                    palLen = pal.Length - palOffs;
                }

                palettes.Add(new FilePalette(new InlineFile(paletteFile, palOffs * 2, palLen * 2, paletteFile.name)));
            }

            Tilemap t = new Tilemap(LayoutFile, 64, image, palettes.ToArray(), bg.BitmapOffset, bg.PaletteOffsets);

            return(t);
        }
Пример #15
0
        public void WhenContentIsWrittenUncompressedToAFileThenTheReadBackContentIsIdentical()
        {
            string newPath = NewFilePath;
            CompressedFile <int> writtenFile = new CompressedFile <int>(newPath);

            Assert.IsFalse(writtenFile.FileExists);
            writtenFile.WriteFile(WriteContent, this, false);
            Assert.IsTrue(writtenFile.FileExists);
            Assert.AreEqual(4, _progress);

            _progress = 0;

            CompressedFile <int> readFile = new CompressedFile <int>(newPath);

            Assert.IsTrue(readFile.FileExists);
            readFile.ReadFile(ReadContent, this);
            Assert.AreEqual(4, _progress);
            Assert.AreEqual(4, _lines.Count);
            Assert.AreEqual("line0", _lines[0]);
            Assert.AreEqual("line1", _lines[1]);
            Assert.AreEqual("line2", _lines[2]);
            Assert.AreEqual("line3", _lines[3]);
        }
Пример #16
0
 protected override void ResetState()
 {
     compressedFile = null;
 }
Пример #17
0
        public static void Main(string[] args)
        {
            bool showHelp        = false;
            bool extractUnknowns = true;
            bool overwriteFiles  = false;
            bool verbose         = false;
            bool uncompress      = false;

            var options = new OptionSet()
            {
                {
                    "o|overwrite",
                    "overwrite existing files",
                    v => overwriteFiles = v != null
                },
                {
                    "nu|no-unknowns",
                    "don't extract unknown files",
                    v => extractUnknowns = v == null
                },
                {
                    "v|verbose",
                    "be verbose",
                    v => verbose = v != null
                },
                {
                    "u|uncompress",
                    "uncompress DCX compressed files",
                    v => uncompress = v != null
                },
                {
                    "h|help",
                    "show this message and exit",
                    v => showHelp = v != null
                },
            };

            List <string> extras;

            try
            {
                extras = options.Parse(args);
            }
            catch (OptionException e)
            {
                Console.Write("{0}: ", GetExecutableName());
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `{0} --help' for more information.", GetExecutableName());
                return;
            }

            if (extras.Count < 1 || extras.Count > 2 || showHelp == true)
            {
                Console.WriteLine("Usage: {0} [OPTIONS]+ input_bhd5 [output_dir]", GetExecutableName());
                Console.WriteLine();
                Console.WriteLine("Options:");
                options.WriteOptionDescriptions(Console.Out);
                return;
            }

            string headerPath = extras[0];
            string outputPath = extras.Count > 1 ? extras[1] : Path.ChangeExtension(headerPath, null) + "_unpack";
            string dataPath;

            if (Path.GetExtension(headerPath) == ".bdt")
            {
                dataPath   = headerPath;
                headerPath = Path.ChangeExtension(headerPath, ".bhd5");
            }
            else
            {
                dataPath = Path.ChangeExtension(headerPath, ".bdt");
            }

            var manager = ProjectData.Manager.Load();

            if (manager.ActiveProject == null)
            {
                Console.WriteLine("Warning: no active project loaded.");
            }

            var hashes = manager.LoadListsFileNames();

            var bhd = new Binder5File();

            using (var input = File.OpenRead(headerPath))
            {
                bhd.Deserialize(input);
            }

            using (var input = File.OpenRead(dataPath))
            {
                long current = 0;
                long total   = bhd.Entries.Count;

                foreach (var entry in bhd.Entries)
                {
                    bool uncompressing = false;

                    current++;

                    string name = hashes[entry.NameHash];
                    if (name == null)
                    {
                        if (extractUnknowns == false)
                        {
                            continue;
                        }

                        string extension;

                        // detect type
                        {
                            var guess = new byte[64];
                            int read  = 0;

                            extension = "unknown";

                            // TODO: fix me
                        }

                        name = entry.NameHash.ToString("X8");
                        name = Path.ChangeExtension(name, "." + extension);
                        name = Path.Combine(extension, name);
                        name = Path.Combine("__UNKNOWN", name);
                    }
                    else
                    {
                        name = name.Replace("/", "\\");
                        if (name.StartsWith("\\") == true)
                        {
                            name = name.Substring(1);
                        }
                    }

                    if (uncompress == true &&
                        entry.Size >= 76)
                    {
                        input.Seek(entry.Offset, SeekOrigin.Begin);
                        if (input.ReadValueU32(Endian.Big) == 0x44435800)
                        {
                            uncompressing = true;

                            var extension = Path.GetExtension(name);
                            if (extension != null &&
                                extension.EndsWith(".dcx") == true)
                            {
                                name = name.Substring(0, name.Length - 4);
                            }
                        }
                    }

                    var entryPath = Path.Combine(outputPath, name);

                    var parentPath = Path.GetDirectoryName(entryPath);
                    if (parentPath != null)
                    {
                        Directory.CreateDirectory(parentPath);
                    }

                    if (overwriteFiles == false &&
                        File.Exists(entryPath) == true)
                    {
                        continue;
                    }

                    if (verbose == true)
                    {
                        Console.WriteLine("[{0}/{1}] {2}",
                                          current,
                                          total,
                                          name);
                    }

                    using (var output = File.Create(entryPath))
                    {
                        if (entry.Size > 0)
                        {
                            if (uncompress == false ||
                                uncompressing == false)
                            {
                                input.Seek(entry.Offset, SeekOrigin.Begin);
                                output.WriteFromStream(input, entry.Size);
                            }
                            else
                            {
                                input.Seek(entry.Offset, SeekOrigin.Begin);
                                using (var temp = CompressedFile.Decompress(input))
                                {
                                    output.WriteFromStream(temp, temp.Length);
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #18
0
        public void GiveFileDoesNotExistWhenIsCompressedIsCalledThenFalseIsReturned()
        {
            CompressedFile <int> file = new CompressedFile <int>(NotExistingFilePath);

            Assert.IsFalse(file.IsCompressed);
        }
Пример #19
0
 public FileDecompresser(CompressedFile fileToDecompress)
 {
     _compressedFile = fileToDecompress;
 }
Пример #20
0
        public static void Main(string[] args)
        {
            bool showHelp       = false;
            bool overwriteFiles = false;
            bool verbose        = false;

            var options = new OptionSet()
            {
                {
                    "o|overwrite",
                    "overwrite existing files",
                    v => overwriteFiles = v != null
                },
                {
                    "v|verbose",
                    "be verbose",
                    v => verbose = v != null
                },
                {
                    "h|help",
                    "show this message and exit",
                    v => showHelp = v != null
                },
            };

            List <string> extras;

            try
            {
                extras = options.Parse(args);
            }
            catch (OptionException e)
            {
                Console.Write("{0}: ", GetExecutableName());
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `{0} --help' for more information.", GetExecutableName());
                return;
            }

            if (extras.Count < 1 ||
                extras.Count > 2 ||
                showHelp == true)
            {
                Console.WriteLine("Usage: {0} [OPTIONS]+ input_file.*bnd [output_dir]", GetExecutableName());
                Console.WriteLine();
                Console.WriteLine("Options:");
                options.WriteOptionDescriptions(Console.Out);
                return;
            }

            string inputPath  = extras[0];
            string outputPath = extras.Count > 1 ? extras[1] : Path.ChangeExtension(inputPath, null) + "_unpack";

            using (var input = File.OpenRead(inputPath))
            {
                var magic = input.ReadValueU32(Endian.Big);
                input.Seek(-4, SeekOrigin.Current);

                Stream data;

                if (magic == 0x44435800)
                {
                    data = CompressedFile.Decompress(input);
                }
                else
                {
                    data = input;
                }

                var bnd = new Binder3File();
                bnd.Deserialize(data);

                long current = 0;
                long total   = bnd.Entries.Count;

                foreach (var entry in bnd.Entries)
                {
                    current++;

                    var entryName = entry.Name;
                    entryName = entryName.Replace('/', '\\');

                    if (Path.IsPathRooted(entryName) == true)
                    {
                        var entryRoot = Path.GetPathRoot(entryName);
                        if (entryRoot != null)
                        {
                            if (entryName.StartsWith(entryRoot) == false)
                            {
                                throw new InvalidOperationException();
                            }
                            entryName = entryName.Substring(entryRoot.Length);
                        }
                    }

                    var entryPath = Path.Combine(outputPath, entryName);

                    if (overwriteFiles == false &&
                        File.Exists(entryPath) == true)
                    {
                        continue;
                    }

                    if (verbose == true)
                    {
                        Console.WriteLine("[{0}/{1}] {2}",
                                          current,
                                          total,
                                          entryName);
                    }

                    var parentPath = Path.GetDirectoryName(entryPath);
                    if (parentPath != null)
                    {
                        Directory.CreateDirectory(parentPath);
                    }

                    using (var output = File.Create(entryPath))
                    {
                        data.Seek(entry.Offset, SeekOrigin.Begin);
                        output.WriteFromStream(data, entry.Size);
                    }
                }
            }
        }
Пример #21
0
        public bool IsCompressedFile()
        {
            CompressedFile <ProgressInfo> modelFile = new CompressedFile <ProgressInfo>(_filename);

            return(modelFile.IsCompressed);
        }
Пример #22
0
 public RarComicPage(CompressedFile entry)
 {
     fEntry = entry;
 }
Пример #23
0
        private async void panelFile_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = e.Data.GetData(DataFormats.FileDrop, false) as string[];

            ICompressor compressor;

            if (comboBoxAlgorithm.Text.Equals("Huffman"))
            {
                compressor = new HuffmanCoding();
            }
            else
            {
                compressor = new RunLengthEncodingCompressor();
            }

            var file = File.ReadAllBytes(@files.First());

            try
            {
                pictureBox.Hide();
                panelFile.BackgroundImage = Image.FromFile(@files.First());
            }
            catch
            {
                pictureBox.Show();
                panelFile.BackgroundImage = null;
            }

            var stopWatch = new Stopwatch();

            stopWatch.Start();

            var task = Task.Run(() =>
            {
                return(compressor.Compress(file));
            });

            compressedFile = await Task.Run(() =>
            {
                var writeStatus = new WriteStatusDelegate(WriteStatus);

                int i = 0;

                while (!task.IsCompleted)
                {
                    if (i == 500)
                    {
                        labelStatus.Invoke(writeStatus, $"Status: {compressor.Percentage.ToString("0.00")} % processado");
                    }

                    i = (i + 1) % 501;
                }

                labelStatus.Invoke(writeStatus, $"Status: 100 % processado");

                var f  = task.Result;
                f.Name = Path.GetFileName(files.First());
                return(f);
            });

            stopWatch.Stop();

            var compressionPercentage = compressedFile.Data.Length * 100M / file.Length;

            labelTempo.Text              = stopWatch.Elapsed.ToString(@"hh\:mm\:ss\.ffff");
            labelTamanho.Text            = (compressedFile.Data.LongLength / 1024M).ToString("0.000") + " kb";
            labelCompressionPercent.Text = $"{compressionPercentage.ToString("0.00")} %";
        }
Пример #24
0
 protected override void LoadState()
 {
     compressedFile = CompressedFile.Parse(FileContents);
 }