Beispiel #1
0
        private System.Xml.XmlDocument GetContentXmlFile(ICSharpCode.SharpZipLib.Zip.ZipFile zipFile)
        {
            // Get file(in zip archive) that contains data ("content.xml").
            // ICSharpCode.SharpZipLib.Zip.ZipEntry contentZipEntry = zipFile["content.xml"];

            // Extract that file to MemoryStream.
            // Stream contentStream = new MemoryStream();
            // contentZipEntry.Extract(contentStream);
            // contentStream.Seek(0, SeekOrigin.Begin);

            // Create XmlDocument from MemoryStream (MemoryStream contains content.xml).
            System.Xml.XmlDocument contentXml = new System.Xml.XmlDocument();


            ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zipFile.GetEntry("content.xml");
            if (ze == null)
            {
                throw new System.ArgumentException("content.xml not found in Zip");
            } // End if (ze == null)

            using (System.IO.Stream contentStream = zipFile.GetInputStream(ze))
            {
                // do something with ZipInputStream
                contentXml.Load(contentStream);
            } // End Using contentStream

            return(contentXml);
        } // End Function GetContentXmlFile
        public static void ExtractPackageAppIconIfNotExists(string apkFilePath, string iconStoreDirectory, string packageName)
        {
            Platforms.Android.AndroidManifestData packageData = GetManifestData(apkFilePath);

            ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(apkFilePath));
            if (!string.IsNullOrEmpty(packageData.ApplicationIconName) && !string.IsNullOrEmpty(packageName))
            {
                XDocument xDocManifest = new XDocument();
                XDocument xDocResource = new XDocument();
                using (var filestream = new FileStream(apkFilePath, FileMode.Open, FileAccess.Read))
                {
                    ICSharpCode.SharpZipLib.Zip.ZipFile zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry item;
                    item = zipfile.GetEntry(packageData.ApplicationIconName);
                    if (item == null)
                        return;
                    string fileType = Path.GetExtension(packageData.ApplicationIconName);

                    using (Stream strm = zipfile.GetInputStream(item))
                    using (FileStream output = File.Create(Path.Combine(iconStoreDirectory, packageName + fileType)))
                    {
                        try
                        {
                            strm.CopyTo(output);
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                }
          

            }
        }
Beispiel #3
0
        public static void ExtractPackageAppIconIfNotExists(string apkFilePath, string iconStoreDirectory, string packageName)
        {
            Platforms.Android.AndroidManifestData packageData = GetManifestData(apkFilePath);

            ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(apkFilePath));
            if (!string.IsNullOrEmpty(packageData.ApplicationIconName) && !string.IsNullOrEmpty(packageName))
            {
                XDocument xDocManifest = new XDocument();
                XDocument xDocResource = new XDocument();
                using (var filestream = new FileStream(apkFilePath, FileMode.Open, FileAccess.Read))
                {
                    ICSharpCode.SharpZipLib.Zip.ZipFile  zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry item;
                    item = zipfile.GetEntry(packageData.ApplicationIconName);
                    if (item == null)
                    {
                        return;
                    }
                    string fileType = Path.GetExtension(packageData.ApplicationIconName);

                    using (Stream strm = zipfile.GetInputStream(item))
                        using (FileStream output = File.Create(Path.Combine(iconStoreDirectory, packageName + fileType)))
                        {
                            try
                            {
                                strm.CopyTo(output);
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }
                }
            }
        }
Beispiel #4
0
        private void DoExtract(
            IPreprocessingStepCallback callback,
            string specificFileToExtract,
            Func <PreprocessingStepParams, bool> onNext,
            string password)
        {
            using (var zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(@params.Location))
            {
                if (password != null)
                {
                    zipFile.Password = password;
                }
                var entriesToEnum = specificFileToExtract != null?
                                    Enumerable.Repeat(zipFile.GetEntry(specificFileToExtract), 1) : zipFile.OfType <ICSharpCode.SharpZipLib.Zip.ZipEntry>();

                foreach (var entry in entriesToEnum.Where(e => e != null))
                {
                    if (entry.IsDirectory)
                    {
                        continue;
                    }

                    if (entry.IsCrypted && password == null)
                    {
                        throw new PasswordException();
                    }

                    string entryFullPath = @params.FullPath + "\\" + entry.Name;
                    string tmpFileName   = callback.TempFilesManager.GenerateNewName();

                    callback.SetStepDescription("Unpacking " + entryFullPath);
                    using (FileStream tmpFs = new FileStream(tmpFileName, FileMode.CreateNew))
                        using (var entryProgress = progressAggregator.CreateProgressSink())
                        {
                            using (var entryStream = zipFile.GetInputStream(entry))
                            {
                                var totalLen = entry.Size;
                                IOUtils.CopyStreamWithProgress(entryStream, tmpFs, pos =>
                                {
                                    if (totalLen > 0)
                                    {
                                        callback.SetStepDescription($"Unpacking {pos * 100 / totalLen}%: {entryFullPath}");
                                        entryProgress.SetValue((double)pos / totalLen);
                                    }
                                }, callback.Cancellation);
                            }
                        }

                    if (!onNext(new PreprocessingStepParams(tmpFileName, entryFullPath,
                                                            @params.PreprocessingHistory.Add(new PreprocessingHistoryItem(name, entry.Name)))))
                    {
                        break;
                    }
                }
            }
        }
Beispiel #5
0
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Tag == null)
            {
                return;
            }

            if (e.Node.Tag.ToString() == "FILE" || e.Node.Tag.ToString() == "ZIP")
            {
                LearnLifeCore.FileReader.FileReader fileReader = new LearnLifeCore.FileReader.FileReader();
                fileReader.Border = LearnLifeWin.Properties.Settings.Default.ReadFileBorder;
                string filename = e.Node.Name;

                if (e.Node.Tag.ToString() == "ZIP" && e.Node.Parent.Parent.Tag.ToString() == "ZIPROOT")
                {
                    OpenFile = string.Empty;

                    filename = Path.Combine(Path.GetTempPath(), e.Node.Text);

                    ICSharpCode.SharpZipLib.Zip.ZipFile zf = null;
                    try
                    {
                        FileStream fs = File.OpenRead(e.Node.Parent.Parent.Name);
                        zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(fs);

                        byte[] buffer    = new byte[4096];
                        Stream zipStream = zf.GetInputStream(zf.GetEntry(e.Node.Name));
                        using (FileStream streamWriter = File.Create(filename))
                        {
                            ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(zipStream, streamWriter, buffer);
                        }
                    }
                    finally
                    {
                        if (zf != null)
                        {
                            zf.IsStreamOwner = true;                // Makes close also shut the underlying stream
                            zf.Close();                             // Ensure we release resources
                        }
                    }
                }
                else
                {
                    isModified = false;
                    OpenFile   = filename;
                }

                ReadLifeFile(fileReader, filename);

                if (e.Node.Tag.ToString() == "ZIP" && e.Node.Parent.Parent.Tag.ToString() == "ZIPROOT")
                {
                    File.Delete(filename);
                }
            }
        }
