Пример #1
0
        public void PutTest()
        {
            IOClient target = new IOClient();
            string   key    = NewKey;

            PrintLn(key);
            PutExtra extra = new PutExtra(); // TODO: 初始化为适当的值

            extra.MimeType = "text/plain";
            extra.Crc32    = 123;
            extra.CheckCrc = CheckCrcType.CHECK;
            extra.Params   = new System.Collections.Generic.Dictionary <string, string>();
            PutPolicy put = new PutPolicy(Bucket);

            target.PutFinished += new EventHandler <PutRet>((o, e) =>
            {
                if (e.OK)
                {
                    RSHelper.RSDel(Bucket, key);
                }
            });
            string token = put.Token();
            PutRet ret   = target.Put(put.Token(), key, StreamEx.ToStream("Hello, Qiniu Cloud!"), extra);

            Assert.IsTrue(ret.OK, "PutFileTest Failure");
        }
Пример #2
0
        public static StudioProject OpenProject(String path)
        {
            // Deserialize project from file
            StudioProject project = null;

            using (var stream = new StreamEx(path))
            {
                project = JsonUtils.Deserialize <StudioProject>(stream);
            }
            project.ProjectDirectory = Path.GetDirectoryName(path);

            // Sync raw lists to models
            project.assets = new Dictionary <string, AssetBase>();
            foreach (var p in project.RawAssets)
            {
                var factory = AssetLoaders[p.AssetLoader];
                project.assets.Add(p.Name, factory.Create(project, p.Name, p.Filename));
            }

            // Set up cache manager
            project.CacheManager = new CacheManager(project);

            // TODO Load up other stuff


            return(project);
        }
Пример #3
0
        public static async Task <List <string> > RSPut(string bucket, int num)
#endif
        {
            IOClient target = new IOClient();
            string   key    = "csharp" + Guid.NewGuid().ToString();
            //PrintLn(key);
            PutExtra extra = new PutExtra();             // TODO: 初始化为适当的值

            extra.MimeType = "text/plain";
            PutPolicy     put     = new PutPolicy(bucket);
            List <string> newKeys = new List <string>();

            for (int i = 0; i < num; i++)
            {
                key = "csharp" + Guid.NewGuid().ToString();
#if NET20 || NET40
                PutRet ret = target.Put(put.Token(), key, StreamEx.ToStream("Hello, Qiniu Cloud!"), extra);
#else
                PutRet ret = await target.PutAsync(put.Token(), key, StreamEx.ToStream("Hello, Qiniu Cloud!"), extra);
#endif
                if (ret.OK)
                {
                    newKeys.Add(key);
                }
            }
            return(newKeys);
        }
Пример #4
0
        static Int32 _fixHeaderType3 = 0x54435243;  // TCRC

        static string readUnicodeString(StreamEx s, int endzerobyteCount)
        {
            List <byte> bytes    = new List <byte>();
            int         endzeros = 0;

            while (s.Position < s.Length)
            {
                byte b = s.ReadByte();
                if ((b == 0) && ((bytes.Count % 2 == 1 && endzeros != 0) || (bytes.Count % 2 == 0)))
                {
                    endzeros++;
                }
                else
                {
                    endzeros = 0;
                }

                if (endzeros == endzerobyteCount)
                {
                    bytes.RemoveRange(bytes.Count - endzerobyteCount + 1, endzerobyteCount - 1);
                    break;
                }

                bytes.Add(b);
            }

            return(new string(_sourceEncoding.GetChars(bytes.ToArray())));
        }
Пример #5
0
        static public int exportFile(string path)
        {
            StreamEx s         = new StreamEx(path, FileMode.Open, FileAccess.Read);
            Int32    textCount = s.ReadInt32BigEndian();

            Int32[] textOffsets = new Int32[textCount + 1];
            for (int i = 0; i < textCount; i++)
            {
                textOffsets[i] = s.ReadInt32BigEndian();
            }
            textOffsets[textCount] = (Int32)s.Length;

            string[] texts = new string[textCount];
            for (int i = 0; i < textCount; i++)
            {
                s.Position = textOffsets[i];
                texts[i]   = s.ReadString(textOffsets[i + 1] - textOffsets[i], _sourceEncoding);

                // 处理字符集差异
                texts[i] = convertStringToGBK(texts[i]);
            }

            Agemo.WriteFile(path + ".txt", _destEncoding, from txt in texts select txt + "{END}");

            return(textCount);
        }
Пример #6
0
        /// <summary>
        /// Constructor.
        /// Read a node from extended stream.
        /// </summary>
        /// <param name="stream">StreamEx object to read from.</param>
        public OwlNode(StreamEx stream)
            : this()
        {
            #if !DEBUG
            try
            {
            #endif
            // Read OwlNode ID
            id = stream.ReadVInt();

            // Read Child Count
            var childCount = stream.ReadVInt();

            // Read Data Length
            var dataLength = stream.ReadVInt();

            // Read Child Nodes
            for (int i = 0; i < childCount; i++)
                children.Add(new OwlNode(stream));

            // Read Data
            Int64 dataStart = stream.Position;
            data = new PartialStreamEx(stream, dataStart, dataLength);

            // Debug Asserts
            Debug.Assert((dataStart + dataLength) < stream.Length, "Invalid Data Length or Position",
                "dataStart = {0}; dataLength = {1}", dataStart, dataLength);
            #if !DEBUG
            }
            catch (Exception x)
            {
                throw new InvalidDataException("Failed to read Owl.OwlNode from stream.", x);
            }
            #endif
        }
