Example #1
0
        public override async System.Threading.Tasks.Task GCode_CodeDom_GenerateCode(CodeTypeDeclaration codeClass, CodeStatementCollection codeStatementCollection, LinkPinControl element, GenerateCodeContext_Method context)
        {
            await EngineNS.Thread.AsyncDummyClass.DummyFunc();

            Type clipType = typeof(EngineNS.Bricks.Animation.BlendTree.Node.BlendTree_ZeroPose);
            CodeVariableDeclarationStatement stateVarDeclaration = new CodeVariableDeclarationStatement(clipType, ValidName, new CodeObjectCreateExpression(new CodeTypeReference(clipType)));

            codeStatementCollection.Add(stateVarDeclaration);
        }
Example #2
0
 public static CodeStatementCollection _(this CodeStatementCollection statements, string expression, params object[] args)
 {
     statements.Add(new CodeSnippetExpression(string.Format(expression, args)));
     return(statements);
 }
        private static CodeAssignStatement FindControlCreateStatement(Type controlType, CodeStatementCollection statements)
        {
            foreach (var statement in statements)
            {
                var codeAssignStatement = statement as CodeAssignStatement;
                if (codeAssignStatement != null)
                {
                    var objCreateExpr = codeAssignStatement.Right as CodeObjectCreateExpression;

                    if (objCreateExpr != null && objCreateExpr.CreateType.BaseType == controlType.ToString() && objCreateExpr.Parameters.Count == 0 &&
                        codeAssignStatement.Left is CodeVariableReferenceExpression)
                    {
                        return(codeAssignStatement);
                    }
                }
            }
            return(null);
        }
Example #4
0
 public static void Return(this CodeStatementCollection statements, CodeExpression expression)
 {
     statements.Add(Return(expression));
 }
        static void GenerateProjectActionsCode(CodeNamespace cns, GenerationOptions options, params ProjectBackend[] projects)
        {
            bool multiProject = projects.Length > 1;

            CodeTypeDeclaration type = new CodeTypeDeclaration("ActionGroups");

            type.Attributes     = MemberAttributes.Private;
            type.TypeAttributes = TypeAttributes.NestedAssembly;
            cns.Types.Add(type);

            // Generate the global action group getter

            CodeMemberMethod met = new CodeMemberMethod();

            met.Name = "GetActionGroup";
            type.Members.Add(met);
            met.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type), "type"));
            if (multiProject)
            {
                met.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "file"));
            }
            met.ReturnType = new CodeTypeReference(typeof(Gtk.ActionGroup));
            met.Attributes = MemberAttributes.Public | MemberAttributes.Static;

            CodeMethodInvokeExpression call = new CodeMethodInvokeExpression(
                new CodeMethodReferenceExpression(
                    new CodeTypeReferenceExpression(new CodeTypeReference(cns.Name + ".ActionGroups")),
                    "GetActionGroup"
                    ),
                new CodePropertyReferenceExpression(
                    new CodeArgumentReferenceExpression("type"),
                    "FullName"
                    )
                );

            if (multiProject)
            {
                call.Parameters.Add(new CodeArgumentReferenceExpression("file"));
            }

            met.Statements.Add(new CodeMethodReturnStatement(call));

            // Generate the global action group getter (overload)

            met      = new CodeMemberMethod();
            met.Name = "GetActionGroup";
            type.Members.Add(met);
            met.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "name"));
            if (multiProject)
            {
                met.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "file"));
            }
            met.ReturnType = new CodeTypeReference(typeof(Gtk.ActionGroup));
            met.Attributes = MemberAttributes.Public | MemberAttributes.Static;

            CodeArgumentReferenceExpression cfile = new CodeArgumentReferenceExpression("file");
            CodeArgumentReferenceExpression cid   = new CodeArgumentReferenceExpression("name");

            CodeStatementCollection projectCol = met.Statements;
            int n = 1;

            foreach (ProjectBackend gp in projects)
            {
                CodeStatementCollection widgetCol;

                if (multiProject)
                {
                    CodeConditionStatement pcond = new CodeConditionStatement();
                    pcond.Condition = new CodeBinaryOperatorExpression(
                        cfile,
                        CodeBinaryOperatorType.IdentityEquality,
                        new CodePrimitiveExpression(gp.Id)
                        );
                    projectCol.Add(pcond);

                    widgetCol  = pcond.TrueStatements;
                    projectCol = pcond.FalseStatements;
                }
                else
                {
                    widgetCol = projectCol;
                }

                foreach (Wrapper.ActionGroup grp in gp.ActionGroups)
                {
                    string          fname    = "group" + (n++);
                    CodeMemberField grpField = new CodeMemberField(new CodeTypeReference(typeof(Gtk.ActionGroup), CodeTypeReferenceOptions.GlobalReference), fname);
                    grpField.Attributes |= MemberAttributes.Static;
                    type.Members.Add(grpField);
                    CodeFieldReferenceExpression grpVar = new CodeFieldReferenceExpression(
                        new CodeTypeReferenceExpression(new CodeTypeReference(cns.Name + ".ActionGroups", CodeTypeReferenceOptions.GlobalReference)),
                        fname
                        );

                    CodeConditionStatement pcond = new CodeConditionStatement();
                    pcond.Condition = new CodeBinaryOperatorExpression(
                        cid,
                        CodeBinaryOperatorType.IdentityEquality,
                        new CodePrimitiveExpression(grp.Name)
                        );
                    widgetCol.Add(pcond);

                    // If the group has not yet been created, create it
                    CodeConditionStatement pcondGrp = new CodeConditionStatement();
                    pcondGrp.Condition = new CodeBinaryOperatorExpression(
                        grpVar,
                        CodeBinaryOperatorType.IdentityEquality,
                        new CodePrimitiveExpression(null)
                        );

                    pcondGrp.TrueStatements.Add(
                        new CodeAssignStatement(
                            grpVar,
                            new CodeObjectCreateExpression(grp.Name)
                            )
                        );

                    pcond.TrueStatements.Add(pcondGrp);
                    pcond.TrueStatements.Add(new CodeMethodReturnStatement(grpVar));

                    widgetCol = pcond.FalseStatements;
                }
                widgetCol.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null)));
            }
            if (met.Statements.Count == 0)
            {
                met.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null)));
            }
        }
        public static WidgetMap GenerateCreationCode(CodeNamespace cns, CodeTypeDeclaration type, Wrapper.ActionGroup grp, CodeExpression groupVarExp, CodeStatementCollection statements, GenerationOptions options, ArrayList warnings)
        {
            statements.Add(new CodeCommentStatement("Action group " + grp.Name));
            GeneratorContext ctx = new ProjectGeneratorContext(cns, type, statements, options);

            ctx.GenerateCreationCode(grp, groupVarExp);
            ctx.EndGeneration();
            warnings.AddRange(ctx.Warnings);
            return(ctx.WidgetMap);
        }
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

            object result = null;

            if (value == null)
            {
                return(result);
            }

            CodeStatementCollection statements = null;
            ExpressionContext       cxt        = manager.Context[typeof(ExpressionContext)] as ExpressionContext;

            if (value.GetType().GetConstructor(new Type[0]) != null)
            {
                if (value is ICollection)
                {
                    ExpressionContext varExct = null;
                    if (cxt != null)
                    {
                        if (cxt.PresetValue != value)
                        {
                            try
                            {
                                statements = new CodeStatementCollection();
                                CodeVariableReferenceExpression varExpression = AddVariableExpression(manager, statements, value);
                                varExct = new ExpressionContext(varExpression, value.GetType(), cxt.Owner, value);
                                manager.Context.Push(varExct);
                                result = this.originalSerializer.Serialize(manager, value);
                                if (result is CodeStatementCollection)
                                {
                                    statements.AddRange(result as CodeStatementCollection);
                                }
                                else if (result is CodeStatement)
                                {
                                    statements.Add(result as CodeStatement);
                                }
                                else if (result is CodeExpression)
                                {
                                    // If the returned result is an expression, it mostly likely means the collection
                                    // can not be serialized using statements, instead it has been serialized as resources.
                                    // In this case, we just over-write the variable init expression with the "GetObject"
                                    // expression for resource objects.
                                    statements.Add(new CodeAssignStatement(varExpression, result as CodeExpression));
                                }

                                result = statements;
                            }
                            finally
                            {
                                if (varExct != null)
                                {
                                    manager.Context.Pop();
                                }
                            }
                        }
                        else
                        {
                            result = this.originalSerializer.Serialize(manager, value);
                        }
                    }
                }
                else
                {
                    statements = new CodeStatementCollection();
                    CodeVariableReferenceExpression varExpression = AddVariableExpression(manager, statements, value);
                    SerializeProperties(manager, statements, value, new Attribute[] { DesignOnlyAttribute.No });
                    SerializeEvents(manager, statements, value, new Attribute[] { DesignOnlyAttribute.No });
                    result = statements;
                }
            }
            else if (cxt != null)
            {
                result = this.originalSerializer.Serialize(manager, value);
            }

            return(result);
        }