Beispiel #6
0
 bool FindEntry(string entryname, out SharpZipLib.Zip.ZipEntry entry)
 {
     try
     {
         entry = zip.GetEntry(entryname);
         return(entry != null);
     }
     catch (Exception e)
     {
         LogUtil.LogError(e.Message);
         entry = null;
         return(false);
     }
 }
Beispiel #7
0
        private void ExtractXmlFiles(Stream stream)
        {
#if SILVERLIGHT
            StreamResourceInfo zipStream = new StreamResourceInfo(stream, null);
#else
            ICSharpCode.SharpZipLib.Zip.ZipFile zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(stream);
#endif

            foreach (string file in FilesToDownload)
            {
                UpdateProgress(0, "Decompressing " + file + "...");
#if !SILVERLIGHT
                // we don't actually want ClientBin part in the zip
                string       part         = file.Remove(0, 10);
                StreamReader sr           = new StreamReader(zipFile.GetInputStream(zipFile.GetEntry(part)));
                string       unzippedFile = sr.ReadToEnd();
                StreamWriter writer       = new StreamWriter(file);
                writer.Write(unzippedFile);
                writer.Close();
#else
                Uri part = new Uri(file, UriKind.Relative);
                // This reading method only works in Silverlight due to the GetResourceStream not existing with 2 arguments in
                // regular .Net-land
                StreamResourceInfo fileStream   = Application.GetResourceStream(zipStream, part);
                StreamReader       sr           = new StreamReader(fileStream.Stream);
                string             unzippedFile = sr.ReadToEnd();
                //Write it in a special way when using IsolatedStorage, due to IsolatedStorage
                //having a huge performance issue when writing small chunks
                IsolatedStorageFileStream isfs = GetFileStream(file, true);

                char[] charBuffer = unzippedFile.ToCharArray();
                int    fileSize   = charBuffer.Length;
                byte[] byteBuffer = new byte[fileSize];
                for (int i = 0; i < fileSize; i++)
                {
                    byteBuffer[i] = (byte)charBuffer[i];
                }
                isfs.Write(byteBuffer, 0, fileSize);
                isfs.Close();
#endif

                UpdateProgress(0, "Finished " + file + "...");
            }

#if !SILVERLIGHT
            zipFile.Close();
#endif
        }
Beispiel #8
0
 public static byte[] GetZipEntry(ICSharpCode.SharpZipLib.Zip.ZipFile file, string entry, bool throwOnError)
 {
     if (file.FindEntry(entry, false) == -1)
     {
         if (throwOnError)
         {
             throw new FormatException("entry not found");
         }
         else
         {
             return(null);
         }
     }
     else
     {
         ICSharpCode.SharpZipLib.Zip.ZipEntry zEntry = file.GetEntry(entry);
         System.IO.Stream s      = file.GetInputStream(zEntry);
         byte[]           result = new byte[zEntry.Size];
         ICSharpCode.SharpZipLib.Core.StreamUtils.ReadFully(s, result);
         return(result);
     }
 }
Beispiel #9
0
        public static bool IsVersionWycFileValid()
        {
            using (var zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile("client.wyc"))
            {
                var zipEntry = zipFile.GetEntry("iuclient.iuc");
                if (zipEntry == null)
                {
                    return(false);
                }
                var    zipInputStream = zipFile.GetInputStream(zipEntry);
                int    firstByte      = zipInputStream.ReadByte();//Måste läsa första byte innan Length på streamen stämmer. Konstigt
                byte[] iucClientFile  = new byte[zipInputStream.Length];
                iucClientFile[0] = (byte)firstByte;
                zipInputStream.Read(iucClientFile, 1, iucClientFile.Length - 1);
                var fr = new wyUpdate.FileReader(new System.IO.MemoryStream(iucClientFile));
                if (fr.IsHeaderValid("IUCDFV2") == false)
                {
                    return(false);
                }

                byte bType = (byte)fr.ReadByte();
                while (!fr.ReachedEndByte(bType, 0xFF))
                {
                    switch (bType)
                    {
                    case 0x03:
                        return(fr.ReadDeprecatedString() == StaticValues.LauncherVersion);

                    default:
                        fr.SkipField(bType);
                        break;
                    }
                    bType = (byte)fr.ReadByte();
                }
                return(false);
            }
        }
Beispiel #10
0
        public static byte[] ReadZipBytes(string pathRoot, string relativeFileName)
        {
            //获取压缩文件内容
            byte[] data = null;
            ICSharpCode.SharpZipLib.Zip.ZipFile zfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(pathRoot);
            try {
                ICSharpCode.SharpZipLib.Zip.ZipEntry entry = zfile.GetEntry(relativeFileName);//"assets/Builds/Indep_Role_FabRole01.assetbundle");
                if (entry == null)
                {
                    return(data);
                }

                Stream sm = zfile.GetInputStream(entry.ZipFileIndex);
                data = new byte[entry.Size];
                sm.Read(data, 0, data.Length);
                sm.Close();
            } catch (Exception e) {
                Debug.LogError(e.ToString());
            } finally {
                zfile.Close();
            }

            return(data);
        }