Пример #7
0
        public static void repack(string input)
        {
            if (!Directory.Exists(input))
            {
                throw new Exception("输入参数必须是目录");
            }

            string[] inputFiles = Directory.GetFiles(input, "*.dds");


            IEnumerable <string> orderFiles = inputFiles.OrderBy(str => int.Parse(str.Substring(str.LastIndexOf('\\') + 1, str.Length - str.LastIndexOf('\\') - 5)));

//            IEnumerable<string> orderFiles = inputFiles.OrderBy(str => str);

            Console.WriteLine("共有{0}个输入文件", inputFiles.Length);

            StreamEx s = new StreamEx(input + ".repack.pac", FileMode.Create, FileAccess.Write);

            s.WriteInt32(inputFiles.Length);

            int i = 0;

            foreach (string file in orderFiles)
            {
                StreamEx sr = new StreamEx(file, FileMode.Open, FileAccess.Read);
                Console.WriteLine("正在封入文件{0}/{1}:{2} {3}->{4}", ++i, file, inputFiles.Length, s.Position, sr.Length);
                s.WriteInt32((Int32)sr.Length);

                s.WriteFromStream(sr, sr.Length);
            }

            s.Close();
        }
Пример #8
0
        static void zeroTo(StreamEx s, int offset)
        {
            int len = offset - (int)s.Position;

            byte[] b = new byte[len];
            s.Write(b);
        }
Пример #9
0
        public static void unpack(string input)
        {
            StreamEx s = new StreamEx(input, System.IO.FileMode.Open, System.IO.FileAccess.Read);

            string unpackdir = Path.GetFullPath(input) + "_unpack";

            if (!Directory.Exists(unpackdir))
            {
                Directory.CreateDirectory(unpackdir);
            }

            Int32 fileCount = s.ReadInt32();

            Console.WriteLine("文件头解析:共有{0}个文件", fileCount);

            for (int i = 0; i < fileCount; i++)
            {
                Int32    fileLength = s.ReadInt32();
                StreamEx sNew       = new StreamEx(unpackdir + "\\" + i.ToString("D5") + ".dds", FileMode.Create, FileAccess.Write);

                Console.WriteLine("正在解包文件{0}/{1}:{2}->{3}", i + 1, fileCount, s.Position, fileLength);

                sNew.WriteFromStream(s, fileLength);
                sNew.Close();
            }
        }
Пример #10
0
        static void zeroTo(StreamEx s, Int64 offset)
        {
            Int64 len = offset - s.Position;

            byte[] b = new byte[len];
            s.Write(b);
        }
Пример #11
0
 private async Task <CallRet> batch(string requestBody)
 {
     return
         (await
          CallWithBinary(Config.RS_HOST + "/batch", "application/x-www-form-urlencoded",
                         StreamEx.ToStream(requestBody), requestBody.Length));
 }