Example #8
0
		protected void GenerateStatements(CodeStatementCollection c)
		{
			foreach (CodeStatement statement in c)
				GenerateStatement(statement);
		}
Example #9
0
        /// <summary>
        ///  Serializes the given object into a CodeDom object.
        /// </summary>
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            CodeStatementCollection      statements = null;
            PropertyDescriptorCollection props      = TypeDescriptor.GetProperties(value);

            using (TraceScope("ComponentCodeDomSerializer::Serialize"))
            {
                ArgumentNullException.ThrowIfNull(manager);
                ArgumentNullException.ThrowIfNull(value);

                if (IsSerialized(manager, value))
                {
                    Debug.Fail("Serialize is being called twice for the same component");
                    return(GetExpression(manager, value));
                }

                // If the object is being inherited, we will will not emit a variable declaration.  Also, we won't
                // do any serialization at all if the object is privately inherited.
                InheritanceLevel     inheritanceLevel     = InheritanceLevel.NotInherited;
                InheritanceAttribute inheritanceAttribute = (InheritanceAttribute)TypeDescriptor.GetAttributes(value)[typeof(InheritanceAttribute)];

                if (inheritanceAttribute is not null)
                {
                    inheritanceLevel = inheritanceAttribute.InheritanceLevel;
                }

                // First, skip everything if we're privately inherited.  We cannot write any code that would affect this
                // component.
                TraceIf(inheritanceLevel == InheritanceLevel.InheritedReadOnly, "Skipping read only inherited component");
                if (inheritanceLevel != InheritanceLevel.InheritedReadOnly)
                {
                    // Things we need to know:
                    //
                    // 1.  What expression should we use for the left hand side
                    //      a) already given to us via GetExpression?
                    //      b) a local variable?
                    //      c) a member variable?
                    //
                    // 2.  Should we generate an init expression for this
                    //     object?
                    //      a) Inherited or existing expression: no
                    //      b) otherwise, yes.

                    statements = new CodeStatementCollection();
                    CodeTypeDeclaration typeDecl  = manager.Context[typeof(CodeTypeDeclaration)] as CodeTypeDeclaration;
                    RootContext         rootCtx   = manager.Context[typeof(RootContext)] as RootContext;
                    CodeExpression      assignLhs = null;
                    CodeExpression      assignRhs;

                    // Defaults for components
                    bool generateLocal  = false;
                    bool generateField  = true;
                    bool generateObject = true;
                    bool isComplete     = false;

                    assignLhs = GetExpression(manager, value);

                    if (assignLhs is not null)
                    {
                        Trace("Existing expression for LHS of value");
                        generateLocal  = false;
                        generateField  = false;
                        generateObject = false;

                        // if we have an existing expression and this is not
                        // a sited component, do not serialize it.  We need this for Everett / 1.0
                        // backwards compat (even though it's wrong).
                        if (value is IComponent comp && comp.Site is null)
                        {
                            // We were in a serialize content
                            // property and would still serialize it.  This code reverses what the
                            // outer if block does for this specific case.  We also need this
                            // for Everett / 1.0 backwards compat.
                            if (!(manager.Context[typeof(ExpressionContext)] is ExpressionContext expCtx) || expCtx.PresetValue != value)
                            {
                                isComplete = true;
                            }
                        }
                    }
                    else
                    {
                        Trace("Creating LHS expression");
                        if (inheritanceLevel == InheritanceLevel.NotInherited)
                        {
                            // See if there is a "GenerateMember" property.  If so,
                            // we might want to generate a local variable.  Otherwise,
                            // we want to generate a field.
                            PropertyDescriptor generateProp = props["GenerateMember"];
                            if (generateProp is not null && generateProp.PropertyType == typeof(bool) && !(bool)generateProp.GetValue(value))
                            {
                                Trace("Object GenerateMember property wants a local variable");
                                generateLocal = true;
                                generateField = false;
                            }
                        }
                        else
                        {
                            generateObject = false;
                        }

                        if (rootCtx is null)
                        {
                            generateLocal = true;
                            generateField = false;
                        }
                    }

                    // Push the component being serialized onto the stack.  It may be handy to
                    // be able to discover this.
                    manager.Context.Push(value);
                    manager.Context.Push(statements);

                    try
                    {
                        string name = manager.GetName(value);

                        string typeName = TypeDescriptor.GetClassName(value);

                        // Output variable / field declarations if we need to
                        if ((generateField || generateLocal) && name is not null)
                        {
                            if (generateField)
                            {
                                if (inheritanceLevel == InheritanceLevel.NotInherited)
                                {
                                    // We need to generate the field declaration.  See if there is a modifiers property on
                                    // the object.  If not, look for a DefaultModifies, and finally assume it's private.
                                    CodeMemberField    field         = new CodeMemberField(typeName, name);
                                    PropertyDescriptor modifiersProp = props["Modifiers"];
                                    MemberAttributes   fieldAttrs;

                                    if (modifiersProp is null)
                                    {
                                        modifiersProp = props["DefaultModifiers"];
                                    }

                                    if (modifiersProp is not null && modifiersProp.PropertyType == typeof(MemberAttributes))
                                    {
                                        fieldAttrs = (MemberAttributes)modifiersProp.GetValue(value);
                                    }
                                    else
                                    {
                                        TraceWarning("No Modifiers or DefaultModifiers property on component {0}. We must assume private.", name);
                                        fieldAttrs = MemberAttributes.Private;
                                    }

                                    field.Attributes = fieldAttrs;
                                    typeDecl.Members.Add(field);
                                    Trace("Field {0} {1} {2} created.", fieldAttrs, typeName, name);
                                }

                                // Next, create a nice LHS for our pending assign statement, when we hook up the variable.
                                assignLhs = new CodeFieldReferenceExpression(rootCtx.Expression, name);
                            }
                            else
                            {
                                if (inheritanceLevel == InheritanceLevel.NotInherited)
                                {
                                    CodeVariableDeclarationStatement local = new CodeVariableDeclarationStatement(typeName, name);

                                    statements.Add(local);
                                    Trace("Local {0} {1} created.", typeName, name);
                                }

                                assignLhs = new CodeVariableReferenceExpression(name);
                            }
                        }

                        // Now output an object create if we need to.  We always see if there is a
                        // type converter that can provide us guidance

                        if (generateObject)
                        {
                            // Ok, now that we've decided if we have a local or a member variable, its now time to serialize the rest of the code.
                            // The first step is to create an assign statement to "new" the object.  For that, we need to know if
                            // the component wants a special IContainer constructor or not.  For that to be valid we must also know
                            // that we can get to an actual IContainer.
                            IContainer      container = manager.GetService(typeof(IContainer)) as IContainer;
                            ConstructorInfo ctor      = null;
                            if (container is not null)
                            {
                                ctor = GetReflectionTypeHelper(manager, value).GetConstructor(BindingFlags.ExactBinding | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, GetContainerConstructor(manager), null);
                            }

                            if (ctor is not null)
                            {
                                Trace("Component has IContainer constructor.");
                                assignRhs = new CodeObjectCreateExpression(typeName, new CodeExpression[]
                                {
                                    SerializeToExpression(manager, container)
                                });
                            }
                            else
                            {
                                // For compat reasons we ignore the isCompleteOld value here.
                                assignRhs = SerializeCreationExpression(manager, value, out bool isCompleteOld);
                                Debug.Assert(isCompleteOld == isComplete, "CCDS Differing");
                            }

                            TraceErrorIf(assignRhs is null, "No RHS code assign for object {0}", value);
                            if (assignRhs is not null)
                            {
                                if (assignLhs is null)
                                {
                                    // We cannot do much more for this object.  If isComplete is true,
                                    // then the RHS now becomes our LHS.  Otherwise, I'm afraid we have
                                    // just failed to serialize this object.
                                    if (isComplete)
                                    {
                                        assignLhs = assignRhs;
                                    }
                                    else
                                    {
                                        TraceError("Incomplete serialization of object, abandoning serialization.");
                                    }
                                }
                                else
                                {
                                    CodeAssignStatement assign = new CodeAssignStatement(assignLhs, assignRhs);
                                    statements.Add(assign);
                                }
                            }
                        }

                        if (assignLhs is not null)
                        {
                            SetExpression(manager, value, assignLhs);
                        }

                        // It should practically be an assert that isComplete is false, but someone may
                        // have an unusual component.
                        if (assignLhs is not null && !isComplete)
                        {
                            // .NET CF needs us to verify that the ISupportInitialize interface exists
                            // (they do not support this interface and will modify their DSM to resolve the type to null).

                            bool supportInitialize = (value is ISupportInitialize);
                            if (supportInitialize)
                            {
                                string fullName = typeof(ISupportInitialize).FullName;
                                supportInitialize = manager.GetType(fullName) is not null;
                            }

                            Type reflectionType = null;
                            if (supportInitialize)
                            {
                                // Now verify that this control implements ISupportInitialize in the project target framework
                                // Don't use operator "is" but rather use IsAssignableFrom on the reflection types.
                                // We have other places where we use operator "is", for example "is IComponent" to generate
                                // specific CodeDOM objects, however we don't have cases of objects which were not an IComponent
                                // in a downlevel framework and became an IComponent in a newer framework, so I'm not replacing
                                // all instances of operator "is" by IsAssignableFrom.
                                reflectionType    = GetReflectionTypeHelper(manager, value);
                                supportInitialize = GetReflectionTypeFromTypeHelper(manager, typeof(ISupportInitialize)).IsAssignableFrom(reflectionType);
                            }

                            bool persistSettings = (value is IPersistComponentSettings) && ((IPersistComponentSettings)value).SaveSettings;
                            if (persistSettings)
                            {
                                string fullName = typeof(IPersistComponentSettings).FullName;
                                persistSettings = manager.GetType(fullName) is not null;
                            }

                            if (persistSettings)
                            {
                                reflectionType  = reflectionType ?? GetReflectionTypeHelper(manager, value);
                                persistSettings = GetReflectionTypeFromTypeHelper(manager, typeof(IPersistComponentSettings)).IsAssignableFrom(reflectionType);
                            }

                            // We implement statement caching only for the main code generation phase.  We don't implement it for other
                            // serialization managers.  How do we tell the difference?  The main serialization manager exists as a service.
                            IDesignerSerializationManager mainManager = manager.GetService(typeof(IDesignerSerializationManager)) as IDesignerSerializationManager;

                            if (supportInitialize)
                            {
                                Trace("Object implements ISupportInitialize.");
                                SerializeSupportInitialize(manager, statements, assignLhs, value, "BeginInit");
                            }

                            SerializePropertiesToResources(manager, statements, value, _designTimeFilter);

                            // Writing out properties is expensive.  But, we're very smart and we cache the results
                            // in ComponentCache.  See if we have cached results.  If so, use 'em.  If not, generate
                            // code and then see if we can cache the results for later.
                            ComponentCache       cache = manager.GetService(typeof(ComponentCache)) as ComponentCache;
                            ComponentCache.Entry entry = null;
                            if (cache is null)
                            {
                                if (manager.GetService(typeof(IServiceContainer)) is ServiceContainer sc)
                                {
                                    cache = new ComponentCache(manager);
                                    sc.AddService(typeof(ComponentCache), cache);
                                }
                            }
                            else
                            {
                                if (manager == mainManager && cache.Enabled)
                                {
                                    entry = cache[value];
                                }
                            }

                            if (entry is null || entry.Tracking)
                            {
                                // Pushing the entry here allows it to be found by the resource code dom serializer,
                                // which will add data to the ResourceBlob property on the entry.
                                if (entry is null)
                                {
                                    entry = new ComponentCache.Entry(cache);

                                    // We cache components even if they're not valid so dependencies are
                                    // still tracked correctly (see comment below).  The problem is, we will create a
                                    // new entry object even if there is still an existing one that is just invalid, and it
                                    // might have dependencies that will be lost.
                                    // we need to make sure we copy over any dependencies that are also tracked.
                                    ComponentCache.Entry oldEntry = cache?.GetEntryAll(value);
                                    if (oldEntry is not null && oldEntry.Dependencies is not null && oldEntry.Dependencies.Count > 0)
                                    {
                                        foreach (object dependency in oldEntry.Dependencies)
                                        {
                                            entry.AddDependency(dependency);
                                        }
                                    }
                                }

                                entry.Component = value;
                                // we need to link the cached entry with its corresponding component right away, before it's put in the context
                                // see CodeDomSerializerBase.cs::GetExpression for usage

                                // This entry will only be used if the valid bit is set.
                                // This is useful because we still need to setup dependency relationships
                                // between components even if they are not cached.  See VSWhidbey 263053.
                                bool correctManager = manager == mainManager;
                                entry.Valid = correctManager && CanCacheComponent(manager, value, props);

                                if (correctManager && cache is not null && cache.Enabled)
                                {
                                    manager.Context.Push(cache);
                                    manager.Context.Push(entry);
                                }

                                try
                                {
                                    entry.Statements = new CodeStatementCollection();
                                    SerializeProperties(manager, entry.Statements, value, _runTimeFilter);
                                    SerializeEvents(manager, entry.Statements, value, null);

                                    foreach (CodeStatement statement in entry.Statements)
                                    {
                                        if (statement is CodeVariableDeclarationStatement local)
                                        {
                                            entry.Tracking = true;
                                            break;
                                        }
                                    }

                                    if (entry.Statements.Count > 0)
                                    {
                                        // if we added some statements, insert the comments
                                        //
                                        entry.Statements.Insert(0, new CodeCommentStatement(string.Empty));
                                        entry.Statements.Insert(0, new CodeCommentStatement(name));
                                        entry.Statements.Insert(0, new CodeCommentStatement(string.Empty));

                                        //
                                        // cache the statements for future usage if possible. We only do this for the main serialization manager, not
                                        // for any other serialization managers that may be calling us for undo or clipboard functions.
                                        if (correctManager && cache is not null && cache.Enabled)
                                        {
                                            cache[value] = entry;
                                        }
                                    }
                                }
                                finally
                                {
                                    if (correctManager && cache is not null && cache.Enabled)
                                    {
                                        Debug.Assert(manager.Context.Current == entry, "Context stack corrupted");
                                        manager.Context.Pop();
                                        manager.Context.Pop();
                                    }
                                }
                            }
                            else
                            {
                                // If we got a cache entry, we will need to take all the resources out of
                                // it and apply them too.
                                if ((entry.Resources is not null || entry.Metadata is not null) && cache is not null && cache.Enabled)
                                {
                                    ResourceCodeDomSerializer res = ResourceCodeDomSerializer.Default;
                                    res.ApplyCacheEntry(manager, entry);
                                }
                            }

                            // Regardless, apply statements.  Either we created them or we got them
                            // out of the cache.
                            statements.AddRange(entry.Statements);

                            if (persistSettings)
                            {
                                SerializeLoadComponentSettings(manager, statements, assignLhs, value);
                            }

                            if (supportInitialize)
                            {
                                SerializeSupportInitialize(manager, statements, assignLhs, value, "EndInit");
                            }
                        }
                    }
        private CodeVariableReferenceExpression AddVariableExpression(IDesignerSerializationManager manager, CodeStatementCollection statements, object value)
        {
            string varName = GetUniqueName(manager, value).Replace('`', '_');
            CodeVariableDeclarationStatement varDecl = new CodeVariableDeclarationStatement(TypeDescriptor.GetClassName(value), varName);

            varDecl.InitExpression = new CodeObjectCreateExpression(TypeDescriptor.GetClassName(value), new CodeExpression[0]);
            statements.Add(varDecl);
            CodeVariableReferenceExpression varExpression = new CodeVariableReferenceExpression(varName);

            SetExpression(manager, value, varExpression);

            return(varExpression);
        }
		bool SerializeProjectResource(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements)
		{
			var propDesc = descriptor as PropertyDescriptor;
			if (propDesc == null) return false;
			
			var component = value as IComponent;
			if (component == null || component.Site == null) return false;
			
			if (!propDesc.ShouldSerializeValue(component)) {
				return false;
			}
			
			var dictService = component.Site.GetService(typeof(IDictionaryService)) as IDictionaryService;
			if (dictService == null) return false;
			
			var resourceInfo = dictService.GetValue(ProjectResourceService.ProjectResourceKey + propDesc.Name) as ProjectResourceInfo;
			if (resourceInfo == null) return false;
			
			if (!Object.ReferenceEquals(resourceInfo.OriginalValue, propDesc.GetValue(value))) {
				LoggingService.Info("Value of property '" + propDesc.Name + "' on component '" + value.ToString() + "' is not equal to stored project resource value. Ignoring this resource.");
				return false;
			}
			
			
			// Find the generated file with the resource accessing class.
			
			var prs = manager.GetService(typeof(ProjectResourceService)) as ProjectResourceService;
			if (prs == null) {
				LoggingService.Warn("ProjectResourceService not found");
				return false;
			}
			
			IProject project = prs.ProjectContent;
			if (project == null) {
				LoggingService.Warn("Serializer cannot proceed because project is not an IProject");
				return false;
			}
			
			string resourceFileDirectory = Path.GetDirectoryName(resourceInfo.ResourceFile);
			string resourceFileName = Path.GetFileName(resourceInfo.ResourceFile);
			var items = project.Items
				.OfType<FileProjectItem>()
				.Where(
					fpi =>
					FileUtility.IsEqualFileName(Path.GetDirectoryName(fpi.FileName), resourceFileDirectory) &&
					FileUtility.IsEqualFileName(fpi.DependentUpon, resourceFileName) &&
					fpi.ItemType == ItemType.Compile &&
					fpi.VirtualName.ToUpperInvariant().Contains("DESIGNER")
				).ToList();
			
			if (items.Count != 1) {
				LoggingService.Info("Did not find exactly one possible file that contains the generated class for the resource file '" + resourceInfo.ResourceFile + "'. Ignoring this resource.");
				return false;
			}
			
			FileName resourceCodeFile = items.Single().FileName;
			
			// We expect a single class to be in this file.
			var resourceClass = SD.ParserService.GetExistingUnresolvedFile(resourceCodeFile).TopLevelTypeDefinitions.Single();
			// Here we assume that VerifyResourceName is the same name transform that
			// was used when generating the resource code file.
			// This should be true as long as the code is generated using the
			// custom tool in SharpDevelop or Visual Studio.
			string resourcePropertyName = StronglyTypedResourceBuilder.VerifyResourceName(resourceInfo.ResourceKey, prs.ProjectContent.CreateCodeDomProvider() ?? new CSharpCodeProvider());
			if (resourcePropertyName == null) {
				throw new InvalidOperationException("The resource name '" + resourceInfo.ResourceKey + "' could not be transformed to a name that is valid in the current programming language.");
			}
			
			
			// Now do the actual serialization.
			
			LoggingService.Debug("Serializing project resource: Component '" + component.ToString() + "', Property: '" + propDesc.Name + "', Resource class: '" + resourceClass.FullName + "', Resource property: '" + resourcePropertyName + "'");
			
			var targetObjectExpr = base.SerializeToExpression(manager, value);
			if (targetObjectExpr == null) {
				LoggingService.Info("Target object could not be serialized: " + value.ToString());
				return false;
			}
			
			if (propDesc.SerializationVisibility == DesignerSerializationVisibility.Content) {
				LoggingService.Debug("-> is a content property, ignoring this.");
				return false;
			}
			
			var propRefSource =
				Easy.Type(
					new CodeTypeReference(resourceClass.FullName, CodeTypeReferenceOptions.GlobalReference)
				).Property(resourcePropertyName);
			
			var extAttr = propDesc.Attributes[typeof(ExtenderProvidedPropertyAttribute)] as ExtenderProvidedPropertyAttribute;
			if (extAttr != null && extAttr.Provider != null) {
				
				// This is an extender property.
				var extProvider = base.SerializeToExpression(manager, extAttr.Provider);
				if (extProvider == null) {
					throw new InvalidOperationException("Could not serialize the extender provider '" + extAttr.Provider.ToString() + "'.");
				}
				
				statements.Add(
					extProvider.InvokeMethod(
						"Set" + propDesc.Name,
						targetObjectExpr,
						propRefSource
					)
				);
				
			} else {
				
				// This is a standard property.
				statements.Add(
					new CodeAssignStatement(
						new CodePropertyReferenceExpression(targetObjectExpr, propDesc.Name),
						propRefSource)
				);
				
			}
			
			return true;
		}
		public override void Serialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements)
		{
			if (!this.SerializeProjectResource(manager, value, descriptor, statements)) {
				this.baseSerializer.Serialize(manager, value, descriptor, statements);
			}
		}
        public CodeExpression GenerateLoadPixbuf(string name, Gtk.IconSize size)
        {
            bool found = false;

            foreach (CodeTypeDeclaration t in cns.Types)
            {
                if (t.Name == "IconLoader")
                {
                    found = true;
                    break;
                }
            }

            if (!found)
            {
                CodeTypeDeclaration cls = new CodeTypeDeclaration("IconLoader");
                cls.Attributes     = MemberAttributes.Private;
                cls.TypeAttributes = System.Reflection.TypeAttributes.NestedAssembly;
                cns.Types.Add(cls);

                CodeMemberMethod met = new CodeMemberMethod();
                cls.Members.Add(met);
                met.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                met.Name       = "LoadIcon";
                met.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Gtk.Widget), "widget"));
                met.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "name"));
                met.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Gtk.IconSize), "size"));
                met.ReturnType = new CodeTypeReference(typeof(Gdk.Pixbuf));

                CodeExpression widgetExp = new CodeVariableReferenceExpression("widget");
                CodeExpression nameExp   = new CodeVariableReferenceExpression("name");
                CodeExpression sizeExp   = new CodeVariableReferenceExpression("size");
                CodeExpression szExp     = new CodeVariableReferenceExpression("sz");
                CodeExpression mgExp     = new CodeBinaryOperatorExpression(szExp, CodeBinaryOperatorType.Divide, new CodePrimitiveExpression(4));
                CodeExpression pmapExp   = new CodeVariableReferenceExpression("pmap");
                CodeExpression gcExp     = new CodeVariableReferenceExpression("gc");
                CodeExpression szM1Exp   = new CodeBinaryOperatorExpression(szExp, CodeBinaryOperatorType.Subtract, new CodePrimitiveExpression(1));
                CodeExpression zeroExp   = new CodePrimitiveExpression(0);
                CodeExpression resExp    = new CodeVariableReferenceExpression("res");

                met.Statements.Add(
                    new CodeVariableDeclarationStatement(typeof(Gdk.Pixbuf), "res",
                                                         new CodeMethodInvokeExpression(
                                                             widgetExp,
                                                             "RenderIcon",
                                                             nameExp,
                                                             sizeExp,
                                                             new CodePrimitiveExpression(null)
                                                             )
                                                         )
                    );

                CodeConditionStatement nullcheck = new CodeConditionStatement();
                met.Statements.Add(nullcheck);
                nullcheck.Condition = new CodeBinaryOperatorExpression(
                    resExp,
                    CodeBinaryOperatorType.IdentityInequality,
                    new CodePrimitiveExpression(null)
                    );
                nullcheck.TrueStatements.Add(new CodeMethodReturnStatement(resExp));

                // int sz, h;
                // Gtk.Icon.SizeLookup (size, out sz, out h);

                nullcheck.FalseStatements.Add(new CodeVariableDeclarationStatement(typeof(int), "sz"));
                nullcheck.FalseStatements.Add(new CodeVariableDeclarationStatement(typeof(int), "sy"));
                nullcheck.FalseStatements.Add(new CodeMethodInvokeExpression(
                                                  new CodeTypeReferenceExpression(typeof(Gtk.Icon).ToGlobalTypeRef()),
                                                  "SizeLookup",
                                                  sizeExp,
                                                  new CodeDirectionExpression(FieldDirection.Out, szExp),
                                                  new CodeDirectionExpression(FieldDirection.Out, new CodeVariableReferenceExpression("sy"))
                                                  ));

                CodeTryCatchFinallyStatement trycatch = new CodeTryCatchFinallyStatement();
                nullcheck.FalseStatements.Add(trycatch);
                trycatch.TryStatements.Add(
                    new CodeMethodReturnStatement(
                        new CodeMethodInvokeExpression(
                            new CodePropertyReferenceExpression(
                                new CodeTypeReferenceExpression(new CodeTypeReference(typeof(Gtk.IconTheme))),
                                "Default"
                                ),
                            "LoadIcon",
                            nameExp,
                            szExp,
                            zeroExp
                            )
                        )
                    );

                CodeCatchClause ccatch = new CodeCatchClause();
                trycatch.CatchClauses.Add(ccatch);

                CodeConditionStatement cond = new CodeConditionStatement();
                ccatch.Statements.Add(cond);

                cond.Condition = new CodeBinaryOperatorExpression(
                    nameExp,
                    CodeBinaryOperatorType.IdentityInequality,
                    new CodePrimitiveExpression("gtk-missing-image")
                    );

                cond.TrueStatements.Add(
                    new CodeMethodReturnStatement(
                        new CodeMethodInvokeExpression(
                            new CodeTypeReferenceExpression(cns.Name + "." + cls.Name),
                            "LoadIcon",
                            widgetExp,
                            new CodePrimitiveExpression("gtk-missing-image"),
                            sizeExp
                            )
                        )
                    );

                CodeStatementCollection stms = cond.FalseStatements;

                stms.Add(
                    new CodeVariableDeclarationStatement(typeof(Gdk.Pixmap), "pmap",
                                                         new CodeObjectCreateExpression(
                                                             typeof(Gdk.Pixmap),
                                                             new CodePropertyReferenceExpression(
                                                                 new CodePropertyReferenceExpression(
                                                                     new CodeTypeReferenceExpression(typeof(Gdk.Screen)),
                                                                     "Default"
                                                                     ),
                                                                 "RootWindow"
                                                                 ),
                                                             szExp,
                                                             szExp
                                                             )
                                                         )
                    );
                stms.Add(
                    new CodeVariableDeclarationStatement(typeof(Gdk.GC), "gc",
                                                         new CodeObjectCreateExpression(typeof(Gdk.GC), pmapExp)
                                                         )
                    );
                stms.Add(
                    new CodeAssignStatement(
                        new CodePropertyReferenceExpression(
                            gcExp,
                            "RgbFgColor"
                            ),
                        new CodeObjectCreateExpression(
                            typeof(Gdk.Color),
                            new CodePrimitiveExpression(255),
                            new CodePrimitiveExpression(255),
                            new CodePrimitiveExpression(255)
                            )
                        )
                    );
                stms.Add(
                    new CodeMethodInvokeExpression(
                        pmapExp,
                        "DrawRectangle",
                        gcExp,
                        new CodePrimitiveExpression(true),
                        zeroExp,
                        zeroExp,
                        szExp,
                        szExp
                        )
                    );
                stms.Add(
                    new CodeAssignStatement(
                        new CodePropertyReferenceExpression(
                            gcExp,
                            "RgbFgColor"
                            ),
                        new CodeObjectCreateExpression(
                            typeof(Gdk.Color),
                            zeroExp, zeroExp, zeroExp
                            )
                        )
                    );
                stms.Add(
                    new CodeMethodInvokeExpression(
                        pmapExp,
                        "DrawRectangle",
                        gcExp,
                        new CodePrimitiveExpression(false),
                        zeroExp,
                        zeroExp,
                        szM1Exp,
                        szM1Exp
                        )
                    );
                stms.Add(
                    new CodeMethodInvokeExpression(
                        gcExp,
                        "SetLineAttributes",
                        new CodePrimitiveExpression(3),
                        new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Gdk.LineStyle)), "Solid"),
                        new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Gdk.CapStyle)), "Round"),
                        new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Gdk.JoinStyle)), "Round")
                        )
                    );
                stms.Add(
                    new CodeAssignStatement(
                        new CodePropertyReferenceExpression(
                            gcExp,
                            "RgbFgColor"
                            ),
                        new CodeObjectCreateExpression(
                            typeof(Gdk.Color),
                            new CodePrimitiveExpression(255),
                            zeroExp,
                            zeroExp
                            )
                        )
                    );
                stms.Add(
                    new CodeMethodInvokeExpression(
                        pmapExp,
                        "DrawLine",
                        gcExp,
                        mgExp,
                        mgExp,
                        new CodeBinaryOperatorExpression(szM1Exp, CodeBinaryOperatorType.Subtract, mgExp),
                        new CodeBinaryOperatorExpression(szM1Exp, CodeBinaryOperatorType.Subtract, mgExp)
                        )
                    );
                stms.Add(
                    new CodeMethodInvokeExpression(
                        pmapExp,
                        "DrawLine",
                        gcExp,
                        new CodeBinaryOperatorExpression(szM1Exp, CodeBinaryOperatorType.Subtract, mgExp),
                        mgExp,
                        mgExp,
                        new CodeBinaryOperatorExpression(szM1Exp, CodeBinaryOperatorType.Subtract, mgExp)
                        )
                    );
                stms.Add(
                    new CodeMethodReturnStatement(
                        new CodeMethodInvokeExpression(
                            new CodeTypeReferenceExpression(typeof(Gdk.Pixbuf)),
                            "FromDrawable",
                            pmapExp,
                            new CodePropertyReferenceExpression(pmapExp, "Colormap"),
                            zeroExp, zeroExp, zeroExp, zeroExp, szExp, szExp
                            )
                        )
                    );
            }

            int sz, h;

            Gtk.Icon.SizeLookup(size, out sz, out h);

            return(new CodeMethodInvokeExpression(
                       new CodeTypeReferenceExpression(new CodeTypeReference(cns.Name + ".IconLoader", CodeTypeReferenceOptions.GlobalReference)),
                       "LoadIcon",
                       rootObject,
                       new CodePrimitiveExpression(name),
                       new CodeFieldReferenceExpression(
                           new CodeTypeReferenceExpression(new CodeTypeReference(typeof(Gtk.IconSize), CodeTypeReferenceOptions.GlobalReference)),
                           size.ToString()
                           )
                       ));
        }
	public CodeStatementCollection(CodeStatementCollection value) {}
