示例#1
0
        public void Returns_empty_for_empty_string()
        {
            var i = StringsFile.GetString("", out var str);

            Assert.AreEqual(0, i);
            Assert.AreEqual("", str);
        }
示例#2
0
        static void Main(string[] args)
        {
            StringsFile.CreateFileIfNotExist();
            WordsDicionary wordsDictionary = new WordsDicionary(StringsFile.ReadLines());

            Console.Write("Search for a word (5 alphnumeric characters) >> ");
            string word = Console.ReadLine();

            while (word != "exit") //change to string compaee
            {
                if (word.Length != 5)
                {
                    Console.WriteLine("Word's length must be exactly 5 alphanumerical characters!");
                }
                else if (!r.IsMatch(word))
                {
                    Console.WriteLine("Word must contains alphanumerical characters only!");
                }
                else
                {
                    int    matchesCnt = wordsDictionary.FindMathces(word);
                    string matchStr   = matchesCnt == 0 ? "was not found in file." : $"was found in the file {matchesCnt} times.";
                    Console.WriteLine($"Word \"{word}\" (or equivalents) {matchStr}");
                }

                Console.Write("Search for a word (5 alphnumeric characters) >> ");
                word = Console.ReadLine();
            }
        }
示例#3
0
        public void Parses_strings(string line, string expected, int end)
        {
            var i = StringsFile.GetString(line, out var str);

            Assert.AreEqual(end, i);
            Assert.AreEqual(expected, str);
        }
示例#4
0
 public string GetPropertyValueAsString(string name, StringsFile stringsFile)
 {
     if (_propertyValues[name].Type == "LocalizedString" && stringsFile != null)
     {
         uint   key = (uint)_propertyValues[name].Value;
         string value;
         if (!stringsFile.Texts.TryGetValue(key, out value))
         {
             return("<string " + key + " not found>");
         }
         return("\"" + stringsFile.Texts[key] + "\"");
     }
     return(_propertyValues[name].ToString());
 }
示例#5
0
        public static bool CookStringFile(string stringPath)
        {
            byte[] stringsBuffer = null;
            try
            {
                stringsBuffer = File.ReadAllBytes(stringPath);
            }
            catch (Exception ex)
            {
                ExceptionLogger.LogException(ex);
                Console.WriteLine(String.Format("Error reading file {0}", stringPath));
                return(false);
            }

            StringsFile stringsFile = new StringsFile(stringsBuffer, Path.GetFileName(stringPath).ToUpper());

            if (stringsFile.HasIntegrity == false)
            {
                Console.WriteLine(String.Format("Failed to parse strings file {0}", stringPath));
                return(false);
            }

            Console.WriteLine(String.Format("Cooking {0}", Path.GetFileNameWithoutExtension(stringPath)));
            stringsBuffer = stringsFile.ToByteArray();
            if (stringsBuffer == null)
            {
                Console.WriteLine(String.Format("Failed to serialize strings file {0}", stringsFile.StringId));
                return(false);
            }

            String writeToPath = stringPath + ".cooked";

            try
            {
                File.WriteAllBytes(writeToPath, stringsBuffer);
            }
            catch (Exception ex)
            {
                ExceptionLogger.LogException(ex);
                Console.WriteLine(String.Format("Failed to write cooked file {0} ", writeToPath));
                return(false);
            }

            return(true);
        }
示例#6
0
        private void OnLoadStrings(object sender, EventArgs e)
        {
            if (openStringsDialog.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }

            StringsFile = new StringsFile();
            var openFile = openStringsDialog.OpenFile();

            try
            {
                StringsFile.Deserialize(openFile);
            }
            finally
            {
                openFile.Close();
            }
        }
