void CreateMethodEditPoint()
        {
            var startPoint = (TextPoint)codeFunction.GetStartPoint();

            endPoint  = (TextPoint)codeFunction.GetEndPoint();
            editPoint = (EditPoint)startPoint.CreateEditPoint();
        }
Beispiel #2
0
 public static void InsertCodeInMethod(CodeFunction2 currentMethod, string codeToInsert)
 {
     TextPoint startPoint = currentMethod.GetStartPoint(vsCMPart.vsCMPartBody);
     // Batch insert the new code so it can be undone in 1 call to undo
     EditPoint pnt = startPoint.CreateEditPoint();
     pnt.Insert(codeToInsert);
     // Format the code (indent it properly)
     pnt.SmartFormat(startPoint);
 }
Beispiel #3
0
        public static void InsertCodeInMethod(CodeFunction2 currentMethod, string codeToInsert)
        {
            TextPoint startPoint = currentMethod.GetStartPoint(vsCMPart.vsCMPartBody);
            // Batch insert the new code so it can be undone in 1 call to undo
            EditPoint pnt = startPoint.CreateEditPoint();

            pnt.Insert(codeToInsert);
            // Format the code (indent it properly)
            pnt.SmartFormat(startPoint);
        }
Beispiel #4
0
        /// <summary>
        /// Returns header text of the function
        /// </summary>
        public static string GetHeaderText(this CodeFunction2 codeFunction)
        {
            if (codeFunction == null)
            {
                throw new ArgumentNullException("codeFunction");
            }

            TextPoint startPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartHeader);
            TextPoint endPoint   = codeFunction.GetStartPoint(vsCMPart.vsCMPartBody);

            EditPoint ep = startPoint.CreateEditPoint();

            if (ep == null)
            {
                return(null);
            }
            else
            {
                return(ep.GetText(endPoint));
            }
        }
Beispiel #5
0
        public static void GenerateConstructor(CodeClass2 codeClass, CodeVariable2[] codeVariables, bool generateComments, vsCMAccess accessModifier)
        {
            CodeGenerator codeGenerator = CreateCodeGenerator(codeClass.Language);


            CodeFunction2 codeFunction = null;

            if (codeClass.Language == CodeModelLanguageConstants.vsCMLanguageCSharp)
            {
                codeFunction = (CodeFunction2)codeClass.AddFunction(codeClass.Name, vsCMFunction.vsCMFunctionConstructor, null, -1, accessModifier, null);
            }
            else if (codeClass.Language == CodeModelLanguageConstants.vsCMLanguageVB)
            {
                codeFunction = (CodeFunction2)codeClass.AddFunction("New", vsCMFunction.vsCMFunctionSub, vsCMTypeRef.vsCMTypeRefVoid, -1, accessModifier, null);
            }

            if (generateComments)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("<doc>");
                sb.AppendLine("<summary>");
                sb.AppendLine("</summary>");
                foreach (CodeVariable2 codeVariable in codeVariables)
                {
                    sb.AppendLine(String.Format("<param name=\"{0}\"></param>", codeVariable.Name));
                }
                sb.Append("</doc>");

                codeFunction.DocComment = sb.ToString();
            }

            foreach (CodeVariable2 codeVariable in codeVariables)
            {
                codeFunction.AddParameter(codeVariable.Name, codeVariable.Type.AsString, -1);
            }

            EditPoint2 editPoint = (EditPoint2)codeFunction.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();

            foreach (CodeVariable2 codeVariable in codeVariables)
            {
                editPoint.Insert(codeGenerator.GenerateAssignStatement(codeVariable.Name, codeVariable.Name));
                editPoint.SmartFormat(editPoint);

                if (Array.IndexOf(codeVariables, codeVariable) < codeVariables.Length - 1)
                {
                    editPoint.InsertNewLine(1);
                }
            }

            editPoint.TryToShow(vsPaneShowHow.vsPaneShowCentered, codeFunction.StartPoint);
        }