Example #15
0
        /// <summary>
        ///  Serializes the given object into a CodeDom object.
        /// </summary>
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            if (manager is null || value is null)
            {
                throw new ArgumentNullException(manager is null ? "manager" : "value");
            }

            // Find our base class's serializer.
            CodeDomSerializer serializer = (CodeDomSerializer)manager.GetSerializer(typeof(Component), typeof(CodeDomSerializer));

            if (serializer is null)
            {
                Debug.Fail("Unable to find a CodeDom serializer for 'Component'.  Has someone tampered with the serialization providers?");

                return(null);
            }

            // Now ask it to serializer
            object retVal = serializer.Serialize(manager, value);
            InheritanceAttribute inheritanceAttribute = (InheritanceAttribute)TypeDescriptor.GetAttributes(value)[typeof(InheritanceAttribute)];
            InheritanceLevel     inheritanceLevel     = InheritanceLevel.NotInherited;

            if (inheritanceAttribute != null)
            {
                inheritanceLevel = inheritanceAttribute.InheritanceLevel;
            }

            if (inheritanceLevel != InheritanceLevel.InheritedReadOnly)
            {
                // Next, see if we are in localization mode.  If we are, and if we can get
                // to a ResourceManager through the service provider, then emit the hierarchy information for
                // this object.  There is a small fragile assumption here:  The resource manager is demand
                // created, so if all of the properties of this control had default values it is possible
                // there will be no resource manager for us.  I'm letting that slip a bit, however, because
                // for Control classes, we always emit at least the location / size information for the
                // control.
                IDesignerHost host = (IDesignerHost)manager.GetService(typeof(IDesignerHost));

                if (host != null)
                {
                    PropertyDescriptor prop = TypeDescriptor.GetProperties(host.RootComponent)["Localizable"];

                    if (prop != null && prop.PropertyType == typeof(bool) && ((bool)prop.GetValue(host.RootComponent)))
                    {
                        SerializeControlHierarchy(manager, host, value);
                    }
                }

                CodeStatementCollection csCollection = retVal as CodeStatementCollection;

                if (csCollection != null)
                {
                    Control control = (Control)value;

                    // Serialize a suspend / resume pair.  We always serialize this
                    // for the root component
                    if ((host != null && control == host.RootComponent) || HasSitedNonReadonlyChildren(control))
                    {
                        SerializeSuspendLayout(manager, csCollection, value);
                        SerializeResumeLayout(manager, csCollection, value);
                        ControlDesigner controlDesigner = host.GetDesigner(control) as ControlDesigner;

                        if (HasAutoSizedChildren(control) || (controlDesigner != null && controlDesigner.SerializePerformLayout))
                        {
                            SerializePerformLayout(manager, csCollection, value);
                        }
                    }

                    // And now serialize the correct z-order relationships for the controls.  We only need to
                    // do this if there are controls in the collection that are inherited.
                    if (HasMixedInheritedChildren(control))
                    {
                        SerializeZOrder(manager, csCollection, control);
                    }
                }
            }

            return(retVal);
        }
 private void GenerateStatements(CodeStatementCollection stms)
 {
     IEnumerator en = stms.GetEnumerator();
     while (en.MoveNext())
     {
         ((ICodeGenerator)this).GenerateCodeFromStatement((CodeStatement)en.Current, output.InnerWriter, options);
     }
 }
