<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <UsingTask TaskName="Tizen.NUI.Xaml.Build.Tasks.XamlGTask" AssemblyFile="$(MSBuildThisFileDirectory)Tizen.NUI.XamlBuild.dll" />
- <UsingTask TaskName="Tizen.NUI.Xaml.Build.Tasks.XamlCTask" AssemblyFile="$(MSBuildThisFileDirectory)Tizen.NUI.XamlBuild.dll" />
+ <UsingTask TaskName="Tizen.NUI.Xaml.Build.Tasks.NUIXamlGTask" AssemblyFile="$(MSBuildThisFileDirectory)Tizen.NUI.XamlBuild.dll" />
+ <UsingTask TaskName="Tizen.NUI.Xaml.Build.Tasks.NUIXamlCTask" AssemblyFile="$(MSBuildThisFileDirectory)Tizen.NUI.XamlBuild.dll" />
<!-- XamlG -->
<Target Name="UpdateDesignTimeXaml" DependsOnTargets="XamlG"/>
</Target>
<Target Name="XamlG" BeforeTargets="BeforeCompile" DependsOnTargets="_FindXamlGFiles; PrepareResourceNames; AfterResolveReferences" Inputs="@(_XamlGInputs)" Outputs="@(_XamlGOutputs)">
- <XamlGTask
+ <NUIXamlGTask
XamlFiles="@(_XamlGInputs)"
OutputFiles="@(_XamlGOutputs)"
Language="$(Language)"
AssemblyName="$(AssemblyName)"
ReferencePath="@(ReferencePath)"
XamlOptimization="$(XamlOptimization)"
- AddXamlCompilationAttribute="True" />
+ AddXamlCompilationAttribute="True" />
<ItemGroup>
<FileWrites Include="@(_XamlGOutputs)" />
<Compile Include="@(_XamlGOutputs)" />
</PropertyGroup>
<Target Name="XamlC" AfterTargets="AfterCompile" Inputs="$(IntermediateOutputPath)$(TargetFileName)" Outputs="$(IntermediateOutputPath)XamlC.stamp" >
- <XamlCTask
+ <NUIXamlCTask
Assembly = "$(IntermediateOutputPath)$(TargetFileName)"
ReferencePath = "@(ReferencePath)"
OptimizeIL = "true"
if (implicitOperator != null)
return true;
- return valueInstance.GetType().InheritsFromOrImplements(module.ImportReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "BindingBase")));
+ return valueInstance.GetType().InheritsFromOrImplements(module.ImportReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "BindingBase")));
}
static void SetBinding(EXamlCreateObject parent, MemberReference bpRef, IElementNode elementNode, IXmlLineInfo iXmlLineInfo, EXamlContext context)
//if this is a MarkupExtension that can be compiled directly, compile and returns the value
var compiledMarkupExtensionName = typeref
- .GetCustomAttribute(Module, (XamlCTask.xamlAssemblyName, XamlCTask.xamlNameSpace, "ProvideCompiledAttribute"))
+ .GetCustomAttribute(Module, (NUIXamlCTask.xamlAssemblyName, NUIXamlCTask.xamlNameSpace, "ProvideCompiledAttribute"))
?.ConstructorArguments?[0].Value as string;
Type compiledMarkupExtensionType;
ICompiledMarkupExtension markupProvider;
Context.IL.Emit(OpCodes.Initobj, Module.ImportReference(typedef));
}
- if (null != XamlCTask.BaseTypeDefiniation && typedef.InheritsFromOrImplements(XamlCTask.BaseTypeDefiniation))
+ if (null != NUIXamlCTask.BaseTypeDefiniation && typedef.InheritsFromOrImplements(NUIXamlCTask.BaseTypeDefiniation))
{
- var field = XamlCTask.BaseTypeDefiniation.Properties.SingleOrDefault(fd => fd.Name == "IsCreateByXaml");
+ var field = NUIXamlCTask.BaseTypeDefiniation.Properties.SingleOrDefault(fd => fd.Name == "IsCreateByXaml");
if (field == null)
return;
--- /dev/null
+/*
+ * Copyright(c) 2022 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Xml;
+using System.ComponentModel;
+using Mono.Cecil;
+using Mono.Cecil.Cil;
+
+using Tizen.NUI.Binding;
+using Tizen.NUI.EXaml;
+using Tizen.NUI.EXaml.Build.Tasks;
+using static Microsoft.Build.Framework.MessageImportance;
+using static Mono.Cecil.Cil.OpCodes;
+
+namespace Tizen.NUI.Xaml.Build.Tasks
+{
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public class NUIXamlCTask : XamlTask
+ {
+ bool hasCompiledXamlResources;
+ public bool KeepXamlResources { get; set; }
+ public bool OptimizeIL { get; set; }
+
+ [Obsolete("OutputGeneratedILAsCode is obsolete as of version 2.3.4. This option is no longer available.")]
+ public bool OutputGeneratedILAsCode { get; set; }
+
+ public bool CompileByDefault { get; set; }
+ public bool ForceCompile { get; set; }
+
+ public bool UseInjection { get; set; }
+
+ public int XamlOptimization { get; set; } = 2;
+
+ public IAssemblyResolver DefaultAssemblyResolver { get; set; }
+
+ public string Type { get; set; }
+ public MethodDefinition InitCompForType { get; private set; }
+ internal bool ReadOnly { get; set; }
+
+ public string outputRootPath { get; set; }
+
+ public bool PrintReferenceAssemblies { get; set; }
+
+ private void PrintParam(string logFileName, string log)
+ {
+ FileStream stream = null;
+ if (false == File.Exists(logFileName))
+ {
+ stream = File.Create(logFileName);
+ }
+ else
+ {
+ stream = File.Open(logFileName, FileMode.Append);
+ }
+
+ byte[] buffer = System.Text.Encoding.Default.GetBytes(log + "\n");
+ stream.Write(buffer, 0, buffer.Length);
+ stream.Close();
+ }
+
+ private void PrintParam(string logFileName)
+ {
+ FileStream stream = File.Create(logFileName);
+
+ string str = "Assembly is " + Assembly + "\n";
+ str += "DependencyPaths is " + DependencyPaths + "\n";
+ str += "ReferencePath is " + ReferencePath + "\n";
+ str += "DebugType is " + DebugType + "\n";
+ str += "Type is " + Type + "\n";
+ str += "ReadOnly is " + ReadOnly + "\n";
+
+ byte[] buffer = Encoding.Default.GetBytes(str);
+ stream.Write(buffer, 0, buffer.Length);
+
+ stream.Close();
+ }
+
+ static private TypeDefinition baseTypeDefiniation = null;
+ static public TypeDefinition BaseTypeDefiniation
+ {
+ get
+ {
+ return baseTypeDefiniation;
+ }
+ }
+
+ private void GatherAssemblyInfo(string p)
+ {
+ try
+ {
+ ModuleDefinition module = ModuleDefinition.ReadModule(p);
+
+ if (null == baseTypeDefiniation)
+ {
+ baseTypeDefiniation = module.GetType("Tizen.NUI.Binding.BindableObject");
+ }
+
+ foreach (var attr in module.Assembly.CustomAttributes)
+ {
+ if (attr.AttributeType.FullName == "Tizen.NUI.XmlnsDefinitionAttribute")
+ {
+ string xmlNamespace = attr.ConstructorArguments[0].Value as string;
+ string clrNamespace = attr.ConstructorArguments[1].Value as string;
+
+ int level = 0;
+ string assemblyName = module.Assembly.FullName;
+
+ if (true == attr.HasProperties)
+ {
+ foreach (var property in attr.Properties)
+ {
+ if ("Level" == property.Name)
+ {
+ level = int.Parse(property.Argument.Value.ToString());
+ }
+ if ("AssemblyName" == property.Name)
+ {
+ assemblyName = property.Argument.Value as string;
+ }
+ }
+ }
+
+ XmlnsDefinitionAttribute attribute = new XmlnsDefinitionAttribute(xmlNamespace, clrNamespace, level);
+ attribute.AssemblyName = assemblyName;
+ s_xmlnsDefinitions.Add(attribute);
+ }
+ }
+
+ module.Dispose();
+ }
+ catch (Exception e)
+ {
+ int temp = 0;
+ }
+ }
+
+ public override bool Execute(out IList<Exception> thrownExceptions)
+ {
+ if (true == PrintReferenceAssemblies)
+ {
+ PrintParam(@"XamlC_Log.txt", "ReferencePath is " + ReferencePath);
+ }
+
+ LoggingHelper.LogWarning("Assembly is " + Assembly);
+
+ thrownExceptions = null;
+
+ LoggingHelper.LogMessage(Normal, $"{new string(' ', 0)}Compiling Xaml, assembly: {Assembly}");
+ var skipassembly = !CompileByDefault;
+ bool success = true;
+
+ if (!File.Exists(Assembly))
+ {
+ throw new Exception(String.Format("Assembly file {0} is not exist", Assembly));
+ //LoggingHelper.LogMessage(Normal, $"{new string(' ', 2)}Assembly file not found. Skipping XamlC.");
+ //return true;
+ }
+
+ s_xmlnsDefinitions.Clear();
+
+ var resolver = DefaultAssemblyResolver ?? new XamlCAssemblyResolver();
+ if (resolver is XamlCAssemblyResolver xamlCResolver)
+ {
+ if (!string.IsNullOrEmpty(DependencyPaths))
+ {
+ foreach (var dep in DependencyPaths.Split(';'))
+ {
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}Adding searchpath {dep}");
+ xamlCResolver.AddSearchDirectory(dep);
+ }
+ }
+
+ if (!string.IsNullOrEmpty(ReferencePath))
+ {
+ var paths = ReferencePath.Replace("//", "/").Split(';');
+
+ foreach (var p in paths)
+ {
+ GatherAssemblyInfo(p);
+
+ var searchpath = System.IO.Path.GetDirectoryName(p);
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}Adding searchpath {searchpath}");
+ xamlCResolver.AddSearchDirectory(searchpath);
+ }
+ }
+ }
+ else
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}Ignoring dependency and reference paths due to an unsupported resolver");
+
+ var readerParameters = new ReaderParameters
+ {
+ AssemblyResolver = resolver,
+ ReadWrite = !ReadOnly,
+ ReadSymbols = NeedDebug,
+ };
+
+ using (var assemblyDefinition = AssemblyDefinition.ReadAssembly(System.IO.Path.GetFullPath(Assembly), readerParameters))
+ {
+ if (null != XamlFilePath)
+ {
+ return GenerateEXaml(XamlFilePath, assemblyDefinition.MainModule, out thrownExceptions);
+ }
+
+ CustomAttribute xamlcAttr;
+ if (assemblyDefinition.HasCustomAttributes &&
+ (xamlcAttr =
+ assemblyDefinition.CustomAttributes.FirstOrDefault(
+ ca => ca.AttributeType.FullName == "Tizen.NUI.Xaml.XamlCompilationAttribute")) != null)
+ {
+ var options = (XamlCompilationOptions)xamlcAttr.ConstructorArguments[0].Value;
+ if ((options & XamlCompilationOptions.Skip) == XamlCompilationOptions.Skip)
+ skipassembly = true;
+ if ((options & XamlCompilationOptions.Compile) == XamlCompilationOptions.Compile)
+ skipassembly = false;
+ }
+
+ foreach (var module in assemblyDefinition.Modules)
+ {
+ var skipmodule = skipassembly;
+ if (module.HasCustomAttributes &&
+ (xamlcAttr =
+ module.CustomAttributes.FirstOrDefault(
+ ca => ca.AttributeType.FullName == "Tizen.NUI.Xaml.XamlCompilationAttribute")) != null)
+ {
+ var options = (XamlCompilationOptions)xamlcAttr.ConstructorArguments[0].Value;
+ if ((options & XamlCompilationOptions.Skip) == XamlCompilationOptions.Skip)
+ skipmodule = true;
+ if ((options & XamlCompilationOptions.Compile) == XamlCompilationOptions.Compile)
+ skipmodule = false;
+ }
+
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}Module: {module.Name}");
+ var resourcesToPrune = new List<EmbeddedResource>();
+ foreach (var resource in module.Resources.OfType<EmbeddedResource>())
+ {
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 4)}Resource: {resource.Name}");
+ string classname;
+ if (!resource.IsXaml(module, out classname))
+ {
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}skipped.");
+ continue;
+ }
+ TypeDefinition typeDef = module.GetType(classname);
+ if (typeDef == null)
+ {
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}no type found... skipped.");
+ continue;
+ }
+ var skiptype = skipmodule;
+ if (typeDef.HasCustomAttributes &&
+ (xamlcAttr =
+ typeDef.CustomAttributes.FirstOrDefault(
+ ca => ca.AttributeType.FullName == "Tizen.NUI.Xaml.XamlCompilationAttribute")) != null)
+ {
+ var options = (XamlCompilationOptions)xamlcAttr.ConstructorArguments[0].Value;
+ if ((options & XamlCompilationOptions.Skip) == XamlCompilationOptions.Skip)
+ skiptype = true;
+ if ((options & XamlCompilationOptions.Compile) == XamlCompilationOptions.Compile)
+ skiptype = false;
+ }
+
+ if (Type != null)
+ skiptype = !(Type == classname);
+
+ if (skiptype && !ForceCompile)
+ {
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}has XamlCompilationAttribute set to Skip and not Compile... skipped.");
+ continue;
+ }
+
+ bool currentRetOfType = false;
+ IList<Exception> currentExceptionsOfType = null;
+
+ if(UseInjection) XamlOptimization = 1;
+ LoggingHelper.LogWarning($"XamlOptimization is {XamlOptimization}.");
+ if (0 == XamlOptimization)
+ {//Use Xaml
+ currentRetOfType = true;
+ }
+ else if (1 == XamlOptimization)
+ {
+ currentRetOfType = DoInjection(typeDef, resource, out currentExceptionsOfType);
+ }
+ else
+ {
+ currentRetOfType = GenerateEXaml(typeDef, resource, out currentExceptionsOfType);
+
+ if (currentRetOfType)
+ {
+ InjectionMethodGetEXamlPath(typeDef);
+ }
+ }
+
+ if (null != currentExceptionsOfType)
+ {
+ if (null == thrownExceptions)
+ {
+ thrownExceptions = new List<Exception>();
+ }
+
+ foreach (var e in currentExceptionsOfType)
+ {
+ thrownExceptions.Add(e);
+ }
+ }
+
+ if (false == currentRetOfType)
+ {
+ success = false;
+ continue;
+ }
+
+ resourcesToPrune.Add(resource);
+ }
+
+ if (hasCompiledXamlResources)
+ {
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 4)}Changing the module MVID");
+ module.Mvid = Guid.NewGuid();
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}done.");
+ }
+ if (!KeepXamlResources)
+ {
+ if (resourcesToPrune.Any())
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 4)}Removing compiled xaml resources");
+ foreach (var resource in resourcesToPrune)
+ {
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Removing {resource.Name}");
+ module.Resources.Remove(resource);
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
+ }
+ }
+ }
+
+ if (!hasCompiledXamlResources)
+ {
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 0)}No compiled resources. Skipping writing assembly.");
+ return success;
+ }
+
+ if (ReadOnly)
+ return success;
+
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 0)}Writing the assembly");
+ try
+ {
+ assemblyDefinition.Write(new WriterParameters
+ {
+ WriteSymbols = NeedDebug,
+ });
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}done.");
+ }
+ catch (Exception e)
+ {
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}failed.");
+ LoggingHelper.LogErrorFromException(e);
+ (thrownExceptions = thrownExceptions ?? new List<Exception>()).Add(e);
+ LoggingHelper.LogMessage(Low, e.StackTrace);
+ success = false;
+ }
+ }
+ return success;
+ }
+
+ private string GetNameSpaceOfResource(EmbeddedResource resource)
+ {
+ var index = resource.Name.LastIndexOf('.');
+ var resourceNameWithoutSubfix = resource.Name.Substring(0, index);
+
+ index = resourceNameWithoutSubfix.LastIndexOf('.');
+ var nameSpace = resourceNameWithoutSubfix.Substring(0, index);
+
+ return nameSpace;
+ }
+
+ bool DoInjection(TypeDefinition typeDef, EmbeddedResource resource, out IList<Exception> thrownExceptions)
+ {
+ thrownExceptions = null;
+
+ var initComp = typeDef.Methods.FirstOrDefault(md => md.Name == "InitializeComponent");
+ if (initComp == null)
+ {
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}no InitializeComponent found... skipped.");
+ return false;
+ }
+
+ CustomAttribute xamlFilePathAttr;
+ var xamlFilePath = typeDef.HasCustomAttributes && (xamlFilePathAttr = typeDef.CustomAttributes.FirstOrDefault(ca => ca.AttributeType.FullName == "Tizen.NUI.Xaml.XamlFilePathAttribute")) != null ?
+ (string)xamlFilePathAttr.ConstructorArguments[0].Value :
+ resource.Name;
+
+ var initCompRuntime = typeDef.Methods.FirstOrDefault(md => md.Name == "__InitComponentRuntime");
+ if (initCompRuntime != null)
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}__InitComponentRuntime already exists... not creating");
+ else
+ {
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Creating empty {typeDef.Name}.__InitComponentRuntime");
+ initCompRuntime = new MethodDefinition("__InitComponentRuntime", initComp.Attributes, initComp.ReturnType);
+ initCompRuntime.Body.InitLocals = true;
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Copying body of InitializeComponent to __InitComponentRuntime");
+ initCompRuntime.Body = new MethodBody(initCompRuntime);
+ var iCRIl = initCompRuntime.Body.GetILProcessor();
+ foreach (var instr in initComp.Body.Instructions)
+ iCRIl.Append(instr);
+ initComp.Body.Instructions.Clear();
+ initComp.Body.GetILProcessor().Emit(OpCodes.Ret);
+ initComp.Body.InitLocals = true;
+
+ typeDef.Methods.Add(initCompRuntime);
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
+ }
+
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Parsing Xaml");
+ var rootnode = ParseXaml(resource.GetResourceStream(), typeDef);
+ if (rootnode == null)
+ {
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}failed.");
+ return false;
+ }
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
+
+ hasCompiledXamlResources = true;
+
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Replacing {0}.InitializeComponent ()");
+ Exception e;
+
+ var embeddedResourceNameSpace = GetNameSpaceOfResource(resource);
+ if (!TryCoreCompile(initComp, rootnode, embeddedResourceNameSpace, out e))
+ {
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}failed.");
+ (thrownExceptions = thrownExceptions ?? new List<Exception>()).Add(e);
+ if (e is XamlParseException xpe)
+ LoggingHelper.LogError(null, null, null, xamlFilePath, xpe.XmlInfo.LineNumber, xpe.XmlInfo.LinePosition, 0, 0, xpe.Message, xpe.HelpLink, xpe.Source);
+ else if (e is XmlException xe)
+ LoggingHelper.LogError(null, null, null, xamlFilePath, xe.LineNumber, xe.LinePosition, 0, 0, xe.Message, xe.HelpLink, xe.Source);
+ else
+ LoggingHelper.LogError(null, null, null, xamlFilePath, 0, 0, 0, 0, e.Message, e.HelpLink, e.Source);
+
+ if (null != e.StackTrace)
+ {
+ LoggingHelper.LogMessage(Low, e.StackTrace);
+ }
+
+ return false;
+ }
+ if (Type != null)
+ InitCompForType = initComp;
+
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
+
+ if (OptimizeIL)
+ {
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Optimizing IL");
+ initComp.Body.Optimize();
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
+ }
+
+#pragma warning disable 0618
+ if (OutputGeneratedILAsCode)
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Decompiling option has been removed. Use a 3rd party decompiler to admire the beauty of the IL generated");
+#pragma warning restore 0618
+
+ return true;
+ }
+
+ bool GenerateEXaml(TypeDefinition typeDef, EmbeddedResource resource, out IList<Exception> thrownExceptions)
+ {
+ thrownExceptions = null;
+
+ ModuleDefinition module = typeDef.Module;
+
+ CustomAttribute xamlFilePathAttr;
+ var xamlFilePath = typeDef.HasCustomAttributes && (xamlFilePathAttr = typeDef.CustomAttributes.FirstOrDefault(ca => ca.AttributeType.FullName == "Tizen.NUI.Xaml.XamlFilePathAttribute")) != null ?
+ (string)xamlFilePathAttr.ConstructorArguments[0].Value :
+ resource.Name;
+
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Parsing Xaml");
+ var rootnode = ParseXaml(resource.GetResourceStream(), typeDef);
+ if (rootnode == null)
+ {
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}failed.");
+ return false;
+ }
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
+
+ hasCompiledXamlResources = true;
+
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Replacing {0}.InitializeComponent ()");
+ Exception e;
+
+ var embeddedResourceNameSpace = GetNameSpaceOfResource(resource);
+ var visitorContext = new EXamlContext(typeDef, typeDef.Module, embeddedResourceNameSpace);
+
+ if (!TryCoreCompile(rootnode, visitorContext, out e))
+ {
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}failed.");
+ (thrownExceptions = thrownExceptions ?? new List<Exception>()).Add(e);
+ if (e is XamlParseException xpe)
+ LoggingHelper.LogError(null, null, null, xamlFilePath, xpe.XmlInfo.LineNumber, xpe.XmlInfo.LinePosition, 0, 0, xpe.Message, xpe.HelpLink, xpe.Source);
+ else if (e is XmlException xe)
+ LoggingHelper.LogError(null, null, null, xamlFilePath, xe.LineNumber, xe.LinePosition, 0, 0, xe.Message, xe.HelpLink, xe.Source);
+ else
+ LoggingHelper.LogError(null, null, null, xamlFilePath, 0, 0, 0, 0, e.Message, e.HelpLink, e.Source);
+
+ if (null != e.StackTrace)
+ {
+ LoggingHelper.LogError(e.StackTrace);
+ }
+
+ return false;
+ }
+ else
+ {
+ var examlDir = outputRootPath + @"res/examl/";
+ if (Directory.Exists(examlDir))
+ {
+ Directory.CreateDirectory(examlDir);
+ }
+
+ var examlFilePath = examlDir + typeDef.FullName + ".examl";
+
+ EXamlOperation.WriteOpertions(examlFilePath, visitorContext);
+ }
+
+ return true;
+ }
+
+ bool GenerateEXaml(string xamlFilePath, ModuleDefinition module, out IList<Exception> thrownExceptions)
+ {
+ thrownExceptions = null;
+
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Parsing Xaml");
+ Stream xamlStream = File.Open(xamlFilePath, FileMode.Open);
+
+ string className;
+ if (!CecilExtensions.IsXaml(xamlStream, module, out className))
+ {
+ thrownExceptions.Add(new Exception($"{xamlFilePath} is not xaml format file"));
+ }
+
+ xamlStream.Seek(0, SeekOrigin.Begin);
+ var typeDef = module.GetTypeDefinition(className);
+
+ if (null == typeDef)
+ {
+ throw new Exception($"Can't find type \"{className}\" in assembly \"{module.Assembly.FullName}\"");
+ }
+
+ var rootnode = ParseXaml(xamlStream, typeDef);
+
+ xamlStream.Close();
+
+ if (rootnode == null)
+ {
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}failed.");
+ return false;
+ }
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
+
+ hasCompiledXamlResources = true;
+
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Replacing {0}.InitializeComponent ()");
+ Exception e;
+
+ var visitorContext = new EXamlContext(typeDef, module, null);
+
+ if (!TryCoreCompile(rootnode, visitorContext, out e))
+ {
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}failed.");
+ (thrownExceptions = thrownExceptions ?? new List<Exception>()).Add(e);
+ if (e is XamlParseException xpe)
+ LoggingHelper.LogError(null, null, null, xamlFilePath, xpe.XmlInfo.LineNumber, xpe.XmlInfo.LinePosition, 0, 0, xpe.Message, xpe.HelpLink, xpe.Source);
+ else if (e is XmlException xe)
+ LoggingHelper.LogError(null, null, null, xamlFilePath, xe.LineNumber, xe.LinePosition, 0, 0, xe.Message, xe.HelpLink, xe.Source);
+ else
+ LoggingHelper.LogError(null, null, null, xamlFilePath, 0, 0, 0, 0, e.Message, e.HelpLink, e.Source);
+
+ if (null != e.StackTrace)
+ {
+ LoggingHelper.LogMessage(Low, e.StackTrace);
+ }
+
+ return false;
+ }
+ else
+ {
+ var examlDir = outputRootPath + @"res/examl/";
+ if (Directory.Exists(examlDir))
+ {
+ Directory.CreateDirectory(examlDir);
+ }
+
+ var examlFilePath = examlDir + typeDef.FullName + ".examl";
+
+ EXamlOperation.WriteOpertions(examlFilePath, visitorContext);
+ }
+
+ return true;
+ }
+
+
+ bool InjectionMethodGetEXamlPath(TypeDefinition typeDef)
+ {
+ var getEXamlPathComp = typeDef.Methods.FirstOrDefault(md => md.Name == "GetEXamlPath");
+ if (getEXamlPathComp == null)
+ {
+ LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}no GetEXamlPath found... skipped.");
+ return false;
+ }
+
+ var examlRelativePath = @"examl/" + typeDef.FullName + ".examl";
+ getEXamlPathComp.Body.Instructions.Clear();
+ getEXamlPathComp.Body.GetILProcessor().Emit(OpCodes.Ldstr, examlRelativePath);
+ getEXamlPathComp.Body.GetILProcessor().Emit(OpCodes.Ret);
+
+ return true;
+ }
+
+ bool TryCoreCompile(MethodDefinition initComp, ILRootNode rootnode, string embeddedResourceNameSpace, out Exception exception)
+ {
+ try
+ {
+ var body = new MethodBody(initComp);
+ var module = body.Method.Module;
+ var type = initComp.DeclaringType;
+
+ MethodDefinition constructorOfRemoveEventsType;
+ TypeDefinition typeOfRemoveEvents = CreateTypeForRemoveEvents(type, out constructorOfRemoveEventsType);
+
+ var field = type.GetOrCreateField("___Info_Of_RemoveEvent___", FieldAttributes.Private, typeOfRemoveEvents);
+
+ body.InitLocals = true;
+ var il = body.GetILProcessor();
+ il.Emit(OpCodes.Ldarg_0);
+ il.Emit(OpCodes.Newobj, constructorOfRemoveEventsType);
+ il.Emit(OpCodes.Stfld, field);
+
+ var resourcePath = GetPathForType(module, type);
+
+ il.Emit(Nop);
+
+ List<Instruction> insOfAddEvent = new List<Instruction>();
+
+ var visitorContext = new ILContext(il, body, insOfAddEvent, module, embeddedResourceNameSpace);
+
+ rootnode.Accept(new XamlNodeVisitor((node, parent) => node.Parent = parent), null);
+ rootnode.Accept(new ExpandMarkupsVisitor(visitorContext), null);
+ rootnode.Accept(new PruneIgnoredNodesVisitor(), null);
+ rootnode.Accept(new CreateObjectVisitor(visitorContext), null);
+
+ Set(visitorContext, visitorContext.Variables[rootnode], "IsCreateByXaml", new ValueNode("true", rootnode.NamespaceResolver), null);
+
+ rootnode.Accept(new SetNamescopesAndRegisterNamesVisitor(visitorContext), null);
+ rootnode.Accept(new SetFieldVisitor(visitorContext), null);
+ rootnode.Accept(new SetResourcesVisitor(visitorContext), null);
+ rootnode.Accept(new SetPropertiesVisitor(visitorContext, true), null);
+
+ AddInsOfRemoveEvent(il, visitorContext.InsOfAddEvent, typeOfRemoveEvents);
+
+ il.Emit(Ret);
+ initComp.Body = body;
+ exception = null;
+ return true;
+ }
+ catch (Exception e)
+ {
+ XamlParseException xamlParseException = e as XamlParseException;
+ if (null != xamlParseException)
+ {
+ XamlParseException ret = new XamlParseException(xamlParseException.Message + "\n" + ReferencePath, xamlParseException.XmlInfo, xamlParseException.InnerException);
+ exception = ret;
+ }
+ else
+ {
+ exception = e;
+ }
+
+ return false;
+ }
+ }
+
+ private void AddInsOfRemoveEvent(ILProcessor ilOfInit, List<Instruction> instructions, TypeDefinition typeDef)
+ {
+ MethodDefinition methodCall = typeDef.GetOrCreateMethod("Call", MethodAttributes.Public, typeof(void));
+ methodCall.Body.Instructions.Clear();
+
+ var fieldOfRemoveEvent = typeDef.DeclaringType.Fields.FirstOrDefault(a => a.Name == "___Info_Of_RemoveEvent___");
+
+ var il = methodCall.Body.GetILProcessor();
+
+ foreach (var ins in instructions)
+ {
+ if (ins.OpCode == OpCodes.Ldloc
+ &&
+ ins.Operand is VariableDefinition variable)
+ {
+ var fieldName = "field" + variable.Index;
+ var field = typeDef.GetOrCreateField(fieldName, FieldAttributes.Public, variable.VariableType);
+
+ ilOfInit.Emit(OpCodes.Ldarg_0);
+ ilOfInit.Emit(OpCodes.Ldfld, fieldOfRemoveEvent);
+ ilOfInit.Emit(OpCodes.Ldloc, variable);
+ ilOfInit.Emit(OpCodes.Stfld, field);
+
+ methodCall.Body.Instructions.Add(Instruction.Create(Ldarg_0));
+ methodCall.Body.Instructions.Add(Instruction.Create(Ldfld, field));
+ }
+ else
+ {
+ bool isReplaced = false;
+ if (ins.OpCode == OpCodes.Callvirt && ins.Operand is MethodReference method)
+ {
+ if (method.Name.StartsWith("add_"))
+ {
+ var eventName = method.Name.Substring("add_".Length);
+ TypeReference _;
+ var typeOfEvent = method.DeclaringType.GetEvent(a => a.Name == eventName, out _);
+
+ if (typeOfEvent is EventDefinition)
+ {
+ var methodOfRemoveEvent = typeDef.Module.ImportReference(method.DeclaringType.ResolveCached()?.Methods.FirstOrDefault(a => a.Name == "remove_" + eventName));
+ if (null != methodOfRemoveEvent)
+ {
+ var newIns = Instruction.Create(ins.OpCode, methodOfRemoveEvent);
+ methodCall.Body.Instructions.Add(newIns);
+
+ isReplaced = true;
+ }
+ }
+ }
+ }
+
+ if (false == isReplaced)
+ {
+ methodCall.Body.Instructions.Add(ins);
+ }
+ }
+ }
+
+ methodCall.Body.Instructions.Add(Instruction.Create(Ret));
+
+ var removeEventMethod = typeDef.DeclaringType.Methods.FirstOrDefault(a => a.Name == "RemoveEventsInXaml");
+ if (null != removeEventMethod)
+ {
+ removeEventMethod.Body.Instructions.Clear();
+ var ilRemoveEvent = removeEventMethod.Body.GetILProcessor();
+
+ ilRemoveEvent.Emit(Ldarg_0);
+ ilRemoveEvent.Emit(Ldfld, fieldOfRemoveEvent);
+ ilRemoveEvent.Emit(Dup);
+
+ var insOfCall = Instruction.Create(Call, methodCall.Resolve());
+
+ ilRemoveEvent.Emit(Brtrue_S, insOfCall);
+ ilRemoveEvent.Emit(Pop);
+
+ var endIns = Instruction.Create(Ret);
+
+ ilRemoveEvent.Emit(Br_S, endIns);
+ ilRemoveEvent.Append(insOfCall);
+
+ ilRemoveEvent.Append(endIns);
+ }
+ }
+
+ TypeDefinition CreateTypeForRemoveEvents(TypeDefinition typeDef, out MethodDefinition constructor)
+ {
+ var module = typeDef.Module;
+
+ var name = "___Type___For___RemoveEvent___";
+ var nestType = typeDef.NestedTypes.FirstOrDefault(a => a.Name == name);
+
+ if (null == nestType)
+ {
+ nestType = new TypeDefinition(typeDef.Namespace, name, TypeAttributes.NestedPrivate | TypeAttributes.BeforeFieldInit | TypeAttributes.Sealed | TypeAttributes.AnsiClass);
+ nestType.BaseType = module.ImportReference(typeof(object));
+ typeDef.NestedTypes.Add(nestType);
+
+ constructor = nestType.AddDefaultConstructor();
+ }
+ else
+ {
+ constructor = nestType.Methods.FirstOrDefault(a => a.IsConstructor);
+ }
+
+ return nestType;
+ }
+
+ bool TryCoreCompile(ILRootNode rootnode, EXamlContext visitorContext, out Exception exception)
+ {
+ try
+ {
+ XmlTypeExtensions.s_xmlnsDefinitions?.Clear();
+ XmlTypeExtensions.s_xmlnsDefinitions = null;
+
+ visitorContext.Values[rootnode] = new EXamlCreateObject(visitorContext, null, rootnode.TypeReference);
+
+ rootnode.Accept(new XamlNodeVisitor((node, parent) => node.Parent = parent), null);
+ rootnode.Accept(new EXamlExpandMarkupsVisitor(visitorContext), null);
+ rootnode.Accept(new PruneIgnoredNodesVisitor(), null);
+ rootnode.Accept(new EXamlCreateObjectVisitor(visitorContext), null);
+ rootnode.Accept(new EXamlSetNamescopesAndRegisterNamesVisitor(visitorContext), null);
+ rootnode.Accept(new EXamlSetFieldVisitor(visitorContext), null);
+ rootnode.Accept(new EXamlSetResourcesVisitor(visitorContext), null);
+ rootnode.Accept(new EXamlSetPropertiesVisitor(visitorContext, true), null);
+
+ exception = null;
+ return true;
+ }
+ catch (Exception e)
+ {
+ XamlParseException xamlParseException = e as XamlParseException;
+ if (null != xamlParseException)
+ {
+ XamlParseException ret = new XamlParseException(xamlParseException.Message + "\n" + ReferencePath, xamlParseException.XmlInfo, xamlParseException.InnerException);
+ exception = ret;
+ }
+ else
+ {
+ exception = e;
+ }
+
+ return false;
+ }
+ }
+
+ private void Set(ILContext Context, VariableDefinition parent, string localName, INode node, IXmlLineInfo iXmlLineInfo)
+ {
+ var module = Context.Body.Method.Module;
+ TypeReference declaringTypeReference;
+ var property = parent.VariableType.GetProperty(pd => pd.Name == localName, out declaringTypeReference);
+ if (null == property)
+ {
+ return;
+ }
+ var propertySetter = property.SetMethod;
+
+ module.ImportReference(parent.VariableType.ResolveCached());
+ var propertySetterRef = module.ImportReference(module.ImportReference(propertySetter).ResolveGenericParameters(declaringTypeReference, module));
+ propertySetterRef.ImportTypes(module);
+ var propertyType = property.ResolveGenericPropertyType(declaringTypeReference, module);
+ var valueNode = node as ValueNode;
+ var elementNode = node as IElementNode;
+
+ if (parent.VariableType.IsValueType)
+ Context.IL.Emit(OpCodes.Ldloca, parent);
+ else
+ Context.IL.Emit(OpCodes.Ldloc, parent);
+
+ if (valueNode != null)
+ {
+ foreach (var instruction in valueNode.PushConvertedValue(Context, propertyType, new ICustomAttributeProvider[] { property, propertyType.ResolveCached() }, valueNode.PushServiceProvider(Context, propertyRef: property), false, true))
+ {
+ Context.IL.Append(instruction);
+ }
+
+ if (parent.VariableType.IsValueType)
+ Context.IL.Emit(OpCodes.Call, propertySetterRef);
+ else
+ Context.IL.Emit(OpCodes.Callvirt, propertySetterRef);
+ }
+ }
+
+ internal static string GetPathForType(ModuleDefinition module, TypeReference type)
+ {
+ foreach (var ca in type.Module.GetCustomAttributes())
+ {
+ if (!TypeRefComparer.Default.Equals(ca.AttributeType, module.ImportReference((xamlAssemblyName, xamlNameSpace, "XamlResourceIdAttribute"))))
+ continue;
+ if (!TypeRefComparer.Default.Equals(ca.ConstructorArguments[2].Value as TypeReference, type))
+ continue;
+ return ca.ConstructorArguments[1].Value as string;
+ }
+ return null;
+ }
+
+ internal static string GetResourceIdForPath(ModuleDefinition module, string path)
+ {
+ foreach (var ca in module.GetCustomAttributes())
+ {
+ if (!TypeRefComparer.Default.Equals(ca.AttributeType, module.ImportReference((xamlAssemblyName, xamlNameSpace, "XamlResourceIdAttribute"))))
+ continue;
+ if (ca.ConstructorArguments[1].Value as string != path)
+ continue;
+ return ca.ConstructorArguments[0].Value as string;
+ }
+ return null;
+ }
+ }
+}
+
--- /dev/null
+/*
+ * Copyright(c) 2022 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+using System;
+using System.IO;
+using System.Xml;
+using System.ComponentModel;
+using Microsoft.Build.Framework;
+using Microsoft.Build.Utilities;
+
+namespace Tizen.NUI.Xaml.Build.Tasks
+{
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public class NUIXamlGTask : Task
+ {
+ [Required]
+ public ITaskItem[] XamlFiles { get; set; }
+
+ [Required]
+ public ITaskItem[] OutputFiles { get; set; }
+
+ public string Language { get; set; }
+ public string AssemblyName { get; set; }
+ public string DependencyPaths { get; set; }
+ public string ReferencePath { get; set; }
+ public int XamlOptimization {get; set;} = 2;
+ public bool AddXamlCompilationAttribute { get; set; }
+ public bool PrintReferenceAssemblies { get; set; }
+
+ private void PrintParam(string logFileName, string log)
+ {
+ FileStream stream = null;
+ if (false == File.Exists(logFileName))
+ {
+ stream = File.Create(logFileName);
+ }
+ else
+ {
+ stream = File.Open(logFileName, FileMode.Append);
+ }
+
+ byte[] buffer = System.Text.Encoding.Default.GetBytes(log + "\n");
+ stream.Write(buffer, 0, buffer.Length);
+ stream.Close();
+ }
+
+ public override bool Execute()
+ {
+ if (true == PrintReferenceAssemblies)
+ {
+ PrintParam(@"XamlG_Log.txt", "ReferencePath is " + ReferencePath);
+ }
+
+ //PrintParam(@"G:\XamlG_Log.txt", "ReferencePath is " + ReferencePath);
+ bool success = true;
+ //Log.LogMessage(MessageImportance.Normal, "Generating code behind for XAML files");
+
+ //NOTE: should not happen due to [Required], but there appears to be a place this is class is called directly
+ if (XamlFiles == null || OutputFiles == null) {
+ //Log.LogMessage("Skipping XamlG");
+ return true;
+ }
+
+ if (XamlFiles.Length != OutputFiles.Length) {
+ Log.LogError("\"{2}\" refers to {0} item(s), and \"{3}\" refers to {1} item(s). They must have the same number of items.", XamlFiles.Length, OutputFiles.Length, "XamlFiles", "OutputFiles");
+ return false;
+ }
+
+ for (int i = 0; i < XamlFiles.Length; i++) {
+ var xamlFile = XamlFiles[i];
+ var outputFile = OutputFiles[i].ItemSpec;
+ if (System.IO.Path.DirectorySeparatorChar == '/' && outputFile.Contains(@"\"))
+ outputFile = outputFile.Replace('\\','/');
+ else if (System.IO.Path.DirectorySeparatorChar == '\\' && outputFile.Contains(@"/"))
+ outputFile = outputFile.Replace('/', '\\');
+
+ var generator = new XamlGenerator(xamlFile, Language, AssemblyName, outputFile, ReferencePath, Log);
+ generator.AddXamlCompilationAttribute = AddXamlCompilationAttribute;
+ generator.XamlOptimization = XamlOptimization;
+ generator.ReferencePath = ReferencePath;
+
+ try {
+ if (!generator.Execute()) {
+ //If Execute() fails, the file still needs to exist because it is added to the <Compile/> ItemGroup
+ File.WriteAllText (outputFile, string.Empty);
+ }
+ }
+ catch (XmlException xe) {
+ Log.LogError(null, null, null, xamlFile.ItemSpec, xe.LineNumber, xe.LinePosition, 0, 0, xe.Message, xe.HelpLink, xe.Source);
+ success = false;
+ }
+ catch (Exception e) {
+ Log.LogError(null, null, null, xamlFile.ItemSpec, 0, 0, 0, 0, e.Message, e.HelpLink, e.Source);
+ success = false;
+ }
+ }
+
+ return success;
+ }
+ }
+}
+
namescopeVarDef = Context.Scopes[parentNode].Item1;
namesInNamescope = Context.Scopes[parentNode].Item2;
}
- if (setNameScope && Context.Variables[node].VariableType.InheritsFromOrImplements(Context.Body.Method.Module.ImportReference((XamlCTask.xamlAssemblyName, XamlCTask.bindingNameSpace, "BindableObject"))))
+ if (setNameScope && Context.Variables[node].VariableType.InheritsFromOrImplements(Context.Body.Method.Module.ImportReference((NUIXamlCTask.xamlAssemblyName, NUIXamlCTask.bindingNameSpace, "BindableObject"))))
SetNameScope(node, namescopeVarDef);
Context.Scopes[node] = new Tuple<VariableDefinition, IList<string>>(namescopeVarDef, namesInNamescope);
}
{
var namescopeVarDef = CreateNamescope();
IList<string> namesInNamescope = new List<string>();
- if (Context.Variables[node].VariableType.InheritsFromOrImplements(Context.Body.Method.Module.ImportReference((XamlCTask.xamlAssemblyName, XamlCTask.bindingNameSpace, "BindableObject"))))
+ if (Context.Variables[node].VariableType.InheritsFromOrImplements(Context.Body.Method.Module.ImportReference((NUIXamlCTask.xamlAssemblyName, NUIXamlCTask.bindingNameSpace, "BindableObject"))))
SetNameScope(node, namescopeVarDef);
Context.Scopes[node] = new System.Tuple<VariableDefinition, IList<string>>(namescopeVarDef, namesInNamescope);
}
VariableDefinition CreateNamescope()
{
var module = Context.Body.Method.Module;
- var vardef = new VariableDefinition(module.ImportReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingInternalNameSpace, "NameScope")));
+ var vardef = new VariableDefinition(module.ImportReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingInternalNameSpace, "NameScope")));
Context.Body.Variables.Add(vardef);
- Context.IL.Emit(OpCodes.Newobj, module.ImportCtorReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingInternalNameSpace, "NameScope"), parameterTypes: null));
+ Context.IL.Emit(OpCodes.Newobj, module.ImportCtorReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingInternalNameSpace, "NameScope"), parameterTypes: null));
Context.IL.Emit(OpCodes.Stloc, vardef);
return vardef;
}
var module = Context.Body.Method.Module;
Context.IL.Emit(OpCodes.Ldloc, Context.Variables[node]);
Context.IL.Emit(OpCodes.Ldloc, ns);
- Context.IL.Emit(OpCodes.Call, module.ImportMethodReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingInternalNameSpace, "NameScope"),
+ Context.IL.Emit(OpCodes.Call, module.ImportMethodReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingInternalNameSpace, "NameScope"),
methodName: "SetNameScope",
parameterTypes: new[] {
- (XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "BindableObject"),
- (XamlCTask.bindingAssemblyName, XamlCTask.bindingInternalNameSpace, "INameScope"),
+ (NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "BindableObject"),
+ (NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingInternalNameSpace, "INameScope"),
},
isStatic: true));
}
Context.IL.Emit(OpCodes.Ldloc, namescopeVarDef);
Context.IL.Emit(OpCodes.Ldstr, str);
Context.IL.Emit(OpCodes.Ldloc, element);
- Context.IL.Emit(OpCodes.Callvirt, module.ImportMethodReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingInternalNameSpace, "INameScope"),
+ Context.IL.Emit(OpCodes.Callvirt, module.ImportMethodReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingInternalNameSpace, "INameScope"),
methodName: "RegisterName",
parameterTypes: new[] {
("mscorlib", "System", "String"),
void SetStyleId(string str, VariableDefinition element)
{
- if (!element.VariableType.InheritsFromOrImplements(Context.Body.Method.Module.ImportReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "Element"))))
+ if (!element.VariableType.InheritsFromOrImplements(Context.Body.Method.Module.ImportReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "Element"))))
return;
var module = Context.Body.Method.Module;
var nop = Instruction.Create(OpCodes.Nop);
Context.IL.Emit(OpCodes.Ldloc, element);
- Context.IL.Emit(OpCodes.Callvirt, module.ImportPropertyGetterReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "Element"), propertyName: "StyleId"));
+ Context.IL.Emit(OpCodes.Callvirt, module.ImportPropertyGetterReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "Element"), propertyName: "StyleId"));
Context.IL.Emit(OpCodes.Brtrue, nop);
Context.IL.Emit(OpCodes.Ldloc, element);
Context.IL.Emit(OpCodes.Ldstr, str);
- Context.IL.Emit(OpCodes.Callvirt, module.ImportPropertySetterReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "Element"), propertyName: "StyleId"));
+ Context.IL.Emit(OpCodes.Callvirt, module.ImportPropertySetterReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "Element"), propertyName: "StyleId"));
Context.IL.Append(nop);
}
}
else if (vardefref.VariableDefinition.VariableType.ImplementsGenericInterface("Tizen.NUI.Xaml.IMarkupExtension`1",
out markupExtension, out genericArguments))
{
- var acceptEmptyServiceProvider = vardefref.VariableDefinition.VariableType.GetCustomAttribute(module, (XamlCTask.xamlAssemblyName, XamlCTask.xamlNameSpace, "AcceptEmptyServiceProviderAttribute")) != null;
+ var acceptEmptyServiceProvider = vardefref.VariableDefinition.VariableType.GetCustomAttribute(module, (NUIXamlCTask.xamlAssemblyName, NUIXamlCTask.xamlNameSpace, "AcceptEmptyServiceProviderAttribute")) != null;
if (vardefref.VariableDefinition.VariableType.FullName == "Tizen.NUI.Xaml.BindingExtension")
foreach (var instruction in CompileBindingPath(node, context, vardefref.VariableDefinition))
yield return instruction;
yield return Instruction.Create(OpCodes.Callvirt, provideValue);
yield return Instruction.Create(OpCodes.Stloc, vardefref.VariableDefinition);
}
- else if (context.Variables[node].VariableType.ImplementsInterface(module.ImportReference((XamlCTask.xamlAssemblyName, XamlCTask.xamlNameSpace, "IMarkupExtension"))))
+ else if (context.Variables[node].VariableType.ImplementsInterface(module.ImportReference((NUIXamlCTask.xamlAssemblyName, NUIXamlCTask.xamlNameSpace, "IMarkupExtension"))))
{
- var acceptEmptyServiceProvider = context.Variables[node].VariableType.GetCustomAttribute(module, (XamlCTask.xamlAssemblyName, XamlCTask.xamlNameSpace, "AcceptEmptyServiceProviderAttribute")) != null;
+ var acceptEmptyServiceProvider = context.Variables[node].VariableType.GetCustomAttribute(module, (NUIXamlCTask.xamlAssemblyName, NUIXamlCTask.xamlNameSpace, "AcceptEmptyServiceProviderAttribute")) != null;
vardefref.VariableDefinition = new VariableDefinition(module.TypeSystem.Object);
yield return Create(Ldloc, context.Variables[node]);
if (acceptEmptyServiceProvider)
else
foreach (var instruction in node.PushServiceProvider(context, bpRef, propertyRef, propertyDeclaringTypeRef))
yield return instruction;
- yield return Create(Callvirt, module.ImportMethodReference((XamlCTask.xamlAssemblyName, XamlCTask.xamlNameSpace, "IMarkupExtension"),
+ yield return Create(Callvirt, module.ImportMethodReference((NUIXamlCTask.xamlAssemblyName, NUIXamlCTask.xamlNameSpace, "IMarkupExtension"),
methodName: "ProvideValue",
parameterTypes: new[] { ("System.ComponentModel", "System", "IServiceProvider") }));
yield return Create(Stloc, vardefref.VariableDefinition);
}
- else if (context.Variables[node].VariableType.ImplementsInterface(module.ImportReference((XamlCTask.xamlAssemblyName, XamlCTask.xamlNameSpace, "IValueProvider"))))
+ else if (context.Variables[node].VariableType.ImplementsInterface(module.ImportReference((NUIXamlCTask.xamlAssemblyName, NUIXamlCTask.xamlNameSpace, "IValueProvider"))))
{
- var acceptEmptyServiceProvider = context.Variables[node].VariableType.GetCustomAttribute(module, (XamlCTask.xamlAssemblyName, XamlCTask.xamlNameSpace, "AcceptEmptyServiceProviderAttribute")) != null;
+ var acceptEmptyServiceProvider = context.Variables[node].VariableType.GetCustomAttribute(module, (NUIXamlCTask.xamlAssemblyName, NUIXamlCTask.xamlNameSpace, "AcceptEmptyServiceProviderAttribute")) != null;
var valueProviderType = context.Variables[node].VariableType;
//If the IValueProvider has a ProvideCompiledAttribute that can be resolved, shortcut this
- var compiledValueProviderName = valueProviderType?.GetCustomAttribute(module, (XamlCTask.xamlAssemblyName, XamlCTask.xamlNameSpace, "ProvideCompiledAttribute"))?.ConstructorArguments?[0].Value as string;
+ var compiledValueProviderName = valueProviderType?.GetCustomAttribute(module, (NUIXamlCTask.xamlAssemblyName, NUIXamlCTask.xamlNameSpace, "ProvideCompiledAttribute"))?.ConstructorArguments?[0].Value as string;
Type compiledValueProviderType;
if (compiledValueProviderName != null && (compiledValueProviderType = Type.GetType(compiledValueProviderName)) != null) {
var compiledValueProvider = Activator.CreateInstance(compiledValueProviderType);
else
foreach (var instruction in node.PushServiceProvider(context, bpRef, propertyRef, propertyDeclaringTypeRef))
yield return instruction;
- yield return Create(Callvirt, module.ImportMethodReference((XamlCTask.xamlAssemblyName, XamlCTask.xamlNameSpace, "IValueProvider"),
+ yield return Create(Callvirt, module.ImportMethodReference((NUIXamlCTask.xamlAssemblyName, NUIXamlCTask.xamlNameSpace, "IValueProvider"),
methodName: "ProvideValue",
parameterTypes: new[] { ("System.ComponentModel", "System", "IServiceProvider") }));
yield return Create(Stloc, vardefref.VariableDefinition);
var actionRef = module.ImportReference(module.ImportReference(("mscorlib", "System", "Action`2")).MakeGenericInstanceType(new [] { tSourceRef, tPropertyRef }));
var funcObjRef = module.ImportReference(module.ImportReference(("mscorlib", "System", "Func`2")).MakeGenericInstanceType(new [] { tSourceRef, module.TypeSystem.Object }));
var tupleRef = module.ImportReference(module.ImportReference(("mscorlib", "System", "Tuple`2")).MakeGenericInstanceType(new [] { funcObjRef, module.TypeSystem.String}));
- var typedBindingRef = module.ImportReference(module.ImportReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingInternalNameSpace, "TypedBinding`2")).MakeGenericInstanceType(new [] { tSourceRef, tPropertyRef}));
+ var typedBindingRef = module.ImportReference(module.ImportReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingInternalNameSpace, "TypedBinding`2")).MakeGenericInstanceType(new [] { tSourceRef, tPropertyRef}));
var ctorInfo = module.ImportReference(typedBindingRef.ResolveCached().Methods.FirstOrDefault(md => md.IsConstructor && !md.IsStatic && md.Parameters.Count == 3 ));
var ctorinforef = ctorInfo.MakeGeneric(typedBindingRef, funcRef, actionRef, tupleRef);
} else
yield return Create(Ldnull);
yield return Instruction.Create(OpCodes.Newobj, module.ImportReference(ctorinforef));
- yield return Instruction.Create(OpCodes.Callvirt, module.ImportPropertySetterReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "BindingExtension"), propertyName: "TypedBinding"));
+ yield return Instruction.Create(OpCodes.Callvirt, module.ImportPropertySetterReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "BindingExtension"), propertyName: "TypedBinding"));
}
static IList<Tuple<PropertyDefinition, string>> ParsePath(string path, TypeReference tSourceRef, IXmlLineInfo lineInfo, ModuleDefinition module)
yield return Create(Ldloc, parent);
yield return Create(Ldsfld, bpRef);
yield return Create(Ldloc, context.Variables[elementNode]);
- yield return Create(Callvirt, module.ImportPropertyGetterReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingInternalNameSpace, "DynamicResource"), propertyName: "Key"));
- yield return Create(Callvirt, module.ImportMethodReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingInternalNameSpace, "IDynamicResourceHandler"),
+ yield return Create(Callvirt, module.ImportPropertyGetterReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingInternalNameSpace, "DynamicResource"), propertyName: "Key"));
+ yield return Create(Callvirt, module.ImportMethodReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingInternalNameSpace, "IDynamicResourceHandler"),
methodName: "SetDynamicResource",
parameterTypes: new[] {
- (XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "BindableProperty"),
+ (NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "BindableProperty"),
("mscorlib", "System", "String"),
}));
}
if (!context.Variables.TryGetValue(valueNode as IElementNode, out varValue))
return false;
- var implicitOperator = varValue.VariableType.GetImplicitOperatorTo(module.ImportReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "BindingBase")), module);
+ var implicitOperator = varValue.VariableType.GetImplicitOperatorTo(module.ImportReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "BindingBase")), module);
if (implicitOperator != null)
return true;
- return varValue.VariableType.InheritsFromOrImplements(module.ImportReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "BindingBase")));
+ return varValue.VariableType.InheritsFromOrImplements(module.ImportReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "BindingBase")));
}
static IEnumerable<Instruction> SetBinding(VariableDefinition parent, FieldReference bpRef, IElementNode elementNode, IXmlLineInfo iXmlLineInfo, ILContext context)
{
var module = context.Body.Method.Module;
var varValue = context.Variables [elementNode];
- var implicitOperator = varValue.VariableType.GetImplicitOperatorTo(module.ImportReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "BindingBase")), module);
+ var implicitOperator = varValue.VariableType.GetImplicitOperatorTo(module.ImportReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "BindingBase")), module);
//TODO: check if parent is a BP
yield return Create(Ldloc, parent);
if (implicitOperator != null)
// IL_000f: call !0 class [Tizen.NUI.Xaml.Core]Tizen.NUI.Xaml.OnPlatform`1<BindingBase>::op_Implicit(class [Tizen.NUI.Xaml.Core]Tizen.NUI.Xaml.OnPlatform`1<!0>)
yield return Create(Call, module.ImportReference(implicitOperator));
- yield return Create(Callvirt, module.ImportMethodReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "BindableObject"),
+ yield return Create(Callvirt, module.ImportMethodReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "BindableObject"),
methodName: "SetBinding",
parameterTypes: new[] {
- (XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "BindableProperty"),
- (XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "BindingBase"),
+ (NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "BindableProperty"),
+ (NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "BindingBase"),
}));
}
if (bpRef == null)
return false;
- if (!parent.VariableType.InheritsFromOrImplements(module.ImportReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "BindableObject"))))
+ if (!parent.VariableType.InheritsFromOrImplements(module.ImportReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "BindableObject"))))
return false;
propertyType = bpRef.GetBindablePropertyType(iXmlLineInfo, module);
if (varType.IsValueType)
yield return Create(Box, varType);
}
- yield return Create(Callvirt, module.ImportMethodReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "BindableObject"),
+ yield return Create(Callvirt, module.ImportMethodReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "BindableObject"),
methodName: "SetValue",
parameterTypes: new[] {
- (XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "BindableProperty"),
+ (NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "BindableProperty"),
("mscorlib", "System", "Object"),
}));
}
return new[] {
Create(Ldloc, parent),
Create(Ldsfld, bpRef),
- Create(Callvirt, module.ImportMethodReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "BindableObject"),
+ Create(Callvirt, module.ImportMethodReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "BindableObject"),
methodName: "GetValue",
- parameterTypes: new[] { (XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "BindableProperty") })),
+ parameterTypes: new[] { (NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "BindableProperty") })),
};
}
//is there a RD.Add() overrides that accepts this ?
var nodeTypeRef = context.Variables[node].VariableType;
var module = context.Body.Method.Module;
- if (module.ImportMethodReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "ResourceDictionary"),
+ if (module.ImportMethodReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "ResourceDictionary"),
methodName: "Add",
parameterTypes: new[] { (nodeTypeRef.Scope.Name, nodeTypeRef.Namespace, nodeTypeRef.Name) }) != null)
return true;
yield return Create(Ldloc, varDef);
if (varDef.VariableType.IsValueType)
yield return Create(Box, module.ImportReference(varDef.VariableType));
- yield return Create(Callvirt, module.ImportMethodReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "ResourceDictionary"),
+ yield return Create(Callvirt, module.ImportMethodReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "ResourceDictionary"),
methodName: "Add",
parameterTypes: new[] {
("mscorlib", "System", "String"),
var nodeTypeRef = context.Variables[node].VariableType;
yield return Create(Ldloc, context.Variables[node]);
- yield return Create(Callvirt, module.ImportMethodReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "ResourceDictionary"),
+ yield return Create(Callvirt, module.ImportMethodReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "ResourceDictionary"),
methodName: "Add",
parameterTypes: new[] { (nodeTypeRef.Scope.Name, nodeTypeRef.Namespace, nodeTypeRef.Name) }));
yield break;
classArguments: new[] { ("mscorlib", "System", "Object") },
paramCount: 2));
- var setterRef = module.ImportPropertySetterReference((XamlCTask.bindingAssemblyName, XamlCTask.bindingNameSpace, "IDataTemplate"), propertyName: "LoadTemplate");
+ var setterRef = module.ImportPropertySetterReference((NUIXamlCTask.bindingAssemblyName, NUIXamlCTask.bindingNameSpace, "IDataTemplate"), propertyName: "LoadTemplate");
parentContext.IL.Emit(OpCodes.Callvirt, setterRef);
loadTemplate.Body.Optimize();
+++ /dev/null
-/*
- * Copyright(c) 2022 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Xml;
-using System.ComponentModel;
-using Mono.Cecil;
-using Mono.Cecil.Cil;
-
-using Tizen.NUI.Binding;
-using Tizen.NUI.EXaml;
-using Tizen.NUI.EXaml.Build.Tasks;
-using static Microsoft.Build.Framework.MessageImportance;
-using static Mono.Cecil.Cil.OpCodes;
-
-namespace Tizen.NUI.Xaml.Build.Tasks
-{
- [EditorBrowsable(EditorBrowsableState.Never)]
- public class XamlCTask : XamlTask
- {
- bool hasCompiledXamlResources;
- public bool KeepXamlResources { get; set; }
- public bool OptimizeIL { get; set; }
-
- [Obsolete("OutputGeneratedILAsCode is obsolete as of version 2.3.4. This option is no longer available.")]
- public bool OutputGeneratedILAsCode { get; set; }
-
- public bool CompileByDefault { get; set; }
- public bool ForceCompile { get; set; }
-
- public bool UseInjection { get; set; }
-
- public int XamlOptimization { get; set; } = 2;
-
- public IAssemblyResolver DefaultAssemblyResolver { get; set; }
-
- public string Type { get; set; }
- public MethodDefinition InitCompForType { get; private set; }
- internal bool ReadOnly { get; set; }
-
- public string outputRootPath { get; set; }
-
- public bool PrintReferenceAssemblies { get; set; }
-
- private void PrintParam(string logFileName, string log)
- {
- FileStream stream = null;
- if (false == File.Exists(logFileName))
- {
- stream = File.Create(logFileName);
- }
- else
- {
- stream = File.Open(logFileName, FileMode.Append);
- }
-
- byte[] buffer = System.Text.Encoding.Default.GetBytes(log + "\n");
- stream.Write(buffer, 0, buffer.Length);
- stream.Close();
- }
-
- private void PrintParam(string logFileName)
- {
- FileStream stream = File.Create(logFileName);
-
- string str = "Assembly is " + Assembly + "\n";
- str += "DependencyPaths is " + DependencyPaths + "\n";
- str += "ReferencePath is " + ReferencePath + "\n";
- str += "DebugType is " + DebugType + "\n";
- str += "Type is " + Type + "\n";
- str += "ReadOnly is " + ReadOnly + "\n";
-
- byte[] buffer = Encoding.Default.GetBytes(str);
- stream.Write(buffer, 0, buffer.Length);
-
- stream.Close();
- }
-
- static private TypeDefinition baseTypeDefiniation = null;
- static public TypeDefinition BaseTypeDefiniation
- {
- get
- {
- return baseTypeDefiniation;
- }
- }
-
- private void GatherAssemblyInfo(string p)
- {
- try
- {
- ModuleDefinition module = ModuleDefinition.ReadModule(p);
-
- if (null == baseTypeDefiniation)
- {
- baseTypeDefiniation = module.GetType("Tizen.NUI.Binding.BindableObject");
- }
-
- foreach (var attr in module.Assembly.CustomAttributes)
- {
- if (attr.AttributeType.FullName == "Tizen.NUI.XmlnsDefinitionAttribute")
- {
- string xmlNamespace = attr.ConstructorArguments[0].Value as string;
- string clrNamespace = attr.ConstructorArguments[1].Value as string;
-
- int level = 0;
- string assemblyName = module.Assembly.FullName;
-
- if (true == attr.HasProperties)
- {
- foreach (var property in attr.Properties)
- {
- if ("Level" == property.Name)
- {
- level = int.Parse(property.Argument.Value.ToString());
- }
- if ("AssemblyName" == property.Name)
- {
- assemblyName = property.Argument.Value as string;
- }
- }
- }
-
- XmlnsDefinitionAttribute attribute = new XmlnsDefinitionAttribute(xmlNamespace, clrNamespace, level);
- attribute.AssemblyName = assemblyName;
- s_xmlnsDefinitions.Add(attribute);
- }
- }
-
- module.Dispose();
- }
- catch (Exception e)
- {
- int temp = 0;
- }
- }
-
- public override bool Execute(out IList<Exception> thrownExceptions)
- {
- if (true == PrintReferenceAssemblies)
- {
- PrintParam(@"XamlC_Log.txt", "ReferencePath is " + ReferencePath);
- }
-
- LoggingHelper.LogWarning("Assembly is " + Assembly);
-
- thrownExceptions = null;
-
- LoggingHelper.LogMessage(Normal, $"{new string(' ', 0)}Compiling Xaml, assembly: {Assembly}");
- var skipassembly = !CompileByDefault;
- bool success = true;
-
- if (!File.Exists(Assembly))
- {
- throw new Exception(String.Format("Assembly file {0} is not exist", Assembly));
- //LoggingHelper.LogMessage(Normal, $"{new string(' ', 2)}Assembly file not found. Skipping XamlC.");
- //return true;
- }
-
- s_xmlnsDefinitions.Clear();
-
- var resolver = DefaultAssemblyResolver ?? new XamlCAssemblyResolver();
- if (resolver is XamlCAssemblyResolver xamlCResolver)
- {
- if (!string.IsNullOrEmpty(DependencyPaths))
- {
- foreach (var dep in DependencyPaths.Split(';'))
- {
- LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}Adding searchpath {dep}");
- xamlCResolver.AddSearchDirectory(dep);
- }
- }
-
- if (!string.IsNullOrEmpty(ReferencePath))
- {
- var paths = ReferencePath.Replace("//", "/").Split(';');
-
- foreach (var p in paths)
- {
- GatherAssemblyInfo(p);
-
- var searchpath = System.IO.Path.GetDirectoryName(p);
- LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}Adding searchpath {searchpath}");
- xamlCResolver.AddSearchDirectory(searchpath);
- }
- }
- }
- else
- LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}Ignoring dependency and reference paths due to an unsupported resolver");
-
- var readerParameters = new ReaderParameters
- {
- AssemblyResolver = resolver,
- ReadWrite = !ReadOnly,
- ReadSymbols = NeedDebug,
- };
-
- using (var assemblyDefinition = AssemblyDefinition.ReadAssembly(System.IO.Path.GetFullPath(Assembly), readerParameters))
- {
- if (null != XamlFilePath)
- {
- return GenerateEXaml(XamlFilePath, assemblyDefinition.MainModule, out thrownExceptions);
- }
-
- CustomAttribute xamlcAttr;
- if (assemblyDefinition.HasCustomAttributes &&
- (xamlcAttr =
- assemblyDefinition.CustomAttributes.FirstOrDefault(
- ca => ca.AttributeType.FullName == "Tizen.NUI.Xaml.XamlCompilationAttribute")) != null)
- {
- var options = (XamlCompilationOptions)xamlcAttr.ConstructorArguments[0].Value;
- if ((options & XamlCompilationOptions.Skip) == XamlCompilationOptions.Skip)
- skipassembly = true;
- if ((options & XamlCompilationOptions.Compile) == XamlCompilationOptions.Compile)
- skipassembly = false;
- }
-
- foreach (var module in assemblyDefinition.Modules)
- {
- var skipmodule = skipassembly;
- if (module.HasCustomAttributes &&
- (xamlcAttr =
- module.CustomAttributes.FirstOrDefault(
- ca => ca.AttributeType.FullName == "Tizen.NUI.Xaml.XamlCompilationAttribute")) != null)
- {
- var options = (XamlCompilationOptions)xamlcAttr.ConstructorArguments[0].Value;
- if ((options & XamlCompilationOptions.Skip) == XamlCompilationOptions.Skip)
- skipmodule = true;
- if ((options & XamlCompilationOptions.Compile) == XamlCompilationOptions.Compile)
- skipmodule = false;
- }
-
- LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}Module: {module.Name}");
- var resourcesToPrune = new List<EmbeddedResource>();
- foreach (var resource in module.Resources.OfType<EmbeddedResource>())
- {
- LoggingHelper.LogMessage(Low, $"{new string(' ', 4)}Resource: {resource.Name}");
- string classname;
- if (!resource.IsXaml(module, out classname))
- {
- LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}skipped.");
- continue;
- }
- TypeDefinition typeDef = module.GetType(classname);
- if (typeDef == null)
- {
- LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}no type found... skipped.");
- continue;
- }
- var skiptype = skipmodule;
- if (typeDef.HasCustomAttributes &&
- (xamlcAttr =
- typeDef.CustomAttributes.FirstOrDefault(
- ca => ca.AttributeType.FullName == "Tizen.NUI.Xaml.XamlCompilationAttribute")) != null)
- {
- var options = (XamlCompilationOptions)xamlcAttr.ConstructorArguments[0].Value;
- if ((options & XamlCompilationOptions.Skip) == XamlCompilationOptions.Skip)
- skiptype = true;
- if ((options & XamlCompilationOptions.Compile) == XamlCompilationOptions.Compile)
- skiptype = false;
- }
-
- if (Type != null)
- skiptype = !(Type == classname);
-
- if (skiptype && !ForceCompile)
- {
- LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}has XamlCompilationAttribute set to Skip and not Compile... skipped.");
- continue;
- }
-
- bool currentRetOfType = false;
- IList<Exception> currentExceptionsOfType = null;
-
- if(UseInjection) XamlOptimization = 1;
- LoggingHelper.LogWarning($"XamlOptimization is {XamlOptimization}.");
- if (0 == XamlOptimization)
- {//Use Xaml
- currentRetOfType = true;
- }
- else if (1 == XamlOptimization)
- {
- currentRetOfType = DoInjection(typeDef, resource, out currentExceptionsOfType);
- }
- else
- {
- currentRetOfType = GenerateEXaml(typeDef, resource, out currentExceptionsOfType);
-
- if (currentRetOfType)
- {
- InjectionMethodGetEXamlPath(typeDef);
- }
- }
-
- if (null != currentExceptionsOfType)
- {
- if (null == thrownExceptions)
- {
- thrownExceptions = new List<Exception>();
- }
-
- foreach (var e in currentExceptionsOfType)
- {
- thrownExceptions.Add(e);
- }
- }
-
- if (false == currentRetOfType)
- {
- success = false;
- continue;
- }
-
- resourcesToPrune.Add(resource);
- }
-
- if (hasCompiledXamlResources)
- {
- LoggingHelper.LogMessage(Low, $"{new string(' ', 4)}Changing the module MVID");
- module.Mvid = Guid.NewGuid();
- LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}done.");
- }
- if (!KeepXamlResources)
- {
- if (resourcesToPrune.Any())
- LoggingHelper.LogMessage(Low, $"{new string(' ', 4)}Removing compiled xaml resources");
- foreach (var resource in resourcesToPrune)
- {
- LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Removing {resource.Name}");
- module.Resources.Remove(resource);
- LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
- }
- }
- }
-
- if (!hasCompiledXamlResources)
- {
- LoggingHelper.LogMessage(Low, $"{new string(' ', 0)}No compiled resources. Skipping writing assembly.");
- return success;
- }
-
- if (ReadOnly)
- return success;
-
- LoggingHelper.LogMessage(Low, $"{new string(' ', 0)}Writing the assembly");
- try
- {
- assemblyDefinition.Write(new WriterParameters
- {
- WriteSymbols = NeedDebug,
- });
- LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}done.");
- }
- catch (Exception e)
- {
- LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}failed.");
- LoggingHelper.LogErrorFromException(e);
- (thrownExceptions = thrownExceptions ?? new List<Exception>()).Add(e);
- LoggingHelper.LogMessage(Low, e.StackTrace);
- success = false;
- }
- }
- return success;
- }
-
- private string GetNameSpaceOfResource(EmbeddedResource resource)
- {
- var index = resource.Name.LastIndexOf('.');
- var resourceNameWithoutSubfix = resource.Name.Substring(0, index);
-
- index = resourceNameWithoutSubfix.LastIndexOf('.');
- var nameSpace = resourceNameWithoutSubfix.Substring(0, index);
-
- return nameSpace;
- }
-
- bool DoInjection(TypeDefinition typeDef, EmbeddedResource resource, out IList<Exception> thrownExceptions)
- {
- thrownExceptions = null;
-
- var initComp = typeDef.Methods.FirstOrDefault(md => md.Name == "InitializeComponent");
- if (initComp == null)
- {
- LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}no InitializeComponent found... skipped.");
- return false;
- }
-
- CustomAttribute xamlFilePathAttr;
- var xamlFilePath = typeDef.HasCustomAttributes && (xamlFilePathAttr = typeDef.CustomAttributes.FirstOrDefault(ca => ca.AttributeType.FullName == "Tizen.NUI.Xaml.XamlFilePathAttribute")) != null ?
- (string)xamlFilePathAttr.ConstructorArguments[0].Value :
- resource.Name;
-
- var initCompRuntime = typeDef.Methods.FirstOrDefault(md => md.Name == "__InitComponentRuntime");
- if (initCompRuntime != null)
- LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}__InitComponentRuntime already exists... not creating");
- else
- {
- LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Creating empty {typeDef.Name}.__InitComponentRuntime");
- initCompRuntime = new MethodDefinition("__InitComponentRuntime", initComp.Attributes, initComp.ReturnType);
- initCompRuntime.Body.InitLocals = true;
- LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
- LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Copying body of InitializeComponent to __InitComponentRuntime");
- initCompRuntime.Body = new MethodBody(initCompRuntime);
- var iCRIl = initCompRuntime.Body.GetILProcessor();
- foreach (var instr in initComp.Body.Instructions)
- iCRIl.Append(instr);
- initComp.Body.Instructions.Clear();
- initComp.Body.GetILProcessor().Emit(OpCodes.Ret);
- initComp.Body.InitLocals = true;
-
- typeDef.Methods.Add(initCompRuntime);
- LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
- }
-
- LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Parsing Xaml");
- var rootnode = ParseXaml(resource.GetResourceStream(), typeDef);
- if (rootnode == null)
- {
- LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}failed.");
- return false;
- }
- LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
-
- hasCompiledXamlResources = true;
-
- LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Replacing {0}.InitializeComponent ()");
- Exception e;
-
- var embeddedResourceNameSpace = GetNameSpaceOfResource(resource);
- if (!TryCoreCompile(initComp, rootnode, embeddedResourceNameSpace, out e))
- {
- LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}failed.");
- (thrownExceptions = thrownExceptions ?? new List<Exception>()).Add(e);
- if (e is XamlParseException xpe)
- LoggingHelper.LogError(null, null, null, xamlFilePath, xpe.XmlInfo.LineNumber, xpe.XmlInfo.LinePosition, 0, 0, xpe.Message, xpe.HelpLink, xpe.Source);
- else if (e is XmlException xe)
- LoggingHelper.LogError(null, null, null, xamlFilePath, xe.LineNumber, xe.LinePosition, 0, 0, xe.Message, xe.HelpLink, xe.Source);
- else
- LoggingHelper.LogError(null, null, null, xamlFilePath, 0, 0, 0, 0, e.Message, e.HelpLink, e.Source);
-
- if (null != e.StackTrace)
- {
- LoggingHelper.LogMessage(Low, e.StackTrace);
- }
-
- return false;
- }
- if (Type != null)
- InitCompForType = initComp;
-
- LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
-
- if (OptimizeIL)
- {
- LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Optimizing IL");
- initComp.Body.Optimize();
- LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
- }
-
-#pragma warning disable 0618
- if (OutputGeneratedILAsCode)
- LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Decompiling option has been removed. Use a 3rd party decompiler to admire the beauty of the IL generated");
-#pragma warning restore 0618
-
- return true;
- }
-
- bool GenerateEXaml(TypeDefinition typeDef, EmbeddedResource resource, out IList<Exception> thrownExceptions)
- {
- thrownExceptions = null;
-
- ModuleDefinition module = typeDef.Module;
-
- CustomAttribute xamlFilePathAttr;
- var xamlFilePath = typeDef.HasCustomAttributes && (xamlFilePathAttr = typeDef.CustomAttributes.FirstOrDefault(ca => ca.AttributeType.FullName == "Tizen.NUI.Xaml.XamlFilePathAttribute")) != null ?
- (string)xamlFilePathAttr.ConstructorArguments[0].Value :
- resource.Name;
-
- LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Parsing Xaml");
- var rootnode = ParseXaml(resource.GetResourceStream(), typeDef);
- if (rootnode == null)
- {
- LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}failed.");
- return false;
- }
- LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
-
- hasCompiledXamlResources = true;
-
- LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Replacing {0}.InitializeComponent ()");
- Exception e;
-
- var embeddedResourceNameSpace = GetNameSpaceOfResource(resource);
- var visitorContext = new EXamlContext(typeDef, typeDef.Module, embeddedResourceNameSpace);
-
- if (!TryCoreCompile(rootnode, visitorContext, out e))
- {
- LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}failed.");
- (thrownExceptions = thrownExceptions ?? new List<Exception>()).Add(e);
- if (e is XamlParseException xpe)
- LoggingHelper.LogError(null, null, null, xamlFilePath, xpe.XmlInfo.LineNumber, xpe.XmlInfo.LinePosition, 0, 0, xpe.Message, xpe.HelpLink, xpe.Source);
- else if (e is XmlException xe)
- LoggingHelper.LogError(null, null, null, xamlFilePath, xe.LineNumber, xe.LinePosition, 0, 0, xe.Message, xe.HelpLink, xe.Source);
- else
- LoggingHelper.LogError(null, null, null, xamlFilePath, 0, 0, 0, 0, e.Message, e.HelpLink, e.Source);
-
- if (null != e.StackTrace)
- {
- LoggingHelper.LogError(e.StackTrace);
- }
-
- return false;
- }
- else
- {
- var examlDir = outputRootPath + @"res/examl/";
- if (Directory.Exists(examlDir))
- {
- Directory.CreateDirectory(examlDir);
- }
-
- var examlFilePath = examlDir + typeDef.FullName + ".examl";
-
- EXamlOperation.WriteOpertions(examlFilePath, visitorContext);
- }
-
- return true;
- }
-
- bool GenerateEXaml(string xamlFilePath, ModuleDefinition module, out IList<Exception> thrownExceptions)
- {
- thrownExceptions = null;
-
- LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Parsing Xaml");
- Stream xamlStream = File.Open(xamlFilePath, FileMode.Open);
-
- string className;
- if (!CecilExtensions.IsXaml(xamlStream, module, out className))
- {
- thrownExceptions.Add(new Exception($"{xamlFilePath} is not xaml format file"));
- }
-
- xamlStream.Seek(0, SeekOrigin.Begin);
- var typeDef = module.GetTypeDefinition(className);
-
- if (null == typeDef)
- {
- throw new Exception($"Can't find type \"{className}\" in assembly \"{module.Assembly.FullName}\"");
- }
-
- var rootnode = ParseXaml(xamlStream, typeDef);
-
- xamlStream.Close();
-
- if (rootnode == null)
- {
- LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}failed.");
- return false;
- }
- LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
-
- hasCompiledXamlResources = true;
-
- LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Replacing {0}.InitializeComponent ()");
- Exception e;
-
- var visitorContext = new EXamlContext(typeDef, module, null);
-
- if (!TryCoreCompile(rootnode, visitorContext, out e))
- {
- LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}failed.");
- (thrownExceptions = thrownExceptions ?? new List<Exception>()).Add(e);
- if (e is XamlParseException xpe)
- LoggingHelper.LogError(null, null, null, xamlFilePath, xpe.XmlInfo.LineNumber, xpe.XmlInfo.LinePosition, 0, 0, xpe.Message, xpe.HelpLink, xpe.Source);
- else if (e is XmlException xe)
- LoggingHelper.LogError(null, null, null, xamlFilePath, xe.LineNumber, xe.LinePosition, 0, 0, xe.Message, xe.HelpLink, xe.Source);
- else
- LoggingHelper.LogError(null, null, null, xamlFilePath, 0, 0, 0, 0, e.Message, e.HelpLink, e.Source);
-
- if (null != e.StackTrace)
- {
- LoggingHelper.LogMessage(Low, e.StackTrace);
- }
-
- return false;
- }
- else
- {
- var examlDir = outputRootPath + @"res/examl/";
- if (Directory.Exists(examlDir))
- {
- Directory.CreateDirectory(examlDir);
- }
-
- var examlFilePath = examlDir + typeDef.FullName + ".examl";
-
- EXamlOperation.WriteOpertions(examlFilePath, visitorContext);
- }
-
- return true;
- }
-
-
- bool InjectionMethodGetEXamlPath(TypeDefinition typeDef)
- {
- var getEXamlPathComp = typeDef.Methods.FirstOrDefault(md => md.Name == "GetEXamlPath");
- if (getEXamlPathComp == null)
- {
- LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}no GetEXamlPath found... skipped.");
- return false;
- }
-
- var examlRelativePath = @"examl/" + typeDef.FullName + ".examl";
- getEXamlPathComp.Body.Instructions.Clear();
- getEXamlPathComp.Body.GetILProcessor().Emit(OpCodes.Ldstr, examlRelativePath);
- getEXamlPathComp.Body.GetILProcessor().Emit(OpCodes.Ret);
-
- return true;
- }
-
- bool TryCoreCompile(MethodDefinition initComp, ILRootNode rootnode, string embeddedResourceNameSpace, out Exception exception)
- {
- try
- {
- var body = new MethodBody(initComp);
- var module = body.Method.Module;
- var type = initComp.DeclaringType;
-
- MethodDefinition constructorOfRemoveEventsType;
- TypeDefinition typeOfRemoveEvents = CreateTypeForRemoveEvents(type, out constructorOfRemoveEventsType);
-
- var field = type.GetOrCreateField("___Info_Of_RemoveEvent___", FieldAttributes.Private, typeOfRemoveEvents);
-
- body.InitLocals = true;
- var il = body.GetILProcessor();
- il.Emit(OpCodes.Ldarg_0);
- il.Emit(OpCodes.Newobj, constructorOfRemoveEventsType);
- il.Emit(OpCodes.Stfld, field);
-
- var resourcePath = GetPathForType(module, type);
-
- il.Emit(Nop);
-
- List<Instruction> insOfAddEvent = new List<Instruction>();
-
- var visitorContext = new ILContext(il, body, insOfAddEvent, module, embeddedResourceNameSpace);
-
- rootnode.Accept(new XamlNodeVisitor((node, parent) => node.Parent = parent), null);
- rootnode.Accept(new ExpandMarkupsVisitor(visitorContext), null);
- rootnode.Accept(new PruneIgnoredNodesVisitor(), null);
- rootnode.Accept(new CreateObjectVisitor(visitorContext), null);
-
- Set(visitorContext, visitorContext.Variables[rootnode], "IsCreateByXaml", new ValueNode("true", rootnode.NamespaceResolver), null);
-
- rootnode.Accept(new SetNamescopesAndRegisterNamesVisitor(visitorContext), null);
- rootnode.Accept(new SetFieldVisitor(visitorContext), null);
- rootnode.Accept(new SetResourcesVisitor(visitorContext), null);
- rootnode.Accept(new SetPropertiesVisitor(visitorContext, true), null);
-
- AddInsOfRemoveEvent(il, visitorContext.InsOfAddEvent, typeOfRemoveEvents);
-
- il.Emit(Ret);
- initComp.Body = body;
- exception = null;
- return true;
- }
- catch (Exception e)
- {
- XamlParseException xamlParseException = e as XamlParseException;
- if (null != xamlParseException)
- {
- XamlParseException ret = new XamlParseException(xamlParseException.Message + "\n" + ReferencePath, xamlParseException.XmlInfo, xamlParseException.InnerException);
- exception = ret;
- }
- else
- {
- exception = e;
- }
-
- return false;
- }
- }
-
- private void AddInsOfRemoveEvent(ILProcessor ilOfInit, List<Instruction> instructions, TypeDefinition typeDef)
- {
- MethodDefinition methodCall = typeDef.GetOrCreateMethod("Call", MethodAttributes.Public, typeof(void));
- methodCall.Body.Instructions.Clear();
-
- var fieldOfRemoveEvent = typeDef.DeclaringType.Fields.FirstOrDefault(a => a.Name == "___Info_Of_RemoveEvent___");
-
- var il = methodCall.Body.GetILProcessor();
-
- foreach (var ins in instructions)
- {
- if (ins.OpCode == OpCodes.Ldloc
- &&
- ins.Operand is VariableDefinition variable)
- {
- var fieldName = "field" + variable.Index;
- var field = typeDef.GetOrCreateField(fieldName, FieldAttributes.Public, variable.VariableType);
-
- ilOfInit.Emit(OpCodes.Ldarg_0);
- ilOfInit.Emit(OpCodes.Ldfld, fieldOfRemoveEvent);
- ilOfInit.Emit(OpCodes.Ldloc, variable);
- ilOfInit.Emit(OpCodes.Stfld, field);
-
- methodCall.Body.Instructions.Add(Instruction.Create(Ldarg_0));
- methodCall.Body.Instructions.Add(Instruction.Create(Ldfld, field));
- }
- else
- {
- bool isReplaced = false;
- if (ins.OpCode == OpCodes.Callvirt && ins.Operand is MethodReference method)
- {
- if (method.Name.StartsWith("add_"))
- {
- var eventName = method.Name.Substring("add_".Length);
- TypeReference _;
- var typeOfEvent = method.DeclaringType.GetEvent(a => a.Name == eventName, out _);
-
- if (typeOfEvent is EventDefinition)
- {
- var methodOfRemoveEvent = typeDef.Module.ImportReference(method.DeclaringType.ResolveCached()?.Methods.FirstOrDefault(a => a.Name == "remove_" + eventName));
- if (null != methodOfRemoveEvent)
- {
- var newIns = Instruction.Create(ins.OpCode, methodOfRemoveEvent);
- methodCall.Body.Instructions.Add(newIns);
-
- isReplaced = true;
- }
- }
- }
- }
-
- if (false == isReplaced)
- {
- methodCall.Body.Instructions.Add(ins);
- }
- }
- }
-
- methodCall.Body.Instructions.Add(Instruction.Create(Ret));
-
- var removeEventMethod = typeDef.DeclaringType.Methods.FirstOrDefault(a => a.Name == "RemoveEventsInXaml");
- if (null != removeEventMethod)
- {
- removeEventMethod.Body.Instructions.Clear();
- var ilRemoveEvent = removeEventMethod.Body.GetILProcessor();
-
- ilRemoveEvent.Emit(Ldarg_0);
- ilRemoveEvent.Emit(Ldfld, fieldOfRemoveEvent);
- ilRemoveEvent.Emit(Dup);
-
- var insOfCall = Instruction.Create(Call, methodCall.Resolve());
-
- ilRemoveEvent.Emit(Brtrue_S, insOfCall);
- ilRemoveEvent.Emit(Pop);
-
- var endIns = Instruction.Create(Ret);
-
- ilRemoveEvent.Emit(Br_S, endIns);
- ilRemoveEvent.Append(insOfCall);
-
- ilRemoveEvent.Append(endIns);
- }
- }
-
- TypeDefinition CreateTypeForRemoveEvents(TypeDefinition typeDef, out MethodDefinition constructor)
- {
- var module = typeDef.Module;
-
- var name = "___Type___For___RemoveEvent___";
- var nestType = typeDef.NestedTypes.FirstOrDefault(a => a.Name == name);
-
- if (null == nestType)
- {
- nestType = new TypeDefinition(typeDef.Namespace, name, TypeAttributes.NestedPrivate | TypeAttributes.BeforeFieldInit | TypeAttributes.Sealed | TypeAttributes.AnsiClass);
- nestType.BaseType = module.ImportReference(typeof(object));
- typeDef.NestedTypes.Add(nestType);
-
- constructor = nestType.AddDefaultConstructor();
- }
- else
- {
- constructor = nestType.Methods.FirstOrDefault(a => a.IsConstructor);
- }
-
- return nestType;
- }
-
- bool TryCoreCompile(ILRootNode rootnode, EXamlContext visitorContext, out Exception exception)
- {
- try
- {
- XmlTypeExtensions.s_xmlnsDefinitions?.Clear();
- XmlTypeExtensions.s_xmlnsDefinitions = null;
-
- visitorContext.Values[rootnode] = new EXamlCreateObject(visitorContext, null, rootnode.TypeReference);
-
- rootnode.Accept(new XamlNodeVisitor((node, parent) => node.Parent = parent), null);
- rootnode.Accept(new EXamlExpandMarkupsVisitor(visitorContext), null);
- rootnode.Accept(new PruneIgnoredNodesVisitor(), null);
- rootnode.Accept(new EXamlCreateObjectVisitor(visitorContext), null);
- rootnode.Accept(new EXamlSetNamescopesAndRegisterNamesVisitor(visitorContext), null);
- rootnode.Accept(new EXamlSetFieldVisitor(visitorContext), null);
- rootnode.Accept(new EXamlSetResourcesVisitor(visitorContext), null);
- rootnode.Accept(new EXamlSetPropertiesVisitor(visitorContext, true), null);
-
- exception = null;
- return true;
- }
- catch (Exception e)
- {
- XamlParseException xamlParseException = e as XamlParseException;
- if (null != xamlParseException)
- {
- XamlParseException ret = new XamlParseException(xamlParseException.Message + "\n" + ReferencePath, xamlParseException.XmlInfo, xamlParseException.InnerException);
- exception = ret;
- }
- else
- {
- exception = e;
- }
-
- return false;
- }
- }
-
- private void Set(ILContext Context, VariableDefinition parent, string localName, INode node, IXmlLineInfo iXmlLineInfo)
- {
- var module = Context.Body.Method.Module;
- TypeReference declaringTypeReference;
- var property = parent.VariableType.GetProperty(pd => pd.Name == localName, out declaringTypeReference);
- if (null == property)
- {
- return;
- }
- var propertySetter = property.SetMethod;
-
- module.ImportReference(parent.VariableType.ResolveCached());
- var propertySetterRef = module.ImportReference(module.ImportReference(propertySetter).ResolveGenericParameters(declaringTypeReference, module));
- propertySetterRef.ImportTypes(module);
- var propertyType = property.ResolveGenericPropertyType(declaringTypeReference, module);
- var valueNode = node as ValueNode;
- var elementNode = node as IElementNode;
-
- if (parent.VariableType.IsValueType)
- Context.IL.Emit(OpCodes.Ldloca, parent);
- else
- Context.IL.Emit(OpCodes.Ldloc, parent);
-
- if (valueNode != null)
- {
- foreach (var instruction in valueNode.PushConvertedValue(Context, propertyType, new ICustomAttributeProvider[] { property, propertyType.ResolveCached() }, valueNode.PushServiceProvider(Context, propertyRef: property), false, true))
- {
- Context.IL.Append(instruction);
- }
-
- if (parent.VariableType.IsValueType)
- Context.IL.Emit(OpCodes.Call, propertySetterRef);
- else
- Context.IL.Emit(OpCodes.Callvirt, propertySetterRef);
- }
- }
-
- internal static string GetPathForType(ModuleDefinition module, TypeReference type)
- {
- foreach (var ca in type.Module.GetCustomAttributes())
- {
- if (!TypeRefComparer.Default.Equals(ca.AttributeType, module.ImportReference((xamlAssemblyName, xamlNameSpace, "XamlResourceIdAttribute"))))
- continue;
- if (!TypeRefComparer.Default.Equals(ca.ConstructorArguments[2].Value as TypeReference, type))
- continue;
- return ca.ConstructorArguments[1].Value as string;
- }
- return null;
- }
-
- internal static string GetResourceIdForPath(ModuleDefinition module, string path)
- {
- foreach (var ca in module.GetCustomAttributes())
- {
- if (!TypeRefComparer.Default.Equals(ca.AttributeType, module.ImportReference((xamlAssemblyName, xamlNameSpace, "XamlResourceIdAttribute"))))
- continue;
- if (ca.ConstructorArguments[1].Value as string != path)
- continue;
- return ca.ConstructorArguments[0].Value as string;
- }
- return null;
- }
- }
-}
-
+++ /dev/null
-/*
- * Copyright(c) 2022 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-using System;
-using System.IO;
-using System.Xml;
-using System.ComponentModel;
-using Microsoft.Build.Framework;
-using Microsoft.Build.Utilities;
-
-namespace Tizen.NUI.Xaml.Build.Tasks
-{
- [EditorBrowsable(EditorBrowsableState.Never)]
- public class XamlGTask : Task
- {
- [Required]
- public ITaskItem[] XamlFiles { get; set; }
-
- [Required]
- public ITaskItem[] OutputFiles { get; set; }
-
- public string Language { get; set; }
- public string AssemblyName { get; set; }
- public string DependencyPaths { get; set; }
- public string ReferencePath { get; set; }
- public int XamlOptimization {get; set;} = 2;
- public bool AddXamlCompilationAttribute { get; set; }
- public bool PrintReferenceAssemblies { get; set; }
-
- private void PrintParam(string logFileName, string log)
- {
- FileStream stream = null;
- if (false == File.Exists(logFileName))
- {
- stream = File.Create(logFileName);
- }
- else
- {
- stream = File.Open(logFileName, FileMode.Append);
- }
-
- byte[] buffer = System.Text.Encoding.Default.GetBytes(log + "\n");
- stream.Write(buffer, 0, buffer.Length);
- stream.Close();
- }
-
- public override bool Execute()
- {
- if (true == PrintReferenceAssemblies)
- {
- PrintParam(@"XamlG_Log.txt", "ReferencePath is " + ReferencePath);
- }
-
- //PrintParam(@"G:\XamlG_Log.txt", "ReferencePath is " + ReferencePath);
- bool success = true;
- //Log.LogMessage(MessageImportance.Normal, "Generating code behind for XAML files");
-
- //NOTE: should not happen due to [Required], but there appears to be a place this is class is called directly
- if (XamlFiles == null || OutputFiles == null) {
- //Log.LogMessage("Skipping XamlG");
- return true;
- }
-
- if (XamlFiles.Length != OutputFiles.Length) {
- Log.LogError("\"{2}\" refers to {0} item(s), and \"{3}\" refers to {1} item(s). They must have the same number of items.", XamlFiles.Length, OutputFiles.Length, "XamlFiles", "OutputFiles");
- return false;
- }
-
- for (int i = 0; i < XamlFiles.Length; i++) {
- var xamlFile = XamlFiles[i];
- var outputFile = OutputFiles[i].ItemSpec;
- if (System.IO.Path.DirectorySeparatorChar == '/' && outputFile.Contains(@"\"))
- outputFile = outputFile.Replace('\\','/');
- else if (System.IO.Path.DirectorySeparatorChar == '\\' && outputFile.Contains(@"/"))
- outputFile = outputFile.Replace('/', '\\');
-
- var generator = new XamlGenerator(xamlFile, Language, AssemblyName, outputFile, ReferencePath, Log);
- generator.AddXamlCompilationAttribute = AddXamlCompilationAttribute;
- generator.XamlOptimization = XamlOptimization;
- generator.ReferencePath = ReferencePath;
-
- try {
- if (!generator.Execute()) {
- //If Execute() fails, the file still needs to exist because it is added to the <Compile/> ItemGroup
- File.WriteAllText (outputFile, string.Empty);
- }
- }
- catch (XmlException xe) {
- Log.LogError(null, null, null, xamlFile.ItemSpec, xe.LineNumber, xe.LinePosition, 0, 0, xe.Message, xe.HelpLink, xe.Source);
- success = false;
- }
- catch (Exception e) {
- Log.LogError(null, null, null, xamlFile.ItemSpec, 0, 0, 0, 0, e.Message, e.HelpLink, e.Source);
- success = false;
- }
- }
-
- return success;
- }
- }
-}
-
IsPartial = true,
TypeAttributes = GetTypeAttributes(classModifier),
CustomAttributes = {
- new CodeAttributeDeclaration(new CodeTypeReference(XamlCTask.xamlNameSpace + ".XamlFilePathAttribute"),
+ new CodeAttributeDeclaration(new CodeTypeReference(NUIXamlCTask.xamlNameSpace + ".XamlFilePathAttribute"),
new CodeAttributeArgument(new CodePrimitiveExpression(XamlFile))),
}
};
if (AddXamlCompilationAttribute)
declType.CustomAttributes.Add(
- new CodeAttributeDeclaration(new CodeTypeReference(XamlCTask.xamlNameSpace + ".XamlCompilationAttribute"),
+ new CodeAttributeDeclaration(new CodeTypeReference(NUIXamlCTask.xamlNameSpace + ".XamlCompilationAttribute"),
new CodeAttributeArgument(new CodeSnippetExpression($"global::{typeof(XamlCompilationOptions).FullName}.Compile"))));
if (HideFromIntellisense)
declType.CustomAttributes.Add(