Beispiel #11
0
 public static bool DeleteEntry(string zipFileName, string entryname, string password = null)
 {
     try
     {
         SharpZipLib.Zip.ZipFile s = new SharpZipLib.Zip.ZipFile(zipFileName);
         s.Password = password;
         SharpZipLib.Zip.ZipEntry entry = s.GetEntry(entryname);
         if (null == entry)
         {
             s.Close();
             return(true);
         }
         s.BeginUpdate();
         s.Delete(entry);
         s.CommitUpdate();
         s.Close();
         return(true);
     }
     catch (Exception e)
     {
         LogUtil.LogError(e.Message);
         return(false);
     }
 }
Beispiel #12
0
		private void btnExport_Click(object sender, EventArgs e)
		{
			//acquire target
			var sfd = new SaveFileDialog();
			sfd.Filter = "XRNS (*.xrns)|*.xrns";
			if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
				return;

			//configuration:
			var outPath = sfd.FileName;
			string templatePath = Path.Combine(Path.GetDirectoryName(outPath), "template.xrns");
			int configuredPatternLength = int.Parse(txtPatternLength.Text);


			//load template
			MemoryStream msSongXml = new MemoryStream();
			var zfTemplate = new ICSharpCode.SharpZipLib.Zip.ZipFile(templatePath);
			{
				int zfSongXmlIndex = zfTemplate.FindEntry("Song.xml", true);
				using (var zis = zfTemplate.GetInputStream(zfTemplate.GetEntry("Song.xml")))
				{
					byte[] buffer = new byte[4096];     // 4K is optimum
					ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(zis, msSongXml, buffer);
				}
			}
			XElement templateRoot = XElement.Parse(System.Text.Encoding.UTF8.GetString(msSongXml.ToArray()));

			//get the pattern pool, and whack the child nodes
			var xPatterns = templateRoot.XPathSelectElement("//Patterns");
			var xPatternPool = xPatterns.Parent;
			xPatterns.Remove();

			var writer = new StringWriter();
			writer.WriteLine("<Patterns>");


			int pulse0_lastNote = -1;
			int pulse0_lastType = -1;
			int pulse1_lastNote = -1;
			int pulse1_lastType = -1;
			int tri_lastNote = -1;
			int noise_lastNote = -1;

			int patternCount = 0;
			int time = 0;
			while (time < Log.Count)
			{
				patternCount++;

				//begin writing pattern: open the tracks list
				writer.WriteLine("<Pattern>");
				writer.WriteLine("<NumberOfLines>{0}</NumberOfLines>", configuredPatternLength);
				writer.WriteLine("<Tracks>");

				//write the pulse tracks
				for (int TRACK = 0; TRACK < 2; TRACK++)
				{
					writer.WriteLine("<PatternTrack type=\"PatternTrack\">");
					writer.WriteLine("<Lines>");

					int lastNote = TRACK == 0 ? pulse0_lastNote : pulse1_lastNote;
					int lastType = TRACK == 0 ? pulse0_lastType : pulse1_lastType;
					for (int i = 0; i < configuredPatternLength; i++)
					{
						int patLine = i;

						int index = i + time;
						if (index >= Log.Count) continue;

						var rec = Log[index];

						PulseState pulse = new PulseState();
						if (TRACK == 0) pulse = rec.pulse0;
						if (TRACK == 1) pulse = rec.pulse1;

						//transform quieted notes to dead notes
						//blech its buggy, im tired
						//if (pulse.vol == 0)
						//  pulse.en = false;

						bool keyoff = false, keyon = false;
						if (lastNote != -1 && !pulse.en)
						{
							lastNote = -1;
							lastType = -1;
							keyoff = true;
						}
						else if (lastNote != pulse.note && pulse.en)
							keyon = true;

						if (lastType != pulse.type && pulse.note != -1)
							keyon = true;

						if (pulse.en)
						{
							lastNote = pulse.note;
							lastType = pulse.type;
						}

						writer.WriteLine("<Line index=\"{0}\">", patLine);
						writer.WriteLine("<NoteColumns>");
						writer.WriteLine("<NoteColumn>");
						if (keyon)
						{
							writer.WriteLine("<Note>{0}</Note>", NameForNote(pulse.note));
							writer.WriteLine("<Instrument>{0:X2}</Instrument>", pulse.type);
						}
						else if (keyoff) writer.WriteLine("<Note>OFF</Note>");

						if(lastNote != -1)
							writer.WriteLine("<Volume>{0:X2}</Volume>", pulse.vol * 8);

						writer.WriteLine("</NoteColumn>");
						writer.WriteLine("</NoteColumns>");
						writer.WriteLine("</Line>");
					}

					//close PatternTrack
					writer.WriteLine("</Lines>");
					writer.WriteLine("</PatternTrack>");

					if (TRACK == 0)
					{
						pulse0_lastNote = lastNote;
						pulse0_lastType = lastType;
					}
					else
					{
						pulse1_lastNote = lastNote;
						pulse1_lastType = lastType;
					}

				} //pulse tracks loop

				//triangle track generation
				{
					writer.WriteLine("<PatternTrack type=\"PatternTrack\">");
					writer.WriteLine("<Lines>");

					for (int i = 0; i < configuredPatternLength; i++)
					{
						int patLine = i;

						int index = i + time;
						if (index >= Log.Count) continue;

						var rec = Log[index];

						TriangleState tri = rec.triangle;

						{
							bool keyoff = false, keyon = false;
							if (tri_lastNote != -1 && !tri.en)
							{
								tri_lastNote = -1;
								keyoff = true;
							}
							else if (tri_lastNote != tri.note && tri.en)
								keyon = true;

							if(tri.en)
								tri_lastNote = tri.note;

							writer.WriteLine("<Line index=\"{0}\">", patLine);
							writer.WriteLine("<NoteColumns>");
							writer.WriteLine("<NoteColumn>");
							if (keyon)
							{
								writer.WriteLine("<Note>{0}</Note>", NameForNote(tri.note));
								writer.WriteLine("<Instrument>08</Instrument>");
							}
							else if (keyoff) writer.WriteLine("<Note>OFF</Note>");

							//no need for tons of these
							//if(keyon) writer.WriteLine("<Volume>80</Volume>");

							writer.WriteLine("</NoteColumn>");
							writer.WriteLine("</NoteColumns>");
							writer.WriteLine("</Line>");
						}
					}

					//close PatternTrack
					writer.WriteLine("</Lines>");
					writer.WriteLine("</PatternTrack>");
				}

				//noise track generation
				{
					writer.WriteLine("<PatternTrack type=\"PatternTrack\">");
					writer.WriteLine("<Lines>");

					for (int i = 0; i < configuredPatternLength; i++)
					{
						int patLine = i;

						int index = i + time;
						if (index >= Log.Count) continue;

						var rec = Log[index];

						NoiseState noise = rec.noise;

						//transform quieted notes to dead notes
						//blech its buggy, im tired
						//if (noise.vol == 0)
						//  noise.en = false;

						{
							bool keyoff = false, keyon = false;
							if (noise_lastNote != -1 && !noise.en)
							{
								noise_lastNote = -1;
								keyoff = true;
							}
							else if (noise_lastNote != noise.note && noise.en)
								keyon = true;

							if (noise.en)
								noise_lastNote = noise.note;

							writer.WriteLine("<Line index=\"{0}\">", patLine);
							writer.WriteLine("<NoteColumns>");
							writer.WriteLine("<NoteColumn>");
							if (keyon)
							{
								writer.WriteLine("<Note>{0}</Note>", NameForNote(noise.note));
								writer.WriteLine("<Instrument>04</Instrument>");
							}
							else if (keyoff) writer.WriteLine("<Note>OFF</Note>");

							if (noise_lastNote != -1)
								writer.WriteLine("<Volume>{0:X2}</Volume>", noise.vol * 8);

							writer.WriteLine("</NoteColumn>");
							writer.WriteLine("</NoteColumns>");
							writer.WriteLine("</Line>");
						}
					}

					//close PatternTrack
					writer.WriteLine("</Lines>");
					writer.WriteLine("</PatternTrack>");
				} //noise track generation

				//write empty track for now for pcm
				for (int TRACK = 4; TRACK < 5; TRACK++)
				{
					writer.WriteLine("<PatternTrack type=\"PatternTrack\">");
					writer.WriteLine("<Lines>");
					writer.WriteLine("</Lines>");
					writer.WriteLine("</PatternTrack>");
				}

				//we definitely need a dummy master track now
				writer.WriteLine("<PatternMasterTrack type=\"PatternMasterTrack\">");
				writer.WriteLine("</PatternMasterTrack>");

				//close tracks
				writer.WriteLine("</Tracks>");

				//close pattern
				writer.WriteLine("</Pattern>");

				time += configuredPatternLength;

			} //main pattern loop

			writer.WriteLine("</Patterns>");
			writer.Flush();

			var xNewPatternList = XElement.Parse(writer.ToString());
			xPatternPool.Add(xNewPatternList);

			//write pattern sequence
			writer = new StringWriter();
			writer.WriteLine("<SequenceEntries>");
			for (int i = 0; i < patternCount; i++)
			{
				writer.WriteLine("<SequenceEntry>");
				writer.WriteLine("<IsSectionStart>false</IsSectionStart>");
				writer.WriteLine("<Pattern>{0}</Pattern>", i);
				writer.WriteLine("</SequenceEntry>");
			}
			writer.WriteLine("</SequenceEntries>");

			var xPatternSequence = templateRoot.XPathSelectElement("//PatternSequence");
			xPatternSequence.XPathSelectElement("SequenceEntries").Remove();
			xPatternSequence.Add(XElement.Parse(writer.ToString()));

			//copy template file to target
			File.Delete(outPath);
			File.Copy(templatePath, outPath);

			var msOutXml = new MemoryStream();
			templateRoot.Save(msOutXml);
			msOutXml.Flush();
			msOutXml.Position = 0;
			var zfOutput = new ICSharpCode.SharpZipLib.Zip.ZipFile(outPath);
			zfOutput.BeginUpdate();
			zfOutput.Add(new Stupid { stream = msOutXml }, "Song.xml");
			zfOutput.CommitUpdate();
			zfOutput.Close();

			//for easier debugging, write patterndata XML
			//DUMP_TO_DISK(msOutXml.ToArray())
		}
        private void btnExport_Click(object sender, EventArgs e)
        {
            //acquire target
            var sfd = new SaveFileDialog();

            sfd.Filter = "XRNS (*.xrns)|*.xrns";
            if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }

            //configuration:
            var    outPath                 = sfd.FileName;
            string templatePath            = Path.Combine(Path.GetDirectoryName(outPath), "template.xrns");
            int    configuredPatternLength = int.Parse(txtPatternLength.Text);


            //load template
            MemoryStream msSongXml  = new MemoryStream();
            var          zfTemplate = new ICSharpCode.SharpZipLib.Zip.ZipFile(templatePath);
            {
                int zfSongXmlIndex = zfTemplate.FindEntry("Song.xml", true);
                using (var zis = zfTemplate.GetInputStream(zfTemplate.GetEntry("Song.xml")))
                {
                    byte[] buffer = new byte[4096];                         // 4K is optimum
                    ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(zis, msSongXml, buffer);
                }
            }
            XElement templateRoot = XElement.Parse(System.Text.Encoding.UTF8.GetString(msSongXml.ToArray()));

            //get the pattern pool, and whack the child nodes
            var xPatterns    = templateRoot.XPathSelectElement("//Patterns");
            var xPatternPool = xPatterns.Parent;

            xPatterns.Remove();

            var writer = new StringWriter();

            writer.WriteLine("<Patterns>");


            int pulse0_lastNote = -1;
            int pulse0_lastType = -1;
            int pulse1_lastNote = -1;
            int pulse1_lastType = -1;
            int tri_lastNote    = -1;
            int noise_lastNote  = -1;

            int patternCount = 0;
            int time         = 0;

            while (time < Log.Count)
            {
                patternCount++;

                //begin writing pattern: open the tracks list
                writer.WriteLine("<Pattern>");
                writer.WriteLine("<NumberOfLines>{0}</NumberOfLines>", configuredPatternLength);
                writer.WriteLine("<Tracks>");

                //write the pulse tracks
                for (int TRACK = 0; TRACK < 2; TRACK++)
                {
                    writer.WriteLine("<PatternTrack type=\"PatternTrack\">");
                    writer.WriteLine("<Lines>");

                    int lastNote = TRACK == 0 ? pulse0_lastNote : pulse1_lastNote;
                    int lastType = TRACK == 0 ? pulse0_lastType : pulse1_lastType;
                    for (int i = 0; i < configuredPatternLength; i++)
                    {
                        int patLine = i;

                        int index = i + time;
                        if (index >= Log.Count)
                        {
                            continue;
                        }

                        var rec = Log[index];

                        PulseState pulse = new PulseState();
                        if (TRACK == 0)
                        {
                            pulse = rec.pulse0;
                        }
                        if (TRACK == 1)
                        {
                            pulse = rec.pulse1;
                        }

                        //transform quieted notes to dead notes
                        //blech its buggy, im tired
                        //if (pulse.vol == 0)
                        //  pulse.en = false;

                        bool keyoff = false, keyon = false;
                        if (lastNote != -1 && !pulse.en)
                        {
                            lastNote = -1;
                            lastType = -1;
                            keyoff   = true;
                        }
                        else if (lastNote != pulse.note && pulse.en)
                        {
                            keyon = true;
                        }

                        if (lastType != pulse.type && pulse.note != -1)
                        {
                            keyon = true;
                        }

                        if (pulse.en)
                        {
                            lastNote = pulse.note;
                            lastType = pulse.type;
                        }

                        writer.WriteLine("<Line index=\"{0}\">", patLine);
                        writer.WriteLine("<NoteColumns>");
                        writer.WriteLine("<NoteColumn>");
                        if (keyon)
                        {
                            writer.WriteLine("<Note>{0}</Note>", NameForNote(pulse.note));
                            writer.WriteLine("<Instrument>{0:X2}</Instrument>", pulse.type);
                        }
                        else if (keyoff)
                        {
                            writer.WriteLine("<Note>OFF</Note>");
                        }

                        if (lastNote != -1)
                        {
                            writer.WriteLine("<Volume>{0:X2}</Volume>", pulse.vol * 8);
                        }

                        writer.WriteLine("</NoteColumn>");
                        writer.WriteLine("</NoteColumns>");
                        writer.WriteLine("</Line>");
                    }

                    //close PatternTrack
                    writer.WriteLine("</Lines>");
                    writer.WriteLine("</PatternTrack>");

                    if (TRACK == 0)
                    {
                        pulse0_lastNote = lastNote;
                        pulse0_lastType = lastType;
                    }
                    else
                    {
                        pulse1_lastNote = lastNote;
                        pulse1_lastType = lastType;
                    }
                }                 //pulse tracks loop

                //triangle track generation
                {
                    writer.WriteLine("<PatternTrack type=\"PatternTrack\">");
                    writer.WriteLine("<Lines>");

                    for (int i = 0; i < configuredPatternLength; i++)
                    {
                        int patLine = i;

                        int index = i + time;
                        if (index >= Log.Count)
                        {
                            continue;
                        }

                        var rec = Log[index];

                        TriangleState tri = rec.triangle;

                        {
                            bool keyoff = false, keyon = false;
                            if (tri_lastNote != -1 && !tri.en)
                            {
                                tri_lastNote = -1;
                                keyoff       = true;
                            }
                            else if (tri_lastNote != tri.note && tri.en)
                            {
                                keyon = true;
                            }

                            if (tri.en)
                            {
                                tri_lastNote = tri.note;
                            }

                            writer.WriteLine("<Line index=\"{0}\">", patLine);
                            writer.WriteLine("<NoteColumns>");
                            writer.WriteLine("<NoteColumn>");
                            if (keyon)
                            {
                                writer.WriteLine("<Note>{0}</Note>", NameForNote(tri.note));
                                writer.WriteLine("<Instrument>08</Instrument>");
                            }
                            else if (keyoff)
                            {
                                writer.WriteLine("<Note>OFF</Note>");
                            }

                            //no need for tons of these
                            //if(keyon) writer.WriteLine("<Volume>80</Volume>");

                            writer.WriteLine("</NoteColumn>");
                            writer.WriteLine("</NoteColumns>");
                            writer.WriteLine("</Line>");
                        }
                    }

                    //close PatternTrack
                    writer.WriteLine("</Lines>");
                    writer.WriteLine("</PatternTrack>");
                }

                //noise track generation
                {
                    writer.WriteLine("<PatternTrack type=\"PatternTrack\">");
                    writer.WriteLine("<Lines>");

                    for (int i = 0; i < configuredPatternLength; i++)
                    {
                        int patLine = i;

                        int index = i + time;
                        if (index >= Log.Count)
                        {
                            continue;
                        }

                        var rec = Log[index];

                        NoiseState noise = rec.noise;

                        //transform quieted notes to dead notes
                        //blech its buggy, im tired
                        //if (noise.vol == 0)
                        //  noise.en = false;

                        {
                            bool keyoff = false, keyon = false;
                            if (noise_lastNote != -1 && !noise.en)
                            {
                                noise_lastNote = -1;
                                keyoff         = true;
                            }
                            else if (noise_lastNote != noise.note && noise.en)
                            {
                                keyon = true;
                            }

                            if (noise.en)
                            {
                                noise_lastNote = noise.note;
                            }

                            writer.WriteLine("<Line index=\"{0}\">", patLine);
                            writer.WriteLine("<NoteColumns>");
                            writer.WriteLine("<NoteColumn>");
                            if (keyon)
                            {
                                writer.WriteLine("<Note>{0}</Note>", NameForNote(noise.note));
                                writer.WriteLine("<Instrument>04</Instrument>");
                            }
                            else if (keyoff)
                            {
                                writer.WriteLine("<Note>OFF</Note>");
                            }

                            if (noise_lastNote != -1)
                            {
                                writer.WriteLine("<Volume>{0:X2}</Volume>", noise.vol * 8);
                            }

                            writer.WriteLine("</NoteColumn>");
                            writer.WriteLine("</NoteColumns>");
                            writer.WriteLine("</Line>");
                        }
                    }

                    //close PatternTrack
                    writer.WriteLine("</Lines>");
                    writer.WriteLine("</PatternTrack>");
                }                 //noise track generation

                //write empty track for now for pcm
                for (int TRACK = 4; TRACK < 5; TRACK++)
                {
                    writer.WriteLine("<PatternTrack type=\"PatternTrack\">");
                    writer.WriteLine("<Lines>");
                    writer.WriteLine("</Lines>");
                    writer.WriteLine("</PatternTrack>");
                }

                //we definitely need a dummy master track now
                writer.WriteLine("<PatternMasterTrack type=\"PatternMasterTrack\">");
                writer.WriteLine("</PatternMasterTrack>");

                //close tracks
                writer.WriteLine("</Tracks>");

                //close pattern
                writer.WriteLine("</Pattern>");

                time += configuredPatternLength;
            }             //main pattern loop

            writer.WriteLine("</Patterns>");
            writer.Flush();

            var xNewPatternList = XElement.Parse(writer.ToString());

            xPatternPool.Add(xNewPatternList);

            //write pattern sequence
            writer = new StringWriter();
            writer.WriteLine("<SequenceEntries>");
            for (int i = 0; i < patternCount; i++)
            {
                writer.WriteLine("<SequenceEntry>");
                writer.WriteLine("<IsSectionStart>false</IsSectionStart>");
                writer.WriteLine("<Pattern>{0}</Pattern>", i);
                writer.WriteLine("</SequenceEntry>");
            }
            writer.WriteLine("</SequenceEntries>");

            var xPatternSequence = templateRoot.XPathSelectElement("//PatternSequence");

            xPatternSequence.XPathSelectElement("SequenceEntries").Remove();
            xPatternSequence.Add(XElement.Parse(writer.ToString()));

            //copy template file to target
            File.Delete(outPath);
            File.Copy(templatePath, outPath);

            var msOutXml = new MemoryStream();

            templateRoot.Save(msOutXml);
            msOutXml.Flush();
            msOutXml.Position = 0;
            var zfOutput = new ICSharpCode.SharpZipLib.Zip.ZipFile(outPath);

            zfOutput.BeginUpdate();
            zfOutput.Add(new Stupid {
                stream = msOutXml
            }, "Song.xml");
            zfOutput.CommitUpdate();
            zfOutput.Close();

            //for easier debugging, write patterndata XML
            //DUMP_TO_DISK(msOutXml.ToArray())
        }