示例#7
0
        public static void Main(string[] args)
        {
            var  mode     = Mode.Unknown;
            bool force    = false;
            bool showHelp = false;

            var options = new OptionSet()
            {
                {
                    "d|decode",
                    "decode strings file",
                    v =>
                    {
                        if (v != null)
                        {
                            mode = Mode.Decode;
                        }
                    }
                },
                {
                    "f|force",
                    "force decode strings file even when strings hash is not correct",
                    v => force = v != null
                },
                {
                    "e|encode",
                    "encode strings file",
                    v =>
                    {
                        if (v != null)
                        {
                            mode = Mode.Encode;
                        }
                    }
                },
                {
                    "h|help",
                    "show this message and exit",
                    v => showHelp = v != null
                },
            };

            List <string> extras;

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

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

            if (mode == Mode.Decode)
            {
                string inputPath  = extras[0];
                string outputPath = extras.Count > 1 ? extras[1] : Path.ChangeExtension(inputPath, ".xml");

                using (var input = File.OpenRead(inputPath))
                {
                    var strings = new StringsFile();
                    strings.Deserialize(input);

                    if (strings.HasStringsHash == true &&
                        strings.StringsHashIsCorrect == false)
                    {
                        if (force == false)
                        {
                            Console.WriteLine("Error: strings hash mismatch! ({0} vs {1})",
                                              strings.StringsHash,
                                              strings.ComputedStringsHash);
                            return;
                        }

                        Console.WriteLine("Warning: strings hash mismatch! ({0} vs {1})",
                                          strings.StringsHash,
                                          strings.ComputedStringsHash);
                    }

                    var settings = new XmlWriterSettings()
                    {
                        Indent          = true,
                        CheckCharacters = false,
                    };

                    using (var output = XmlWriter.Create(outputPath, settings))
                    {
                        output.WriteStartDocument();
                        output.WriteStartElement("strings");
                        output.WriteAttributeString("version", strings.Version.ToString(CultureInfo.InvariantCulture));
                        output.WriteAttributeString("encryption_key",
                                                    strings.EncryptionKey.ToString(CultureInfo.InvariantCulture));

                        output.WriteStartElement("keys");
                        foreach (var kv in strings.Keys)
                        {
                            output.WriteStartElement("key");
                            output.WriteAttributeString("id", kv.Key);
                            output.WriteValue(kv.Value);
                            output.WriteEndElement();
                        }
                        output.WriteEndElement();

                        output.WriteStartElement("texts");
                        foreach (var kv in strings.Texts)
                        {
                            output.WriteStartElement("text");
                            output.WriteAttributeString("id", kv.Key.ToString(CultureInfo.InvariantCulture));
                            output.WriteValue(kv.Value);
                            output.WriteEndElement();
                        }
                        output.WriteEndElement();

                        output.WriteEndElement();
                        output.WriteEndDocument();
                    }
                }
            }
            else if (mode == Mode.Encode)
            {
                string inputPath  = extras[0];
                string outputPath = extras.Count > 1 ? extras[1] : Path.ChangeExtension(inputPath, ".w2strings");

                using (var input = File.OpenRead(inputPath))
                {
                    var doc = new XPathDocument(input);
                    var nav = doc.CreateNavigator();

                    var root = nav.SelectSingleNode("/strings");
                    if (root == null)
                    {
                        throw new FormatException();
                    }

                    var strings = new StringsFile
                    {
                        Version       = uint.Parse(root.GetAttribute("version", "")),
                        EncryptionKey = uint.Parse(root.GetAttribute("encryption_key", "")),
                    };

                    var keys = root.Select("keys/key");
                    strings.Keys.Clear();
                    while (keys.MoveNext() == true)
                    {
                        if (keys.Current == null)
                        {
                            throw new InvalidOperationException();
                        }

                        strings.Keys.Add(
                            keys.Current.GetAttribute("id", ""),
                            uint.Parse(keys.Current.Value));
                    }

                    var texts = root.Select("texts/text");
                    strings.Texts.Clear();
                    while (texts.MoveNext() == true)
                    {
                        if (texts.Current == null)
                        {
                            throw new InvalidOperationException();
                        }

                        var value = texts.Current.Value;
                        value = value.Replace("\r\n", "\n");
                        value = value.Replace("\r", "");

                        strings.Texts.Add(
                            uint.Parse(texts.Current.GetAttribute("id", "")),
                            value);
                    }

                    using (var output = File.Create(outputPath))
                    {
                        strings.Serialize(output);
                    }
                }
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
示例#8
0
        private void LoadConverters()
        {
            ScriptActions.AddConverter(new FormatConverter
            {
                Key         = "script_cxml",
                Title       = "Custom XML",
                Extension   = "xml",
                ExportEvent = (MemoryStream ms, bool escape) =>
                {
                    try
                    {
                        Dictionary <string, object> root = new ScriptData(new BinaryReader(ms), Utils.IsRaid()).Root;
                        return(new CustomXMLNode("table", root, "").ToString(0, escape));
                    } catch (Exception e)
                    {
                        MessageBox.Show($"Failed to read scriptdata: \n {e.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        return(null);
                    }
                },
                Type = "scriptdata"
            });

            //Temporary until I get source code of this DLL, hopefully.
            ScriptActions.AddConverter(new FormatConverter
            {
                Key               = "stream",
                Title             = "Stream to Wav",
                RequiresAttention = false,
                Extension         = "wav",
                Type              = "stream",
                SaveEvent         = (Stream stream, string toPath) =>
                {
                    WavFile file = new WavFile(stream);
                    WavProcessor.ConvertToPCM(file);
                    file.WriteFile(toPath);
                },
            });

            ScriptActions.AddConverter(new FormatConverter
            {
                Key         = "diesel_strings",
                Title       = "Diesel",
                Extension   = "strings",
                ImportEvent = (path) => new StringsFile(path),
                Type        = "strings"
            });

            ScriptActions.AddConverter(new FormatConverter
            {
                Key               = "movie",
                Title             = "Bink Video",
                Extension         = "bik",
                Type              = "movie",
                RequiresAttention = false
            });

            //Loop each XML format to have it automatically get .xml suffix

            ScriptActions.AddConverter(new FormatConverter
            {
                Key               = "xmL_conversion",
                Type              = "text",
                Extension         = "xml",
                RequiresAttention = false
            });

            ScriptActions.AddConverter(new FormatConverter
            {
                Key               = "texture_dds",
                Title             = "DDS",
                Extension         = "dds",
                Type              = "texture",
                RequiresAttention = false
            });

            ScriptActions.AddConverter(new FormatConverter
            {
                Key         = "strings_csv",
                Title       = "CSV",
                Extension   = "csv",
                ExportEvent = (MemoryStream ms, bool arg0) =>
                {
                    //Excel doesn't seem to like it?
                    StringsFile str       = new StringsFile(ms);
                    StringBuilder builder = new StringBuilder();
                    builder.Append("ID,String\n");
                    foreach (var entry in str.LocalizationStrings)
                    {
                        builder.Append("\"" + entry.ID.ToString() + "\",\"" + entry.Text + "\"\n");
                    }
                    Console.WriteLine(builder.ToString());
                    return(builder.ToString());
                },
                Type = "strings"
            });

            ScriptActions.AddConverter(new FormatConverter
            {
                Key         = "script_json",
                Title       = "JSON",
                Extension   = "json",
                ExportEvent = (MemoryStream ms, bool arg0) =>
                {
                    try
                    {
                        ScriptData sdata = new ScriptData(new BinaryReader(ms), Utils.IsRaid());
                        return((new JSONNode("table", sdata.Root, "")).ToString());
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show($"Failed to read scriptdata: \n {e.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        return(null);
                    }
                },
                Type = "scriptdata"
            });

            ScriptActions.AddConverter(new FormatConverter
            {
                Key         = "strings_json",
                Title       = "JSON",
                Extension   = "json",
                ExportEvent = (MemoryStream ms, bool arg0) =>
                {
                    StringsFile str       = new StringsFile(ms);
                    StringBuilder builder = new StringBuilder();
                    builder.Append("{\n");
                    for (int i = 0; i < str.LocalizationStrings.Count; i++)
                    {
                        StringEntry entry = str.LocalizationStrings[i];
                        builder.Append("\t");
                        builder.Append("\"" + entry.ID + "\" : \"" + entry.Text + "\"");
                        if (i < str.LocalizationStrings.Count - 1)
                        {
                            builder.Append(",");
                        }
                        builder.Append("\n");
                    }
                    builder.Append("}");
                    Console.WriteLine(builder.ToString());
                    return(builder.ToString());
                },
                Type = "strings"
            });
        }
示例#9
0
 public string GetPropertyValueAsString(string name, StringsFile stringsFile)
 {
     if (_propertyValues[name].Type == "LocalizedString" && stringsFile != null)
     {
         uint key = (uint) _propertyValues[name].Value;
         string value;
         if (!stringsFile.Texts.TryGetValue(key, out value))
         {
             return "<string " + key + " not found>";
         }
         return "\"" + stringsFile.Texts[key] + "\"";
     }
     return _propertyValues[name].ToString();
 }
示例#10
0
        public void LoadConverters()
        {
            FormatConverter cXML = new FormatConverter()
            {
                Key       = "script_cxml",
                Title     = "Custom XML",
                Extension = "xml",
                Type      = "scriptdata"
            };

            cXML.ExportEvent += (MemoryStream ms, bool escape) =>
            {
                return(new CustomXMLNode("table", (Dictionary <string, object>) new ScriptData(new BinaryReader(ms)).Root, "").ToString(0, escape));
            };

            ScriptActions.AddConverter(cXML);

            FormatConverter Strings = new FormatConverter()
            {
                Key       = "diesel_strings",
                Title     = "Diesel",
                Extension = "strings",
                Type      = "strings"
            };

            Strings.ImportEvent += (path) => new StringsFile(path);
            ScriptActions.AddConverter(Strings);

            /*ScriptActions.AddConverter(new FormatConverter()
             * {
             *  Key = "texture_dds",
             *  Title = "DDS",
             *  Extension = "dds",
             *  Type = "texture"
             * });*/

            FormatConverter stringsCSV = new FormatConverter()
            {
                Key       = "strings_csv",
                Title     = "CSV",
                Extension = "csv",
                Type      = "strings"
            };

            //Excel doesn't seem to like it?
            stringsCSV.ExportEvent += (MemoryStream ms, bool arg0) =>
            {
                StringsFile   str     = new StringsFile(ms);
                StringBuilder builder = new StringBuilder();
                builder.Append("ID,String\n");
                foreach (var entry in str.LocalizationStrings)
                {
                    builder.Append("\"" + entry.ID.ToString() + "\",\"" + entry.Text + "\"\n");
                }
                Console.WriteLine(builder.ToString());
                return(builder.ToString());
            };

            ScriptActions.AddConverter(stringsCSV);

            FormatConverter scriptJSON = new FormatConverter()
            {
                Key       = "script_json",
                Title     = "JSON",
                Extension = "json",
                Type      = "scriptdata"
            };

            scriptJSON.ExportEvent += (MemoryStream ms, bool arg0) =>
            {
                ScriptData sdata = new ScriptData(new BinaryReader(ms));
                return((new JSONNode("table", sdata.Root, "")).ToString());
            };

            ScriptActions.AddConverter(scriptJSON);

            FormatConverter stringsJSON = new FormatConverter()
            {
                Key       = "strings_json",
                Title     = "JSON",
                Extension = "json",
                Type      = "strings"
            };

            //Excel doesn't seem to like it?
            stringsJSON.ExportEvent += (MemoryStream ms, bool arg0) =>
            {
                StringsFile   str     = new StringsFile(ms);
                StringBuilder builder = new StringBuilder();
                builder.Append("{\n");
                for (int i = 0; i < str.LocalizationStrings.Count; i++)
                {
                    StringEntry entry = str.LocalizationStrings[i];
                    builder.Append("\t");
                    builder.Append("\"" + entry.ID + "\" : \"" + entry.Text + "\"");
                    if (i < str.LocalizationStrings.Count - 1)
                    {
                        builder.Append(",");
                    }
                    builder.Append("\n");
                }
                builder.Append("}");
                Console.WriteLine(builder.ToString());
                return(builder.ToString());
            };

            ScriptActions.AddConverter(stringsJSON);

            FormatConverter stringsView = new FormatConverter()
            {
                Key       = "strings_view",
                Title     = "Strings view",
                Extension = "strings",
                Type      = "strings"
            };

            //Excel doesn't seem to like it?
            stringsView.ExportEvent += (MemoryStream ms, bool arg0) =>
            {
                new StringViewer(ms).Show();
                return(ms);
            };

            ScriptActions.AddConverter(stringsView);
        }
示例#11
0
 public void Throws_for_null()
 {
     Assert.ThrowsException <ArgumentNullException> (() => StringsFile.GetString(null, out var str));
 }
示例#12
0
 public StringViewer(Stream str) : this()
 {
     this.Strings = new StringsFile(str);
 }
示例#13
0
 public StringViewer(string file) : this()
 {
     this.Strings = new StringsFile(file);
 }
示例#14
0
 public StringViewer(StringsFile strFile) : this()
 {
     this.Strings = strFile;
 }