Example #17
0
        /// <summary>
        ///  Serializes a method invocation on the control being serialized.  Used to serialize Suspend/ResumeLayout pairs, etc.
        /// </summary>
        private void SerializeMethodInvocation(IDesignerSerializationManager manager, CodeStatementCollection statements, object control, string methodName, CodeExpressionCollection parameters, Type[] paramTypes, StatementOrdering ordering)
        {
            using (TraceScope("ControlCodeDomSerializer::SerializeMethodInvocation(" + methodName + ")"))
            {
                string name = manager.GetName(control);
                Trace(name + "." + methodName);

                // Use IReflect to see if this method name exists on the control.
                paramTypes = ToTargetTypes(control, paramTypes);
                MethodInfo mi = TypeDescriptor.GetReflectionType(control).GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance, null, paramTypes, null);

                if (mi != null)
                {
                    CodeExpression field = SerializeToExpression(manager, control);
                    CodeMethodReferenceExpression method       = new CodeMethodReferenceExpression(field, methodName);
                    CodeMethodInvokeExpression    methodInvoke = new CodeMethodInvokeExpression();
                    methodInvoke.Method = method;

                    if (parameters != null)
                    {
                        methodInvoke.Parameters.AddRange(parameters);
                    }

                    CodeExpressionStatement statement = new CodeExpressionStatement(methodInvoke);

                    switch (ordering)
                    {
                    case StatementOrdering.Prepend:
                        statement.UserData["statement-ordering"] = "begin";
                        break;

                    case StatementOrdering.Append:
                        statement.UserData["statement-ordering"] = "end";
                        break;

                    default:
                        Debug.Fail("Unsupported statement ordering: " + ordering);
                        break;
                    }

                    statements.Add(statement);
                }
            }
        }
