public static string ConvertDateToString(this DateTime date, ConvertFormat format)
        {
            switch (format)
            {
            case ConvertFormat.YYYY_MM_DD:
                return(date.ToString("yyyy-MM-dd"));

            case ConvertFormat.YYYYMMDD:
                return(date.ToString("yyyyMMdd"));

            case ConvertFormat.HHMMSS:
                return(date.ToString("HHmmss"));

            case ConvertFormat.YYYY_S_MM_S_DD:
                return(date.ToString("yyyy/MM/dd"));

            case ConvertFormat.YYYYMMDDHHMMSS:
                return(date.ToString("yyyyMMddHHmmss"));

            case ConvertFormat.YYYY_DOT_MM_DOT_DD:
                return(date.ToString("yyy.MM.dd"));

            default:
                return(date.ToLongDateString());
            }
        }
 public void ConvertWithType()
 {
     using var format = new StringFormatTest("3");
     Assert.That(
         ConvertFormat.With(typeof(FormatTestDuplicatedConverter2), format),
         Is.EqualTo(3));
 }
Beispiel #3
0
        public static void TranslatePOwithAnotherPO(string BasePO, string TargetPo)
        {
            Po BPo = null, TPo = null;

            using (DataStream name = DataStreamFactory.FromFile(BasePO, FileOpenMode.Read))
                using (BinaryFormat binaryname = new BinaryFormat(name))
                {
                    BPo = (Po)ConvertFormat.With <Po2Binary>(binaryname);
                }

            using (DataStream name = DataStreamFactory.FromFile(TargetPo, FileOpenMode.Read))
                using (BinaryFormat binaryname = new BinaryFormat(name))
                {
                    TPo = (Po)ConvertFormat.With <Po2Binary>(binaryname);
                }

            foreach (PoEntry entryBPo in BPo.Entries)
            {
                foreach (PoEntry entryTPo in TPo.Entries)
                {
                    if (entryBPo.Original == entryTPo.Original && (entryBPo.Translated != null && entryBPo.Translated != ""))
                    {
                        entryTPo.Translated = entryBPo.Translated;

                        if (entryBPo.TranslatorComment != string.Empty && entryBPo.TranslatorComment != null && entryBPo.TranslatorComment.Trim() != "")
                        {
                            entryTPo.TranslatorComment = entryBPo.TranslatorComment;
                        }
                    }
                }
            }

            ConvertFormat.To <BinaryFormat>(TPo).Stream.WriteTo(TargetPo);
        }
Beispiel #4
0
        /// <summary>
        /// Transforms a Yarhl node using a chain of converters.
        /// </summary>
        /// <param name="node">The original node.</param>
        /// <param name="converters">Converters list.</param>
        /// <param name="parameters">Allowed parameters list.</param>
        public static void Transform(this Node node, List <ConverterInfo> converters, List <ParameterInfo> parameters)
        {
            var yarhlConverters = PluginManager.Instance.GetConverters().Select(x => x.Metadata).ToList();

            foreach (ConverterInfo converterInfo in converters)
            {
                ConverterMetadata metadata = yarhlConverters.Find(x => x.Name == converterInfo.TypeName);

                if (metadata == null)
                {
                    throw new UnknownConverterException($"Unknown converter: {converterInfo.TypeName}");
                }

                IConverter converter = (IConverter)Activator.CreateInstance(metadata.Type);

                System.Reflection.MethodInfo initializer = metadata.Type.GetMethod("Initialize");
                ParameterInfo parameter = parameters.Find(x => x.Id == converterInfo.ParameterId);
                if (initializer != null && parameter != null)
                {
                    _ = initializer.Invoke(converter, new object[] { parameter.Value });
                }

                node.ChangeFormat((IFormat)ConvertFormat.With(converter, node.Format));
            }
        }
        private static void CompressFiles(IEnumerable <Node> files, int compressorVersion)
        {
            var compressorParameters = new CompressorParameters
            {
                Endianness = 0x00,
                Version    = (byte)compressorVersion,
            };

            Parallel.ForEach(files, node =>
            {
                var parFile = node.GetFormatAs <ParFile>();
                if (parFile == null || !parFile.CanBeCompressed || compressorVersion == 0x00 ||
                    parFile.Stream.Length == 0)
                {
                    return;
                }

                FileCompressing?.Invoke(node);
                var compressed =
                    (ParFile)ConvertFormat.With <Compressor, CompressorParameters>(compressorParameters, parFile);

                long diff = parFile.Stream.Length - compressed.Stream.Length;
                if (diff >= 0 && (parFile.Stream.Length < 2048 || diff >= 2048))
                {
                    node.ChangeFormat(compressed);
                }

                FileCompressed?.Invoke(node);
            });
        }
 public void ConvertWithInit()
 {
     using var format = new StringFormatTest("3");
     Assert.That(
         ConvertFormat.With <HiddenConverter, int>(4, format),
         Is.EqualTo(7));
 }
