Ejemplo n.º 1
0
Archivo: Thread.cs Proyecto: Exe0/Eto
		public Thread(Action action, Generator generator = null)
			: base(generator, typeof(IThread), false)
		{
			this.action = action;
			Handler.Create();
			Initialize();
		}
Ejemplo n.º 2
0
        public WhatToDoNext RunProject(string filename)
        {
            IProject project = new Project(filename);

            Generator generator = new Generator(project);

            Console.WriteLine("Processing `{0}'...", filename);
            DateTime start = DateTime.Now;
            try
            {
                generator.Process();
            }
            catch (Exception e)
            {
                Log.Fatal(e);
            }
            DateTime end = DateTime.Now;
            Console.WriteLine("Generated framework for project `{0}'", project.Name);
            Console.WriteLine("    in `{0}' seconds", (end - start).Seconds);
            Console.WriteLine("    at `{0}'", project.OutputPath);
            Console.WriteLine();
            WriteStats(generator.Agregator);
            Console.WriteLine();

            return WhatToDoNext.GoAhead;
        }
Ejemplo n.º 3
0
        public void CrossoverTest()
        {
            var obj = new SimpleClass();
            var generator = new Generator<SimpleClass>();
            CodeExpression<SimpleClass> leftTree = generator.BuildRandomExpressionTree();
            CodeExpression<SimpleClass> rightTree = generator.BuildRandomExpressionTree();

            Trace.WriteLine("Vor dem Crossover");
            Trace.WriteLine("-----------------");
            Trace.WriteLine("");
            Trace.WriteLine("Tree links:");
            Trace.WriteLine(leftTree);

            Trace.WriteLine("");
            Trace.WriteLine("Tree rechts:");
            Trace.WriteLine(rightTree);

            generator.Crossover(ref leftTree, ref rightTree);

            Trace.WriteLine("");
            Trace.WriteLine("Nach dem Crossover");
            Trace.WriteLine("------------------");
            Trace.WriteLine("");
            Trace.WriteLine("Tree links:");
            Trace.WriteLine(leftTree);

            Trace.WriteLine("");
            Trace.WriteLine("Tree rechts:");
            Trace.WriteLine(rightTree);
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Analyses last char of password and removes all chars which are located on same phone key.
 /// </summary>
 /// <returns type="System.Char[]">Array of chars.</returns>
 public override char[] GetChars(Generator generator, Word password, char[] charsList)
 {
     ValidateInput(generator, password, charsList);
     if (charsList.Length == 0) return charsList;
     // Keep only letters and numbers.
     var chars = charsList.Intersect(charsets.Chars["Letnums"]);
     // Limit if this is second+ letter only.
     if (password.Chars.Length > 0)
     {
         // Get last char.
         var lastChar = password.Chars.Last();
         // Route thru GSM Phone keys.
         for (int i = 0; i == 9; i++)
         {
             char[] keys = charsets.Chars["PhoneKey" + i];
             // If current key contains last char of password then...
             if (keys.Contains(lastChar))
             {
                 // Remove all chars located on same key.
                 chars = chars.Intersect(keys);
                 break;
             }
         }
     }
     charsList = chars.ToArray();
     ValidateOutput(generator, password, charsList);
     return charsList;
 }
Ejemplo n.º 5
0
        public override void EmitCode(Generator generator, int depth, int ident)
        {
            if ( String.IsNullOrEmpty( GetName() ) )
                return;

            INode returntype;
            bool constness, pointer;

            string types = base.ResolveType( 1, out returntype, out constness, out pointer );

            types = generator.ResolveType( types, constness, pointer, true, false );

            generator.EmitLine( "public enum " + name + " : " + EnumShortCodes[types], depth );
            generator.EmitLine( "{", depth );

            foreach( INode child in children )
            {
                if ( child is EnumConstantNode )
                {
                    generator.EmitLine( String.Format( "{0} = {1},", child.GetName(), child.GetAttribute( "value" ) ), depth + 1 );
                }
            }

            generator.EmitLine( "};", depth );
            generator.EmitLine( "", depth );
        }
Ejemplo n.º 6
0
 public JabbRApplication(Generator generator = null)
     : base(generator, typeof(IJabbRApplication))
 {
     this.Style = "application";
     this.Name = "JabbR";
     this.Configuration = new JabbR.Desktop.Model.Configuration();
 }
Ejemplo n.º 7
0
 /// <summary>
 ///     Create new ridge generator with user-supplied source. Usually one would use this with <see cref="ValueNoise" /> or
 ///     gradient noise with less dimensions, but
 ///     some weird effects may be achieved with other generators.
 /// </summary>
 /// <param name="source">noise source</param>
 public RidgeNoise(Generator source)
     : base(source)
 {
     Offset = 1;
     Gain = 2;
     m_exponent = 1;
 }
        public bool TryMakeTurbofan(float bypassratio, int numberofshafts, Generator gen, List<Spool> spools, int egt, int isp,
                                    int numberofcycles, List<Propellant> fueList, List<Oxidiser> oxidisers, string manuf, string model,
                                    string serialnumber, float maxpower, float operatingtime, float fuelflow, OnOff stat, out Turbofan incomingTurbofan, bool isgeared = false,
                                    bool hasreverse = true, PoweredAircraft parentvehicle = null)
        {
            try
            {
                Turbofan turbofan = MakeTurbofan(bypassratio, numberofshafts, gen, spools, egt, isp,
                    numberofcycles, fueList,
                    oxidisers, manuf, model, serialnumber, maxpower, operatingtime, fuelflow, stat, isgeared, hasreverse,
                    parentvehicle);

                incomingTurbofan = turbofan;
                return true;
            }
            catch (ArgumentNullException argumentNullException)
            {
                Console.WriteLine(argumentNullException.Message);
                incomingTurbofan = null;
                return false;
            }
            catch (ArgumentException argumentException)
            {
                Console.WriteLine(argumentException.Message);
                incomingTurbofan = null;
                return false;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                incomingTurbofan = null;
                return false;
            }
        }
Ejemplo n.º 9
0
		///<summary>
		/// Create new translation
		///</summary>
		///<param name="source">Source generator</param>
		///<param name="x">Translate amount along X axis</param>
		///<param name="y">Translate amount along Y axis</param>
		///<param name="z">Translate amount along Z axis</param>
		public Translate(Generator source, float x, float y, float z)
		{
			m_source = source;
			m_z = z;
			m_y = y;
			m_x = x;
		}
Ejemplo n.º 10
0
 /// <summary>
 /// Creates a new fractal noise, supplying your own source generator
 /// </summary>
 /// <param name="source">source noise</param>
 protected FractalNoiseBase(Generator source)
 {
     m_Noise = source;
     Lacunarity = 2.17f;
     OctaveCount = 6;
     Frequency = 1;
 }
Ejemplo n.º 11
0
 // Use this for initialization
 void Start()
 {
     g = GameObject.Find("Main Camera").GetComponent<Generator>();
     var t = GetComponent<Renderer>().material;
     t.SetFloat("X_Curvature", g.sindelta * 0.005f);
     t.SetFloat("Y_Curvature", g.cosdelta * 0.005f);
 }
Ejemplo n.º 12
0
        public void When_changing_only_single_bit_then_the_id_is_generated_correctly()
        {
            var numberOfGenerators = Math.Pow(2, Generator.NumberOfGeneratorIdBits);
            var target = new byte[8];
            var generator = new Generator((short)(numberOfGenerators - 1), DateTime.Today);

            generator.WriteValuesToByteArray(target, 4398046511103, 8191);
            Assert.Equal(new string('1', 64), GetString(target));

            generator.WriteValuesToByteArray(target, 4398046511103, 8190);
            Assert.Equal(new string('1', 63) + "0", GetString(target));

            generator.WriteValuesToByteArray(target, 4398046511102, 8191);
            Assert.Equal(
                new string('1', Generator.NumberOfTimeBits - 1) + "0" + new string('1', 64 - Generator.NumberOfTimeBits),
                GetString(target));

            generator = new Generator((short)(numberOfGenerators - 2), DateTime.Today);
            generator.WriteValuesToByteArray(target, 4398046511103, 8191);
            Assert.Equal(
                new string('1', 63 - Generator.NumberOfSequenceBits) + "0" + new string('1', Generator.NumberOfSequenceBits),
                GetString(target));

            for (int i = 0; i < numberOfGenerators; i++)
            {
                generator = new Generator((short)i, DateTime.Today);
                generator.WriteValuesToByteArray(target, 0, 0);
                Assert.Equal(new string('0', Generator.NumberOfTimeBits), GetString(target).Substring(0, Generator.NumberOfTimeBits));
                Assert.Equal(new string('0', Generator.NumberOfSequenceBits), GetString(target).Substring(64 - Generator.NumberOfSequenceBits, Generator.NumberOfSequenceBits));

                var m = Convert.ToString(i, 2).PadLeft(Generator.NumberOfGeneratorIdBits, '0');
                Assert.Equal(m, GetString(target).Substring(Generator.NumberOfTimeBits, Generator.NumberOfGeneratorIdBits));
            }
        }
Ejemplo n.º 13
0
		/// <summary>
		/// Clears the pen cache
		/// </summary>
		/// <remarks>
		/// This is useful if you are using the <see cref="Cached"/> method to cache pens and want to clear it
		/// to conserve memory or resources.
		/// </remarks>
		/// <param name="generator">Generator to clear the pen cache for</param>
		public static void ClearCache (Generator generator = null)
		{
			var cache = generator.Cache<PenKey, Pen> (cacheKey);
			lock (cache) {
				cache.Clear ();
			}
		}
Ejemplo n.º 14
0
		public override ToolItem GenerateToolBarItem(Generator generator, ToolBarTextAlign textAlign)
		{
			var tbb = new SeparatorToolItem(generator) { Type = ToolBarType };
			if (!string.IsNullOrEmpty (ToolBarItemStyle))
				tbb.Style = ToolBarItemStyle;
			return tbb;
		}
Ejemplo n.º 15
0
 /// <summary>
 /// Analyses type of last char (volve or consonant) and removes all chars of same type.
 /// This creates <volve>,<consonant>,<volve>,<consonant>,... password.
 /// </summary>
 /// <returns type="System.Char[]">Array of chars.</returns>
 public override char[] GetChars(Generator generator, Word password, char[] charsList)
 {
     ValidateInput(generator, password, charsList);
     if (charsList.Length == 0) return charsList;
     // Keep only proper chars (volves and consonants).
     var chars = charsList.Intersect(charsets.Chars["Letters"]);
     // If password already contains some chars then...
     if (password.Chars.Length > 0)
     {
         // If last character is volve then...
         if (charsets.Chars["Volves"].Contains(password.Chars.Last()))
         {
             // Keep only consonants.
             chars = chars.Intersect(charsets.Chars["Consonants"]);
         }
         else
         {
             // Keep only volves.
             chars = chars.Intersect(charsets.Chars["Volves"]);
         }
     }
     charsList = chars.ToArray();
     ValidateOutput(generator, password, charsList);
     return charsList;
 }
Ejemplo n.º 16
0
		///<summary>
		/// Create new scaling
		///</summary>
		///<param name="source">Source generator</param>
		///<param name="x">Scale amount along X axis</param>
		///<param name="y">Scale amount along Y axis</param>
		///<param name="z">Scale amount along Z axis</param>
		public Scale(Generator source, float x, float y, float z)
		{
			m_source = source;
			m_z = z;
			m_y = y;
			m_x = x;
		}
Ejemplo n.º 17
0
 ///<summary>
 /// Create new scaling
 ///</summary>
 ///<param name="source">Source generator</param>
 ///<param name="x">Scale amount along X axis</param>
 ///<param name="y">Scale amount along Y axis</param>
 ///<param name="z">Scale amount along Z axis</param>
 public Scale(Generator source, float x, float y, float z)
 {
     m_Source = source;
     m_Z = z;
     m_Y = y;
     m_X = x;
 }
Ejemplo n.º 18
0
 // Use this for initialization
 void Start()
 {
     this.client = new CIPC_CS_Unity.CLIENT.CLIENT(this.myPort, this.remoteIP, this.serverPort);
     this.client.Setup(CIPC_CS_Unity.CLIENT.MODE.Sender);
     this.generator = GameObject.FindGameObjectWithTag("Generator").GetComponent<Generator>();
     this.List_SendHuman = new List<Human>();
 }
Ejemplo n.º 19
0
		/// <summary>
		/// Initializes a new instance of the IndexedBitmap class
		/// </summary>
		/// <param name="generator">Generator to use for the handler</param>
		/// <param name="width">Width of the bitmap in pixels</param>
		/// <param name="height">Height of the bitmap in pixels</param>
		/// <param name="bitsPerPixel">Number of bits per pixel, usually 4 (16 colours), 8 (64 colours), or 8 (256 colours)</param>
		public IndexedBitmap (Generator generator, int width, int height, int bitsPerPixel)
			: base(generator, typeof(IIndexedBitmap))
		{
			this.BitsPerPixel = bitsPerPixel;
			handler = (IIndexedBitmap)Handler;
			handler.Create(width, height, bitsPerPixel);
		}
Ejemplo n.º 20
0
 /// <summary>
 /// Analyse password and make suer that all char types set for use are used inside password.
 /// </summary>
 /// <returns type="System.Char[]">Array of chars.</returns>
 public override char[] GetChars(Generator generator, Word password, char[] charsList)
 {
     ValidateInput(generator, password, charsList);
     if (charsList.Length == 0) return charsList;
     Preset p = generator.Preset;
     // How many chars left to generate.
     int leftChars = p.PasswordLength - password.Chars.Length;
     bool haveUppercase = p.UseUppercase && password.Chars.Intersect(p.CharsUppercase).Count() > 0;
     bool haveLowercase = p.UseLowercase && password.Chars.Intersect(p.CharsLowercase).Count() > 0;
     bool haveNumbers = p.UseNumbers && password.Chars.Intersect(p.CharsNumbers).Count() > 0;
     bool haveSymbols = p.UseSymbols && password.Chars.Intersect(p.CharsSymbols).Count() > 0;
     bool haveExtra = p.UseExtra && p.CharsExtra.Length > 0 && password.Chars.Intersect(p.CharsExtra).Count() > 0;
     // How many char types are not used yet.
     int tc = 0;
     if (p.UseUppercase && !haveUppercase) tc++;
     if (p.UseLowercase && !haveLowercase) tc++;
     if (p.UseNumbers && !haveNumbers) tc++;
     if (p.UseSymbols && !haveSymbols) tc++;
     if (p.UseExtra && !haveExtra) tc++;
     // if no space for random generation left then...
     if (leftChars == tc)
     {
         Preset preset = generator.Preset.Copy();
         //Disable chars which were used
         if (preset.UseUppercase && haveUppercase) preset.UseUppercase = false;
         if (preset.UseLowercase && haveLowercase) preset.UseLowercase = false;
         if (preset.UseNumbers && haveNumbers) preset.UseNumbers = false;
         if (preset.UseSymbols && haveSymbols) preset.UseSymbols = false;
         if (preset.UseExtra && haveExtra) preset.UseExtra = false;
         // Generate new chars list.
         charsList = preset.GetChars().Intersect(charsList).ToArray();
     }
     ValidateOutput(generator, password, charsList);
     return charsList;
 }
Ejemplo n.º 21
0
        ///<summary>
        /// Creates a texture to use as a bump map, taking height settings as input.
        ///</summary>
        ///<param name="length">Texture length.</param>
        ///<param name="height">Texture height</param>
        ///<param name="settings">heightmap  source</param>
        ///<returns></returns>
        public static Texture BumpMap(int width, int height, Generator noise)
        {
            var res = new Texture2D(width, height, TextureFormat.RGB24, false);
            for (int mip = 0; mip < res.mipmapCount; mip++)
            {
                Color[] cols = new Color[width * height];
                for (int ii = 0; ii < width; ii++)
                {
                    for (int jj = 0; jj < height; jj++)
                    {
                        var left = noise.GetValue((ii - 0.5f) / width, (float)jj / height, 0);
                        var right = noise.GetValue((ii + 0.5f) / width, (float)jj / height, 0);
                        var down = noise.GetValue((float)ii / width, (jj - 0.5f) / height, 0);
                        var up = noise.GetValue((float)ii / width, (jj + 0.5f) / height, 0);
                        Vector3 normal = new Vector3(right - left, up - down, 1).normalized;
                        cols[ii + jj * width] = new Color(normal.x, normal.y, normal.z);
                    }
                }
                res.SetPixels(cols, mip);
                width >>= 1;
                height >>= 1;
            }
            res.Apply(false);

            return res;
        }
Ejemplo n.º 22
0
		protected Application(Generator g, Type type, bool initialize = true)
				: base(g, type, initialize)
		{
			Application.Instance = this;
			handler = (IApplication)base.Handler;
			Generator.Initialize(g); // make everything use this by default
		}
Ejemplo n.º 23
0
		protected RadioMenuItem (Generator generator, Type type, RadioMenuItem controller, bool initialize = true)
			: base (generator, type, false)
		{
			Handler.Create (controller);
			if (initialize)
				Initialize ();
		}
        public void ParseTracker()
        {
            var generator = new Generator();
            generator.Settings.ContextNaming = ContextNaming.Preserve;
            generator.Settings.EntityNaming = EntityNaming.Singular;
            generator.Settings.RelationshipNaming = RelationshipNaming.ListSuffix;
            generator.Settings.TableNaming = TableNaming.Singular;

            var selector = GetDatabaseSchema("Tracker");
            Assert.IsNotNull(selector);

            EntityContext entityContext = generator.Generate(selector);

            Assert.IsNotNull(entityContext);

            var settings = new XmlWriterSettings { Indent = true };
            var serializer = new XmlSerializer(typeof(EntityContext));

            using (var writer = XmlWriter.Create(@"..\..\Tracker.Generated.xml", settings))
                serializer.Serialize(writer, entityContext);

            string contextDirectory = @"..\..\..\Tracker.Core";
            string mappingDirectory = @"..\..\..\Tracker.Core\Mapping";

            Synchronizer.UpdateFromSource(entityContext, contextDirectory, mappingDirectory);

            using (var writer = XmlWriter.Create(@"..\..\Tracker.Updated.xml", settings))
                serializer.Serialize(writer, entityContext);
        }
Ejemplo n.º 25
0
        static void Main(string[] args)
        {
            // Flag to indicate if we should write a report about every decision we make:
            var report = false;
            // Flag to indicate if we should launch the installer integrity tester at the end:
            var testIntegrity = false;
            // Flag to indicate if we should include all feature-unassigned files in FW_Core:
            var addOrphans = false;

            foreach (var arg in args)
            {
                switch (arg.ToLowerInvariant())
                {
                    case "report":
                        report = true;
                        break;
                    case "check":
                        testIntegrity = true;
                        break;
                    case "addorphans":
                        addOrphans = true;
                        break;
                }
            }
            var gen = new Generator(report, addOrphans, testIntegrity);
            gen.Run();
        }
Ejemplo n.º 26
0
		public GeneratorContext(Generator g)
		{
			previous = Generator.Current;
			previousValidate = Generator.ValidateGenerator;
			Generator.Initialize(g);
			Eto.Generator.ValidateGenerator = g;
		}
Ejemplo n.º 27
0
 /// <summary>
 /// Creates a new fractal noise using default source: gradient noise seeded by supplied seed value
 /// </summary>
 /// <param name="seed">seed value</param>
 protected FractalNoiseBase(int seed)
 {
     m_Noise = new GradientNoise(seed);
     Lacunarity = 2.17f;
     OctaveCount = 6;
     Frequency = 1;
 }
Ejemplo n.º 28
0
 public virtual void ValidateOutput(Generator generator, Word password, char[] chars)
 {
     if (chars.Length == 0)
     {
         password.AppendLog("Error: '{0}' filter removed all chars from list.\r\n", FilterName);
     }
 }
Ejemplo n.º 29
0
		/// <summary>
		/// Initializes a new instance of the <see cref="Eto.Forms.Window"/> class.
		/// </summary>
		/// <param name="generator">Generator to create the handler instance</param>
		/// <param name="type">Type of interface to create for the handler, must implement <see cref="IWindow"/></param>
		/// <param name="initialize"><c>true</c> to initialize the handler, false if the subclass will initialize</param>
		protected Window(Generator generator, Type type, bool initialize = true)
			: base(generator, type, false)
		{
			if (initialize)
				Initialize();
			HandleEvent(ClosedEvent);
		}
Ejemplo n.º 30
0
		public override MenuItem Generate(Generator generator)
		{
			var mi = new SeparatorMenuItem(generator);
			if (!string.IsNullOrEmpty(MenuItemStyle))
				mi.Style = MenuItemStyle;
			return mi;
		}
Ejemplo n.º 31
0
 public override void Prepare(Generator generator)
 {
     base.Prepare(generator);
     slot = generator.Assembler.AddVariable();
     statement.Prepare(generator);
 }
 public void UndefinedBoundTypeThrowsArgumentOutOfRangeException(int sut, Generator <int> g, int bound1, int bound2) =>
 Should.Throw <ArgumentOutOfRangeException>(() => sut.InRange(bound1, bound2, (BoundType)g.First(n => n > 100)))
 .ParamName.ShouldBe("boundType");
        public void TestMultipleElementSet()
        {
            var values = new[] { Generator.GetInt32().ToString(), Generator.GetInt32().ToString(), Generator.GetInt32().ToString() };

            // Construction using ImmutableSortedTreeSet.Create
            var set = ImmutableSortedTreeSet.Create(values);

            Assert.Equal(values.OrderBy(x => x, Comparer <string> .Default), set);

            set = ImmutableSortedTreeSet.Create <string>(comparer: null, values);
            Assert.Same(Comparer <string> .Default, set.KeyComparer);
            Assert.Equal(values.OrderBy(x => x, Comparer <string> .Default), set);

            set = ImmutableSortedTreeSet.Create(StringComparer.OrdinalIgnoreCase, values);
            Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
            Assert.Equal(values.OrderBy(x => x, StringComparer.OrdinalIgnoreCase), set);

            // Construction using ImmutableSortedTreeSet.ToImmutableSortedTreeSet
            set = values.ToImmutableSortedTreeSet();
            Assert.Same(Comparer <string> .Default, set.KeyComparer);
            Assert.Equal(values.OrderBy(x => x, Comparer <string> .Default), set);

            set = values.ToImmutableSortedTreeSet(comparer: null);
            Assert.Same(Comparer <string> .Default, set.KeyComparer);
            Assert.Equal(values.OrderBy(x => x, Comparer <string> .Default), set);

            set = values.ToImmutableSortedTreeSet(StringComparer.OrdinalIgnoreCase);
            Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
            Assert.Equal(values.OrderBy(x => x, StringComparer.OrdinalIgnoreCase), set);
        }
        public void TestMinMax()
        {
            Assert.Equal(0, ImmutableSortedTreeSet <int> .Empty.Min);
            Assert.Equal(0, ImmutableSortedTreeSet <int> .Empty.Max);
            Assert.Null(ImmutableSortedTreeSet <object> .Empty.Min);
            Assert.Null(ImmutableSortedTreeSet <object> .Empty.Max);

            var set = ImmutableSortedTreeSet.CreateRange(Enumerable.Range(0, 100).Select(x => Generator.GetInt32()));

            Assert.Equal(set.Min(), set.Min);
            Assert.Equal(set.Max(), set.Max);
        }
Ejemplo n.º 35
0
 public IFileBody End()
 {
     Data = Generator.Generate(PatternConfig.ClassPattern);
     Source.Invoke().Generator.AddGenerationData(typeof(IClass), Data);
     return(Source.Invoke());
 }
Ejemplo n.º 36
0
 public Clipboard(Generator generator)
     : base(generator, typeof(Clipboard.IHandler))
 {
 }
Ejemplo n.º 37
0
 public override void Resolve(Generator generator)
 {
     base.Resolve(generator);
     expression.Resolve(generator);
     statement.Resolve(generator);
 }
Ejemplo n.º 38
0
        private void EmitCodeStruct(Generator generator, int depth, int ident)
        {
            generator.EmitLine("[StructLayout(LayoutKind.Sequential,Pack=8)]", depth);
            int attribMarker = generator.GetMarker();

            generator.EmitLine("public struct " + GetName(), depth);
            generator.EmitLine("{", depth);

            foreach (INode child in children)
            {
                if (child is FieldNode && !String.IsNullOrEmpty(child.GetName()))
                {
                    INode basetype;
                    bool  constness, pointer;
                    bool  arraytype = false;

                    string size  = "";
                    string types = child.ResolveType(0, out basetype, out constness, out pointer);

                    if (basetype is ArrayTypeNode)
                    {
                        size  = basetype.GetAttribute("size");
                        types = basetype.ResolveType(1, out basetype, out constness, out pointer);

                        pointer   = true;
                        arraytype = true;
                    }

                    types = generator.ResolveType(types, constness, pointer, true, false);

                    if (types == "bool")
                    {
                        generator.EmitLine("[MarshalAs(UnmanagedType.I1)]", depth + 1);
                    }
                    else if (types == "string")
                    {
                        if (arraytype)
                        {
                            generator.EmitLine("[MarshalAs(UnmanagedType.ByValTStr, SizeConst = " + size + ")]", depth + 1);
                        }
                        else
                        {
                            types = "string";
                        }
                    }
                    else if (types == "Byte[]")
                    {
                        if (arraytype)
                        {
                            generator.EmitLine("[MarshalAs(UnmanagedType.ByValArray, SizeConst = " + size + ")]", depth + 1);
                        }
                        else
                        {
                            types = "IntPtr";
                        }
                    }
                    else if (types == "CSteamID" || types == "CGameID")
                    {
                        types = "UInt64";
                    }
                    else if (pointer)
                    {
                        types = "IntPtr";
                    }
                    else if (types == child.GetName())
                    {
                        continue;
                    }

                    generator.EmitLine(String.Format("public {0} {1};", types, child.GetName()), depth + 1);
                }
                else if (child is EnumNode)
                {
                    // anonymous enum declaration
                    EnumNode innerEnum = child as EnumNode;
                    int      callback  = innerEnum.EmitCodeInnerStructCallback(generator, depth + 1);

                    if (callback > 0)
                    {
                        generator.InsertLine("[InteropHelp.CallbackIdentity(" + callback + ")]", attribMarker, depth);
                    }
                }
                else if (child is FieldNode)
                {
                    //  anonymous field like union
                    // not implemented!
                }
            }

            generator.EmitLine("};", depth);
            generator.EmitLine("", depth);
        }
 internal SectionSourceModelCollection(Generator processor)
 {
     Processor = processor;
     DocumentBussinessManager = new DocumentBussiness();
 }
Ejemplo n.º 40
0
        private void EmitCodeClass(Generator generator, int depth, int ident)
        {
            generator.EmitLine("[StructLayout(LayoutKind.Sequential,Pack=4)]", depth);
            generator.EmitLine("public class " + name + "VTable", depth);
            generator.EmitLine("{", depth);

            int index = 0;

            foreach (INode child in children)
            {
                if (child is CXXMethodNode && ShouldEmitMember(child))
                {
                    generator.EmitLine("public IntPtr " + child.GetName() + index++ + ";", depth + 1);
                }
                else if (child is CXXDestructorNode)
                {
                    generator.EmitLine("private IntPtr DTor" + GetName() + index++ + ";", depth + 1);
                }
            }

            generator.EmitLine("};", depth);
            generator.EmitLine("", depth);

            string className = GetName().Substring(1);
            string macroName = null;

            if (className.StartsWith("Steam"))
            {
                string classValue = className.Substring(0, className.Length - 3).ToUpper();
                string intValue   = className.Substring(className.Length - 3, 3);

                macroName = classValue + "_INTERFACE_VERSION_" + intValue;
            }
            else if (className.StartsWith("Client"))
            {
                macroName = className.ToUpper() + "_INTERFACE_VERSION";
            }

            if (macroName != null)
            {
                string macroValue = generator.FindMacroByName(macroName);

                if (macroValue != null)
                {
                    generator.EmitLine("[InteropHelp.InterfaceVersion(" + macroValue + ")]", depth);
                }
            }

            generator.EmitLine("public class " + GetName() + " : InteropHelp.NativeWrapper<" + GetName() + "VTable>", depth);
            generator.EmitLine("{", depth);

            index = 0;

            foreach (INode child in children)
            {
                if (child is CXXDestructorNode)
                {
                    index++;
                }
                else if (child is CXXMethodNode && ShouldEmitMember(child))
                {
                    child.EmitCode(generator, depth + 1, index++);
                }
            }

            generator.EmitLine("};", depth);
        }
Ejemplo n.º 41
0
 /// <summary>
 /// Multiplies how much the "vertices" of each cell are skewed.<br/>
 /// 0 will create perfect squares, whereas 1 will push those "vertices" around and create a cellular / fractured look.
 /// </summary>
 /// <param name="gen">Generator to use</param>
 public void SetJitterModifier(Generator gen)
 {
     API_CellularSetJitterModifierGen(_genID, (int)_type, gen._genID);
 }
Ejemplo n.º 42
0
 public InitCommand(CommandLineOptions options)
 {
     _options         = options;
     NModelsGenerator = new Generator();
 }
Ejemplo n.º 43
0
        public TagBuilder ProcessTagBuilder(TagHelperContext context, TagHelperOutput output)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            // Pass through attributes that are also well-known HTML attributes. Must be done prior to any copying
            // from a TagBuilder.

            // NP: Had to add && context.AllAttributes.ContainsName("type") because CopyHtmlAttribute expects value in context attributes
            // issue is that we already set the InputTypeName in the constructor (with our different usage). I THINK these values
            // are only set if THE USER sent in a value in the tags...
            if (InputTypeName != null && context.AllAttributes.ContainsName("type"))
            {
                output.CopyHtmlAttribute("type", context);
            }

            if (Value != null && context.AllAttributes.ContainsName(nameof(Value)))
            {
                output.CopyHtmlAttribute(nameof(Value), context);
            }

            // Note null or empty For.Name is allowed because TemplateInfo.HtmlFieldPrefix may be sufficient.
            // IHtmlGenerator will enforce name requirements.
            var metadata      = For.Metadata;
            var modelExplorer = For.ModelExplorer;

            if (metadata == null)
            {
                ThrowExOnMetadataNull(ForAttributeName, For.Name);
            }

            string inputType;
            string inputTypeHint;

            if (string.IsNullOrEmpty(InputTypeName))
            {
                // Note GetInputType never returns null.
                inputType = GetInputType(modelExplorer, out inputTypeHint);
            }
            else
            {
                inputType     = InputTypeName.ToLowerInvariant();
                inputTypeHint = null;
            }

            // inputType may be more specific than default the generator chooses below.
            if (!output.Attributes.ContainsName("type"))
            {
                output.Attributes.SetAttribute("type", inputType);
            }

            TagBuilder tagBuilder;

            switch (inputType)
            {
            case "hidden":
                tagBuilder = GenerateHidden(modelExplorer, null);
                break;

            case "checkbox":
                tagBuilder = GenerateCheckBox(modelExplorer, output, null);
                break;

            case "password":
                tagBuilder = Generator.GeneratePassword(
                    ViewContext,
                    modelExplorer,
                    For.Name,
                    value: null,
                    htmlAttributes: null);
                break;

            case "radio":
                tagBuilder = GenerateRadio(modelExplorer, null);
                break;

            default:
                tagBuilder = GenerateTextBox(modelExplorer, inputTypeHint, inputType, null);
                break;
            }
            return(tagBuilder);
        }