Example #18
0
 public override void OnExportClientServerCode(ActionBranch previousAction, ActionBranch nextAction, ILimnorCodeCompiler compiler, CodeMemberMethod method, CodeStatementCollection statements,
                                               StringCollection jsCode, StringCollection methodCode, JsMethodCompiler data)
 {
     if (_actionList != null)
     {
         int last = _actionList.Count - 1;
         for (int k = 0; k < _actionList.Count; k++)
         {
             if (_actionList[k].Action != null)
             {
                 ActionBranch nt = null;
                 if (k == last)
                 {
                     nt = nextAction;
                     if (nt != null && nt.UseInput)
                     {
                         nt.InputName = this.OutputCodeName;
                         nt.InputType = this.OutputType;
                         nt.SetInputName(OutputCodeName, OutputType);
                     }
                 }
                 _actionList[k].Action.ExportJavaScriptCode(this, nt, jsCode, methodCode, data);
             }
         }
     }
 }
Example #19
0
 private void SerializeSuspendLayout(IDesignerSerializationManager manager, CodeStatementCollection statements, object control)
 {
     SerializeMethodInvocation(manager, statements, control, "SuspendLayout", null, Array.Empty <Type>(), StatementOrdering.Prepend);
 }
Example #20
0
        public static WidgetMap GenerateCreationCode(CodeNamespace cns, CodeTypeDeclaration type, Gtk.Widget w, CodeExpression widgetVarExp, CodeStatementCollection statements, GenerationOptions options, ArrayList warnings)
        {
            statements.Add(new CodeCommentStatement("Widget " + w.Name));
            GeneratorContext ctx = new ProjectGeneratorContext(cns, type, statements, options);

            Stetic.Wrapper.Widget ww = Stetic.Wrapper.Widget.Lookup(w);
            ctx.GenerateCreationCode(ww, widgetVarExp);
            ctx.EndGeneration();
            warnings.AddRange(ctx.Warnings);
            return(ctx.WidgetMap);
        }