Beispiel #7
0
        public NodeContainerFormat Convert(BinaryFormat source)
        {
            var container = new NodeContainerFormat();

            var po = new Po {
                Header = new PoHeader("Jump Ultimate Stars", "TranScene", "es")
                {
                    LanguageTeam = "TranScene",
                }
            };

            var reader = new DataReader(source.Stream)
            {
                DefaultEncoding = Encoding.GetEncoding("shift_jis"),
            };

            JusData.reader         = reader;
            reader.Stream.Position = 0x00;
            BinaryFormat poBin;
            var          mangaIndex   = MangaIndex.getInstance();
            int          numQuestions = reader.ReadInt32();

            string currentManga = mangaIndex.getMangaName(0xFF);
            int    mangaCount   = 0;

            for (int i = 0; i < numQuestions; i++)
            {
                var q = JquizData.readData();
                if (q.manga != currentManga)
                {
                    poBin = ConvertFormat.With <Po2Binary>(po) as BinaryFormat;
                    container.Root.Add(new Node($"jquiz-{mangaCount}-{currentManga}.po", poBin));
                    po = new Po {
                        Header = new PoHeader("Jump Ultimate Stars", "TranScene", "es")
                        {
                            LanguageTeam = "TranScene",
                        }
                    };
                    mangaCount++;
                    currentManga = q.manga;
                }
                po.Add(new PoEntry(q.question)
                {
                    Context           = $"{i} - Question",
                    ExtractedComments = $"{q.photo}-{q.mangaCode}-{q.unknown}-{q.num}"
                });
                for (int j = 0; j < q.answers.Length; j++)
                {
                    po.Add(new PoEntry(q.answers[j])
                    {
                        Context = $"{i} - Answer {j}"
                    });
                }
            }

            poBin = ConvertFormat.With <Po2Binary>(po) as BinaryFormat;
            container.Root.Add(new Node($"jquiz-{mangaCount}-{currentManga}.po", poBin));

            return(container);
        }
 public void ConvertWithGeneric()
 {
     using var format = new StringFormatTest("3");
     Assert.That(
         ConvertFormat.With <FormatTestDuplicatedConverter1>(format),
         Is.EqualTo(3));
 }
Beispiel #9
0
        public void ConvertBasicHeaderNoEntries()
        {
            var po = new Po(new PoHeader("myId", "yo", "es")
            {
                CreationDate = "today"
            });
            string text = @"msgid """"
msgstr """"
""Project-Id-Version: myId\n""
""Report-Msgid-Bugs-To: yo\n""
""POT-Creation-Date: today\n""
""PO-Revision-Date: \n""
""Last-Translator: \n""
""Language-Team: \n""
""Language: es\n""
""MIME-Version: 1.0\n""
""Content-Type: text/plain; charset=UTF-8\n""
""Content-Transfer-Encoding: 8bit\n""
";

            text = text.Replace("\r\n", "\n");

            var newPo = ConvertStringToPo(text);

            CompareText(ConvertFormat.To <BinaryFormat>(po), text);
            Assert.AreEqual(po.Header.ProjectIdVersion, newPo.Header.ProjectIdVersion);
            Assert.AreEqual(po.Header.ReportMsgidBugsTo, newPo.Header.ReportMsgidBugsTo);
            Assert.AreEqual(po.Header.CreationDate, newPo.Header.CreationDate);
            Assert.AreEqual(po.Header.Language, newPo.Header.Language);
            Assert.IsEmpty(newPo.Header.LastTranslator);
            Assert.IsEmpty(newPo.Entries);
        }