Beispiel #14
0
        private void ExtractXmlFiles(Stream stream)
        {
#if SILVERLIGHT
            StreamResourceInfo zipStream = new StreamResourceInfo(stream, null);
#else
            ICSharpCode.SharpZipLib.Zip.ZipFile zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(stream);
#endif

            foreach (string file in FilesToDownload)
            {
                UpdateProgress(0, "Decompressing " + file + "...");
#if !SILVERLIGHT
                // we don't actually want ClientBin part in the zip
                string part = file.Remove(0, 10);
                StreamReader sr = new StreamReader(zipFile.GetInputStream(zipFile.GetEntry(part)));
                string unzippedFile = sr.ReadToEnd();
                StreamWriter writer = new StreamWriter(file);
                writer.Write(unzippedFile);
                writer.Close();
#else
                Uri part = new Uri(file, UriKind.Relative);
                // This reading method only works in Silverlight due to the GetResourceStream not existing with 2 arguments in
                // regular .Net-land
                StreamResourceInfo fileStream = Application.GetResourceStream(zipStream, part);
                StreamReader sr = new StreamReader(fileStream.Stream);
                string unzippedFile = sr.ReadToEnd();
                //Write it in a special way when using IsolatedStorage, due to IsolatedStorage
                //having a huge performance issue when writing small chunks
                IsolatedStorageFileStream isfs = GetFileStream(file, true);
                    
                char[] charBuffer = unzippedFile.ToCharArray();
                int fileSize = charBuffer.Length;
                byte[] byteBuffer = new byte[fileSize];
                for (int i = 0; i < fileSize; i++) byteBuffer[i] = (byte)charBuffer[i];
                isfs.Write(byteBuffer, 0, fileSize);
                isfs.Close();
#endif

                UpdateProgress(0, "Finished " + file + "...");
            }

#if !SILVERLIGHT
            zipFile.Close();
#endif
        }