Example #21
0
        /// <summary>
        ///  This method actually performs the serialization.  When the member is serialized
        ///  the necessary statements will be added to the statements collection.
        /// </summary>
        public override void Serialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements)
        {
            if (manager is null)
            {
                throw new ArgumentNullException(nameof(manager));
            }
            if (value is null)
            {
                throw new ArgumentNullException(nameof(value));
            }
            if (!(descriptor is PropertyDescriptor propertyToSerialize))
            {
                throw new ArgumentNullException(nameof(descriptor));
            }
            if (statements is null)
            {
                throw new ArgumentNullException(nameof(statements));
            }

            try
            {
                ExtenderProvidedPropertyAttribute exAttr = (ExtenderProvidedPropertyAttribute)propertyToSerialize.Attributes[typeof(ExtenderProvidedPropertyAttribute)];
                bool isExtender        = (exAttr != null && exAttr.Provider != null);
                bool serializeContents = propertyToSerialize.Attributes.Contains(DesignerSerializationVisibilityAttribute.Content);

                CodeDomSerializer.Trace("Serializing property {0}", propertyToSerialize.Name);
                if (serializeContents)
                {
                    SerializeContentProperty(manager, value, propertyToSerialize, isExtender, statements);
                }
                else if (isExtender)
                {
                    SerializeExtenderProperty(manager, value, propertyToSerialize, statements);
                }
                else
                {
                    SerializeNormalProperty(manager, value, propertyToSerialize, statements);
                }
            }
            catch (Exception e)
            {
                // Since we usually go through reflection, don't
                // show what our engine does, show what caused
                // the problem.
                if (e is TargetInvocationException)
                {
                    e = e.InnerException;
                }

                manager.ReportError(new CodeDomSerializerException(string.Format(SR.SerializerPropertyGenFailed, propertyToSerialize.Name, e.Message), manager));
            }
        }
Example #22
0
 public ProjectGeneratorContext(CodeNamespace cns, CodeTypeDeclaration type, CodeStatementCollection statements, GenerationOptions options) : base(cns, "w", statements, options)
 {
     this.type = type;
 }
