public IElement GetElementContaining(EventResponseSave ers)
        {
            for (int i = 0; i < ObjectFinder.Self.GlueProject.Screens.Count; i++)
            {
                foreach (EventResponseSave possibleErs in ObjectFinder.Self.GlueProject.Screens[i].Events)
                {
                    if (possibleErs == ers)
                    {
                        return(ObjectFinder.Self.GlueProject.Screens[i]);
                    }
                }
            }
            for (int i = 0; i < ObjectFinder.Self.GlueProject.Entities.Count; i++)
            {
                foreach (EventResponseSave possibleErs in ObjectFinder.Self.GlueProject.Entities[i].Events)
                {
                    if (possibleErs == ers)
                    {
                        return(ObjectFinder.Self.GlueProject.Entities[i]);
                    }
                }
            }

            return(null);
        }
        private void SaveText()
        {
            if (EditorLogic.CurrentEventResponseSave != null && mIsCodeValid)
            {
                IElement          currentElement = EditorLogic.CurrentElement;
                EventResponseSave currentEvent   = EditorLogic.CurrentEventResponseSave;


                if (this.syntaxBoxControl1.Document.Text != mLastSavedText)
                {
                    if (HasMatchingBrackets(this.syntaxBoxControl1.Document.Text))
                    {
                        mLastSavedText = this.syntaxBoxControl1.Document.Text;

                        EventCodeGenerator.InjectTextForEventAndSaveCustomFile(currentElement, EditorLogic.CurrentEventResponseSave, mLastSavedText);
                        PluginManager.ReceiveOutput("Saved " + EditorLogic.CurrentEventResponseSave);
                        GlueCommands.Self.GenerateCodeCommands.GenerateCurrentElementCode();
                        GluxCommands.Self.SaveGlux();
                    }
                    else
                    {
                        PluginManager.ReceiveError("Mismatch of } and { in event " + EditorLogic.CurrentEventResponseSave);
                    }
                }
            }
        }
Beispiel #3
0
        private void GetEventSignatureAndArgs(NamedObjectSave namedObjectSave, EventResponseSave eventResponseSave, out string type, out string signatureArgs)
        {
            if (namedObjectSave == null)
            {
                throw new ArgumentNullException(nameof(namedObjectSave));
            }

            if (namedObjectSave.GetAssetTypeInfo() == AssetTypeInfoManager.Self.CollisionRelationshipAti &&
                eventResponseSave.SourceObjectEvent == "CollisionOccurred")
            {
                bool firstThrowaway;
                bool secondThrowaway;

                var firstType  = AssetTypeInfoManager.GetFirstGenericType(namedObjectSave, out firstThrowaway);
                var secondType = AssetTypeInfoManager.GetSecondGenericType(namedObjectSave, out secondThrowaway);

                type          = $"System.Action<{firstType}, {secondType}>";
                signatureArgs = $"{firstType} first, {secondType} second";
            }
            else
            {
                type          = null;
                signatureArgs = null;
            }
        }
Beispiel #4
0
 public void ReactToChange(string changedMember, object oldValue, EventResponseSave ers, IElement container)
 {
     if (changedMember == "EventName")
     {
         ReactToEventRename(oldValue, ers, container);
     }
 }
Beispiel #5
0
        public void SetBackingObjects(IElement element, EventResponseSave eventResponse)
        {
            mElement       = element;
            mEventResponse = eventResponse;

            RefreshLists();
        }