Ejemplo n.º 44
0
        /// <inheritdoc />
        /// <remarks>Does nothing if <see cref="For"/> is <c>null</c>.</remarks>
        /// <exception cref="InvalidOperationException">
        /// Thrown if <see cref="Format"/> is non-<c>null</c> but <see cref="For"/> is <c>null</c>.
        /// </exception>
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            // Pass through attributes that are also well-known HTML attributes. Must be done prior to any copying
            // from a TagBuilder.
            if (InputTypeName != null)
            {
                output.CopyHtmlAttribute("type", context);
            }

            if (Value != null)
            {
                output.CopyHtmlAttribute(nameof(Value), context);
            }

            // Note null or empty For.Name is allowed because TemplateInfo.HtmlFieldPrefix may be sufficient.
            // IHtmlGenerator will enforce name requirements.
            var metadata      = For.Metadata;
            var modelExplorer = For.ModelExplorer;

            if (metadata == null)
            {
                throw new InvalidOperationException(Resources.FormatTagHelpers_NoProvidedMetadata(
                                                        "<input>",
                                                        ForAttributeName,
                                                        nameof(IModelMetadataProvider),
                                                        For.Name));
            }

            string inputType;
            string inputTypeHint;

            if (string.IsNullOrEmpty(InputTypeName))
            {
                // Note GetInputType never returns null.
                inputType = GetInputType(modelExplorer, out inputTypeHint);
            }
            else
            {
                inputType     = InputTypeName.ToLowerInvariant();
                inputTypeHint = null;
            }

            // inputType may be more specific than default the generator chooses below.
            if (!output.Attributes.ContainsName("type"))
            {
                output.Attributes.SetAttribute("type", inputType);
            }

            TagBuilder tagBuilder;

            switch (inputType)
            {
            case "hidden":
                tagBuilder = GenerateHidden(modelExplorer);
                break;

            case "checkbox":
                tagBuilder = GenerateCheckBox(modelExplorer, output);
                break;

            case "password":
                tagBuilder = Generator.GeneratePassword(
                    ViewContext,
                    modelExplorer,
                    For.Name,
                    value: null,
                    htmlAttributes: null);
                break;

            case "radio":
                tagBuilder = GenerateRadio(modelExplorer);
                break;

            default:
                tagBuilder = GenerateTextBox(modelExplorer, inputTypeHint, inputType);
                break;
            }

            if (tagBuilder != null)
            {
                // This TagBuilder contains the one <input/> element of interest.
                output.MergeAttributes(tagBuilder);
                if (tagBuilder.HasInnerHtml)
                {
                    // Since this is not the "checkbox" special-case, no guarantee that output is a self-closing
                    // element. A later tag helper targeting this element may change output.TagMode.
                    output.Content.AppendHtml(tagBuilder.InnerHtml);
                }
            }
        }