Example #23
0
        /// <summary>
        ///  This serializes the given property on this object as a content property.
        /// </summary>
        private void SerializeContentProperty(IDesignerSerializationManager manager, object value, PropertyDescriptor property, bool isExtender, CodeStatementCollection statements)
        {
            CodeDomSerializer.Trace("Property is marked as Visibility.Content.  Recursing.");

            object propertyValue = GetPropertyValue(manager, property, value, out bool validValue);

            // For persist contents objects, we don't just serialize the properties on the object; we
            // serialize everything.
            //
            CodeDomSerializer serializer = null;

            if (propertyValue is null)
            {
                CodeDomSerializer.TraceError("Property {0} is marked as Visibility.Content but it is returning null.", property.Name);

                string name = manager.GetName(value);

                if (name is null)
                {
                    name = value.GetType().FullName;
                }

                manager.ReportError(new CodeDomSerializerException(string.Format(SR.SerializerNullNestedProperty, name, property.Name), manager));
            }
            else
            {
                serializer = (CodeDomSerializer)manager.GetSerializer(propertyValue.GetType(), typeof(CodeDomSerializer));
                if (serializer != null)
                {
                    // Create a property reference expression and push it on the context stack.
                    // This allows the serializer to gain some context as to what it should be
                    // serializing.
                    CodeExpression target = SerializeToExpression(manager, value);

                    if (target is null)
                    {
                        CodeDomSerializer.TraceWarning("Unable to convert value to expression object");
                    }
                    else
                    {
                        CodeExpression propertyRef = null;

                        if (isExtender)
                        {
                            CodeDomSerializer.Trace("Content property is an extender.");
                            ExtenderProvidedPropertyAttribute exAttr = (ExtenderProvidedPropertyAttribute)property.Attributes[typeof(ExtenderProvidedPropertyAttribute)];

                            // Extender properties are method invokes on a target "extender" object.
                            //
                            CodeExpression extender = SerializeToExpression(manager, exAttr.Provider);
                            CodeExpression extended = SerializeToExpression(manager, value);

                            CodeDomSerializer.TraceWarningIf(extender is null, "Extender object {0} could not be serialized.", manager.GetName(exAttr.Provider));
                            CodeDomSerializer.TraceWarningIf(extended is null, "Extended object {0} could not be serialized.", manager.GetName(value));
                            if (extender != null && extended != null)
                            {
                                CodeMethodReferenceExpression methodRef    = new CodeMethodReferenceExpression(extender, "Get" + property.Name);
                                CodeMethodInvokeExpression    methodInvoke = new CodeMethodInvokeExpression
                                {
                                    Method = methodRef
                                };
                                methodInvoke.Parameters.Add(extended);
                                propertyRef = methodInvoke;
                            }
                        }
                        else
                        {
                            propertyRef = new CodePropertyReferenceExpression(target, property.Name);
                        }

                        if (propertyRef != null)
                        {
                            ExpressionContext tree = new ExpressionContext(propertyRef, property.PropertyType, value, propertyValue);
                            manager.Context.Push(tree);

                            object result = null;

                            try
                            {
                                SerializeAbsoluteContext absolute = (SerializeAbsoluteContext)manager.Context[typeof(SerializeAbsoluteContext)];

                                if (IsSerialized(manager, propertyValue, absolute != null))
                                {
                                    result = GetExpression(manager, propertyValue);
                                }
                                else
                                {
                                    result = serializer.Serialize(manager, propertyValue);
                                }
                            }
                            finally
                            {
                                Debug.Assert(manager.Context.Current == tree, "Serializer added a context it didn't remove.");
                                manager.Context.Pop();
                            }

                            if (result is CodeStatementCollection csc)
                            {
                                foreach (CodeStatement statement in csc)
                                {
                                    statements.Add(statement);
                                }
                            }
                            else
                            {
                                if (result is CodeStatement cs)
                                {
                                    statements.Add(cs);
                                }
                            }
                        }
                    }
                }
                else
                {
                    CodeDomSerializer.TraceError("Property {0} is marked as Visibilty.Content but there is no serializer for it.", property.Name);

                    manager.ReportError(new CodeDomSerializerException(string.Format(SR.SerializerNoSerializerForComponent, property.PropertyType.FullName), manager));
                }
            }
        }
        private static void ReplaceControlCreateStatement(Type ctrlType, CodeAssignStatement objAssignStatement, CodeStatementCollection statements)
        {
            /* Generate code like below
             *
             * IServiceProvider __activator = HttpRuntime.WebObjectActivator;
             *
             * if (activator != null) {
             *  _ctrl = (ctrlType)activator.GetService(ctrlType);
             * }
             *
             * // if default c-tor exists
             * else {
             *  _ctrl = new ....
             * }
             * // if no default c-tor
             * else {
             *  _ctrl = null
             * }
             *
             */
            var webObjectActivatorExpr = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("System.Web.HttpRuntime"), "WebObjectActivator");
            var activatorRefExpr       = new CodeVariableReferenceExpression("__activator");

            var getServiceExpr        = new CodeMethodInvokeExpression(webObjectActivatorExpr, "GetService", new CodeTypeOfExpression(ctrlType));
            var castExpr              = new CodeCastExpression(new CodeTypeReference(ctrlType), getServiceExpr);
            var createObjectStatement = new CodeConditionStatement()
            {
                Condition = new CodeBinaryOperatorExpression(activatorRefExpr,
                                                             CodeBinaryOperatorType.IdentityInequality,
                                                             new CodePrimitiveExpression(null))
            };

            createObjectStatement.TrueStatements.Add(new CodeAssignStatement(objAssignStatement.Left, castExpr));

            // If default c-tor exists
            if (ctrlType.GetConstructor(Type.EmptyTypes) != null)
            {
                createObjectStatement.FalseStatements.Add(objAssignStatement);
            }
            else
            {
                createObjectStatement.FalseStatements.Add(new CodeAssignStatement(objAssignStatement.Left, new CodePrimitiveExpression(null)));
            }

            // replace the old assign statement
            var indexOfStatement = statements.IndexOf(objAssignStatement);

            statements.Insert(indexOfStatement, createObjectStatement);
            statements.Insert(indexOfStatement, new CodeAssignStatement(activatorRefExpr, webObjectActivatorExpr));
            statements.Insert(indexOfStatement, new CodeVariableDeclarationStatement(typeof(IServiceProvider), "__activator"));
            statements.Remove(objAssignStatement);
        }
Example #25
0
        /// <summary>
        ///  This serializes the given property on this object.
        /// </summary>
        private void SerializeExtenderProperty(IDesignerSerializationManager manager, object value, PropertyDescriptor property, CodeStatementCollection statements)
        {
            AttributeCollection attributes = property.Attributes;

            using (CodeDomSerializer.TraceScope("PropertyMemberCodeDomSerializer::" + nameof(SerializeExtenderProperty)))
            {
                ExtenderProvidedPropertyAttribute exAttr = (ExtenderProvidedPropertyAttribute)attributes[typeof(ExtenderProvidedPropertyAttribute)];

                // Extender properties are method invokes on a target "extender" object.
                //
                CodeExpression extender = SerializeToExpression(manager, exAttr.Provider);
                CodeExpression extended = SerializeToExpression(manager, value);

                CodeDomSerializer.TraceWarningIf(extender is null, "Extender object {0} could not be serialized.", manager.GetName(exAttr.Provider));
                CodeDomSerializer.TraceWarningIf(extended is null, "Extended object {0} could not be serialized.", manager.GetName(value));
                if (extender != null && extended != null)
                {
                    CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression(extender, "Set" + property.Name);
                    object         propValue = GetPropertyValue(manager, property, value, out bool validValue);
                    CodeExpression serializedPropertyValue = null;

                    // Serialize the value of this property into a code expression.  If we can't get one,
                    // then we won't serialize the property.
                    if (validValue)
                    {
                        ExpressionContext tree = null;

                        if (propValue != value)
                        {
                            // make sure the value isn't the object or we'll end up printing
                            // this property instead of the value.
                            tree = new ExpressionContext(methodRef, property.PropertyType, value);
                            manager.Context.Push(tree);
                        }

                        try
                        {
                            serializedPropertyValue = SerializeToExpression(manager, propValue);
                        }
                        finally
                        {
                            if (tree != null)
                            {
                                Debug.Assert(manager.Context.Current == tree, "Context stack corrupted.");
                                manager.Context.Pop();
                            }
                        }
                    }

                    if (serializedPropertyValue != null)
                    {
                        CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression
                        {
                            Method = methodRef
                        };
                        methodInvoke.Parameters.Add(extended);
                        methodInvoke.Parameters.Add(serializedPropertyValue);
                        statements.Add(methodInvoke);
                    }
                }
            }
        }
Example #26
0
 public static void Throw <T> (this CodeStatementCollection statements, params CodeExpression [] parameters) where T : Exception
 {
     statements.Add(Throw <T> (parameters));
 }