Beispiel #6
0
        void HandleAfterVariableSet(object sender, VariableSetArgs e)
        {
            try
            {
                if (mControl != null && mControl.Enabled)
                {
                    ElementRuntime elementRuntime = sender as ElementRuntime;
                    // If the user has just selected the element runtime,then it hasn't been set
                    // as the current element yet, so we can't use the GlueViewState facade
                    // IElement element = GlueViewState.Self.CurrentElement;
                    IElement element = elementRuntime.AssociatedIElement;

                    if (element != null)
                    {
                        string variableName = e.VariableName;

                        EventResponseSave ers = element.GetEvent("After" + variableName + "Set");

                        if (ers != null)
                        {
                            mParserLog.AppendLine("Reacting to after " + e.VariableName + " Set in the file :\n\t\t" + EventResponseSave.GetSharedCodeFullFileName(element, FileManager.GetDirectory(GlueViewState.Self.CurrentGlueProjectFile)));

                            ApplyEventResponseSave(elementRuntime, ers);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                int m = 3;
            }
        }
Beispiel #7
0
        private TreeNode FindEventResponseSaveInEntities(EventResponseSave eventResponse, TreeNodeCollection nodeCollection)
        {
            TreeNode foundNode = null;

            foreach (TreeNode treeNode in nodeCollection)
            {
                if (treeNode is EntityTreeNode)
                {
                    foundNode = ((EntityTreeNode)treeNode).GetTreeNodeFor(eventResponse);
                    if (foundNode != null)
                    {
                        break;
                    }
                }
                else
                {
                    foundNode = FindEventResponseSaveInEntities(eventResponse, treeNode.Nodes);
                    if (foundNode != null)
                    {
                        break;
                    }
                }
            }
            return(foundNode);
        }
        internal void HandleEventRemoved(IElement element, EventResponseSave eventResponse)
        {
            bool hasAnyEvents = element.Events.Count > 0;

            if (!hasAnyEvents)
            {
                RemoveEventGeneratedCodefile(element);
            }
        }
        private static void SetUpCodeEditorForEventResponse()
        {
            EventResponseSave ers = EditorLogic.CurrentEventResponseSave;

            EventSave eventSave = ers.GetEventSave();
            string    args      = ers.GetArgsForMethod(EditorLogic.CurrentElement);

            MainGlueWindow.Self.CodeEditor.TopText    = "void On" + ers.EventName + "(" + args + ")\n{";
            MainGlueWindow.Self.CodeEditor.BottomText = "}";
        }
 public TreeNode GetTreeNodeFor(EventResponseSave eventResponse)
 {
     foreach (TreeNode treeNode in this.mEventsTreeNode.Nodes)
     {
         if (treeNode.Tag == eventResponse)
         {
             return(treeNode);
         }
     }
     return(null);
 }
Beispiel #11
0
        private void ApplyEventResponseSave(ElementRuntime elementRuntime, EventResponseSave ers)
        {
            IElement element          = elementRuntime.AssociatedIElement;
            string   projectDirectory = FileManager.GetDirectory(GlueViewState.Self.CurrentGlueProjectFile);

            string[] lines    = GetMethodLines(element, ers, projectDirectory);
            string   fileName = EventResponseSave.GetSharedCodeFullFileName(element, projectDirectory);

            CodeContext codeContext = new CodeContext(elementRuntime);

            ApplyLinesInternal(lines, 0, lines.Length, element, codeContext, fileName);
        }
Beispiel #12
0
        public void Initialize()
        {
            OverallInitializer.Initialize();

            mEntitySave = new EntitySave();
            mEntitySave.ImplementsIWindow = true;
            mEntitySave.Name = "EventTestEntity";
            mEntitySave.ImplementsIWindow = true;
            ObjectFinder.Self.GlueProject.Entities.Add(mEntitySave);

            mScreenSave      = new ScreenSave();
            mScreenSave.Name = "EventTestScreen";
            ObjectFinder.Self.GlueProject.Screens.Add(mScreenSave);

            NamedObjectSave nos = new NamedObjectSave();

            nos.SourceType      = SourceType.Entity;
            nos.SourceClassType = "EventTestEntity";
            mScreenSave.NamedObjects.Add(nos);


            EventResponseSave ers = new EventResponseSave();

            ers.SourceObject      = "EventTestEntity";
            ers.SourceObjectEvent = "Click";
            ers.EventName         = "EventTestEntityClick";
            mScreenSave.Events.Add(ers);

            EventResponseSave pushErs = new EventResponseSave();

            pushErs.SourceObject      = "EventTestEntity";
            pushErs.SourceObjectEvent = "Push";
            pushErs.EventName         = "EventTestEntityPush";
            mScreenSave.Events.Add(pushErs);

            // Create a POList so we can expose its event(s)
            mListNos                        = new NamedObjectSave();
            mListNos.SourceType             = SourceType.FlatRedBallType;
            mListNos.SourceClassType        = "PositionedObjectList<T>";
            mListNos.SourceClassGenericType = "Sprite";
            mScreenSave.NamedObjects.Add(mListNos);

            mDerivedEntitySave            = new EntitySave();
            mDerivedEntitySave.Name       = "EventTestsDerivedEntity";
            mDerivedEntitySave.BaseEntity = mEntitySave.Name;
            ObjectFinder.Self.GlueProject.Entities.Add(mDerivedEntitySave);
        }
        private void SetEventValue(string categoryString, IEventContainer eventContainer, string value)
        {
            switch (categoryString)
            {
            case "Active Events":

                EventResponseSave eventToModify = null;

                for (int i = eventContainer.Events.Count - 1; i > -1; i--)
                {
                    if (eventContainer.Events[i].EventName == this.Name)
                    {
                        eventToModify = eventContainer.Events[i];
                        break;
                    }
                }

                if (eventToModify == null)
                {
                    throw new Exception("Could not find an event by the name of " + Name);
                }
                else
                {
                    string valueAsString = value;

                    if (string.IsNullOrEmpty(valueAsString) || valueAsString == "<NONE>")
                    {
                        eventContainer.Events.Remove(eventToModify);
                    }
                    else
                    {
                        //eventToModify.InstanceMethod = valueAsString;
                    }
                }
                //EventSave eventSave = EditorLogic.Current
                break;

            case "Unused Events":

                //EventSave eventSave = EventManager.AllEvents[Name];

                //eventSave.InstanceMethod = value;

                //EditorLogic.CurrentEventContainer.Events.Add(eventSave);
                break;
            }
        }
Beispiel #14
0
        void HandleResolutionChange(ElementRuntime elementRuntime)
        {
            if (elementRuntime != null)
            {
                IElement element = elementRuntime.AssociatedIElement;

                if (element != null)
                {
                    EventResponseSave ers = element.GetEvent("ResolutionOrOrientationChanged");

                    if (ers != null)
                    {
                        ApplyEventResponseSave(elementRuntime, ers);
                    }
                }
            }
        }
        private void UpdateIncludedAndExcluded(EventResponseSave instance)
        {
            ////////////////////Early Out/////////////////////////
            if (instance == null)
            {
                return;
            }
            ///////////////////End Early Out///////////////////////
            ResetToDefault();

            ExcludeMember("ToStringDelegate");
            ExcludeMember("Contents");

            AvailableCustomVariables typeConverter = new AvailableCustomVariables(CurrentElement);

            typeConverter.IncludeNone = false;

            typeConverter.InclusionPredicate = DoesCustomVariableCreateEvent;
            IncludeMember(typeof(EventResponseSave).GetProperty("SourceVariable").Name,
                          typeof(EventResponseSave), typeConverter);


            if (string.IsNullOrEmpty(instance.SourceVariable))
            {
                ExcludeMember(typeof(EventResponseSave).GetProperty("BeforeOrAfter").Name);
            }



            AvailableNamedObjectsAndFiles availableNamedObjects = new AvailableNamedObjectsAndFiles(
                CurrentElement);

            availableNamedObjects.IncludeReferencedFiles = false;
            IncludeMember(typeof(EventResponseSave).GetProperty("SourceObject").Name,
                          typeof(EventResponseSave),
                          availableNamedObjects);

            AvailableEvents availableEvents = new AvailableEvents();

            availableEvents.Element         = CurrentElement;
            availableEvents.NamedObjectSave = CurrentElement.GetNamedObjectRecursively(instance.SourceObject);
            IncludeMember(typeof(EventResponseSave).GetProperty("SourceObjectEvent").Name,
                          typeof(EventResponseSave),
                          availableEvents);
        }
Beispiel #16
0
        private string[] GetMethodLines(IElement element, EventResponseSave ers, string projectDirectory)
        {
            string[] toReturn = null;
            lock (mCachedMethodLines)
            {
                if (!mCachedMethodLines.ContainsKey(ers.EventName))
                {
                    ParsedMethod parsedMethod =
                        ers.GetParsedMethodFromAssociatedFile(element, projectDirectory);
                    string[] lines = parsedMethod.MethodContents.Split(separators, StringSplitOptions.RemoveEmptyEntries);

                    mCachedMethodLines.Add(ers.EventName, lines);
                }

                toReturn = mCachedMethodLines[ers.EventName];
            }
            return(toReturn);
        }
Beispiel #17
0
        public void TestRenamingEvents()
        {
            EventResponseSave ers = new EventResponseSave();

            ers.EventName    = "Whatever";
            ers.DelegateType = "System.EventHandler";
            mEntitySave.Events.Add(ers);
            string fileName = ers.GetSharedCodeFullFileName();

            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }

            string directory = FileManager.CurrentDirectory + fileName;

            string contents = "int m = 33;";


            string contentsFileName = EventCodeGenerator.InjectTextForEventAndSaveCustomFile(
                mEntitySave, ers, contents);

            string entireFileContents = FileManager.FromFileText(contentsFileName);

            // Make sure that this file contains the contents
            if (!entireFileContents.Contains(contents))
            {
                throw new Exception("The entire files aren't being added to the event");
            }

            // Test renaming now
            string oldName = ers.EventName;

            string newName = "AfterRename";

            ers.EventName = newName;

            // I can't write unit tests for this yet because it requires that
            // all generate code be moved out of BaseElementTreeNode into CodeWriter:
            //EventResponseSavePropertyChangeHandler.Self.ReactToChange("EventName", oldName, ers, mEntitySave);

            //entireFileContents = FileManager.FromFileText(contentsFileName);
        }
Beispiel #18
0
        public TreeNode EventResponseTreeNode(EventResponseSave eventResponse)
        {
            TreeNode foundNode = null;

            foreach (ScreenTreeNode treeNode in ElementViewWindow.ScreensTreeNode.Nodes)
            {
                foundNode = treeNode.GetTreeNodeFor(eventResponse);
                if (foundNode != null)
                {
                    return(foundNode);
                }
            }

            TreeNodeCollection nodeCollection = ElementViewWindow.EntitiesTreeNode.Nodes;

            foundNode = FindEventResponseSaveInEntities(eventResponse, nodeCollection);

            return(foundNode);
        }
Beispiel #19
0
        public static ICodeBlock FillWithGeneratedEventCode(ICodeBlock currentBlock, EventResponseSave ers, IElement element)
        {
            EventSave eventSave = ers.GetEventSave();

            string args = ers.GetArgsForMethod(element);

            if (!string.IsNullOrEmpty(ers.SourceObject) && !string.IsNullOrEmpty(ers.SourceObjectEvent))
            {
                currentBlock = currentBlock
                               .Function("void", "On" + ers.EventName + "Tunnel", args);

                string reducedArgs = StripTypesFromArguments(args);

                currentBlock.If("this." + ers.EventName + " != null")
                .Line(ers.EventName + "(" + reducedArgs + ");")
                .End();

                currentBlock = currentBlock.End();
            }
            return(currentBlock);
        }
        internal void ReactToScreenChangedValue(string changedMember, object oldValue)
        {
            ScreenSave screenSave = EditorLogic.CurrentScreenSave;

            #region Name

            if (changedMember == "ClassName")
            {
                ReactToChangedClassName(oldValue, screenSave);
            }

            #endregion

            #region BaseScreen

            else if (changedMember == "BaseScreen")
            {
                if (ProjectManager.VerifyInheritanceGraph(screenSave) == ProjectManager.CheckResult.Failed)
                {
                    screenSave.BaseScreen = (string)oldValue;
                }
                else
                {
                    screenSave.UpdateFromBaseType();
                }
            }

            #endregion


            EventResponseSave eventSave = screenSave.GetEvent(changedMember);

            if (eventSave != null)
            {
                //if (!string.IsNullOrEmpty(eventSave.InstanceMethod) && EditorLogic.CurrentElement != null)
                //{
                //    InsertMethodCallInElementIfNecessary(EditorLogic.CurrentScreenSave, eventSave.InstanceMethod);
                //}
            }
        }
Beispiel #21
0
        public static ICodeBlock FillWithCustomEventCode(ICodeBlock currentBlock, EventResponseSave ers, string contents, IElement element)
        {
            string args = ers.GetArgsForMethod(element);

            // We used to not
            // generate the empty
            // shell of an event if
            // the contents were empty.
            // However now we want to for
            // two reasons:
            // 1:  A user may want to add an
            // event in Glue, but then mdoify
            // the event in Visual Studio.  The
            // user shouldn't be forced into adding
            // some content in Glue first to wdit the
            // event in Visual Studio.
            // 2:  A designer may decide to remove the
            // contents of a method.  If this happens then
            // code that the designer doesn't work with shouldn't
            // break (IE, if the code calls the OnXXXX method).
            //if (!string.IsNullOrEmpty(contents))
            {
                // Need to modify the event CSV to include the arguments for this event

                currentBlock = currentBlock
                               .Function("void", "On" + ers.EventName, args);

                currentBlock.TabCharacter = "";

                int tabCount = currentBlock.TabCount;
                currentBlock.TabCount = 0;

                currentBlock
                .Line(contents);

                currentBlock = currentBlock.End();
            }
            return(currentBlock);
        }
        private void UpdateEventsTreeNode()
        {
            while (this.mEventsTreeNode.Nodes.Count < mSaveObject.Events.Count)
            {
                int indexAddingAt = mEventsTreeNode.Nodes.Count;

                TreeNode newNode = mEventsTreeNode.Nodes.Add(mSaveObject.Events[indexAddingAt].EventName);
                newNode.ImageKey         = "edit_code.png";
                newNode.SelectedImageKey = "edit_code.png";
            }

            while (this.mEventsTreeNode.Nodes.Count > mSaveObject.Events.Count)
            {
                mEventsTreeNode.Nodes.RemoveAt(mEventsTreeNode.Nodes.Count - 1);
            }

            for (int i = 0; i < mSaveObject.Events.Count; i++)
            {
                TreeNode treeNode = mEventsTreeNode.Nodes[i];

                EventResponseSave eventSave = mSaveObject.Events[i];

                if (treeNode.Tag != eventSave)
                {
                    treeNode.Tag = eventSave;
                }


                string textToSet = eventSave.EventName;

                if (treeNode.Text != textToSet)
                {
                    treeNode.Text = textToSet;
                }
            }
        }
        public void UpdateDisplayToCurrentObject()
        {
            string fullFileName = "<Unable to get file name>";

            try
            {
                EventResponseSave eventResponseSave = EditorLogic.CurrentEventResponseSave;
                IElement          element           = EditorLogic.CurrentElement;

                fullFileName = eventResponseSave.GetSharedCodeFullFileName();

                string contents = FileManager.FromFileText(fullFileName);

                CSharpParser parser     = new CSharpParser();
                SyntaxTree   syntaxTree = parser.Parse(contents);
                mIsCodeValid = syntaxTree.Errors.Count == 0;

                if (mIsCodeValid)
                {
                    ParsedMethod parsedMethod = eventResponseSave.GetParsedMethodFromAssociatedFile();

                    string textToAssign = null;
                    if (parsedMethod == null)
                    {
                        textToAssign = eventResponseSave.GetEventContents();
                    }
                    else
                    {
                        StringBuilderDocument document = new StringBuilderDocument(contents);

                        bool wasFound;

                        textToAssign = GetMethodContentsFor(syntaxTree, document, eventResponseSave.EventName, out wasFound);
                        if (wasFound)
                        {
                            textToAssign = textToAssign.Replace("\n", "\r\n");
                        }
                        else
                        {
                            mIsCodeValid = false;
                            textToAssign = "Could not find the method, or encountered a parse error.";
                        }
                    }

                    textToAssign = RemoveWhiteSpaceForCodeWindow(textToAssign);
                    this.syntaxBoxControl1.Document.Text = textToAssign;
                    mLastSavedText = this.syntaxBoxControl1.Document.Text;
                }
                else
                {
                    this.syntaxBoxControl1.Document.Text = "This code file is not a complete code file:\n" +
                                                           fullFileName +
                                                           "\nGlue is unable to parse it.  Please correct the problems in Visual Studio";
                }
            }
            catch (Exception e)
            {
                mIsCodeValid = false;
                this.syntaxBoxControl1.Document.Text = "Error parsing file:\n" +
                                                       fullFileName +
                                                       "\nMore details:\n\n" + e.ToString();
            }
        }
Beispiel #24
0
        /// <summary>
        /// Injects the insideOfMethod into an event for the argument
        /// </summary>
        /// <param name="currentElement">The IElement containing the EventResponseSave.</param>
        /// <param name="eventResponseSave">The EventResponseSave which should have its contents set or replaced.</param>
        /// <param name="insideOfMethod">The inside of the methods to assign.</param>
        /// <returns>The full file name which contains the method contents.</returns>
        public static string InjectTextForEventAndSaveCustomFile(IElement currentElement, EventResponseSave eventResponseSave, string insideOfMethod)
        {
            // In case the user passes null we don't want to have null reference exceptions:
            if (insideOfMethod == null)
            {
                insideOfMethod = "";
            }

            ParsedMethod parsedMethod =
                eventResponseSave.GetParsedMethodFromAssociatedFile();


            string fullFileName = eventResponseSave.GetSharedCodeFullFileName();

            bool forceRegenerate = false;

            string fileContents = null;

            if (File.Exists(fullFileName))
            {
                fileContents    = FileManager.FromFileText(fullFileName);
                forceRegenerate = fileContents.Contains("public partial class") == false && fileContents.Contains("{") == false;

                if (forceRegenerate)
                {
                    GlueGui.ShowMessageBox("Forcing a regneration of " + fullFileName + " because it appears to be empty.");
                }
            }

            CreateEmptyCodeIfNecessary(currentElement, fullFileName, forceRegenerate);

            fileContents = FileManager.FromFileText(fullFileName);

            int indexToAddAt = 0;

            if (parsedMethod != null)
            {
                int startIndex;
                int endIndex;
                GetStartAndEndIndexForMethod(parsedMethod, fileContents, out startIndex, out endIndex);
                // We want to include the \r\n at the end, so add 2
                endIndex += 2;
                string whatToRemove = fileContents.Substring(startIndex, endIndex - startIndex);

                fileContents = fileContents.Replace(whatToRemove, null);

                indexToAddAt = startIndex;
                // remove the method to re-add it
            }
            else
            {
                indexToAddAt = EventManager.GetLastLocationInClass(fileContents, startOfLine: true);
            }
            ICodeBlock codeBlock = new CodeDocument(2);

            codeBlock.TabCharacter = "    ";

            insideOfMethod = "" + insideOfMethod.Replace("\r\n", "\r\n            ");
            codeBlock      = EventCodeGenerator.FillWithCustomEventCode(codeBlock, eventResponseSave, insideOfMethod, currentElement);

            string methodContents = codeBlock.ToString();


            fileContents = fileContents.Insert(indexToAddAt, codeBlock.ToString());

            eventResponseSave.Contents = null;
            try
            {
                FlatRedBall.Glue.IO.FileWatchManager.IgnoreNextChangeOnFile(fullFileName);
                FileManager.SaveText(fileContents, fullFileName);
            }
            catch (Exception e)
            {
                PluginManager.ReceiveError("Could not save file to " + fullFileName);
            }
            return(fullFileName);
        }
Beispiel #25
0
        private static void ReactToEventRename(object oldValue, EventResponseSave ers, IElement container)
        {
            string oldName = oldValue as string;
            string newName = ers.EventName;
            // The code
            // inside this
            // event handler
            // are saved in the
            // Element.Event.cs file
            // so that it can be edited
            // in Visual Studio.  If the
            // EventResponseSave changes then
            // it will use a new method.  We need
            // to take out the old method and move
            // the contents to the new method.

            // We'll "cheat" by setting the name to the old
            // one and getting the contents, then switching it
            // back to the new:
            string fullFileName = ers.GetSharedCodeFullFileName();

            if (!System.IO.File.Exists(fullFileName))
            {
                PluginManager.ReceiveError("Could not find the file " + fullFileName);
            }
            else if (CodeEditorControl.DetermineIfCodeFileIsValid(fullFileName) == false)
            {
                PluginManager.ReceiveError("Invalid code file " + fullFileName);
            }
            else
            {
                ers.EventName = oldName;
                string contents =
                    CodeEditorControl.RemoveWhiteSpaceForCodeWindow(ers.GetEventContents());

                ers.EventName = newName;
                // Now save the contents into the new method:

                if (string.IsNullOrEmpty(contents) || CodeEditorControl.HasMatchingBrackets(contents))
                {
                    EventCodeGenerator.InjectTextForEventAndSaveCustomFile(
                        container, ers, contents);
                    PluginManager.ReceiveOutput("Saved " + ers);
                    GlueCommands.Self.GenerateCodeCommands.GenerateCurrentElementCode();

                    DialogResult result = MessageBox.Show("Would you like to delete the old method On" + oldName + "?", "Delete old function?", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        int startIndex;
                        int endIndex;

                        contents = FileManager.FromFileText(fullFileName);

                        EventCodeGenerator.GetStartAndEndIndexForMethod(contents,
                                                                        "On" + oldName, out startIndex, out endIndex);

                        contents = contents.Remove(startIndex, endIndex - startIndex);

                        FileManager.SaveText(contents, fullFileName);
                    }
                }
                else
                {
                    PluginManager.ReceiveError("Mismatch of } and { in event " + ers);
                }
            }
        }
Beispiel #26
0
        public static void RemoveNamedObject(NamedObjectSave namedObjectToRemove, bool performSave, bool updateUi, List <string> additionalFilesToRemove)
        {
            StringBuilder removalInformation = new StringBuilder();

            // The additionalFilesToRemove is included for consistency with other methods.  It may be used later

            // There are the following things that need to happen:
            // 1.  Remove the NamedObject from the Glue project (GLUX)
            // 2.  Remove any variables that use this NamedObject as their source
            // 3.  Remove the named object from the GUI
            // 4.  Update the variables for any NamedObjects that use this element containing this NamedObject
            // 5.  Find any Elements that contain NamedObjects that are DefinedByBase - if so, see if we should remove those or make them not DefinedByBase
            // 6.  Remove any events that tunnel into this.

            IElement element = namedObjectToRemove.GetContainer();

            if (element != null)
            {
                if (!namedObjectToRemove.RemoveSelfFromNamedObjectList(element.NamedObjects))
                {
                    throw new ArgumentException();
                }

                #region Remove all CustomVariables that reference the removed NamedObject
                for (int i = element.CustomVariables.Count - 1; i > -1; i--)
                {
                    CustomVariable variable = element.CustomVariables[i];

                    if (variable.SourceObject == namedObjectToRemove.InstanceName)
                    {
                        removalInformation.AppendLine("Removed variable " + variable.ToString());

                        element.CustomVariables.RemoveAt(i);
                    }
                }
                #endregion

                // Remove any events that use this
                for (int i = element.Events.Count - 1; i > -1; i--)
                {
                    EventResponseSave ers = element.Events[i];
                    if (ers.SourceObject == namedObjectToRemove.InstanceName)
                    {
                        removalInformation.AppendLine("Removed event " + ers.ToString());
                        element.Events.RemoveAt(i);
                    }
                }

                // Remove any objects that use this as a layer
                for (int i = 0; i < element.NamedObjects.Count; i++)
                {
                    if (element.NamedObjects[i].LayerOn == namedObjectToRemove.InstanceName)
                    {
                        removalInformation.AppendLine("Removed the following object from the deleted Layer: " + element.NamedObjects[i].ToString());
                        element.NamedObjects[i].LayerOn = null;
                    }
                }



                element.RefreshStatesToCustomVariables();

                #region Ask the user what to do with all NamedObjects that are DefinedByBase

                List <IElement> derivedElements = new List <IElement>();
                if (element is EntitySave)
                {
                    derivedElements.AddRange(ObjectFinder.Self.GetAllEntitiesThatInheritFrom(element as EntitySave));
                }
                else
                {
                    derivedElements.AddRange(ObjectFinder.Self.GetAllScreensThatInheritFrom(element as ScreenSave));
                }

                foreach (IElement derivedElement in derivedElements)
                {
                    // At this point, namedObjectToRemove is already removed from the current Element, so this will only
                    // return NamedObjects that exist in the derived.
                    NamedObjectSave derivedNamedObject = derivedElement.GetNamedObjectRecursively(namedObjectToRemove.InstanceName);

                    if (derivedNamedObject != null && derivedNamedObject != namedObjectToRemove && derivedNamedObject.DefinedByBase)
                    {
                        MultiButtonMessageBox mbmb = new MultiButtonMessageBox();
                        mbmb.MessageText = "What would you like to do with the object " + derivedNamedObject.ToString();
                        mbmb.AddButton("Keep it", DialogResult.OK);
                        mbmb.AddButton("Delete it", DialogResult.Cancel);

                        DialogResult result = mbmb.ShowDialog(MainGlueWindow.Self);

                        if (result == DialogResult.OK)
                        {
                            // Keep it
                            derivedNamedObject.DefinedByBase = false;
                            BaseElementTreeNode treeNode = GlueState.Self.Find.ElementTreeNode(derivedElement);

                            if (updateUi)
                            {
                                treeNode.UpdateReferencedTreeNodes();
                            }
                            CodeWriter.GenerateCode(derivedElement);
                        }
                        else
                        {
                            // Delete it
                            RemoveNamedObject(derivedNamedObject, performSave, updateUi, additionalFilesToRemove);
                        }
                    }
                }
                #endregion


                var elementTreeNode = GlueState.Self.Find.ElementTreeNode(element);

                if (updateUi)
                {
                    elementTreeNode.UpdateReferencedTreeNodes();
                }
                CodeWriter.GenerateCode(element);
                if (element is EntitySave)
                {
                    List <NamedObjectSave> entityNamedObjects = ObjectFinder.Self.GetAllNamedObjectsThatUseEntity(element.Name);

                    foreach (NamedObjectSave nos in entityNamedObjects)
                    {
                        nos.UpdateCustomProperties();
                    }
                }
            }

            if (performSave)
            {
                GluxCommands.Self.SaveGlux();
            }
        }
        public override object GetValue(object component)
        {
            if (Owner != null)
            {
                if (Owner is FileAssociationSettings)
                {
                    return(((FileAssociationSettings)Owner).GetApplicationForExtension(this.Name));
                }
                else
                {
                    return(null);
                }
            }


            #region StateSave

            if (EditorLogic.CurrentStateSave != null)
            {
                return(EditorLogic.CurrentStateSave.GetValue(this.Name));
            }

            #endregion

            #region NamedObjectSave

            else if (EditorLogic.CurrentNamedObject != null)
            {
                NamedObjectSave asNamedObject = EditorLogic.CurrentNamedObject;

                if (this.Attributes.Count > 0 && this.Attributes[0] is CategoryAttribute)
                {
                    string category = ((CategoryAttribute)this.Attributes[0]).Category;

                    switch (category)
                    {
                    case "Active Events":

                        EventSave eventSave = asNamedObject.GetEvent(Name);
                        if (eventSave != null)
                        {
                            return(eventSave.InstanceMethod);
                        }
                        else
                        {
                            return("");
                        }

                    //break;
                    case "Unused Events":
                        return("");

                    //break;
                    case "Custom Variable Set Events":
                        return(EditorLogic.CurrentNamedObject.GetCustomVariable(this.Name.Replace(" Set", "")).EventOnSet);

                    //break;
                    default:
                        return(EditorLogic.CurrentNamedObject.GetPropertyValue(this.Name));
                    }
                }
                else
                {
                    return(EditorLogic.CurrentNamedObject.GetPropertyValue(this.Name));
                }
            }
            #endregion



            #region CustomVariable

            else if (EditorLogic.CurrentCustomVariable != null)
            {
                if (EditorLogic.CurrentEntitySave != null)
                {
                    return(EditorLogic.CurrentEntitySave.GetPropertyValue(EditorLogic.CurrentCustomVariable.Name));
                }
                else
                {
                    return(EditorLogic.CurrentScreenSave.GetPropertyValue(EditorLogic.CurrentCustomVariable.Name));
                }
            }

            #endregion

            #region ScreenSave

            else if (EditorLogic.CurrentScreenSave != null)
            {
                if (this.Attributes.Count > 0 && this.Attributes[0] is CategoryAttribute)
                {
                    string category = ((CategoryAttribute)this.Attributes[0]).Category;

                    switch (category)
                    {
                    case "Active Events":
                        EventResponseSave eventSave = EditorLogic.CurrentScreenSave.GetEvent(Name);
                        //if (eventSave != null)
                        //{
                        //    return eventSave.InstanceMethod;
                        //}
                        //else
                        {
                            return("");
                        }

                    case "Unused Events":
                        return("");

                    default:
                        return("");
                    }
                }
                return("");
            }

            #endregion

            #region EntitySave

            else if (EditorLogic.CurrentEntitySave != null)
            {
                return(EditorLogic.CurrentEntitySave.GetPropertyValue(this.Name));
            }

            #endregion

            else
            {
                return(null);
            }
        }
Beispiel #28
0
 private void HandleGetEventSignatureArgs(NamedObjectSave namedObject, EventResponseSave eventResponseSave, out string type, out string args)
 {
     EventCodeGenerator.Self.HandleGetEventSignatureArgs(namedObject, eventResponseSave, out type, out args);
 }
Beispiel #29
0
        private static void GenerateInitializeForEvent(ICodeBlock codeBlock, IElement element, EventResponseSave ers)
        {
            bool wasEventAdded = false;

            //We always want this to happen, even if it's
            // emtpy
            //if (!string.IsNullOrEmpty(ers.Contents))
            //{
            NamedObjectSave sourceNos = null;
            bool            shouldCloseIfStatementForNos = false;

            if (!string.IsNullOrEmpty(ers.SourceVariable))
            {
                // This is tied to a variable, so the name comes from the variable event rather than the
                // event name itself
                string eventName = ers.BeforeOrAfter.ToString() + ers.SourceVariable + "Set";
                codeBlock.Line("this." + eventName + " += On" + ers.EventName + ";");
                wasEventAdded = true;
            }

            else if (string.IsNullOrEmpty(ers.SourceObject) || ers.SourceObject == "<NONE>")
            {
                string    leftSide  = null;
                EventSave eventSave = ers.GetEventSave();
                if (eventSave == null || string.IsNullOrEmpty(eventSave.ExternalEvent))
                {
                    leftSide = "this." + ers.EventName;
                }
                else
                {
                    leftSide = eventSave.ExternalEvent;
                }



                codeBlock.Line(leftSide + " += On" + ers.EventName + ";");
                wasEventAdded = true;
            }
            else if (!string.IsNullOrEmpty(ers.SourceObjectEvent))
            {
                // Only append this if the source NOS is fully-defined.  If not, we don't want to generate compile errors.
                sourceNos = element.GetNamedObject(ers.SourceObject);

                if (sourceNos != null && sourceNos.IsFullyDefined)
                {
                    NamedObjectSaveCodeGenerator.AddIfConditionalSymbolIfNecesssary(codeBlock, sourceNos);

                    string leftSide = null;

                    leftSide = ers.SourceObject + "." + ers.SourceObjectEvent;

                    codeBlock.Line(leftSide + " += On" + ers.EventName + ";");
                    wasEventAdded = true;
                    shouldCloseIfStatementForNos = true;
                }
            }

            if (!string.IsNullOrEmpty(ers.SourceObject) && !string.IsNullOrEmpty(ers.SourceObjectEvent) && wasEventAdded)
            {
                codeBlock.Line(ers.SourceObject + "." + ers.SourceObjectEvent + " += On" + ers.EventName + "Tunnel;");
                if (shouldCloseIfStatementForNos)
                {
                    NamedObjectSaveCodeGenerator.AddEndIfIfNecessary(codeBlock, sourceNos);
                }
            }
        }
        public static void ElementDoubleClicked()
        {
            TreeNode selectedNode = SelectedNode;

            if (selectedNode != null)
            {
                string text = selectedNode.Text;



                #region Double-clicked a file
                string extension       = FileManager.GetExtension(text);
                string sourceExtension = null;

                if (EditorLogic.CurrentReferencedFile != null && !string.IsNullOrEmpty(EditorLogic.CurrentReferencedFile.SourceFile))
                {
                    sourceExtension = FileManager.GetExtension(EditorLogic.CurrentReferencedFile.SourceFile);
                }
                if (EditorLogic.CurrentReferencedFile != null && !string.IsNullOrEmpty(extension))
                {
                    string application = "";

                    ReferencedFileSave currentReferencedFileSave = EditorLogic.CurrentReferencedFile;
                    string             fileName;

                    if (currentReferencedFileSave != null && currentReferencedFileSave.OpensWith != "<DEFAULT>")
                    {
                        application = currentReferencedFileSave.OpensWith;
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(sourceExtension))
                        {
                            application = EditorData.FileAssociationSettings.GetApplicationForExtension(sourceExtension);
                        }
                        else
                        {
                            application = EditorData.FileAssociationSettings.GetApplicationForExtension(extension);
                        }
                    }

                    if (currentReferencedFileSave != null)
                    {
                        if (!string.IsNullOrEmpty(currentReferencedFileSave.SourceFile))
                        {
                            fileName = "\"" + ProjectManager.MakeAbsolute(ProjectManager.ContentDirectoryRelative + currentReferencedFileSave.SourceFile, true) + "\"";
                        }
                        else
                        {
                            fileName = "\"" + ProjectManager.MakeAbsolute(ProjectManager.ContentDirectoryRelative + currentReferencedFileSave.Name) + "\"";
                        }
                    }
                    else
                    {
                        fileName = "\"" + ProjectManager.MakeAbsolute(text) + "\"";
                    }

                    if (string.IsNullOrEmpty(application) || application == "<DEFAULT>")
                    {
                        try
                        {
                            ProcessManager.OpenProcess(fileName, null);
                        }
                        catch (Exception ex)
                        {
                            System.Windows.Forms.MessageBox.Show("Error opening " + fileName + "\nTry navigating to this file and opening it through explorer");
                        }
                    }
                    else
                    {
                        bool applicationFound = true;
                        try
                        {
                            application = FileManager.Standardize(application);
                        }
                        catch
                        {
                            applicationFound = false;
                        }

                        if (!System.IO.File.Exists(application) || applicationFound == false)
                        {
                            string error = "Could not find the application\n\n" + application;

                            System.Windows.Forms.MessageBox.Show(error);
                        }
                        else
                        {
                            ProcessManager.OpenProcess(application, fileName);
                        }
                    }
                }

                #endregion

                #region Double-clicked a named object

                else if (selectedNode.IsNamedObjectNode())
                {
                    NamedObjectSave nos = selectedNode.Tag as NamedObjectSave;

                    if (nos.SourceType == SourceType.Entity)
                    {
                        TreeNode entityNode = GlueState.Self.Find.EntityTreeNode(nos.SourceClassType);

                        SelectedNode = entityNode;
                    }
                    else if (nos.SourceType == SourceType.FlatRedBallType && nos.IsGenericType)
                    {
                        // Is this an entity?
                        EntitySave genericEntityType = ObjectFinder.Self.GetEntitySave(nos.SourceClassGenericType);

                        if (genericEntityType != null)
                        {
                            SelectedNode = GlueState.Self.Find.EntityTreeNode(genericEntityType);
                        }
                    }
                    else if (nos.SourceType == SourceType.File && !string.IsNullOrEmpty(nos.SourceFile))
                    {
                        ReferencedFileSave rfs      = nos.GetContainer().GetReferencedFileSave(nos.SourceFile);
                        TreeNode           treeNode = GlueState.Self.Find.ReferencedFileSaveTreeNode(rfs);

                        SelectedNode = treeNode;
                    }
                }

                #endregion

                #region Double-clicked a CustomVariable
                else if (selectedNode.IsCustomVariable())
                {
                    CustomVariable customVariable = EditorLogic.CurrentCustomVariable;

                    if (!string.IsNullOrEmpty(customVariable.SourceObject))
                    {
                        NamedObjectSave namedObjectSave = EditorLogic.CurrentElement.GetNamedObjectRecursively(customVariable.SourceObject);

                        if (namedObjectSave != null)
                        {
                            SelectedNode = GlueState.Self.Find.NamedObjectTreeNode(namedObjectSave);
                        }
                    }
                }

                #endregion

                #region Double-click an Event

                else if (selectedNode.IsEventResponseTreeNode())
                {
                    EventResponseSave ers = EditorLogic.CurrentEventResponseSave;

                    if (!string.IsNullOrEmpty(ers.SourceObject))
                    {
                        NamedObjectSave namedObjectSave = EditorLogic.CurrentElement.GetNamedObjectRecursively(ers.SourceObject);

                        if (namedObjectSave != null)
                        {
                            SelectedNode = GlueState.Self.Find.NamedObjectTreeNode(namedObjectSave);
                        }
                    }
                }


                #endregion

                #region Double-click an Enity/Screen

                else if (selectedNode.IsElementNode())
                {
                    IElement element = selectedNode.Tag as IElement;

                    string baseObject = element.BaseElement;

                    if (!string.IsNullOrEmpty(baseObject))
                    {
                        IElement baseElement = ObjectFinder.Self.GetIElement(baseObject);

                        SelectedNode = GlueState.Self.Find.ElementTreeNode(baseElement);
                    }
                }

                #endregion

                #region Code

                else if (selectedNode.IsCodeNode())
                {
                    var fileName = selectedNode.Text;

                    var absolute = GlueState.Self.CurrentGlueProjectDirectory + fileName;

                    if (System.IO.File.Exists(absolute))
                    {
                        System.Diagnostics.Process.Start(absolute);
                    }
                }

                #endregion
            }
        }