Beispiel #15
0
        public void Load(string WorldDataLocation, string WorldName)
        {
            XPathDocument   _doc = new XPathDocument(WorldDataLocation.FormatDirectory() + WorldName + ".xml");
            XPathNavigator  _nav = _doc.CreateNavigator();
            XPathExpression _expr;

            _expr = _nav.Compile("/gg2world");

            XPathNodeIterator _Iter = _nav.Select(_expr);

            _Iter.MoveNext();

            var _Nav2 = _Iter.Current.Clone();

            WorldName = _Nav2.GetAttribute("worldname", "");

            _expr = _nav.Compile("/gg2world/screen");

            XPathNodeIterator _ScreenIterator = null; _Nav2 = null;

            _ScreenIterator = _nav.Select(_expr);

            ICSharpCode.SharpZipLib.Zip.ZipFile _Zip = new ICSharpCode.SharpZipLib.Zip.ZipFile(WorldDataLocation.FormatDirectory() + WorldName + "_Data.zip");


            while (_ScreenIterator.MoveNext())
            {
                var    _TmpScreenNavigator = _ScreenIterator.Current.Clone();
                string _tmpKey             = _TmpScreenNavigator.GetAttribute("key", "");

                #region Load the Images into Memory

                Point  _t         = ParseScreenKey(_tmpKey);
                Screen _NewScreen = new Screen(_t, this);

                var _IStream = _Zip.GetInputStream(_Zip.GetEntry("Back/" + _tmpKey + "_Back.png"));

                System.IO.MemoryStream _MemStream = ((System.IO.Stream)_IStream).ToMemoryStream();
                // Load The Texture in The TextureManager
                _TextureManager.LoadTexture(_tmpKey, _MemStream);

                _MemStream.Dispose();

                var _IPassStream = _Zip.GetInputStream(_Zip.GetEntry("Pass/" + _tmpKey + "_Pass.png"));
                _MemStream = ((System.IO.Stream)_IPassStream).ToMemoryStream();
                // Load The Texture in The TextureManager
                _TextureManager.LoadTexture(_tmpKey + "(PASS)", _MemStream);

                _MemStream.Dispose();

                #endregion

                var    _TmpPassableNavigator = _TmpScreenNavigator.SelectSingleNode("passablecompile");
                string _CompiledPassable     = _TmpPassableNavigator.Value;

                int PassableCompilePosition = 0;
                for (int x = 0; x < 800; x = x + 50)
                {
                    for (int y = 0; y < 600; y = y + 50)
                    {
                        bool _TmpBool = false;
                        if (_CompiledPassable.Substring(PassableCompilePosition, 1) == "1")
                        {
                            _TmpBool = true;
                        }

                        _NewScreen.PassableCompile.Add(new Point(x, y), _TmpBool);
                        PassableCompilePosition++;
                    }
                }

                #region Load the MapObjects
                //var _exprmo = .Compile("/mapobject");


                var _IterS = _TmpScreenNavigator.SelectChildren("mapobject", "");
                while (_IterS.MoveNext())
                {
                    MapObject _MO = new MapObject();

                    var _TmpNav2 = _IterS.Current.Clone();

                    string _DL = _TmpNav2.GetAttribute("drawlocation", "");
                    Point  _P  = new Point();
                    _MO.DrawLocation = _P.FromString(_DL);

                    _DL = _TmpNav2.GetAttribute("imagesize", "");
                    System.Drawing.Size _Sz = new System.Drawing.Size();
                    _MO.ImageSize = _Sz.ToXnaPoint(_DL);

                    _MO.Position     = (Enumerations.RelativePosition)Enum.Parse(typeof(Enumerations.RelativePosition), _TmpNav2.GetAttribute("position", ""));
                    _MO.ResourceName = _TmpNav2.GetAttribute("resourcename", "");

                    if (!_TextureManager.HasTexture(_MO.ResourceName))
                    {
                        var _IObjectStream = _Zip.GetInputStream(_Zip.GetEntry("Objects/" + _MO.ResourceName + "_Object.png"));
                        _MemStream = ((System.IO.Stream)_IObjectStream).ToMemoryStream();
                        // Load The Texture in The TextureManager
                        _TextureManager.LoadTexture(_MO.ResourceName, _MemStream);

                        _MemStream.Dispose();
                    }
                    _MO.ID = new Guid(_TmpNav2.GetAttribute("id", ""));

                    _NewScreen.MapObjects.Add(_MO.ID, _MO);
                }
                #endregion


                this._ScreenBuffer.Add(_t, _NewScreen);
            }
        }