Ejemplo n.º 45
0
        public void Generator_ForSequence2()
        {
            int[] expected = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512 };

            Assert.AreEqual(expected, Generator.Generate(1, 2, (first, second) => (6 * second - 8 * first), 10));
        }
Ejemplo n.º 46
0
 public void SetUp()
 {
     generator = new Generator();
 }
Ejemplo n.º 47
0
 public TableLayout(Size size, Generator generator = null)
     : base(generator, typeof(ITableLayout), false)
 {
     this.CellSize = size;
 }
Ejemplo n.º 48
0
        public void Generator_ForSequence1()
        {
            int[] expected = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 };

            Assert.AreEqual(expected, Generator.Generate(1, 1, (first, second) => (second + first), 10));
        }
Ejemplo n.º 49
0
        /// <summary>
        /// 访问并呈现当前标签实例。
        /// </summary>
        /// <param name="context">当前HTML标签上下文,包含当前HTML相关信息。</param>
        /// <param name="output">当前标签输出实例,用于呈现标签相关信息。</param>
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            Data = Data ?? ViewContext.ViewData.Model as IPageEnumerable;
            if (Data == null || Data.Pages == 0)
            {
                output.SuppressOutput();
                return;
            }
            if (context.AllAttributes.ContainsName(HrefAttributeName))
            {
                _createAnchor = page =>
                {
                    var tagBuilder = new TagBuilder("a");
                    tagBuilder.MergeAttribute("href", Href.Replace("$page;", page.ToString()));
                    return(tagBuilder);
                };
            }
            else
            {
                IDictionary <string, object> routeValues = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);
                if (_routeValues != null && _routeValues.Count > 0)
                {
                    foreach (var routeValue in _routeValues)
                    {
                        routeValues.Add(routeValue.Key, routeValue.Value);
                    }
                }

                if (Area != null)
                {
                    routeValues["area"] = Area;
                }

                if (Route == null)
                {
                    _createAnchor = page =>
                    {
                        routeValues["page"] = page;
                        return(Generator.GenerateActionLink(
                                   ViewContext,
                                   linkText: string.Empty,
                                   actionName: Action,
                                   controllerName: Controller,
                                   protocol: Protocol,
                                   hostname: Host,
                                   fragment: Fragment,
                                   routeValues: routeValues,
                                   htmlAttributes: null));
                    };
                }
                else
                {
                    _createAnchor = page =>
                    {
                        routeValues["page"] = page;
                        return(Generator.GenerateRouteLink(
                                   ViewContext,
                                   linkText: string.Empty,
                                   routeName: Route,
                                   protocol: Protocol,
                                   hostName: Host,
                                   fragment: Fragment,
                                   routeValues: routeValues,
                                   htmlAttributes: null));
                    };
                }
            }

            var builder = new TagBuilder("ul");

            builder.AddCssClass("pagination");
            if (!Border)
            {
                builder.AddCssClass("borderless");
            }
            int endIndex;
            var startIndex = Cores.GetRange(Data.Page, Data.Pages, Factor, out endIndex);

            if (Data.Page > 1)
            {
                builder.InnerHtml.AppendHtml(CreateLink(Data.Page - 1, Resources.LastPage, title: Resources.LastPage));
            }
            if (startIndex > 1)
            {
                builder.InnerHtml.AppendHtml(CreateLink(1, "1"));
            }
            if (startIndex > 2)
            {
                builder.InnerHtml.AppendHtml("<li><span>…</span></li>");
            }
            for (int i = startIndex; i < endIndex; i++)
            {
                builder.InnerHtml.AppendHtml(CreateLink(i, i.ToString(), "active"));
            }
            if (endIndex < Data.Pages)
            {
                builder.InnerHtml.AppendHtml("<li><span>…</span></li>");
            }
            if (endIndex <= Data.Pages)
            {
                builder.InnerHtml.AppendHtml(CreateLink(Data.Pages, Data.Pages.ToString()));
            }
            if (Data.Page < Data.Pages)
            {
                builder.InnerHtml.AppendHtml(CreateLink(Data.Page + 1, Resources.NextPage, title: Resources.NextPage));
            }
            output.TagName = "ul";
            output.MergeAttributes(builder);
            output.Content.AppendHtml(builder.InnerHtml);
        }
 private void Generate()
 {
     Generator.Generate(attribute, contentType);
 }
