/// <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)); } }
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); }
public void ConvertWithInit() { using var format = new StringFormatTest("3"); Assert.That( ConvertFormat.With <HiddenConverter, int>(4, format), Is.EqualTo(7)); }
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 ConvertWithType() { using var format = new StringFormatTest("3"); Assert.That( ConvertFormat.With(typeof(FormatTestDuplicatedConverter2), format), Is.EqualTo(3)); }
public void ConvertWithGeneric() { using var format = new StringFormatTest("3"); Assert.That( ConvertFormat.With <FormatTestDuplicatedConverter1>(format), Is.EqualTo(3)); }
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 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}")); }
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}")); }
public void ConvertWithTypeThrowsIfTypeIsNull() { var format = new StringFormatTest("3"); Type type = null; Assert.That( () => ConvertFormat.With(type, format), Throws.ArgumentNullException); }
public void ConvertWithInstance() { var format = new StringFormatTest("3"); var converter = new HiddenConverter(); Assert.That( ConvertFormat.With(converter, format), Is.EqualTo(3)); }
public void ConvertWithInstanceThrowsIfConverterIsNull() { var format = new StringFormatTest("3"); HiddenConverter converter = null; Assert.That( () => ConvertFormat.With(converter, format), Throws.ArgumentNullException); }
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)); Assert.Throws <InvalidOperationException>( () => ConvertFormat.With <ConvertDerived>(val)); }
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); Assert.DoesNotThrow(() => conv = (int)ConvertFormat.With <ConvertBase>(format)); Assert.AreEqual(15, conv); }
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); }
/// <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})") });
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")); }
/// <summary> /// Transform the node format to another format with a given converter. /// </summary> /// <returns>This node.</returns> /// <typeparam name="TConv">The type of the converter to use.</typeparam> public Node TransformWith <TConv>() where TConv : IConverter, new() { if (Disposed) { throw new ObjectDisposedException(nameof(Node)); } if (Format == null) { throw new InvalidOperationException( "Cannot transform a node without format"); } ChangeFormat((IFormat)ConvertFormat.With <TConv>(Format)); return(this); }
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); }
static void Export(string input, string outputYml, string outputPo) { using (Node node = NodeFactory.FromFile(input)) { node.TransformWith <Binary2Clyt>(); Clyt clyt = node.GetFormatAs <Clyt>(); using (var ymlBin = (BinaryFormat)ConvertFormat.With <Clyt2Yml>(clyt)) { ymlBin.Stream.WriteTo(outputYml); } node.TransformWith <Clyt2Po>() .TransformWith <Po2Binary>() .Stream.WriteTo(outputPo); } }
public void ConvertWithInstanceThrowsExceptionIfInvalidConverter() { var format = new StringFormatTest("3"); string msg = "Converter cannot convert from/to the type"; Assert.That( () => ConvertFormat.With <SingleOuterConverterExample>(format), Throws.InvalidOperationException.With.Message.EqualTo(msg)); Assert.That( () => ConvertFormat.With <ConverterAndOtherInterface, int>(4, format), Throws.InvalidOperationException.With.Message.EqualTo(msg)); var converter = new SingleOuterConverterExample(); Assert.That( () => ConvertFormat.With(converter, format), Throws.InvalidOperationException.With.Message.EqualTo(msg)); }
public void ConvertWithThrowsExceptionIfNoImplementIConverter() { var format = new StringFormatTest("3"); string msg = "Converter doesn't implement IConverter<,>"; Assert.That( () => ConvertFormat.With <ConverterWithoutGenericInterface>(format), Throws.InvalidOperationException.With.Message.EqualTo(msg)); Assert.That( () => ConvertFormat.With <ConverterWithoutGenericInterface, int>(4, format), Throws.InvalidOperationException.With.Message.EqualTo(msg)); var converter = new ConverterWithoutGenericInterface(); Assert.That( () => ConvertFormat.With(converter, format), Throws.InvalidOperationException.With.Message.EqualTo(msg)); }
// Read the all text from a file ".po". public static List <string> ExtracTextFromPo(string PoAddress) { List <string> Text = new List <string>(); Po PoTranslated = null; string Sentence = null; using (DataStream name = DataStreamFactory.FromFile(PoAddress, FileOpenMode.Read)) using (BinaryFormat binaryname = new BinaryFormat(name)) { PoTranslated = (Po)ConvertFormat.With <Po2Binary>(binaryname); } foreach (PoEntry entry in PoTranslated.Entries) { if (entry.Original == "[EMPTY_LINE]" || entry.Translated == "[EMPTY_LINE]") { Sentence = ""; } else if (entry.Translated.Trim() != null && entry.Translated.Trim() != "") { Sentence = entry.Translated; } else { Sentence = entry.Original; } //Delete new extra lines and space. BND files are excluded from this. if (DRAT.eraseExtraLinefeedsToolStripMenuItem.Checked == true && Sentence != "" && Path.GetFileName(Path.GetDirectoryName(Path.GetDirectoryName(PoAddress))).ToLower() != "bnd") { Sentence = Sentence.Trim(); } if (Path.GetFileName(Path.GetDirectoryName(Path.GetDirectoryName(PoAddress))).ToLower() != "bnd" && Sentence != null && Sentence != "" && (DRAT.tabControl1.SelectedTab.Text.Contains("DRAE") || Path.GetFileNameWithoutExtension(PoAddress).ToLower().Contains("novel"))) // If the user is working on AE or with some Novel. { Sentence += "\n"; //Some files need it to be displayed in the right spot on the screen. } Text.Add(Sentence); //And finally save the sentence. } return(Text); // Return all the sentences. }
/// <summary> /// Transform the node format to another format with a given converter /// initialized with parameters. /// </summary> /// <returns>This node.</returns> /// <typeparam name="TConv">The type of the converter to use.</typeparam> /// <typeparam name="TParam">The type for initializing the converter.</typeparam> /// <param name="param">Parameters to initialize the converter.</param> public Node TransformWith <TConv, TParam>(TParam param) where TConv : IConverter, IInitializer <TParam>, new() { if (Disposed) { throw new ObjectDisposedException(nameof(Node)); } if (Format == null) { throw new InvalidOperationException( "Cannot transform a node without format"); } var dst = ConvertFormat.With <TConv, TParam>(param, Format); ChangeFormat((IFormat)dst); return(this); }
/// <summary> /// Splits a Po file (BinaryFormat) in smaller parts. /// </summary> /// <param name="source">Original Po file.</param> /// <returns>A container with the smaller parts.</returns> public NodeContainerFormat Convert(BinaryFormat source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } source.Stream.Seek(0); Yarhl.Media.Text.Po po = (Yarhl.Media.Text.Po)ConvertFormat.With <Yarhl.Media.Text.Binary2Po>(source); var result = (NodeContainerFormat)ConvertFormat.With <Splitter>(po); foreach (Node n in result.Root.Children) { n.TransformWith <Yarhl.Media.Text.Po2Binary>(); } return(result); }
/// <summary> /// Transforms the node format with the specified converter. /// </summary> /// <returns>This node.</returns> /// <param name="converterType">The type of the converter to use.</param> public Node TransformWith(Type converterType) { if (Disposed) { throw new ObjectDisposedException(nameof(Node)); } if (converterType == null) { throw new ArgumentNullException(nameof(converterType)); } if (Format == null) { throw new InvalidOperationException( "Cannot transform a node without format"); } ChangeFormat((IFormat)ConvertFormat.With(converterType, Format)); return(this); }
public void ConvertNeedsToBeHiddenIfConstructorsHaveArgs() { // With MEF we can't have an extension without a default constructor // because it will throw an exception in every general request. // So we need to hide those extensions. using var test = new StringFormatTest("3"); var ex = Assert.Throws <InvalidOperationException>(() => ConvertFormat.To(typeof(long), test)); Assert.AreEqual( "Cannot find converter for: " + $"{typeof(StringFormatTest).FullName} -> {typeof(long).FullName}", ex.Message); // But we can use the With() var converter = new FormatTestNoConstructor("3"); Assert.AreEqual( 0, ConvertFormat.With(converter, new StringFormatTest("1"))); }
/// <summary> /// Calls a translator converter. /// </summary> /// <param name="node">The original node.</param> /// <param name="translation">The node with the translation.</param> /// <param name="translator">The translator converter.</param> public static void Translate(this Node node, Node translation, string translator) { var yarhlConverters = PluginManager.Instance.GetConverters().Select(x => x.Metadata).ToList(); ConverterMetadata metadata = yarhlConverters.Find(x => x.Name == translator); if (metadata == null) { throw new UnknownConverterException($"Unknown converter: {translator}"); } IConverter converter = (IConverter)Activator.CreateInstance(metadata.Type); System.Reflection.MethodInfo initializer = metadata.Type.GetMethod("Initialize"); if (initializer != null) { _ = initializer.Invoke(converter, new object[] { translation.Format }); } node.ChangeFormat((IFormat)ConvertFormat.With(converter, node.Format)); }
public void ConvertNeedsToBeHiddenIfNoPublicConstructor() { // With MEF we can't have an extension without a default constructor // because it will throw an exception in every general request. // So we need to hide those extensions. var test = new StringFormatTest("3"); var ex = Assert.Throws <InvalidOperationException>(() => ConvertFormat.To(typeof(ulong), test)); Assert.AreEqual( "Cannot find converter for: " + $"{typeof(StringFormatTest).FullName} -> {typeof(ulong).FullName}", ex.Message); // But we can use the With() of classes with Factory pattern. var converter = FormatTestPrivateConstructor.Create(); Assert.AreEqual( ConvertFormat.With(converter, new StringFormatTest("1")), 0); }
private static Po LoadPo(string language) { string resourceName = $"{ResourcesName.Prefix}.{language}.po"; var assembly = typeof(L10n).Assembly; var stream = assembly.GetManifestResourceStream(resourceName); if (stream == null) { Logger.Log($"Cannot find language resource: {resourceName}"); return(null); } try { using var binaryPo = new BinaryFormat(DataStreamFactory.FromStream(stream)); return((Po)ConvertFormat.With <Binary2Po>(binaryPo)); } catch (Exception ex) { Logger.Log($"Error parsing language resource: {ex}"); return(null); } }