Beispiel #16
0
        public static async Task <ClassBuilder?> ProcessFileAsync(Options options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var fileName = options.ApplicationTouchpanelPath;

            return(await Task.Run(async() =>
            {
                TouchpanelCore = new ClassBuilder(ClassType.Touchpanel);
                if ((!fileName.EndsWith(".vtz", StringComparison.OrdinalIgnoreCase) &&
                     !fileName.EndsWith("Environment.xml", StringComparison.OrdinalIgnoreCase) &&
                     !fileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase) &&
                     !fileName.EndsWith(".c3p", StringComparison.OrdinalIgnoreCase)
                     ) || !System.IO.File.Exists(fileName))
                {
                    return null;
                }

                var contents = "";
                if (fileName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase))
                {
                    contents = System.IO.File.ReadAllText(fileName);
                }
                else
                {
                    var zip = new ICSharpCode.SharpZipLib.Zip.ZipFile(fileName);
                    if (zip.FindEntry("swf/Environment.xml", true) > -1)
                    {
                        var entry = zip.GetEntry("swf/Environment.xml");
                        using (var reader = new System.IO.StreamReader(zip.GetInputStream(entry)))
                        {
                            contents = await reader.ReadToEndAsync();
                        }
                    }
                    else if (zip.FindEntry("Environment.xml", true) > -1)
                    {
                        var entry = zip.GetEntry("Environment.xml");
                        using (var reader = new System.IO.StreamReader(zip.GetInputStream(entry)))
                        {
                            contents = await reader.ReadToEndAsync();
                        }
                    }
                }

                if (string.IsNullOrEmpty(contents))
                {
                    return null;
                }


                var doc = XDocument.Parse(contents);

                TouchpanelCore.ClassName = doc?.Root?.Element("ObjectName")?.Value ?? "";
                TouchpanelCore.Namespace = options.RootNamespace;
                options.PanelNamespace = $"{options.RootNamespace}.{TouchpanelCore.ClassName}";

                // Projects potentially have a theme join.
                GenericParser.ParseTheme(doc?.Root?.Element("Properties"), TouchpanelCore);

                // Try to parse for background joins as well.
                GenericParser.ParseBackgroundJoins(doc?.Root?.Element("Properties"), TouchpanelCore);

                // Then we have to determine if there are hardkeys in play.
                if (options.ParseHardkeys)
                {
                    if (int.TryParse(doc?.Root?.Element("Properties")?.Element("Hardkeys")?.Element("NumHardkeys")?.Value, out var count) && count > 0)
                    {
                        var hardkeys = from hk in doc?.Root?.Element("Properties")?.Element("Hardkeys")?.Descendants()
                                       where hk?.Name == "Hardkey"
                                       select hk;
                        if (hardkeys.Any())
                        {
                            foreach (var hk in hardkeys)
                            {
                                var key = HardkeyParser.ParseElement(hk, options);
                                if (key != null)
                                {
                                    TouchpanelCore.AddJoin(key);
                                }
                            }
                        }
                    }
                }

                var pages = from p in doc?.Root?.Element("Properties")?.Element("Pages")?.Descendants()
                            where p?.Element("TargetControl")?.Value == "Page"
                            select p;
                var subpages = from sp in doc?.Root?.Element("Properties")?.Element("Pages")?.Descendants()
                               where sp?.Element("TargetControl")?.Value == "Subpage"
                               select sp;

                foreach (var page in pages)
                {
                    var pageBuilder = new ClassBuilder(ClassType.Page)
                    {
                        ClassName = page?.Element("ObjectName")?.Value ?? "",
                        NamespaceBase = $"{options.PanelNamespace}.Components"
                    };

                    if (pageBuilder.ClassName == "Subpage Reference" || pageBuilder.ClassName == "Page")
                    {
                        pageBuilder.ClassName = page?.Attribute("Name")?.Value ?? "";
                    }

                    if (string.IsNullOrEmpty(pageBuilder.ClassName))
                    {
                        throw new NullReferenceException("Unable to determine a name for a page or subpage reference.");
                    }

                    var props = page?.Element("Properties");

                    if (ushort.TryParse(props?.Element("DigitalJoin").Value, out var pageJoin) && pageJoin > 0)
                    {
                        pageBuilder.AddJoin(new JoinBuilder(pageJoin, pageBuilder.SmartJoin, "IsVisible", JoinType.Digital, JoinDirection.ToPanel));
                    }

                    if (props != null)
                    {
                        pageBuilder.DigitalOffset = GenericParser.ParseDigitalOffset(props);
                        pageBuilder.AnalogOffset = GenericParser.ParseAnalogOffset(props);
                        pageBuilder.SerialOffset = GenericParser.ParseSerialOffset(props);

                        GenericParser.ParseBackgroundJoins(props, pageBuilder);

                        var transitionJoin = GenericParser.GetTransitionCompleteJoin(props);
                        if (transitionJoin != null)
                        {
                            pageBuilder.AddJoin(transitionJoin);
                        }
                    }

                    var pageChildren = props?.Element("Children")?.Elements()?.Where(e => e?.Name.LocalName != "Subpage");
                    if (pageChildren != null)
                    {
                        foreach (var c in pageChildren)
                        {
                            GenericParser.ParseChildElement(c, pageBuilder);
                        }
                    }

                    var subpageCount = props?.Element("Children")?.Elements().Where(e => e.Name == "Subpage").Count();
                    if (subpageCount > 0)
                    {
                        foreach (var sp in page?.Element("Properties")?.Element("Children")?.Elements()?.Where(e => e.Name == "Subpage") ?? Array.Empty <XElement>())
                        {
                            var subElement = subpages.Where(sub => sub.Attribute("uid")?.Value == sp.Element("Properties")?.Element("PageID")?.Value).FirstOrDefault();
                            if (subElement == null)
                            {
                                continue;
                            }
                            var subBuilder = new ClassBuilder(ClassType.Page)
                            {
                                ClassName = sp?.Element("ObjectName")?.Value ?? "",
                                Namespace = pageBuilder.Namespace
                            };

                            if (subBuilder.ClassName == "Subpage Reference" || subBuilder.ClassName == "SubpageReference" || subBuilder.ClassName == "Page")
                            {
                                var rootSubpage = subpages.Where(s => (s.Attribute("uid")?.Value ?? "null1") == (sp?.Attribute("uid").Value ?? "null2")).FirstOrDefault();
                                subBuilder.ClassName = rootSubpage?.Attribute("Name")?.Value ?? "";
                            }

                            if (string.IsNullOrEmpty(subBuilder.ClassName))
                            {
                                throw new NullReferenceException("Unable to determine a name for a page or subpage reference.");
                            }

                            var subProps = sp?.Element("Properties");

                            if (subProps != null)
                            {
                                if (ushort.TryParse(subProps?.Element("DigitalJoin").Value, out var subpageJoin) && subpageJoin > 0)
                                {
                                    subBuilder.AddJoin(new JoinBuilder(subpageJoin, subBuilder.SmartJoin, "IsVisible", JoinType.Digital, JoinDirection.ToPanel));
                                }

                                subBuilder.DigitalOffset = GenericParser.ParseDigitalOffset(subProps);
                                subBuilder.AnalogOffset = GenericParser.ParseAnalogOffset(subProps);
                                subBuilder.SerialOffset = GenericParser.ParseSerialOffset(subProps);

                                var transitionJoin = GenericParser.GetTransitionCompleteJoin(subProps);

                                if (transitionJoin != null)
                                {
                                    subBuilder.AddJoin(transitionJoin);
                                }
                            }

                            subProps = subElement.Element("Properties");

                            if (subProps != null)
                            {
                                GenericParser.ParseBackgroundJoins(subProps, subBuilder);
                                if (subProps.Element("Children")?.Elements()?.Count() > 0)
                                {
                                    foreach (var c in subProps.Element("Children").Elements().Where(e => e.Name.LocalName != "Subpage"))
                                    {
                                        GenericParser.ParseChildElement(c, subBuilder);
                                    }
                                }
                            }

                            if (subBuilder.IsValid)
                            {
                                pageBuilder.AddPage(subBuilder);
                            }
                        }
                    }

                    TouchpanelCore.AddPage(pageBuilder);
                }

                return TouchpanelCore;
            }));
        }