Ejemplo n.º 51
0
 /// <inheritdoc/>
 public override string ToString() => $"SrpParameters.Create<{Hasher.AlgorithmName}>(\"{Prime.ToHex()}\", \"{Generator.ToHex()}\")";
Ejemplo n.º 52
0
 public TableLayout(int width, int height, Generator generator = null)
     : this(new Size(width, height), generator)
 {
 }
Ejemplo n.º 53
0
 public TreeGridView(Generator generator) : this(generator, typeof(IHandler))
 {
 }
Ejemplo n.º 54
0
            public bool Execute(GeneratorExecutionContext context)
            {
                Lang language;

                switch (Language)
                {
                case LanguageNames.CSharp:
                    language = Lang.CSharp;
                    break;

                case LanguageNames.VisualBasic:
                    language = Lang.VisualBasic;
                    break;

                default:
                    LogError(Lang.CSharp, $"GenerateResxSource doesn't support language: '{Language}'");
                    return(false);
                }

                var extension = language switch
                {
                    Lang.CSharp => "cs",
                    Lang.VisualBasic => "vb",
                    _ => "cs",
                };

                OutputTextHintName = ResourceName + $".Designer.{extension}";

                if (string.IsNullOrEmpty(ResourceName))
                {
                    LogError(language, "ResourceName not specified");
                    return(false);
                }

                var resourceAccessName = RoslynString.IsNullOrEmpty(ResourceClassName) ? ResourceName : ResourceClassName;

                SplitName(resourceAccessName, out var namespaceName, out var className);

                var classIndent  = namespaceName == null ? "" : "    ";
                var memberIndent = classIndent + "    ";

                var text = ResourceFile.GetText(context.CancellationToken);

                if (text is null)
                {
                    LogError(language, "ResourceFile was null");
                    return(false);
                }

                var strings = new StringBuilder();

                foreach (var node in XDocument.Parse(text.ToString()).Descendants("data"))
                {
                    var name = node.Attribute("name")?.Value;
                    if (name == null)
                    {
                        LogError(language, "Missing resource name");
                        return(false);
                    }

                    var value = node.Elements("value").FirstOrDefault()?.Value.Trim();
                    if (value == null)
                    {
                        LogError(language, $"Missing resource value: '{name}'");
                        return(false);
                    }

                    if (name.Length == 0)
                    {
                        LogError(language, $"Empty resource name");
                        return(false);
                    }

                    var docCommentString = value.Length > maxDocCommentLength?value.Substring(0, maxDocCommentLength) + " ..." : value;

                    RenderDocComment(language, memberIndent, strings, docCommentString);

                    var identifier = GetIdentifierFromResourceName(name);

                    var defaultValue = IncludeDefaultValues ? ", " + CreateStringLiteral(value, language) : string.Empty;

                    switch (language)
                    {
                    case Lang.CSharp:
                        if (AsConstants)
                        {
                            strings.AppendLine($"{memberIndent}internal const string @{identifier} = \"{name}\";");
                        }
                        else
                        {
                            strings.AppendLine($"{memberIndent}internal static {(IncludeDefaultValues || !Generator.SupportsNullable(context) ? "string" : "string?")} @{identifier} => GetResourceString(\"{name}\"{defaultValue});");
                        }

                        if (EmitFormatMethods)
                        {
                            var resourceString = new ResourceString(name, value);

                            if (resourceString.HasArguments)
                            {
                                RenderDocComment(language, memberIndent, strings, docCommentString);
                                RenderFormatMethod(memberIndent, language, strings, resourceString);
                            }
                        }
                        break;

                    case Lang.VisualBasic:
                        if (AsConstants)
                        {
                            strings.AppendLine($"{memberIndent}Friend Const [{identifier}] As String = \"{name}\"");
                        }
                        else
                        {
                            strings.AppendLine($"{memberIndent}Friend Shared ReadOnly Property [{identifier}] As String");
                            strings.AppendLine($"{memberIndent}  Get");
                            strings.AppendLine($"{memberIndent}    Return GetResourceString(\"{name}\"{defaultValue})");
                            strings.AppendLine($"{memberIndent}  End Get");
                            strings.AppendLine($"{memberIndent}End Property");
                        }

                        if (EmitFormatMethods)
                        {
                            throw new NotImplementedException();
                        }
                        break;

                    default:
                        throw new InvalidOperationException();
                    }
                }

                INamedTypeSymbol?methodImplOptions = context.Compilation.GetOrCreateTypeByMetadataName(typeof(MethodImplOptions).FullName);
                var hasAggressiveInlining          = methodImplOptions?.MemberNames.Contains(nameof(MethodImplOptions.AggressiveInlining)) ?? false;

                var hasNotNullIfNotNull = context.Compilation.GetOrCreateTypeByMetadataName("System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute") is object;

                string?getStringMethod;

                if (OmitGetResourceString)
                {
                    getStringMethod = null;
                }
                else
                {
                    switch (language)
                    {
                    case Lang.CSharp:
                        var getResourceStringAttributes = new List <string>();
                        if (hasAggressiveInlining)
                        {
                            getResourceStringAttributes.Add("[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]");
                        }

                        if (hasNotNullIfNotNull)
                        {
                            getResourceStringAttributes.Add("[return: global::System.Diagnostics.CodeAnalysis.NotNullIfNotNull(\"defaultValue\")]");
                        }

                        getStringMethod = $@"{memberIndent}internal static global::System.Globalization.CultureInfo{(Generator.SupportsNullable(context) ? "?" : "")} Culture {{ get; set; }}
{string.Join(Environment.NewLine, getResourceStringAttributes.Select(attr => memberIndent + attr))}
{memberIndent}internal static {(Generator.SupportsNullable(context) ? "string?" : "string")} GetResourceString(string resourceKey, {(Generator.SupportsNullable(context) ? "string?" : "string")} defaultValue = null) =>  ResourceManager.GetString(resourceKey, Culture) ?? defaultValue;";
                        if (EmitFormatMethods)
                        {
                            getStringMethod += $@"

{memberIndent}private static string GetResourceString(string resourceKey, string[]? formatterNames)
{memberIndent}{{
{memberIndent}   var value = GetResourceString(resourceKey) ?? """";
{memberIndent}   if (formatterNames != null)
{memberIndent}   {{
{memberIndent}       for (var i = 0; i < formatterNames.Length; i++)
{memberIndent}       {{
{memberIndent}           value = value.Replace(""{{"" + formatterNames[i] + ""}}"", ""{{"" + i + ""}}"");
{memberIndent}       }}
{memberIndent}   }}
{memberIndent}   return value;
{memberIndent}}}
";
                        }
                        break;

                    case Lang.VisualBasic:
                        getStringMethod = $@"{memberIndent}Friend Shared Property Culture As Global.System.Globalization.CultureInfo
{memberIndent}<Global.System.Runtime.CompilerServices.MethodImpl(Global.System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)>
{memberIndent}Friend Shared Function GetResourceString(ByVal resourceKey As String, Optional ByVal defaultValue As String = Nothing) As String
{memberIndent}    Return ResourceManager.GetString(resourceKey, Culture)
{memberIndent}End Function";
                        if (EmitFormatMethods)
                        {
                            throw new NotImplementedException();
                        }
                        break;

                    default:
                        throw new InvalidOperationException();
                    }
                }

                string?namespaceStart, namespaceEnd;

                if (namespaceName == null)
                {
                    namespaceStart = namespaceEnd = null;
                }
                else
                {
                    switch (language)
                    {
                    case Lang.CSharp:
                        namespaceStart = $@"namespace {namespaceName}{Environment.NewLine}{{";
                        namespaceEnd   = "}";
                        break;

                    case Lang.VisualBasic:
                        namespaceStart = $"Namespace Global.{namespaceName}";
                        namespaceEnd   = "End Namespace";
                        break;

                    default:
                        throw new InvalidOperationException();
                    }
                }

                string resourceTypeName;
                string?resourceTypeDefinition;

                if (string.IsNullOrEmpty(ResourceClassName) || ResourceName == ResourceClassName)
                {
                    // resource name is same as accessor, no need for a second type.
                    resourceTypeName       = className;
                    resourceTypeDefinition = null;
                }
                else
                {
                    // resource name differs from the access class, need a type for specifying the resources
                    // this empty type must remain as it is required by the .NETNative toolchain for locating resources
                    // once assemblies have been merged into the application
                    resourceTypeName = ResourceName;

                    SplitName(resourceTypeName, out var resourceNamespaceName, out var resourceClassName);
                    var resourceClassIndent = resourceNamespaceName == null ? "" : "    ";

                    switch (language)
                    {
                    case Lang.CSharp:
                        resourceTypeDefinition = $"{resourceClassIndent}internal static class {resourceClassName} {{ }}";
                        if (resourceNamespaceName != null)
                        {
                            resourceTypeDefinition = $@"namespace {resourceNamespaceName}
{{
{resourceTypeDefinition}
}}";
                        }
                        break;

                    case Lang.VisualBasic:
                        resourceTypeDefinition = $@"{resourceClassIndent}Friend Class {resourceClassName}
{resourceClassIndent}End Class";
                        if (resourceNamespaceName != null)
                        {
                            resourceTypeDefinition = $@"Namespace {resourceNamespaceName}
{resourceTypeDefinition}
End Namespace";
                        }
                        break;

                    default:
                        throw new InvalidOperationException();
                    }
                }

                // The ResourceManager property being initialized lazily is an important optimization that lets .NETNative
                // completely remove the ResourceManager class if the disk space saving optimization to strip resources
                // (/DisableExceptionMessages) is turned on in the compiler.
                string result;

                switch (language)
                {
                case Lang.CSharp:
                    result = $@"// <auto-generated/>

{(Generator.SupportsNullable(context) ? "#nullable enable" : "")}
using System.Reflection;

{resourceTypeDefinition}
{namespaceStart}
{classIndent}internal static partial class {className}
{classIndent}{{
{memberIndent}private static global::System.Resources.ResourceManager{(Generator.SupportsNullable(context) ? "?" : "")} s_resourceManager;
{memberIndent}internal static global::System.Resources.ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new global::System.Resources.ResourceManager(typeof({resourceTypeName})));
{getStringMethod}
{strings}
{classIndent}}}
{namespaceEnd}
";
                    break;

                case Lang.VisualBasic:
                    result = $@"' <auto-generated/>

Imports System.Reflection

{resourceTypeDefinition}
{namespaceStart}
{classIndent}Friend Partial Class {className}
{memberIndent}Private Sub New
{memberIndent}End Sub
{memberIndent}
{memberIndent}Private Shared s_resourceManager As Global.System.Resources.ResourceManager
{memberIndent}Friend Shared ReadOnly Property ResourceManager As Global.System.Resources.ResourceManager
{memberIndent}    Get
{memberIndent}        If s_resourceManager Is Nothing Then
{memberIndent}            s_resourceManager = New Global.System.Resources.ResourceManager(GetType({resourceTypeName}))
{memberIndent}        End If
{memberIndent}        Return s_resourceManager
{memberIndent}    End Get
{memberIndent}End Property
{getStringMethod}
{strings}
{classIndent}End Class
{namespaceEnd}
";
                    break;

                default:
                    throw new InvalidOperationException();
                }

                OutputText = SourceText.From(result, Encoding.UTF8, SourceHashAlgorithm.Sha256);
                return(true);
            }
Ejemplo n.º 55
0
Archivo: Form.cs Proyecto: pcdummy/Eto
 public Form(Generator g) : this(g, typeof(IForm))
 {
 }
Ejemplo n.º 56
0
 protected TreeGridView(Generator generator, Type type, bool initialize = true)
     : base(generator, type, initialize)
 {
 }
Ejemplo n.º 57
0
        public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
        {
            if (!VisitType(array, quals))
            {
                return(false);
            }

            switch (array.SizeType)
            {
            case ArrayType.ArraySize.Constant:
                if (Context.MarshalKind != MarshalKind.NativeField &&
                    Context.MarshalKind != MarshalKind.ReturnVariableArray)
                {
                    goto case ArrayType.ArraySize.Incomplete;
                }

                var    supportBefore = Context.Before;
                string value         = Generator.GeneratedIdentifier("value");
                var    arrayType     = array.Type.Desugar();
                supportBefore.WriteLine($"{arrayType}[] {value} = null;");
                supportBefore.WriteLine($"if ({Context.ReturnVarName} != null)");
                supportBefore.WriteOpenBraceAndIndent();
                supportBefore.WriteLine($"{value} = new {arrayType}[{array.Size}];");
                supportBefore.WriteLine($"for (int i = 0; i < {array.Size}; i++)");
                if (array.Type.IsPointerToPrimitiveType(PrimitiveType.Void))
                {
                    supportBefore.WriteLineIndent($@"{value}[i] = new global::System.IntPtr({
                            Context.ReturnVarName}[i]);");
                }
                else
                {
                    var   finalArrayType = arrayType.GetPointee() ?? arrayType;
                    Class @class;
                    if ((finalArrayType.TryGetClass(out @class)) && @class.IsRefType)
                    {
                        if (arrayType == finalArrayType)
                        {
                            supportBefore.WriteLineIndent(
                                "{0}[i] = {1}.{2}(*(({1}.{3}*)&({4}[i * sizeof({1}.{3})])));",
                                value, array.Type, Helpers.CreateInstanceIdentifier,
                                Helpers.InternalStruct, Context.ReturnVarName);
                        }
                        else
                        {
                            supportBefore.WriteLineIndent(
                                $@"{value}[i] = {finalArrayType}.{Helpers.CreateInstanceIdentifier}(({
                                        typePrinter.IntPtrType}) {Context.ReturnVarName}[i]);");
                        }
                    }
                    else
                    {
                        if (arrayType.IsPrimitiveType(PrimitiveType.Bool))
                        {
                            supportBefore.WriteLineIndent($@"{value}[i] = {
                                    Context.ReturnVarName}[i] != 0;");
                        }
                        else if (arrayType.IsPrimitiveType(PrimitiveType.Char) &&
                                 Context.Context.Options.MarshalCharAsManagedChar)
                        {
                            supportBefore.WriteLineIndent($@"{value}[i] = global::System.Convert.ToChar({
                                    Context.ReturnVarName}[i]);");
                        }
                        else
                        {
                            supportBefore.WriteLineIndent($@"{value}[i] = {
                                    Context.ReturnVarName}[i];");
                        }
                    }
                }
                supportBefore.UnindentAndWriteCloseBrace();
                Context.Return.Write(value);
                break;

            case ArrayType.ArraySize.Incomplete:
                // const char* and const char[] are the same so we can use a string
                if (array.Type.Desugar().IsPrimitiveType(PrimitiveType.Char) &&
                    array.QualifiedType.Qualifiers.IsConst)
                {
                    var pointer = new PointerType {
                        QualifiedPointee = array.QualifiedType
                    };
                    Context.ReturnType = new QualifiedType(pointer);
                    return(this.VisitPointerType(pointer, quals));
                }
                MarshalArray(array);
                break;

            case ArrayType.ArraySize.Variable:
                Context.Return.Write(Context.ReturnVarName);
                break;
            }

            return(true);
        }
Ejemplo n.º 58
0
Archivo: Form.cs Proyecto: pcdummy/Eto
 protected Form(Generator g, Type type, bool initialize = true)
     : base(g, type, initialize)
 {
 }
Ejemplo n.º 59
0
        public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals)
        {
            if (!VisitType(pointer, quals))
            {
                return(false);
            }

            var param      = Context.Parameter;
            var isRefParam = param != null && (param.IsInOut || param.IsOut);

            var pointee = pointer.Pointee.Desugar();

            if (pointee.IsConstCharString())
            {
                if (param.IsOut)
                {
                    MarshalString(pointee);
                    Context.Return.Write($"{typePrinter.IntPtrType}.Zero");
                    Context.ArgumentPrefix.Write("&");
                    return(true);
                }
                if (param.IsInOut)
                {
                    MarshalString(pointee);
                    pointer.QualifiedPointee.Visit(this);
                    Context.ArgumentPrefix.Write("&");
                    return(true);
                }
                if (pointer.IsReference)
                {
                    Context.Return.Write($@"({typePrinter.PrintNative(
                        pointee.GetQualifiedPointee())}*) ");
                    pointer.QualifiedPointee.Visit(this);
                    Context.ArgumentPrefix.Write("&");
                    return(true);
                }
            }

            var finalPointee = (pointee.GetFinalPointee() ?? pointee).Desugar();

            if (finalPointee.IsPrimitiveType(out PrimitiveType primitive) ||
                finalPointee.IsEnumType())
            {
                if (isRefParam)
                {
                    var local = Generator.GeneratedIdentifier($@"{
                        param.Name}{Context.ParameterIndex}");
                    Context.Before.WriteLine($@"fixed ({
                        pointer.Visit(typePrinter)} {local} = &{param.Name})");
                    Context.HasCodeBlock = true;
                    Context.Before.WriteOpenBraceAndIndent();
                    Context.Return.Write(local);
                    return(true);
                }

                if (Context.Context.Options.MarshalCharAsManagedChar &&
                    primitive == PrimitiveType.Char)
                {
                    Context.Return.Write($"({typePrinter.PrintNative(pointer)}) &{param.Name}");
                    return(true);
                }

                pointer.QualifiedPointee.Visit(this);

                if (Context.Parameter.IsIndirect)
                {
                    Context.ArgumentPrefix.Write("&");
                }

                bool isVoid = primitive == PrimitiveType.Void &&
                              pointee.IsAddress() && pointer.IsReference() &&
                              (quals.IsConst || pointer.QualifiedPointee.Qualifiers.IsConst ||
                               pointer.GetFinalQualifiedPointee().Qualifiers.IsConst);
                if (pointer.Pointee.Desugar(false) is TemplateParameterSubstitutionType ||
                    isVoid)
                {
                    var    local = Generator.GeneratedIdentifier($@"{
                        param.Name}{Context.ParameterIndex}");
                    string cast  = isVoid ? $@"({pointee.Visit(
                        new CppTypePrinter { PrintTypeQualifiers = false })}) " : string.Empty;
                    Context.Before.WriteLine($"var {local} = {cast}{Context.Return};");
                    Context.Return.StringBuilder.Clear();
                    Context.Return.Write(local);
                }
                if (new QualifiedType(pointer, quals).IsConstRefToPrimitive())
                {
                    Context.Return.StringBuilder.Insert(0, '&');
                }

                return(true);
            }


            string arg = Generator.GeneratedIdentifier(Context.ArgName);

            if (pointee.TryGetClass(out Class @class) && @class.IsValueType)
            {
                if (Context.Parameter.Usage == ParameterUsage.Out)
                {
                    var qualifiedIdentifier = (@class.OriginalClass ?? @class).Visit(typePrinter);
                    Context.Before.WriteLine("var {0} = new {1}.{2}();",
                                             arg, qualifiedIdentifier, Helpers.InternalStruct);
                }
                else
                {
                    Context.Before.WriteLine("var {0} = {1}.{2};",
                                             arg, Context.Parameter.Name, Helpers.InstanceIdentifier);
                }

                Context.Return.Write($"new {typePrinter.IntPtrType}(&{arg})");
                return(true);
            }

            if (pointee.IsPointerTo(out Type type) &&
                type.Desugar().TryGetClass(out Class c))
            {
                pointer.QualifiedPointee.Visit(this);
                Context.Before.WriteLine($"var {arg} = {Context.Return};");
                Context.Return.StringBuilder.Clear();
                Context.Return.Write($"new {typePrinter.IntPtrType}(&{arg})");
                return(true);
            }

            return(pointer.QualifiedPointee.Visit(this));
        }
Ejemplo n.º 60
0
        static void Main(string[] args)
        {
            var    showHelp                               = args.Length == 0;
            var    namespaces                             = new List <string>();
            var    outputFolder                           = (string)null;
            var    integerType                            = typeof(string);
            var    namespacePrefix                        = "";
            var    verbose                                = false;
            var    nullables                              = false;
            var    pclCompatible                          = false;
            var    enableDataBinding                      = false;
            var    emitOrder                              = false;
            var    entityFramework                        = false;
            var    interfaces                             = true;
            var    pascal                                 = true;
            var    assembly                               = false;
            var    collectionType                         = typeof(Collection <>);
            Type   collectionImplementationType           = null;
            var    codeTypeReferenceOptions               = default(CodeTypeReferenceOptions);
            string textValuePropertyName                  = "Value";
            var    generateDebuggerStepThroughAttribute   = true;
            var    disableComments                        = false;
            var    doNotUseUnderscoreInPrivateMemberNames = false;
            var    generateDescriptionAttribute           = true;
            var    enableUpaCheck                         = true;
            var    generateComplexTypesForCollections     = true;

            var options = new OptionSet {
                { "h|help", "show this message and exit", v => showHelp = v != null },
                { "n|namespace=", @"map an XML namespace to a C# namespace
Separate XML namespace and C# namespace by '='.
One option must be given for each namespace to be mapped.
A file name may be given by appending a pipe sign (|) followed by a file name (like schema.xsd) to the XML namespace.
If no mapping is found for an XML namespace, a name is generated automatically (may fail).", v => namespaces.Add(v) },
                { "o|output=", "the {FOLDER} to write the resulting .cs files to", v => outputFolder = v },
                { "i|integer=", @"map xs:integer and derived types to {TYPE} instead of automatic approximation
{TYPE} can be i[nt], l[ong], or d[ecimal].", v => {
                      switch (v)
                      {
                      case "i":
                      case "int":
                          integerType = typeof(int);
                          break;

                      case "l":
                      case "long":
                          integerType = typeof(long);
                          break;

                      case "d":
                      case "decimal":
                          integerType = typeof(decimal);
                          break;
                      }
                  } },
                { "e|edb|enable-data-binding", "enable INotifyPropertyChanged data binding", v => enableDataBinding = v != null },
                { "r|order", "emit order for all class members stored as XML element", v => emitOrder = v != null },
                { "c|pcl", "PCL compatible output", v => pclCompatible = v != null },
                { "p|prefix=", "the {PREFIX} to prepend to auto-generated namespace names", v => namespacePrefix = v },
                { "v|verbose", "print generated file names on stdout", v => verbose = v != null },
                { "0|nullable", "generate nullable adapter properties for optional elements/attributes w/o default values", v => nullables = v != null },
                { "f|ef", "generate Entity Framework Code First compatible classes", v => entityFramework = v != null },
                { "t|interface", "generate interfaces for groups and attribute groups (default is enabled)", v => interfaces = v != null },
                { "a|pascal", "use Pascal case for class and property names (default is enabled)", v => pascal = v != null },
                { "av|assemblyVisible", "use the internal visibility modifier (default is false)", v => assembly = v != null },
                { "u|enableUpaCheck", "should XmlSchemaSet check for Unique Particle Attribution (UPA) (default is enabled)", v => enableUpaCheck = v != null },
                { "ct|collectionType=", "collection type to use (default is " + typeof(Collection <>).FullName + ")", v => collectionType = v == null ? typeof(Collection <>) : Type.GetType(v, true) },
                { "cit|collectionImplementationType=", "the default collection type implementation to use (default is null)", v => collectionImplementationType = v == null ? null : Type.GetType(v, true) },
                { "ctro|codeTypeReferenceOptions=", "the default CodeTypeReferenceOptions Flags to use (default is unset; can be: {GlobalReference, GenericTypeParameter})", v => codeTypeReferenceOptions = v == null ? default(CodeTypeReferenceOptions) : (CodeTypeReferenceOptions)Enum.Parse(typeof(CodeTypeReferenceOptions), v, false) },
                { "tvpn|textValuePropertyName=", "the name of the property that holds the text value of an element (default is Value)", v => textValuePropertyName = v },
                { "dst|debuggerStepThrough", "generate DebuggerStepThroughAttribute (default is enabled)", v => generateDebuggerStepThroughAttribute = v != null },
                { "dc|disableComments", "do not include comments from xsd", v => disableComments = v != null },
                { "nu|noUnderscore", "do not generate underscore in private member name (default is false)", v => doNotUseUnderscoreInPrivateMemberNames = v != null },
                { "da|description", "generate DescriptionAttribute (default is true)", v => generateDescriptionAttribute = v != null },
                { "cc|complexTypesForCollections", "generate complex types for collections (default is true)", v => generateComplexTypesForCollections = v != null },
            };

            var globsAndUris = options.Parse(args);

            if (showHelp)
            {
                ShowHelp(options);
                return;
            }

            var uris = new List <string>();

            foreach (var globOrUri in globsAndUris)
            {
                if (Uri.IsWellFormedUriString(globOrUri, UriKind.Absolute))
                {
                    uris.Add(globOrUri);
                    continue;
                }

                var expandedGlob = Glob.ExpandNames(globOrUri).ToList();
                if (expandedGlob.Count == 0)
                {
                    System.Console.WriteLine($"No files found for '{globOrUri}'");
                    Environment.Exit(1);
                }

                uris.AddRange(expandedGlob);
            }

            var namespaceMap = namespaces.Select(n => CodeUtilities.ParseNamespace(n, namespacePrefix)).ToNamespaceProvider(key =>
            {
                var xn   = key.XmlSchemaNamespace;
                var name = string.Join(".", xn.Split('/').Where(p => p != "schema" && GeneratorConfiguration.IdentifierRegex.IsMatch(p))
                                       .Select(n => n.ToTitleCase(NamingScheme.PascalCase)));
                if (!string.IsNullOrEmpty(namespacePrefix))
                {
                    name = namespacePrefix + (string.IsNullOrEmpty(name) ? "" : ("." + name));
                }
                return(name);
            });

            if (!string.IsNullOrEmpty(outputFolder))
            {
                outputFolder = Path.GetFullPath(outputFolder);
            }

            var generator = new Generator
            {
                NamespaceProvider                    = namespaceMap,
                OutputFolder                         = outputFolder,
                GenerateNullables                    = nullables,
                EnableDataBinding                    = enableDataBinding,
                EmitOrder                            = emitOrder,
                IntegerDataType                      = integerType,
                EntityFramework                      = entityFramework,
                GenerateInterfaces                   = interfaces,
                NamingScheme                         = pascal ? NamingScheme.PascalCase : NamingScheme.Direct,
                AssemblyVisible                      = assembly,
                CollectionType                       = collectionType,
                CollectionImplementationType         = collectionImplementationType,
                CodeTypeReferenceOptions             = codeTypeReferenceOptions,
                TextValuePropertyName                = textValuePropertyName,
                GenerateDebuggerStepThroughAttribute = generateDebuggerStepThroughAttribute,
                DisableComments                      = disableComments,
                GenerateDescriptionAttribute         = generateDescriptionAttribute,
                PrivateMemberPrefix                  = doNotUseUnderscoreInPrivateMemberNames ? "" : "_",
                EnableUpaCheck                       = enableUpaCheck,
                GenerateComplexTypesForCollections   = generateComplexTypesForCollections
            };

            if (pclCompatible)
            {
                generator.UseXElementForAny = true;
                generator.GenerateDesignerCategoryAttribute    = false;
                generator.GenerateSerializableAttribute        = false;
                generator.GenerateDebuggerStepThroughAttribute = false;
                generator.DataAnnotationMode           = DataAnnotationMode.None;
                generator.GenerateDescriptionAttribute = false;
            }

            if (verbose)
            {
                generator.Log = s => System.Console.Out.WriteLine(s);
            }

            generator.Generate(uris);
        }