Example #27
0
        /// <summary>
        ///  This serializes the given property on this object.
        /// </summary>
        private void SerializeNormalProperty(IDesignerSerializationManager manager, object value, PropertyDescriptor property, CodeStatementCollection statements)
        {
            using (CodeDomSerializer.TraceScope("CodeDomSerializer::" + nameof(SerializeProperty)))
            {
                CodeExpression target = SerializeToExpression(manager, value);

                CodeDomSerializer.TraceWarningIf(target is null, "Unable to serialize target for property {0}", property.Name);
                if (target != null)
                {
                    CodeExpression propertyRef = new CodePropertyReferenceExpression(target, property.Name);

                    CodeExpression serializedPropertyValue = null;

                    // First check for a member relationship service to see if this property
                    // is related to another member.  If it is, then we will use that
                    // relationship to construct the property assign statement.  if
                    // it isn't, then we're serialize ourselves.

                    if (manager.GetService(typeof(MemberRelationshipService)) is MemberRelationshipService relationships)
                    {
                        MemberRelationship relationship = relationships[value, property];

                        if (relationship != MemberRelationship.Empty)
                        {
                            CodeExpression rhsTarget = SerializeToExpression(manager, relationship.Owner);

                            if (rhsTarget != null)
                            {
                                serializedPropertyValue = new CodePropertyReferenceExpression(rhsTarget, relationship.Member.Name);
                            }
                        }
                    }

                    if (serializedPropertyValue is null)
                    {
                        // Serialize the value of this property into a code expression.  If we can't get one,
                        // then we won't serialize the property.
                        //
                        object propValue = GetPropertyValue(manager, property, value, out bool validValue);

                        if (validValue)
                        {
                            ExpressionContext tree = null;

                            if (propValue != value)
                            {
                                // make sure the value isn't the object or we'll end up printing
                                // this property instead of the value.
                                tree = new ExpressionContext(propertyRef, property.PropertyType, value);
                                manager.Context.Push(tree);
                            }

                            try
                            {
                                serializedPropertyValue = SerializeToExpression(manager, propValue);
                            }
                            finally
                            {
                                if (tree != null)
                                {
                                    Debug.Assert(manager.Context.Current == tree, "Context stack corrupted.");
                                    manager.Context.Pop();
                                }
                            }
                        }
                    }

                    if (serializedPropertyValue != null)
                    {
                        CodeAssignStatement assign = new CodeAssignStatement(propertyRef, serializedPropertyValue);
                        statements.Add(assign);
                    }
                }
            }
        }
Example #28
0
 public TableEntry(object owner, CodeStatementCollection statements)
 {
     Owner      = owner;
     Statements = statements;
 }
Example #29
0
 public CodeBlock(CodeLine line, string method, CodeStatementCollection statements, BlockKind kind, CodeBlock parent)
     : this(line, method, statements, kind, parent, null, null)
 {
 }
	public void AddRange(CodeStatementCollection value) {}
Example #31
0
 protected void GenerateBlock(CodeStatementCollection statements)
 {
     OutputStartingBrace();
     GenerateStatements(statements);
     OutputEndingBrace();
 }
Example #32
0
 private void ValidateStatements(CodeStatementCollection stmts)
 {
     foreach (CodeStatement stmt in stmts)
     {
         ValidateStatement(stmt);
     }
 }
Example #33
0
        private static CodeElement WalkStatements(TextPoint Point, vsCMElement Scope, CodeStatementCollection statements)
        {
            foreach (CodeStatement cs in statements)
            {
                if (Scope == vsCMElement.vsCMElementAssignmentStmt && cs is CodeAssignStatement)
                {
                    if (IsInRange(cs, Point))
                    {
                        return((CodeElement)cs.UserData[CodeKey]);
                    }
                }

                if (Scope == vsCMElement.vsCMElementLocalDeclStmt && cs is CodeVariableDeclarationStatement)
                {
                    if (IsInRange(cs, Point))
                    {
                        return((CodeElement)cs.UserData[CodeKey]);
                    }
                }

                CodeExpressionStatement ces = cs as CodeExpressionStatement;
                if (ces != null)
                {
                    if (Scope == vsCMElement.vsCMElementFunctionInvokeStmt && ces.Expression is CodeMethodInvokeExpression)
                    {
                        if (IsInRange(cs, Point))
                        {
                            return((CodeElement)cs.UserData[CodeKey]);
                        }
                    }
                    if (Scope == vsCMElement.vsCMElementPropertySetStmt && ces.Expression is CodePropertySetValueReferenceExpression)
                    {
                        if (IsInRange(cs, Point))
                        {
                            return((CodeElement)cs.UserData[CodeKey]);
                        }
                    }
                }

                if (Scope == vsCMElement.vsCMElementOther && IsInRange(cs, Point))
                {
                    return((CodeElement)cs.UserData[CodeKey]);
                }
            }
            return(null);
        }
	// Generate code for a statement collection.
	protected void GenerateStatements(CodeStatementCollection e)
			{
				if(e == null)
				{
					return;
				}
				foreach(CodeStatement stmt in e)
				{
					((ICodeGenerator)this).GenerateCodeFromStatement
							(stmt, writer.InnerWriter, Options);
				}
			}
Example #35
0
        internal static void BindSignalHandlers(CodeExpression targetObjectVar, ObjectWrapper wrapper, Stetic.WidgetMap map, CodeStatementCollection statements, GenerationOptions options)
        {
            foreach (Signal signal in wrapper.Signals)
            {
                SignalDescriptor descriptor = signal.SignalDescriptor;

                CodeExpression createDelegate;

                if (options.UsePartialClasses)
                {
                    createDelegate =
                        new CodeDelegateCreateExpression(
                            new CodeTypeReference(descriptor.HandlerTypeName, CodeTypeReferenceOptions.GlobalReference),
                            new CodeThisReferenceExpression(),
                            signal.Handler);
                }
                else
                {
                    createDelegate =
                        new CodeMethodInvokeExpression(
                            new CodeTypeReferenceExpression(new CodeTypeReference(typeof(Delegate), CodeTypeReferenceOptions.GlobalReference)),
                            "CreateDelegate",
                            new CodeTypeOfExpression(descriptor.HandlerTypeName),
                            targetObjectVar,
                            new CodePrimitiveExpression(signal.Handler));

                    createDelegate = new CodeCastExpression(descriptor.HandlerTypeName.ToGlobalTypeRef(), createDelegate);
                }

                CodeAttachEventStatement cevent = new CodeAttachEventStatement(
                    new CodeEventReferenceExpression(
                        map.GetWidgetExp(wrapper),
                        descriptor.Name),
                    createDelegate);

                statements.Add(cevent);
            }

            Wrapper.Widget widget = wrapper as Wrapper.Widget;
            if (widget != null && widget.IsTopLevel)
            {
                // Bind local action signals
                foreach (Wrapper.ActionGroup grp in widget.LocalActionGroups)
                {
                    foreach (Wrapper.Action ac in grp.Actions)
                    {
                        BindSignalHandlers(targetObjectVar, ac, map, statements, options);
                    }
                }
            }

            Gtk.Container cont = wrapper.Wrapped as Gtk.Container;
            if (cont != null)
            {
                foreach (Gtk.Widget child in cont.AllChildren)
                {
                    Stetic.Wrapper.Widget ww = Stetic.Wrapper.Widget.Lookup(child);
                    if (ww != null)
                    {
                        BindSignalHandlers(targetObjectVar, ww, map, statements, options);
                    }
                }
            }
        }
Example #36
0
 protected void GenerateStatements(CodeStatementCollection stmts)
 {
     foreach (CodeStatement stmt in stmts)
     {
         ((ICodeGenerator)this).GenerateCodeFromStatement(stmt, _output.InnerWriter, _options);
     }
 }
Example #37
0
        public override bool OnExportCode(ActionBranch previousAction, ActionBranch nextAction, ILimnorCodeCompiler compiler, CodeMemberMethod method, CodeStatementCollection statements)
        {
            bool bRet = false;

            if (_actionList != null)
            {
                int last = _actionList.Count - 1;
                for (int k = 0; k < _actionList.Count; k++)
                {
                    if (_actionList[k].Action != null)
                    {
                        bRet = _actionList[k].Action.IsMethodReturn;
                        ActionBranch nt = null;
                        if (k == last)
                        {
                            nt = nextAction;
                            if (nt != null && nt.UseInput)
                            {
                                nt.InputName = this.OutputCodeName;
                                nt.InputType = this.OutputType;
                                nt.SetInputName(OutputCodeName, OutputType);
                            }
                        }
                        _actionList[k].Action.ExportCode(this, nt, compiler, this.Method, method, statements, compiler.Debug);
                    }
                }
            }
            return(bRet);
        }