Пример #12
0
 /// <summary>
 /// Loads the config file.
 /// </summary>
 public static void InitializeInstance()
 {
     logger.Debug("Starting to load configuration file.");
     if (instance == null)
     {
         var path = Path.Combine(Application.StartupPath, ConfigFilename);
         // Attemp to load the existing file first
         if (File.Exists(path))
         {
             logger.Trace("Configuration file found, attempting to load.");
             try
             {
                 using (var stream = new StreamEx(path))
                 {
                     instance = JsonUtils.Deserialize <StudioSettings>(stream);
                 }
                 logger.Info("Successfully loaded the configuration file.");
             }
             catch (Exception x)
             {
                 logger.Error("Failed to load existing configuration file. Exception Type: {0}; Message: {1}", x.GetType().Name, x.Message);
                 MessageBox.Show(String.Format("Failed to load the configuration file!\nYour settings will be restored to defaults.\n\nError info: {0}", x.Message),
                                 "Error",
                                 MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
         }
         // If instance is still null, either no file exists or load failed.
         if (instance == null)
         {
             instance = new StudioSettings();
             instance.Save();
             logger.Info("Created new configuration file with default values.");
         }
     }
 }
Пример #13
0
        /// <summary>
        /// Set data associated with the node.
        /// </summary>
        /// <param name="stream"></param>
        public void SetData(Stream stream)
        {
            // TODO Dispose old stream stream (how?)

            // Assign new stream
            data = (stream as StreamEx) ?? new StreamEx(stream);
        }
Пример #14
0
        private KeyValuePair <string, string>[] Read(ZeroPositionStreamPasser sp)
        {
            StreamEx s = sp.GetStream();

            s.Position = 0x0;
            Int32 header = s.ReadInt32BigEndian();

            int count = s.ReadInt32BigEndian();

            Int32[] keyaddresses = new Int32[count];
            Int32[] blockaddress = new Int32[count];

            for (int i = 0; i < count; i++)
            {
                keyaddresses[i] = (Int32)s.Position;
                Int32 addrread = s.ReadInt32BigEndian();
                keyaddresses[i] = addrread == 0 ? 0 : keyaddresses[i] + addrread;

                blockaddress[i] = (Int32)s.Position;
                addrread        = s.ReadInt32BigEndian();
                blockaddress[i] = addrread == 0 ? 0 : blockaddress[i] + addrread;
            }

            Encoding encoding = Encoding.GetEncoding("utf-8");

            KeyValuePair <string, string>[] result = new KeyValuePair <string, string> [count];
            for (int i = 0; i < count; i++)
            {
                string key = "";
                string txt = "";

                if (keyaddresses[i] != 0)
                {
                    s.Position = keyaddresses[i];
                    key        = s.ReadString((int)(s.Length - s.Position), encoding);
                }
//                     ((
//                     (blockaddress[i] == 0)
//                     ? (i + 1 == count ? (Int32)s.Length : keyaddresses[i + 1])
//                     : blockaddress[i])
//                     - keyaddresses[i],encoding);
                if (blockaddress[i] != 0)
                {
//                    txt = s.ReadString(((i + 1 == count) ? (Int32)s.Length : keyaddresses[i + 1]) - blockaddress[i], encoding);
                    s.Position = blockaddress[i];
                    txt        = s.ReadString((int)(s.Length - s.Position), encoding);

                    for (int k = 0; k < _convertChar.Count; k++)
                    {
                        txt = txt.Replace(_convertChar[k].Key, _convertChar[k].Value);
                    }
                }

                result[i] = new KeyValuePair <string, string>(key, txt);
            }
            return(result);
        }
Пример #15
0
        public static void repack(string input)
        {
            if (!Directory.Exists(input))
            {
                throw new Exception("输入参数必须是目录");
            }

            string[] inputFiles = Directory.GetFiles(input);

            List <headerNode> headers = new List <headerNode>();
            int lastOffset            = 0x10 + inputFiles.Length * 0x40;

            align(ref lastOffset);

            for (int i = 0; i < inputFiles.Length; i++)
            {
                headerNode h = new headerNode();
                FileInfo   f = new FileInfo(inputFiles[i]);
                h.fileName   = f.Name;
                h.fileLength = (int)f.Length;
                h.fileOffset = lastOffset;

                lastOffset += h.fileLength;
                align(ref lastOffset);

                headers.Add(h);
            }
            Console.WriteLine("共有{0}个输入文件", headers.Count);

            StreamEx s = new StreamEx(input + ".repack.dat", FileMode.Create, FileAccess.Write);

            s.WriteInt64BigEndian(fixHeaderPS3FS_V1);
            s.WriteInt32BigEndian(inputFiles.Length);
            s.WriteInt32BigEndian(0);

            for (int i = 0; i < headers.Count; i++)
            {
                s.WriteSimpleString(headers[i].fileName, 0x30);
                s.WriteInt32BigEndian(0);
                s.WriteInt32BigEndian(headers[i].fileLength);
                s.WriteInt32BigEndian(0);
                s.WriteInt32BigEndian(headers[i].fileOffset);
            }
            Console.WriteLine("文件索引写入完毕");

            for (int i = 0; i < headers.Count; i++)
            {
                Console.WriteLine("正在封入文件{0}/{1}:{2} ({3}->{4})", i + 1, headers.Count, headers[i].fileName, headers[i].fileOffset, headers[i].fileLength);

                s.Position = headers[i].fileOffset;
                StreamEx sr = new StreamEx(inputFiles[i], FileMode.Open, FileAccess.Read);
                s.WriteFromStream(sr, headers[i].fileLength);
            }
            zeroTo(s, lastOffset);
            s.Close();
        }
Пример #16
0
        /// <summary>
        /// Saves all data to the config file and overwrites all previous data.
        /// </summary>
        public void Save()
        {
            logger.Info("Saving configuration file.");
            var path = Path.Combine(Application.StartupPath, ConfigFilename);

            using (var stream = new StreamEx(path, FileMode.Create, FileAccess.Write))
            {
                this.Serialize(stream);
            }
        }
Пример #17
0
        public static void GetRefInfo(string input, out int width, out int height, out int charHeight, out int charCount)
        {
            StreamEx s = new StreamEx(input, System.IO.FileMode.Open, System.IO.FileAccess.Read);

            s.Position = 0x18;
            charHeight = s.ReadInt32BigEndian();
            charCount  = s.ReadInt32BigEndian();
            width      = s.ReadInt32BigEndian();
            height     = s.ReadInt32BigEndian();
        }
Пример #18
0
    //打开文件包的函数
    public static PackageBase Open(String Path)
    {
        StreamEx s;

        try {
            s = new StreamEx(Path, FileMode.Open, FileAccess.ReadWrite);
        }
        catch {
            s = new StreamEx(Path, FileMode.Open, FileAccess.Read);
        }
        return(new DAT(s));
    }
Пример #19
0
        /// <summary>
        ///     Deserializes an object from a JSON stream.
        /// </summary>
        /// <typeparam name="T">Type of the object to deserialize.</typeparam>
        /// <param name="stream">Stream</param>
        /// <returns></returns>
        public static T Deserialize <T>(StreamEx stream)
        {
            // Check arguments
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            // Deserialize
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

            return((T)serializer.ReadObject(stream));
        }
Пример #20
0
        public static bool ExportFont(string input, string refinput)
        {
            StreamEx sOri = new StreamEx(input, System.IO.FileMode.Open, System.IO.FileAccess.Read);

            List <UInt16> originChars = new List <UInt16>();

            while (sOri.Position < sOri.Length)
            {
                originChars.Add(sOri.ReadUInt16BigEndian());
                sOri.Position += 6;
            }
            sOri.Close();

            // load ref file
            StreamEx sRef = new StreamEx(refinput, System.IO.FileMode.Open, System.IO.FileAccess.Read);

            if (sRef.Length < 2)
            {
                return(false);
            }
            byte xff = sRef.ReadByte();
            byte xfe = sRef.ReadByte();

            if (xff != 0xff || xfe != 0xfe)
            {
                return(false);
            }
            while (sRef.Position < sRef.Length)
            {
                UInt16 c = sRef.ReadUInt16();
                if (!originChars.Contains(c))
                {
                    // add not already exist char
                    originChars.Add(c);
                }
            }
            sRef.Close();

            StreamEx sExp = new StreamEx(input + ".txt", System.IO.FileMode.Create, System.IO.FileAccess.Write);

            sExp.WriteByte(0xff);
            sExp.WriteByte(0xfe);
            foreach (UInt16 c in originChars)
            {
                sExp.WriteUInt16(c);
            }

            sExp.Close();

            return(true);
        }
Пример #21
0
        public static void unpack(string input)
        {
            string inputbin = input + ".bin";
            string inputdat = input + ".dat";

            Console.WriteLine(inputbin);
            Console.WriteLine(inputdat);
            StreamEx sbin = new StreamEx(inputbin, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            StreamEx sdat = new StreamEx(inputdat, System.IO.FileMode.Open, System.IO.FileAccess.Read);

            string unpackdir = Path.GetFullPath(input);

            if (!Directory.Exists(unpackdir))
            {
                Directory.CreateDirectory(unpackdir);
            }

            Int64 fixedHeaderRead = sbin.ReadInt32BigEndian();

            if (fixedHeaderRead != fixHeaderNLCM)
            {
                throw new Exception("文件头不能识别");
            }

            sbin.ReadInt32BigEndian();
            sbin.ReadInt32BigEndian();
            Int32 count = sbin.ReadInt32BigEndian();

            Console.WriteLine("{0}个索引", count);
            sbin.Position = 0x38;

            for (int i = 0; i < count; i++)
            {
                Int32 length = sbin.ReadInt32BigEndian();
                sbin.Position += 4;
                Int32 offset = sbin.ReadInt32BigEndian();
                sbin.Position += 4;

                sdat.Position = offset;

                string   newfile = unpackdir + "\\" + i.ToString("D5") + ".bin";
                StreamEx sNew    = new StreamEx(newfile, FileMode.Create, FileAccess.Write);

                Console.WriteLine("解包文件{0}/{1}:{2} ({3}->{4})", i + 1, count, newfile, offset, length);

                sNew.WriteFromStream(sdat, length);
                sNew.Close();
            }
        }
Пример #22
0
        /// <summary>
        /// Serializes the Project Model to a file.
        /// </summary>
        /// <param name="path">Path of the file.</param>
        public static void Serialize(String path, ProjectModel model)
        {
            // Make sure that the parent directory exists
            if (!Directory.Exists(Path.GetDirectoryName(path)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(path));
            }

            // Serialize
            using (var stream = new StreamEx(path, FileMode.Create))
            {
                var serializer = new DataContractJsonSerializer(typeof(ProjectModel));
                serializer.WriteObject(stream, model);
            }
        }
Пример #23
0
        public static bool GenCodInf(string input)
        {
            StreamEx sInput = new StreamEx(input, System.IO.FileMode.Open, System.IO.FileAccess.Read);

            if (sInput.Length < 2)
            {
                return(false);
            }
            byte xff = sInput.ReadByte();
            byte xfe = sInput.ReadByte();

            if (xff != 0xff || xfe != 0xfe)
            {
                return(false);
            }

            List <UInt16> chars = new List <UInt16>();

            while (sInput.Position < sInput.Length)
            {
                chars.Add(sInput.ReadUInt16());
            }

            UInt16 totWidth   = 2048;
            UInt16 totHeight  = 2048;
            byte   charWidth  = 32;
            byte   charHeight = 32;

            StreamEx sInf = new StreamEx(input + ".inf.dat", System.IO.FileMode.Create, System.IO.FileAccess.Write);

            sInf.WriteUInt16BigEndian((UInt16)chars.Count);
            sInf.WriteUInt16BigEndian((UInt16)totWidth);
            sInf.WriteUInt16BigEndian((UInt16)totHeight);
            sInf.WriteByte(charWidth);
            sInf.WriteByte(charHeight);
            sInf.Close();

            StreamEx sCod = new StreamEx(input + ".cod.dat", System.IO.FileMode.Create, System.IO.FileAccess.Write);

            for (int i = 0; i < chars.Count; i++)
            {
                sCod.WriteUInt16BigEndian(chars[i]);
                sCod.WriteUInt16BigEndian((UInt16)(i % (totWidth / charWidth) * charWidth));
                sCod.WriteUInt16BigEndian((UInt16)(i / (totWidth / charWidth) * charHeight));
                sCod.WriteUInt16BigEndian((UInt16)(charWidth - 2));
            }
            return(true);
        }
Пример #24
0
        MemoryStream Download(Uri url, string referer, IList <RemoteCookie> cookies)
        {
            var wr  = WebRequest.Create(url);
            var hwr = wr as HttpWebRequest;

            if (hwr != null)
            {
                hwr.UserAgent = BrowserUserAgent;

                if (!string.IsNullOrWhiteSpace(referer))
                {
                    hwr.Referer = referer;
                }

                if (cookies != null && cookies.Count > 0)
                {
                    hwr.CookieContainer = new CookieContainer();
                    foreach (var remoteCookie in cookies)
                    {
                        try
                        {
                            var c = new Cookie(remoteCookie.Name, remoteCookie.Content, remoteCookie.Path);
                            hwr.CookieContainer.Add(url, c);
                        }
                        catch { }
                    }
                }
            }

            var resData = new MemoryStream();

            try
            {
                var res = wr.GetResponse();
                using (var resNetData = res.GetResponseStream())
                {
                    StreamEx.CopyFromNetStream(resNetData, resData, false, true);
                }

                return(resData);
            }
            catch (Exception)
            {
                resData.Dispose();
                throw;
            }
        }
Пример #25
0
        public static void Import(string input)
        {
            StreamEx s = new StreamEx(input, System.IO.FileMode.Open, System.IO.FileAccess.Read);

            string[] txtVal = Agemo.ReadFile(input + ".txt", _agemoEncoding);
            StreamEx si     = new StreamEx(input + ".imp", System.IO.FileMode.Create, System.IO.FileAccess.Write);

            // section offset
            s.Position = 0x10;
            Int32 sec1Offset = s.ReadInt32BigEndian();
            Int32 sec2Offset = s.ReadInt32BigEndian();
            Int32 sec3Offset = s.ReadInt32BigEndian();

            // before text data
            s.Position = 0;
            byte[] beforeText = s.Read(sec3Offset);
            si.Write(beforeText);
            si.Flush();

            // text
            UInt16[] txtOffset = new UInt16[txtVal.Length];
            for (int i = 0; i < txtVal.Length; i++)
            {
                txtOffset[i] = (UInt16)si.Position;
                txtVal[i]    = txtVal[i].Substring(0, txtVal[i].Length - 5);

                for (int k = 0; k < _convertChar.Count; k++)
                {
                    txtVal[i] = txtVal[i].Replace(_convertChar[k].Value, _convertChar[k].Key);
                }

                for (int j = 0; j < txtVal[i].Length; j++)
                {
                    si.WriteUInt16BigEndian((UInt16)txtVal[i][j]);
                }
                si.WriteUInt16(0);
            }

            // text offset
            si.Position = sec1Offset;
            for (int i = 0; i < txtOffset.Length; i++)
            {
                si.Position += 6;
                si.WriteUInt16BigEndian(txtOffset[i]);
            }
            si.Close();
        }
Пример #26
0
        internal static void repack(string input)
        {
            if (!Directory.Exists(input))
            {
                throw new Exception("输入参数必须是目录");
            }

            string[] inputFiles = Directory.GetFiles(input, "*.bin");


            //IEnumerable<string> orderFiles = inputFiles.OrderBy(str => int.Parse(str.Substring(str.LastIndexOf('\\') + 1, str.Length - str.LastIndexOf('\\') - 5)));
            IEnumerable <string> orderFiles = inputFiles.OrderBy(str => str);

            Console.WriteLine("共有{0}个输入文件", inputFiles.Length);

            StreamEx sbin = new StreamEx(input + ".repack.bin", FileMode.Create, FileAccess.Write);
            StreamEx sdat = new StreamEx(input + ".repack.dat", FileMode.Create, FileAccess.Write);

            sbin.WriteInt32BigEndian(fixHeaderNLCM);
            sbin.WriteInt32BigEndian(0x38);
            sbin.WriteInt32BigEndian(0x14);
            sbin.WriteInt32BigEndian(inputFiles.Length);
            sbin.WriteInt32BigEndian(0x1);

            int ii = input.LastIndexOf('\\');

            sbin.WriteSimpleString(input.Substring(ii + 1, input.Length - ii - 1) + ".dat", 0x24);

            int i = 0;

            foreach (string file in orderFiles)
            {
                StreamEx sr = new StreamEx(file, FileMode.Open, FileAccess.Read);
                Console.WriteLine("封入文件{0}/{1}:{2} {3}->{4}", ++i, file, inputFiles.Length, sdat.Position, sr.Length);
                sbin.WriteInt32BigEndian((Int32)sr.Length);
                sbin.WriteInt32BigEndian(0);
                sbin.WriteInt32BigEndian((Int32)sdat.Position);
                sbin.WriteInt32BigEndian(0);

                sdat.WriteFromStream(sr, sr.Length);

                align(sdat);
            }

            sbin.Close();
            sdat.Close();
        }
Пример #27
0
        public override void BuildCache()
        {
            // Do not proceed if there is an error
            if (Error != null)
            {
                return;
            }

            // Get the cache manager
            CacheManager cacheMgr = Project.CacheManager;

            string path = Path.Combine(Project.GetAssetDirectory(), Filename);

            using (Image img = Image.FromFile(path))
            {
                // Get Frame Dimension
                FrameDimension dimension = new FrameDimension(img.FrameDimensionsList[0]);

                // Cahce frames and their thumbnails
                for (int i = 0; i < FrameCount; i++)
                {
                    string frameName = String.Format("{0}/F/{1}", ID, i);
                    string thumbName = String.Format("{0}/C/{1}", ID, i);

                    // Select the frame
                    img.SelectActiveFrame(dimension, i);

                    // Cache the frame
                    using (StreamEx frameTmp = new StreamEx(new MemoryStream()))
                    {
                        img.Save(frameTmp, ImageFormat.Png);
                        frameTmp.Position = 0;
                        cacheMgr.AddEntry(frameName, frameTmp);
                    }

                    // Cache the thumbnail
                    using (StreamEx thumbTemp = new StreamEx(new MemoryStream()))
                    {
                        Image thumb = GetThumbnailEx(img, Project.ThumbnailSize);
                        thumb.Save(thumbTemp, ImageFormat.Png);
                        thumbTemp.Position = 0;
                        cacheMgr.AddEntry(thumbName, thumbTemp);
                    }
                }
            }
        }
Пример #28
0
        /// <summary>
        /// Deserializes the Project Model froma file.
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static ProjectModel Deserialize(String path)
        {
            // Make sure the file is there
            if (!File.Exists(path))
            {
                throw new FileNotFoundException("Cannot find the specified file!", path);
            }

            // Deserialize
            ProjectModel model = null;

            using (var stream = new StreamEx(path))
            {
                var serializer = new DataContractJsonSerializer(typeof(ProjectModel));
                model = (ProjectModel)serializer.ReadObject(stream);
            }

            return(model);
        }
Пример #29
0
        public static void GetCharset(string input, out List <UInt16> chars)
        {
            StreamEx s = new StreamEx(input, System.IO.FileMode.Open, System.IO.FileAccess.Read);

            byte xff = s.ReadByte();
            byte xfe = s.ReadByte();

            if (xff != 0xff || xfe != 0xfe)
            {
                throw new Exception("字库文件需要使用Big-edian unicode格式文本文件");
            }

            chars = new List <UInt16>();
            while (s.Position < s.Length)
            {
                chars.Add(s.ReadUInt16());
            }
            s.Close();
        }
Пример #30
0
        static public int importFile(string path)
        {
            string[] texts   = Agemo.ReadFile(path + ".txt", _destEncoding);
            StreamEx ssource = new StreamEx(path, FileMode.Open, FileAccess.Read);

            Int32 header = ssource.ReadInt32BigEndian();

            if (header != 0x00444D47)
            {
                throw new Exception("不支持的文件头");
            }

            ssource.Position = 0x14;
            Int32 tagCount   = ssource.ReadInt32BigEndian();
            Int32 textCount  = ssource.ReadInt32BigEndian();
            Int32 textOffset = ssource.ReadInt32BigEndian() + tagCount * 8 + 0x30;

            StreamEx sdest = new StreamEx(path + ".imp", System.IO.FileMode.Create, System.IO.FileAccess.Write);

            ssource.Position = 0;
            sdest.WriteFromStream(ssource, textOffset);

            for (int i = 0; i < texts.Length; i++)
            {
                texts[i] = texts[i].Remove(texts[i].Length - 5);
                // 处理字符集差异
                foreach (KeyValuePair <string, string> kvp in _convertChar)
                {
                    texts[i] = texts[i].Replace(kvp.Value, kvp.Key);
                }
                sdest.WriteString(texts[i], _sourceEncoding.GetByteCount(texts[i]) + 1, _sourceEncoding);
            }

            Int32 textLength = (int)(sdest.Position - textOffset);

            sdest.Position = 0x20;
            sdest.WriteInt32BigEndian(textLength);

            sdest.Close();

            return(texts.Length);
        }
Пример #31
0
        /// <summary>
        ///     请求持久化
        /// </summary>
        /// <param name="entry"></param>
        /// <param name="fops"></param>
        /// <param name="notifyURL"></param>
        /// <returns></returns>
        public async Task <string> Do(EntryPath entry, string[] fops, Uri notifyURL, string pipleline, int force = 0)
        {
            if ((fops.Length < 1) || string.IsNullOrEmpty(entry?.Bucket) ||
                (notifyURL == null) || !notifyURL.IsAbsoluteUri)
            {
                throw new Exception("params error");
            }
            StringBuilder sb = new StringBuilder();

            sb.Append(fops[0]);

            for (int i = 1; i < fops.Length; ++i)
            {
                sb.Append(";");
                sb.Append(fops[i]);
            }

            string body = string.Format("bucket={0}&key={1}&fops={2}&notifyURL={3}&force={4}&pipeline={5}", entry.Bucket,
                                        StringEx.ToUrlEncode(entry.Key), StringEx.ToUrlEncode(sb.ToString()), notifyURL.ToString(), force,
                                        pipleline);
            CallRet ret =
                await
                CallWithBinary(Config.API_HOST + "/pfop/", "application/x-www-form-urlencoded",
                               StreamEx.ToStream(body), body.Length);

            if (ret.OK)
            {
                try
                {
                    PersistentId pid = JsonConvert.DeserializeObject <PersistentId>(ret.Response);
                    return(pid.persistentId);
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            else
            {
                throw new Exception(ret.Response);
            }
        }
        /// <summary>
        /// Builds or rebuilds the cache associated with the asset.
        /// </summary>
        public override void BuildCache()
        {
            // Get the cache manager of current project
            var cacheMgr = Project.CacheManager;

            // Cache the thumbnail
            var name = String.Format("{0}/C/0", ID);

            // Get the thumbnail
            var original = GetOriginalImage();
            thumbnail = GetThumbnailEx(original, Project.ThumbnailSize);

            // Write cache
            using (var temporary = new StreamEx(new MemoryStream()))
            {
                thumbnail.Save(temporary, ImageFormat.Png);
                temporary.Position = 0;
                cacheMgr.AddEntry(name, temporary);
            }

            // Release memory
            original.Dispose();
        }
Пример #33
0
        /// <summary>
        /// Deserializes the Project Model froma file.
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static ProjectModel Deserialize(String path)
        {
            // Make sure the file is there
            if (!File.Exists(path))
                throw new FileNotFoundException("Cannot find the specified file!", path);

            // Deserialize
            ProjectModel model = null;
            using (var stream = new StreamEx(path))
            {
                var serializer = new DataContractJsonSerializer(typeof(ProjectModel));
                model = (ProjectModel)serializer.ReadObject(stream);
            }

            return model;
        }
Пример #34
0
 /// <summary>
 /// Saves all data to the config file and overwrites all previous data.
 /// </summary>
 public void Save()
 {
     logger.Info("Saving configuration file.");
     var path = Path.Combine(Application.StartupPath, ConfigFilename);
     using (var stream = new StreamEx(path, FileMode.Create, FileAccess.Write))
     {
         this.Serialize(stream);
     }
 }
Пример #35
0
 /// <summary>
 /// Loads the config file.
 /// </summary>
 public static void InitializeInstance()
 {
     logger.Debug("Starting to load configuration file.");
     if (instance == null)
     {
         var path = Path.Combine(Application.StartupPath, ConfigFilename);
         // Attemp to load the existing file first
         if (File.Exists(path))
         {
             logger.Trace("Configuration file found, attempting to load.");
             try
             {
                 using (var stream = new StreamEx(path))
                 {
                     instance = JsonUtils.Deserialize<StudioSettings>(stream);
                 }
                 logger.Info("Successfully loaded the configuration file.");
             }
             catch (Exception x)
             {
                 logger.Error("Failed to load existing configuration file. Exception Type: {0}; Message: {1}", x.GetType().Name, x.Message);
                 MessageBox.Show(String.Format("Failed to load the configuration file!\nYour settings will be restored to defaults.\n\nError info: {0}", x.Message),
                     "Error",
                     MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
         }
         // If instance is still null, either no file exists or load failed.
         if (instance == null)
         {
             instance = new StudioSettings();
             instance.Save();
             logger.Info("Created new configuration file with default values.");
         }
     }
 }
Пример #36
0
        public override Image GetFrameThumbnail(int index)
        {
            // Return null if there is an error.
            if (Error != null)
                return null;

            // Check if index is within range
            if (index < 0 || index >= frameCount)
                throw new ArgumentOutOfRangeException("index");

            string thumbName = String.Format("{0}/C/{1}", ID, index); // Frame name
            // If it is not cached in memory...
            if (thumbnails[index] == null)
            {
                // Attempt to get frame from cache
                if (!Project.CacheManager.ContainsEntry(thumbName))
                {
                    // If thumbnail is not in the cache, put it there
                    using (Image frame = GetFrameImage(index))
                    using (StreamEx stream = new StreamEx(new MemoryStream()))
                    {
                        Image thumb = GetThumbnailEx(frame, Project.ThumbnailSize);
                        thumb.Save(stream, ImageFormat.Png);
                        stream.Position = 0;
                        Project.CacheManager.AddEntry(thumbName, stream);
                    }
                }
            }

            thumbnails[index] = Image.FromStream(Project.CacheManager.GetEntry(thumbName));
            return thumbnails[index];
        }
Пример #37
0
        public override void BuildCache()
        {
            // Do not proceed if there is an error
            if (Error != null)
                return;

            // Get the cache manager
            CacheManager cacheMgr = Project.CacheManager;

            string path = Path.Combine(Project.GetAssetDirectory(), Filename);

            using (Image img = Image.FromFile(path))
            {
                // Get Frame Dimension
                FrameDimension dimension = new FrameDimension(img.FrameDimensionsList[0]);

                // Cahce frames and their thumbnails
                for (int i = 0; i < FrameCount; i++)
                {
                    string frameName = String.Format("{0}/F/{1}", ID, i);
                    string thumbName = String.Format("{0}/C/{1}", ID, i);

                    // Select the frame
                    img.SelectActiveFrame(dimension, i);

                    // Cache the frame
                    using (StreamEx frameTmp = new StreamEx(new MemoryStream()))
                    {
                        img.Save(frameTmp, ImageFormat.Png);
                        frameTmp.Position = 0;
                        cacheMgr.AddEntry(frameName, frameTmp);
                    }

                    // Cache the thumbnail
                    using (StreamEx thumbTemp = new StreamEx(new MemoryStream()))
                    {
                        Image thumb = GetThumbnailEx(img, Project.ThumbnailSize);
                        thumb.Save(thumbTemp, ImageFormat.Png);
                        thumbTemp.Position = 0;
                        cacheMgr.AddEntry(thumbName, thumbTemp);
                    }
                }
            }
        }
Пример #38
0
        public static StudioProject OpenProject(String path)
        {
            // Deserialize project from file
            StudioProject project = null;
            using (var stream = new StreamEx(path))
            {
                project = JsonUtils.Deserialize<StudioProject>(stream);
            }
            project.ProjectDirectory = Path.GetDirectoryName(path);

            // Sync raw lists to models
            project.assets = new Dictionary<string, AssetBase>();
            foreach (var p in project.RawAssets)
            {
                var factory = AssetLoaders[p.AssetLoader];
                project.assets.Add(p.Name, factory.Create(project, p.Name, p.Filename));
            }

            // Set up cache manager
            project.CacheManager = new CacheManager(project);

            // TODO Load up other stuff

            return project;
        }
Пример #39
0
        public override Image GetFrameImage(int index)
        {
            // Return null if there is an error.
            if (Error != null)
                return null;

            // Check if index is within range
            if (index < 0 || index >= frameCount)
                throw new ArgumentOutOfRangeException("index");

            // Attempt to get frame from cache
            string frameName = String.Format("{0}/F/{1}", ID, index); // Frame name
            if (!Project.CacheManager.ContainsEntry(frameName))
            {
                // If frame is not in the cache, put it in there
                using (Image original = GetOriginalImage())
                {
                    FrameDimension dimension = new FrameDimension(original.FrameDimensionsList[0]);
                    original.SelectActiveFrame(dimension, index);

                    using (StreamEx frametmp = new StreamEx(new MemoryStream()))
                    {
                        original.Save(frametmp, ImageFormat.Png);
                        frametmp.Position = 0;
                        Project.CacheManager.AddEntry(frameName, frametmp);
                    }
                }
            }

            return Image.FromStream(Project.CacheManager.GetEntry(frameName));
        }
Пример #40
0
        /// <summary>
        /// Serializes the Project Model to a file.
        /// </summary>
        /// <param name="path">Path of the file.</param>
        public static void Serialize(String path, ProjectModel model)
        {
            // Make sure that the parent directory exists
            if (!Directory.Exists(Path.GetDirectoryName(path)))
                Directory.CreateDirectory(Path.GetDirectoryName(path));

            // Serialize
            using (var stream = new StreamEx(path, FileMode.Create))
            {
                var serializer = new DataContractJsonSerializer(typeof(ProjectModel));
                serializer.WriteObject(stream, model);
            }
        }
Пример #41
0
        public void SaveProject()
        {
            // Sync models to raw lists
            RawAssets.Clear();
            RawAssets.AddRange(
                from a in Assets select
                    new AssetInfo
                    {
                        AssetLoader = a.FactoryName,
                        Filename = a.Filename,
                        Name = a.Name
                    }
                );

            // Serialize projec to project file
            using (var stream = new StreamEx(GetProjectFile(), FileMode.Create))
            {
                this.Serialize(stream);
            }

            // TODO Save other stuff
        }
Пример #42
0
 /// <summary>
 ///     Constructor.
 ///     Initializes a new instance.
 /// </summary>
 /// <param name="stream">StreamEx object to wrap.</param>
 protected StreamExEnforcer(StreamEx stream)
 {
     this.stream = stream;
 }
Пример #43
0
 /// <summary>
 ///     Validates the StreamEx object.
 ///     Throws exceptions on error.
 /// </summary>
 /// <param name="stream"></param>
 protected abstract void ValidateStream(StreamEx stream);
Пример #44
0
 /// <summary>
 /// Constructor.
 /// Create an empty node with the specified ID.
 /// Length is calculated at write-time.
 /// </summary>
 /// <param name="id">Desired ID for the new node.</param>
 public OwlNode(Int64 id)
     : this()
 {
     this.id = new VInt(id);
     data = new StreamEx(new MemoryStream()); // Buffer for stream.
 }
Пример #45
0
        /// <summary>
        /// Writes the node to stream.
        /// </summary>
        /// <param name="stream">StreamEx object to write to.</param>
        public void WriteToStream(StreamEx stream)
        {
            // Write ID
            stream.WriteVInt(id);

            // Write Child Count
            stream.WriteVInt(new VInt(children.Count));

            // Write Data Length (0 if null)
            stream.WriteVInt(new VInt(data == null ? 0 : data.Length));

            // Write Children
            foreach (var child in children)
                child.WriteToStream(stream);

            // Write Data
            data.Position = 0;
            if (data != null)
                data.CopyTo(stream);
        }
Пример #46
0
        /// <summary>
        /// Set data associated with the node.
        /// </summary>
        /// <param name="stream"></param>
        public void SetData(Stream stream)
        {
            // TODO Dispose old stream stream (how?)

            // Assign new stream
            data = (stream as StreamEx) ?? new StreamEx(stream);
        }