Beispiel #10
0
        public void ConvertNoHeaderEntries()
        {
            var testPo = new Po();

            testPo.Add(new PoEntry {
                Original = "original"
            });
            testPo.Add(new PoEntry {
                Original = "totranslate", Translated = "translated"
            });

            string text = @"
msgid ""original""
msgstr """"

msgid ""totranslate""
msgstr ""translated""
";

            text = text.Replace("\r\n", "\n");
            var newPo = ConvertStringToPo(text);

            CompareText(ConvertFormat.To <BinaryFormat>(testPo), text);
            Assert.IsNull(newPo.Header);
            Assert.AreEqual(2, newPo.Entries.Count);
        }
Beispiel #11
0
 public void ConvertWithTypeThrowsIfNoImplementIConverter()
 {
     using var format = new StringFormatTest("3");
     Assert.That(
         () => ConvertFormat.With(typeof(DateTime), format),
         Throws.InvalidOperationException.With.Message.EqualTo(
             $"Cannot find converter {typeof(DateTime).FullName}"));
 }
Beispiel #12
0
 public void ConvertWithTypeThrowsIfConverterNotFound()
 {
     using var format = new StringFormatTest("3");
     Assert.That(
         () => ConvertFormat.With(typeof(HiddenConverter), format),
         Throws.InvalidOperationException.With.Message.EqualTo(
             $"Cannot find converter {typeof(HiddenConverter).FullName}"));
 }
Beispiel #13
0
        static Po ConvertStringToPo(string binary)
        {
            using BinaryFormat textFormat = new BinaryFormat();
            new TextWriter(textFormat.Stream).Write(binary);
            textFormat.Stream.Position = 0;

            return(ConvertFormat.To <Po>(textFormat));
        }
Beispiel #14
0
        public void ConvertToWithTypeThrowsIfTypeIsNull()
        {
            Type dstType = null;

            Assert.That(
                () => ConvertFormat.To(dstType, "3"),
                Throws.ArgumentNullException);
        }
Beispiel #15
0
 public void ConvertToThrowsIfSrcIsNull()
 {
     Assert.That(
         () => ConvertFormat.To <int>(null),
         Throws.ArgumentNullException);
     Assert.That(
         () => ConvertFormat.To(typeof(int), null),
         Throws.ArgumentNullException);
 }
Beispiel #16
0
        public void ConvertWithInstanceThrowsIfConverterIsNull()
        {
            var             format    = new StringFormatTest("3");
            HiddenConverter converter = null;

            Assert.That(
                () => ConvertFormat.With(converter, format),
                Throws.ArgumentNullException);
        }
Beispiel #17
0
        public void ConvertWithInstance()
        {
            var format    = new StringFormatTest("3");
            var converter = new HiddenConverter();

            Assert.That(
                ConvertFormat.With(converter, format),
                Is.EqualTo(3));
        }
Beispiel #18
0
        public void ConvertWithTypeThrowsIfTypeIsNull()
        {
            var  format = new StringFormatTest("3");
            Type type   = null;

            Assert.That(
                () => ConvertFormat.With(type, format),
                Throws.ArgumentNullException);
        }
Beispiel #19
0
        public void ConvertFromBaseWithDerivedConverterThrows()
        {
            // We cannot do the inverse, from base type use the derived converter
            Base val = new Base {
                X = 3
            };

            Assert.Throws <InvalidOperationException>(
                () => ConvertFormat.To <ushort>(val));
        }
Beispiel #20
0
        public void ConvertFromDerivedWithBaseConverter()
        {
            var format = new Derived {
                Y = 11, X = 10
            };
            int conv = 0;

            Assert.DoesNotThrow(() => conv = ConvertFormat.To <int>(format));
            Assert.AreEqual(15, conv);
        }
Beispiel #21
0
        public void ConvertToThrowsIfNoConverter()
        {
            var ex = Assert.Throws <InvalidOperationException>(() =>
                                                               ConvertFormat.To(typeof(short), (short)3));

            Assert.AreEqual(
                "Cannot find converter for: " +
                $"{typeof(short).FullName} -> {typeof(short).FullName}",
                ex.Message);
        }
Beispiel #22
0
        public void ConvertToThrowsIfThereAreTwoEqualConverters()
        {
            var test = new StringFormatTest("3");
            var ex   = Assert.Throws <InvalidOperationException>(() =>
                                                                 ConvertFormat.To(typeof(short), test));

            Assert.AreEqual(
                "Multiple converters for: " +
                $"{typeof(StringFormatTest).FullName} -> {typeof(short).FullName}",
                ex.Message);
        }
Beispiel #23
0
        public void ConvertFromImplementationWithInterfaceConverter()
        {
            var format = new InterfaceImpl {
                Z = 14
            };
            int conv = 0;

            Assert.DoesNotThrow(() => conv = (int)ConvertFormat.With <ConverterInterface>(format));
            Assert.AreEqual(14, conv);

            Assert.DoesNotThrow(() => conv = ConvertFormat.To <int>(format));
            Assert.AreEqual(14, conv);
        }
Beispiel #24
0
        /// <summary>
        /// Create a SLLZ compressed BinaryFormat.
        /// </summary>
        /// <param name="source">original format.</param>
        /// <returns>The compressed binary.</returns>
        public ParFile Convert(BinaryFormat source)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            return(_compressorParameters.CompressionType switch
            {
                CompressionType.Standard => (ParFile)ConvertFormat.With <CompressStandard, CompressorParameters>(_compressorParameters, source),
                CompressionType.Zlib => (ParFile)ConvertFormat.With <CompressZlib, CompressorParameters>(_compressorParameters, source),
                _ => throw new FormatException($"SLLZ: Bad Compression Type ({_compressorParameters.CompressionType})")
            });
Beispiel #25
0
        /// <summary>
        /// Reads a format from this stream.
        /// </summary>
        /// <returns>The format read.</returns>
        /// <typeparam name="T">The type of the format to read.</typeparam>
        public T ReadFormat <T>()
        {
            if (Disposed)
            {
                throw new ObjectDisposedException(nameof(DataStream));
            }

            T format;

            using (var binary = new BinaryFormat(this))
                format = ConvertFormat.To <T>(binary);
            return(format);
        }
Beispiel #26
0
        public void ConvertToDerivedWithDerivedConverter()
        {
            // Just to validate converter, derived with derived converter
            Derived derived = null;

            Assert.DoesNotThrow(() => derived = ConvertFormat.To <Derived>((ushort)4));
            Assert.AreEqual(5, derived.Y);
            Assert.AreEqual(4, derived.X);

            ushort conv = 0;

            Assert.DoesNotThrow(() => conv = ConvertFormat.To <ushort>(derived));
            Assert.AreEqual(5, conv);
        }
Beispiel #27
0
        public void ConvertFullHeaderNoEntries()
        {
            var header = new PoHeader("myId", "yo", "SC")
            {
                CreationDate   = "today",
                RevisionDate   = "tomorrow",
                LastTranslator = "she",
                LanguageTeam   = "bestteam",
                PluralForms    = "pl",
            };

            header.Extensions["Generator"] = "yarhl";
            header.Extensions["Hey"]       = "hoy";

            var testPo = new Po(header);

            string text = @"msgid """"
msgstr """"
""Project-Id-Version: myId\n""
""Report-Msgid-Bugs-To: yo\n""
""POT-Creation-Date: today\n""
""PO-Revision-Date: tomorrow\n""
""Last-Translator: she\n""
""Language-Team: bestteam\n""
""Language: SC\n""
""MIME-Version: 1.0\n""
""Content-Type: text/plain; charset=UTF-8\n""
""Content-Transfer-Encoding: 8bit\n""
""Plural-Forms: pl\n""
""X-Generator: yarhl\n""
""X-Hey: hoy\n""
";

            text = text.Replace("\r\n", "\n");
            var newPo     = ConvertStringToPo(text);
            var newHeader = newPo.Header;

            CompareText(ConvertFormat.To <BinaryFormat>(testPo), text);
            Assert.AreEqual(header.ProjectIdVersion, newHeader.ProjectIdVersion);
            Assert.AreEqual(header.ReportMsgidBugsTo, newHeader.ReportMsgidBugsTo);
            Assert.AreEqual(header.CreationDate, newHeader.CreationDate);
            Assert.AreEqual(header.RevisionDate, newHeader.RevisionDate);
            Assert.AreEqual(header.LastTranslator, newHeader.LastTranslator);
            Assert.AreEqual(header.LanguageTeam, newHeader.LanguageTeam);
            Assert.AreEqual(header.Language, newHeader.Language);
            Assert.AreEqual(header.PluralForms, newHeader.PluralForms);
            Assert.That(header.Extensions["Generator"], Is.EqualTo(newHeader.Extensions["Generator"]));
            Assert.That(header.Extensions["Hey"], Is.EqualTo(newHeader.Extensions["Hey"]));
            Assert.IsEmpty(newPo.Entries);
        }
Beispiel #28
0
        public void ConvertToBaseWithDerivedConverter()
        {
            // It should use the converter: ushort -> Derived
            // The converter will generate a derived type and will cast-down
            // to base.
            Base val = null;

            Assert.DoesNotThrow(() => val = ConvertFormat.To <Base>((ushort)3));
            Assert.IsInstanceOf <Derived>(val);
            Assert.AreEqual(3, val.X);

            Assert.DoesNotThrow(() => val = ConvertFormat.To <Base>((int)3));
            Assert.IsInstanceOf <Base>(val);
            Assert.AreEqual(5, val.X);
        }
Beispiel #29
0
        private static void ImportDig(Node nDIG, Node nATM, Node nPNG, string outputPath)
        {
            log.Info("Importing " + nDIG.Name + ", " + nATM.Name + " and " + nPNG.Name);

            DIG  originalDig = nDIG.TransformWith <Binary2DIG>().GetFormatAs <DIG>();
            ALMT originalAtm = nATM.TransformWith <Binary2ALMT>().GetFormatAs <ALMT>();

            // New stream
            var stream     = new MemoryStream();
            var dataStream = DataStreamFactory.FromStreamKeepingOwnership(stream, 0, 0);

            // Copy the png to the bitmap stream
            nPNG.Stream.WriteTo(dataStream);

            // Import the new PNG file
            Bitmap newImage = (Bitmap)Image.FromStream(stream);

            var         quantization = new FixedPaletteQuantization(originalDig.Palette.GetPalette(0));
            ColorFormat format;

            if (originalDig.PaletteType == 16)
            {
                format = ColorFormat.Indexed_4bpp;
            }
            else
            {
                format = ColorFormat.Indexed_8bpp;
            }

            Texim.ImageMapConverter importer = new Texim.ImageMapConverter
            {
                Format        = format,
                PixelEncoding = PixelEncoding.HorizontalTiles,
                Quantization  = quantization,
                //Mapable = new MatchMapping(originalDig.Pixels.GetPixels())
            };

            (Palette _, PixelArray pixelInfo, MapInfo[] mapInfos) = importer.Convert(newImage);

            originalDig.Pixels = pixelInfo;
            originalAtm.Info   = mapInfos;

            BinaryFormat bDig = (BinaryFormat)ConvertFormat.With <Binary2DIG>(originalDig);
            BinaryFormat bAtm = (BinaryFormat)ConvertFormat.With <Binary2ALMT>(originalAtm);

            Utils.Lzss(bDig, "-evn").Stream.WriteTo(Path.Combine(outputPath, nDIG.Name + ".evn.dig"));
            bAtm.Stream.WriteTo(Path.Combine(outputPath, nATM.Name + ".atm"));
        }
Beispiel #30
0
        public void ConvertWithThrowsIfFormatIsNull()
        {
            StringFormatTest format = null;

            Assert.That(
                () => ConvertFormat.With <HiddenConverter>(format),
                Throws.ArgumentNullException);
            Assert.That(
                () => ConvertFormat.With <HiddenConverter, int>(4, format),
                Throws.ArgumentNullException);

            var converter = new HiddenConverter();

            Assert.That(
                () => ConvertFormat.With(converter, format),
                Throws.ArgumentNullException);
        }
Beispiel #31
0
 /// <summary>
 /// Convert The current Image to the specified format
 /// </summary>
 /// <param name="format">The destination format of the new image</param>
 /// <returns></returns>
 public FreeImage ConvertTo(ConvertFormat format)
 {
     switch (format)
     {
         case ConvertFormat.Bits4:
             return new FreeImage(FreeImageApi.ConvertTo4Bits(this.m_Handle));
         case ConvertFormat.Bits8:
             return new FreeImage(FreeImageApi.ConvertTo8Bits(this.m_Handle));
         case ConvertFormat.Bits16_565:
             return new FreeImage(FreeImageApi.ConvertTo16Bits565(this.m_Handle));
         case ConvertFormat.Bits16_555:
             return new FreeImage(FreeImageApi.ConvertTo16Bits555(this.m_Handle));
         case ConvertFormat.Bits24:
             return new FreeImage(FreeImageApi.ConvertTo24Bits(this.m_Handle));
         case ConvertFormat.Bits32:
             return new FreeImage(FreeImageApi.ConvertTo32Bits(this.m_Handle));
     }
     return null;
 }