Beispiel #6
0
        /// <summary>
        /// Add function to the specified class with the given body.
        /// </summary>
        /// <param name="p_securedClass"></param>
        /// <param name="p_functionName"></param>
        /// <param name="p_functionBody"></param>
        private static void AddFunction(CodeClass2 p_securedClass, string p_functionName, string p_functionBody)
        {
            // Add a method with a parameter to the class.
            CodeFunction2 testFunction = (CodeFunction2)p_securedClass.AddFunction(p_functionName, vsCMFunction.vsCMFunctionFunction, "void", -1, vsCMAccess.vsCMAccessPublic, null);

            testFunction.AddAttribute("TestMethod", string.Empty);

            var startPoint = testFunction.GetStartPoint(vsCMPart.vsCMPartBody);
            var endPoint   = testFunction.GetEndPoint(vsCMPart.vsCMPartBody);
            var editPoint  = startPoint.CreateEditPoint() as EditPoint2;

            // Clear the default generated body
            editPoint.Delete(endPoint);
            editPoint.Indent(null, 1);

            // Write the body of the function
            editPoint.Insert(p_functionBody);
            editPoint.InsertNewLine();

            endPoint = testFunction.GetEndPoint(vsCMPart.vsCMPartBody);
            editPoint.SmartFormat(endPoint);
        }
    public static void AddUniqueAttributeOnNewLine(this CodeFunction2 func, string name, string value)
    {
        bool found = false;

        // Loop through the existing elements and if the attribute they sent us already exists, then we will not re-add it.
        foreach (CodeAttribute2 attr in func.Attributes)
        {
            if (attr.Name == name)
            {
                found = true;
            }
        }
        if (!found)
        {
            // Get the starting location for the method, so we know where to insert the attributes
            var       pt = func.GetStartPoint();
            EditPoint p  = (func.DTE.ActiveDocument.Object("") as TextDocument).CreateEditPoint(pt);
            // Insert the attribute at the top of the function
            p.Insert(string.Format("[{0}({1})]\r\n", name, value));
            // Reformat the document, so the new attribute is properly aligned with the function, otherwise it will be at the beginning of the line.
            func.DTE.ExecuteCommand("Edit.FormatDocument");
        }
    }
        // add a class to the given namespace
        private void AddClassToNamespace(CodeNamespace ns)
        {
            // add a class
            CodeClass2 chess = (CodeClass2)ns.AddClass("Chess", -1, null, null, vsCMAccess.vsCMAccessPublic);

            // add a function with a parameter and a comment
            CodeFunction2 move = (CodeFunction2)chess.AddFunction("Move", vsCMFunction.vsCMFunctionFunction, "int", -1, vsCMAccess.vsCMAccessPublic, null);

            move.AddParameter("IsOK", "bool", -1);
            move.Comment = "This is the move function";

            // add some text to the body of the function
            EditPoint2 editPoint = (EditPoint2)move.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();

            editPoint.Indent(null, 0);
            editPoint.Insert("int a = 1;");
            editPoint.InsertNewLine(1);
            editPoint.Indent(null, 3);
            editPoint.Insert("int b = 3;");
            editPoint.InsertNewLine(2);
            editPoint.Indent(null, 3);
            editPoint.Insert("return a + b; //");
        }
        /// <summary>
        /// Explores given method using C# lookuper
        /// </summary>
        protected virtual void Explore(AbstractBatchCommand parentCommand, CodeFunction2 codeFunction, CodeNamespace parentNamespace, CodeElement2 codeClassOrStruct, Predicate <CodeElement> exploreable, bool isLocalizableFalse)
        {
            if (codeFunction.MustImplement)
            {
                return;                             // method must not be abstract or declated in an interface
            }
            if (!exploreable(codeFunction as CodeElement))
            {
                return;                                            // predicate must eval to true
            }
            // there is no way of knowing whether a function is not declared 'extern'. In that case, following will throw an exception.
            string functionText = null;

            try {
                functionText = codeFunction.GetText(); // get method text
            } catch (Exception) { }
            if (string.IsNullOrEmpty(functionText))
            {
                return;
            }

            TextPoint startPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartBody);

            // is method decorated with Localizable(false)
            bool functionLocalizableFalse = (codeFunction as CodeElement).HasLocalizableFalseAttribute();

            var list = parentCommand.LookupInCSharp(functionText, startPoint, parentNamespace, codeClassOrStruct, codeFunction.Name, null, isLocalizableFalse || functionLocalizableFalse);

            // add context to result items (surounding few lines of code)
            EditPoint2 editPoint = (EditPoint2)startPoint.CreateEditPoint();

            foreach (AbstractResultItem item in list)
            {
                item.CodeModelSource = codeFunction;
                AddContextToItem(item, editPoint);
            }

            // read optional arguments initializers (just to show them - they cannot be moved)
            TextPoint headerStartPoint = null;

            try {
                headerStartPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartHeader);
            } catch (Exception) { }
            if (headerStartPoint == null)
            {
                return;
            }

            string headerText = codeFunction.GetHeaderText();

            // search method header
            var headerList = parentCommand.LookupInCSharp(headerText, headerStartPoint, parentNamespace, codeClassOrStruct, codeFunction.Name, null, isLocalizableFalse || functionLocalizableFalse);

            // add to list
            editPoint = (EditPoint2)startPoint.CreateEditPoint();
            foreach (AbstractResultItem item in headerList)
            {
                item.IsConst         = true;
                item.CodeModelSource = codeFunction;
                AddContextToItem(item, editPoint);
            }
        }
        public void GenerateClass()
        {
            if (classFile == null)
            {
                return;
            }

            ImportModelSourceToContentProject();

            StringBuilder sb       = new StringBuilder();
            string        variable = sb.
                                     Append("Camera camera;\r\n").
                                     Append("Terrain terrain;\r\n").
                                     Append("Texture2D heightMap;\r\n").
                                     Append("World world;\r\n").
                                     Append("Grid grid;\r\n").
                                     ToString();

            sb.Clear();
            Vector3 cameraPos = mapModel.MainCamera.Position;
            Vector3 cameraRot = mapModel.MainCamera.EulerRotation;

            sb.
            Append("CollisionSystem collisionSystem = new CollisionSystemPersistentSAP();\r\n").
            Append("world = new World(collisionSystem);\r\n").
            Append("world.AllowDeactivation = true;\r\n").
            Append("world.Gravity = new JVector(0, ").Append(mapModel.PhysicsWorld.Gravity).Append("f, 0);\r\n").
            Append("world.ContactSettings.MaterialCoefficientMixing = ContactSettings.MaterialCoefficientMixingType.").Append(mapModel.PhysicsWorld.MaterialCoefficientMixing.ToString()).Append(";\r\n").
            Append("collisionSystem.CollisionDetected += new CollisionDetectedHandler(collisionSystem_CollisionDetected);\r\n\r\n").
            Append("camera = new Camera(this);\r\n").
            Append("camera.Name = \"camera\";\r\n").
            Append("camera.Position = new Vector3(").Append(cameraPos.X).Append("f, ").Append(cameraPos.Y).Append("f, ").Append(cameraPos.Z).Append("f);\r\n").
            Append("camera.EulerRotation = new Vector3(").Append(cameraRot.X).Append("f, ").Append(cameraRot.Y).Append("f, ").Append(cameraRot.Z).Append("f);\r\n");
            foreach (EditorModel.PropertyModel.Script script in mapModel.MainCamera.Scripts)
            {
                sb.Append("camera.AddScript(new ").Append(System.IO.Path.GetFileNameWithoutExtension(script.Name)).Append("());\r\n");
            }
            sb.Append("Components.Add(camera);\r\n\r\n");
            string constructor = sb.ToString();

            sb.Clear();
            sb.
            Append("heightMap = Content.Load<Texture2D>(\"" + heightMapAsset + "\");\r\n").
            Append("terrain = new Terrain(GraphicsDevice, camera, heightMap, this, world);\r\n").
            Append("terrain.Texture = Content.Load<Texture2D>(\"" + textureAsset + "\");\r\n").
            Append("Components.Add(terrain);\r\n\r\n").
            Append("grid = new Grid(this, terrain, 8, camera, GraphicsDevice, new BasicEffect(GraphicsDevice), world);\r\n").
            Append("grid.RoadModel = Content.Load<Model>(\"jalan_raya\");\r\n").
            Append("grid.RoadModel_belok = Content.Load<Model>(\"jalan_raya_belok\");\r\n").
            Append("grid.GridMap = Content.Load<Texture2D>(\"gridmap_Game2\");\r\n").
            Append("grid.ImportGridMap();\r\n\r\n");
            string loadContent = sb.ToString();

            sb.Clear();
            string update = sb.
                            Append("float step = (float)gameTime.ElapsedGameTime.TotalSeconds;\r\n").
                            Append("if (step > 1.0f / 100.0f) step = 1.0f / 100.0f;\r\n").
                            Append("world.Step(step, true);\r\n").
                            ToString();

            sb.Clear();
            string draw = sb.
                          ToString();

            sb.Clear();
            foreach (CodeLines codeLines in codeLinesList)
            {
                variable    += codeLines.Code[CodeLines.CodePosition.Variable] + ((codeLines.Code[CodeLines.CodePosition.Variable] != "") ? "\r\n" : "");
                constructor += codeLines.Code[CodeLines.CodePosition.Constructor] + ((codeLines.Code[CodeLines.CodePosition.Constructor] != "") ? "\r\n" : "");
                loadContent += codeLines.Code[CodeLines.CodePosition.LoadContent] + ((codeLines.Code[CodeLines.CodePosition.LoadContent] != "") ? "\r\n" : "");
                draw        += codeLines.Code[CodeLines.CodePosition.Draw] + ((codeLines.Code[CodeLines.CodePosition.Draw] != "") ? "\r\n" : "");
            }

            EditPoint editPoint    = null;
            EditPoint movePoint    = null;
            string    startPattern = "#region XnaLevelEditor";
            string    endPattern   = "#endregion";

            if (codeClass != null)
            {
                editPoint = codeClass.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();
                editPoint.FindPattern(startPattern, (int)vsFindOptions.vsFindOptionsNone, ref editPoint);
                movePoint = editPoint.CreateEditPoint();
                movePoint.FindPattern(endPattern, (int)vsFindOptions.vsFindOptionsNone);
                editPoint.ReplaceText(movePoint, "\r\n" + variable, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat);
                movePoint.SmartFormat(movePoint);
            }

            if (constructorFunction != null)
            {
                editPoint = constructorFunction.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();
                editPoint.FindPattern(startPattern, (int)vsFindOptions.vsFindOptionsNone, ref editPoint);
                movePoint = editPoint.CreateEditPoint();
                movePoint.FindPattern(endPattern, (int)vsFindOptions.vsFindOptionsNone);
                editPoint.ReplaceText(movePoint, "\r\n" + constructor, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat);
                movePoint.SmartFormat(movePoint);
            }

            if (loadContentFunction != null)
            {
                editPoint = loadContentFunction.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();
                editPoint.FindPattern(startPattern, (int)vsFindOptions.vsFindOptionsNone, ref editPoint);
                movePoint = editPoint.CreateEditPoint();
                movePoint.FindPattern(endPattern, (int)vsFindOptions.vsFindOptionsNone);
                editPoint.ReplaceText(movePoint, "\r\n" + loadContent, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat);
                movePoint.SmartFormat(movePoint);
            }

            if (updateFunction != null)
            {
                editPoint = updateFunction.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();
                editPoint.FindPattern(startPattern, (int)vsFindOptions.vsFindOptionsNone, ref editPoint);
                movePoint = editPoint.CreateEditPoint();
                movePoint.FindPattern(endPattern, (int)vsFindOptions.vsFindOptionsNone);
                editPoint.ReplaceText(movePoint, "\r\n" + update, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat);
                movePoint.SmartFormat(movePoint);
            }

            if (drawFunction != null)
            {
                editPoint = drawFunction.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();
                editPoint.FindPattern(startPattern, (int)vsFindOptions.vsFindOptionsNone, ref editPoint);
                movePoint = editPoint.CreateEditPoint();
                movePoint.FindPattern(endPattern, (int)vsFindOptions.vsFindOptionsNone);
                editPoint.ReplaceText(movePoint, "\r\n" + draw, (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat);
                movePoint.SmartFormat(movePoint);
            }
        }
        /// <summary>
        /// Used by C# ad-hoc methods (move and inline) to get information about the block of code, where right-click was performed.
        /// This methods makes use of document's FileCodeModel, which is not available for ASP .NET files - these files are thus
        /// handled by their own parser.
        /// </summary>
        /// <param name="text">Text of the block (e.g. code of a method, declaration of a variable...)</param>
        /// <param name="startPoint">Beginning of the text</param>
        /// <param name="codeFunctionName">Name of the function, where right-click was performed, null if right-click was performed on a variable.</param>
        /// <param name="codeVariableName">Name of the variable, where right-click was performed, null otherwise.</param>
        /// <param name="codeClass">Name of the class, where the code block is located.</param>
        /// <param name="selectionSpan">Current selection span.</param>
        /// <returns>True, if all necessary information was succesfully obtained, false otherwise.</returns>
        protected bool GetCodeBlockFromSelection(out string text, out TextPoint startPoint, out string codeFunctionName, out string codeVariableName, out CodeElement2 codeClass, out TextSpan selectionSpan, out bool isConst, out object codeModelSource)
        {
            // get current selection span
            TextSpan[] spans = new TextSpan[1];
            int        hr    = textView.GetSelectionSpan(spans);

            Marshal.ThrowExceptionForHR(hr);

            selectionSpan = spans[0];

            object o;

            hr = textLines.CreateTextPoint(selectionSpan.iStartLine, selectionSpan.iStartIndex, out o);
            Marshal.ThrowExceptionForHR(hr);
            TextPoint selectionPoint = (TextPoint)o;

            startPoint = null;
            text       = null;
            bool ok = false;

            codeFunctionName = null;
            codeVariableName = null;
            codeClass        = null;
            isConst          = false;
            codeModelSource  = null;

            // It is impossible to find out the code block, where right-click was performed. Following code
            // assumes that valid string literals or references can only be found in a method, in a class variable (as initializers)
            // or in a property code. C# syntax permits more locations (attributes, default argument values in .NET 4+) but we can ignore
            // these, because they are all evaluated at compile-time, making resource references impossible.

            // assume we are in a function (method)
            try {
                CodeFunction2 codeFunction = (CodeFunction2)currentCodeModel.CodeElementFromPoint(selectionPoint, vsCMElement.vsCMElementFunction);
                codeFunctionName = codeFunction.Name;
                codeClass        = codeFunction.GetClass(); // extension
                codeModelSource  = codeFunction;

                text = codeFunction.GetText();
                if (!string.IsNullOrEmpty(text))
                {
                    startPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartBody);
                    ok         = true;
                }
            } catch (Exception) {
                // it's not a method - maybe a property?
                try {
                    CodeProperty codeProperty = (CodeProperty)currentCodeModel.CodeElementFromPoint(selectionPoint, vsCMElement.vsCMElementProperty);
                    codeFunctionName = codeProperty.Name;
                    codeClass        = codeProperty.GetClass();
                    codeModelSource  = codeProperty;
                    text             = codeProperty.GetText();

                    if (!string.IsNullOrEmpty(text))
                    {
                        startPoint = codeProperty.GetStartPoint(vsCMPart.vsCMPartBody);
                        ok         = true;
                    }
                } catch (Exception) {
                    // not a property, either. It must be a variable - or there's no valid code block
                    try {
                        CodeVariable2 codeVariable = (CodeVariable2)currentCodeModel.CodeElementFromPoint(selectionPoint, vsCMElement.vsCMElementVariable);
                        if (codeVariable.InitExpression != null)
                        {
                            codeVariableName = codeVariable.Name;
                            codeClass        = codeVariable.GetClass();
                            isConst          = codeVariable.ConstKind == vsCMConstKind.vsCMConstKindConst;
                            codeModelSource  = codeVariable;

                            startPoint = codeVariable.StartPoint;
                            text       = codeVariable.GetText();
                            if ((codeClass.Kind == vsCMElement.vsCMElementStruct && codeVariable.IsShared) ||
                                (codeClass.Kind == vsCMElement.vsCMElementClass || codeClass.Kind == vsCMElement.vsCMElementModule) &&
                                !string.IsNullOrEmpty(text))
                            {
                                ok = true;
                            }
                        }
                    } catch (Exception) {
                        return(false);
                    }
                }
            }

            return(ok);
        }