private void RefreshEventsForElement(ElementSave selectedElement) { EventsViewModel viewModel = new EventsViewModel(); viewModel.InstanceSave = null; viewModel.ElementSave = selectedElement; mEventsDataGrid.Instance = viewModel; mEventsDataGrid.MembersToIgnore.Add("InstanceSave"); mEventsDataGrid.MembersToIgnore.Add("ElementSave"); mEventsDataGrid.Categories[0].Name = "Events on this"; MemberCategory exposed = new MemberCategory(); exposed.Name = "Exposed"; var exposedEvents = SelectedState.Self.SelectedElement.Events.Where(item => !string.IsNullOrEmpty(item.ExposedAsName)); foreach (var eventSave in exposedEvents) { EventInstanceMember instanceMember = new EventInstanceMember( SelectedState.Self.SelectedElement, SelectedState.Self.SelectedInstance, eventSave); var local = eventSave; instanceMember.ContextMenuEvents.Add( "Rename", delegate { TextInputWindow tiw = new TextInputWindow(); tiw.Message = "Enter new name"; tiw.Result = local.ExposedAsName; if (tiw.ShowDialog() == System.Windows.Forms.DialogResult.OK) { bool isValid = true; // todo: //string whyNotValid = null; //isValid = NameVerifier.Self.IsEventNameValid(tiw.Result, out whyNotValid); if (isValid) { string oldName = local.ExposedAsName; local.ExposedAsName = tiw.Result; RenameManager.Self.HandleRename(selectedElement, local, oldName); GumCommands.Self.FileCommands.TryAutoSaveCurrentElement(); GumCommands.Self.GuiCommands.RefreshPropertyGrid(); } } }); exposed.Members.Add(instanceMember); } mEventsDataGrid.Categories.Add(exposed); }
private static void AddRegisterCode(ICodeBlock codeBlock, Gum.DataTypes.ElementSave element) { string elementNameString = element.Name.Replace("\\", "\\\\"); var qualifiedName = GueDerivingClassCodeGenerator.Self.GetQualifiedRuntimeTypeFor(element); codeBlock.Line( "GumRuntime.ElementSaveExtensions.RegisterGueInstantiationType(\"" + elementNameString + "\", typeof(" + qualifiedName + "));"); var needsGeneric = element is StandardElementSave && element.Name == "Container"; if (needsGeneric) { codeBlock.Line( "GumRuntime.ElementSaveExtensions.RegisterGueInstantiationType(\"" + elementNameString + "<T>" + "\", typeof(" + qualifiedName + "<>" + "));"); } }
internal void HandleElementAdd(GumElement gumElement) { var glueProject = GluePluginState.Self.GlueProject; ///////////////////////Early Out/////////////////////// if (glueProject == null || GluePluginState.Self.InitializationState != InitializationState.Initialized) { return; } ////////////////////End Early Out///////////////////// var glueElement = GumToGlueConverter.Self.ConvertElement(gumElement); if (glueElement is GlueScreen) { glueProject.Screens.Add(glueElement as GlueScreen); } else if (glueElement is GlueEntity) { glueProject.Entities.Add(glueElement as GlueEntity); } // Create the code file before saving the glue project so that it's already there and Glue // doesn't complain about a missing file: CodeCreationLogic.Self.TrySaveCustomCodeFileFor(glueElement); FileManager.XmlSerialize(glueProject, GluePluginState.Self.GlueProjectFilePath.StandardizedCaseSensitive); }
public void TryAutoSaveElement(ElementSave elementSave) { if (ProjectManager.Self.GeneralSettingsFile.AutoSave && elementSave != null) { ProjectManager.Self.SaveElement(elementSave); } }
public bool IsInstanceNameValid(string instanceName, InstanceSave instanceSave, ElementSave elementSave, out string whyNotValid) { IsNameValidCommon(instanceName, out whyNotValid); if (string.IsNullOrEmpty(whyNotValid)) { IsNameAlreadyUsed(instanceName, instanceSave, elementSave, out whyNotValid); } return string.IsNullOrEmpty(whyNotValid); }
private static void AddRegisterCode(ICodeBlock codeBlock, Gum.DataTypes.ElementSave element) { string elementNameString = element.Name.Replace("\\", "\\\\"); codeBlock.Line( "GumRuntime.ElementSaveExtensions.RegisterGueInstantiationType(\"" + elementNameString + "\", typeof(" + GueDerivingClassCodeGenerator.GetQualifiedRuntimeTypeFor(element) + "));"); }
public StateSave AddState(ElementSave elementToAddTo, StateSaveCategory category, string name) { if (elementToAddTo == null) { throw new Exception("Could not add state named " + name + " because no element is selected"); } StateSave stateSave = new StateSave(); stateSave.Name = name; AddState(elementToAddTo, category, stateSave); return stateSave; }
public StateReferencingInstanceMember(InstanceSavePropertyDescriptor ispd, StateSave stateSave, string variableName, InstanceSave instanceSave, ElementSave elementSave) : base(variableName, stateSave) { mInstanceSave = instanceSave; mStateSave = stateSave; mVariableName = variableName; mPropertyDescriptor = ispd; mElementSave = elementSave; this.CustomGetEvent += GetEvent; this.CustomSetEvent += SetEvent; this.CustomGetTypeEvent += GetTypeEvent; this.SortValue = int.MaxValue; if (instanceSave != null) { this.Instance = instanceSave; } else { this.Instance = elementSave; } DisplayName = RootVariableName; TryAddExposeVariableMenuOptions(instanceSave); // This could be slow since we have to check it for every variable in an object. // Maybe we'll want to pass this in to the function? StandardElementSave standardElement = null; if (instanceSave != null) { standardElement = ObjectFinder.Self.GetRootStandardElementSave(instanceSave); } else { standardElement = ObjectFinder.Self.GetRootStandardElementSave(elementSave); } VariableSave standardVariable = null; if (standardElement != null) { standardVariable = standardElement.DefaultState.Variables.FirstOrDefault(item => item.Name == RootVariableName); } if (standardVariable != null) { this.SortValue = standardVariable.DesiredOrder; } }
public bool IsExposedVariableNameValid(string variableName, ElementSave elementSave, out string whyNotValid) { whyNotValid = null; IsNameValidCommon(variableName, out whyNotValid); if (string.IsNullOrEmpty(whyNotValid)) { IsNameAlreadyUsed(variableName, null, elementSave, out whyNotValid); } return string.IsNullOrEmpty(whyNotValid); }
private void GenerateInterpolateBetween(ElementSave elementSave, ICodeBlock currentBlock, string enumType, IEnumerable<StateSave> states) { // We used to only generate these if there was were any states in this category, but // since Gum generated code supports dynamic states, there could be states in a category // even if they're not defined in Gum. //if (states.Count() > 0) { currentBlock = currentBlock.Function("public void", "InterpolateBetween", enumType + " firstState, " + enumType + " secondState, float interpolationValue"); GenerateDebugCheckForInterpolationValueNaN(currentBlock); Dictionary<VariableSave, InterpolationCharacteristic> interpolationCharacteristics = new Dictionary<VariableSave, InterpolationCharacteristic>(); CreateStartingValueVariables(elementSave, states, currentBlock, interpolationCharacteristics); currentBlock = currentBlock.Switch("firstState"); currentBlock = SetInterpolateBetweenValuesForStates(elementSave, enumType, states, currentBlock, interpolationCharacteristics, FirstValue); currentBlock = currentBlock.End(); currentBlock = currentBlock.Switch("secondState"); currentBlock = SetInterpolateBetweenValuesForStates(elementSave, enumType, states, currentBlock, interpolationCharacteristics, SecondValue); currentBlock = currentBlock.End(); currentBlock = AssignValuesUsingStartingValues(elementSave, currentBlock, interpolationCharacteristics); currentBlock = currentBlock.If("interpolationValue < 1"); string fieldToAssign; if (enumType == "VariableState") { fieldToAssign = "mCurrentVariableState"; } else { fieldToAssign = "mCurrent" + enumType + "State"; } currentBlock.Line(fieldToAssign + " = firstState;"); currentBlock = currentBlock.End().Else(); currentBlock.Line(fieldToAssign + " = secondState;"); currentBlock = currentBlock.End(); } }
public InstanceSave AddInstance(ElementSave elementToAddTo, string name) { if (elementToAddTo == null) { throw new Exception("Could not add instance named " + name + " because no element is selected"); } InstanceSave instanceSave = new InstanceSave(); instanceSave.Name = name; instanceSave.ParentContainer = elementToAddTo; instanceSave.BaseType = StandardElementsManager.Self.DefaultType; elementToAddTo.Instances.Add(instanceSave); return instanceSave; }
private static ElementAnimationsSave GetAnimationsFor(ElementSave elementSave) { string gumFolder = FileManager.GetDirectory(AppState.Self.GumProjectSave.FullFileName); string fullAnimationName = null; fullAnimationName = gumFolder + elementSave.Subfolder + "/" + elementSave.Name + "Animations.ganx"; ElementAnimationsSave animations = null; if (!string.IsNullOrEmpty(fullAnimationName) && System.IO.File.Exists(fullAnimationName)) { animations = FileManager.XmlDeserialize<ElementAnimationsSave>(fullAnimationName); } return animations; }
private void AddStates(GlueElement glueElement, GumElement gumElement) { foreach (var glueState in glueElement.States) { var gumState = ToGumState(glueState, glueElement); gumElement.States.Add(gumState); } foreach (var glueStateCategory in glueElement.StateCategoryList) { var gumStateCategory = ToGumStateCategory(glueStateCategory, glueElement); gumElement.Categories.Add(gumStateCategory); } }
private void AdjustNewlyCreatedGumInstance(GumElement container, InstanceSave instance) { var state = container.DefaultState; if (instance.BaseType == "Circle") { // See if there is already radius, width, and height values var instancePrefix = instance.Name + "."; var defaultState = container.DefaultState; var width = defaultState.GetVariableSave($"{instancePrefix}Width"); var height = defaultState.GetVariableSave($"{instancePrefix}Height"); var radius = defaultState.GetVariableSave($"{instancePrefix}Radius"); if (width == null && height == null && radius == null) { // circles in Glue default to a radius of 16, so match that defaultState.Variables.Add(new VariableSave { Name = $"{instancePrefix}Width", Type = "float", Value = 32.0f, SetsValue = true }); defaultState.Variables.Add(new VariableSave { Name = $"{instancePrefix}Height", Type = "float", Value = 32.0f, SetsValue = true }); defaultState.Variables.Add(new VariableSave { Name = $"{instancePrefix}Radius", Type = "float", Value = 16.0f, SetsValue = true }); } GumCommands.Self.WireframeCommands.Refresh(); GumCommands.Self.FileCommands.TryAutoSaveCurrentElement(); GumCommands.Self.GuiCommands.RefreshPropertyGrid(force: true); } }
public void ReloadElement(ElementSave element) { string projectRootDirectory = FileManager.GetDirectory(this.FullFileName); var gumLoadResult = new GumLoadResult(); if (element is ScreenSave) { var matchingReference = ScreenReferences.FirstOrDefault(item => item.Name == element.Name); ScreenSave newScreen = matchingReference?.ToElementSave <ScreenSave>( projectRootDirectory, GumProjectSave.ScreenExtension, gumLoadResult); if (newScreen != null) { Screens.Remove(element as ScreenSave); Screens.Add(newScreen); } } else if (element is ComponentSave) { var matchingReference = ComponentReferences.FirstOrDefault(item => item.Name == element.Name); ComponentSave newComonent = matchingReference?.ToElementSave <ComponentSave>( projectRootDirectory, GumProjectSave.ComponentExtension, gumLoadResult); if (newComonent != null) { Components.Remove(element as ComponentSave); Components.Add(newComonent); } } else if (element is StandardElementSave) { var matchingReference = StandardElementReferences.FirstOrDefault(item => item.Name == element.Name); StandardElementSave newStandardElement = matchingReference?.ToElementSave <StandardElementSave>( projectRootDirectory, GumProjectSave.ComponentExtension, gumLoadResult); if (newStandardElement != null) { StandardElements.Remove(element as StandardElementSave); StandardElements.Add(newStandardElement); } } }
public static bool GetIsFileFromRoot(this VariableSave variable, InstanceSave instance) { if (string.IsNullOrEmpty(variable.SourceObject)) { ElementSave root = ObjectFinder.Self.GetRootStandardElementSave(instance); var variableInRoot = root.DefaultState.Variables.FirstOrDefault(item => item.Name == variable.GetRootName()); if (variableInRoot != null) { return(variableInRoot.IsFile); } } else { ElementSave elementForInstance = ObjectFinder.Self.GetElementSave(instance.BaseType); string rootName = variable.GetRootName(); VariableSave exposedVariable = elementForInstance.DefaultState.Variables.FirstOrDefault(item => item.ExposedAsName == rootName); if (exposedVariable != null) { InstanceSave subInstance = elementForInstance.Instances.FirstOrDefault(item => item.Name == exposedVariable.SourceObject); if (subInstance != null) { return(exposedVariable.GetIsFileFromRoot(subInstance)); } } else { // it's not exposed, so let's just get to the root of it: ElementSave root = ObjectFinder.Self.GetRootStandardElementSave(instance); var variableInRoot = root.DefaultState.Variables.FirstOrDefault(item => item.Name == variable.GetRootName()); if (variableInRoot != null) { return(variableInRoot.IsFile); } } } return(false); }
public static StateSave GetStateSaveRecursively(this ElementSave element, string stateName) { var foundState = element.AllStates.FirstOrDefault(item => item.Name == stateName); if (foundState != null) { return(foundState); } if (!string.IsNullOrEmpty(element.BaseType)) { var baseElement = ObjectFinder.Self.GetElementSave(element.BaseType); return(baseElement.GetStateSaveRecursively(stateName)); } return(null); }
/// <summary> /// Generates and saves the code for the passed Gum ElementSave, but does not add the resulting .cs file to the VisualStudio project. /// </summary> /// <param name="element">The element to generate.</param> /// <returns></returns> public bool GenerateCodeFor(Gum.DataTypes.ElementSave element, CodeGenerationSavingBehavior savingBehavior = CodeGenerationSavingBehavior.AlwaysSave) { if (element == null) { throw new ArgumentNullException(nameof(element)); } bool wasSaved = false; string directoryToSave = GumRuntimesFolder; string generatedCode = mGueDerivingClassCodeGenerator.GenerateCodeFor(element); bool shouldSave; string saveLocation = directoryToSave + element.Name + "Runtime.Generated.cs"; if (savingBehavior == CodeGenerationSavingBehavior.AlwaysSave) { shouldSave = true; } else // if(savingBehavior == CodeGenerationSavingBehavior.SaveIfGeneratedDiffers) { // We only want to save this file if what we've just generated is different than what is already on disk: if (!System.IO.File.Exists(saveLocation)) { shouldSave = true; } else { var existingText = File.ReadAllText(saveLocation); shouldSave = existingText != generatedCode; } } if (!string.IsNullOrEmpty(generatedCode) && shouldSave) { wasSaved = TrySaveMultipleTimes(saveLocation, generatedCode); } return(wasSaved); }
private static void FixStateVariableTypes(ElementSave elementSave, StateSave state, ref bool wasModified) { foreach (var variable in state.Variables.Where(item => item.Type == "string" && item.Name.Contains("State"))) { string name = variable.Name; var withoutState = name.Substring(0, name.Length - "State".Length); if (variable.Name == "State") { variable.Type = "State"; wasModified = true; } else if (elementSave.Categories.Any(item => item.Name == withoutState)) { variable.Type = withoutState; wasModified = true; } } }
public static GraphicalUiElement CreateGueForElement(ElementSave elementSave, bool fullInstantiation = false) { GraphicalUiElement toReturn = null; if (mElementToGueTypes.ContainsKey(elementSave.Name)) { var type = mElementToGueTypes[elementSave.Name]; var constructor = type.GetConstructor(new Type[] { typeof(bool), typeof(bool) }); bool callAssignReferences = fullInstantiation; toReturn = constructor.Invoke(new object[] { fullInstantiation, callAssignReferences }) as GraphicalUiElement; } else { toReturn = new GraphicalUiElement(); } toReturn.ElementSave = elementSave; return toReturn; }
private void GenerateStateInterpolateBetween(ElementSave elementSave, ICodeBlock currentBlock) { currentBlock.Line("#region State Interpolation"); string enumType = "VariableState"; IEnumerable<StateSave> states = elementSave.States; GenerateInterpolateBetween(elementSave, currentBlock, enumType, states); foreach (var category in elementSave.Categories) { enumType = category.Name; states = category.States; GenerateInterpolateBetween(elementSave, currentBlock, enumType, states); } currentBlock.Line("#endregion"); }
public static void SetStatesAndCategoriesRecursively(this GraphicalUiElement graphicalElement, ElementSave elementSave) { if(!string.IsNullOrEmpty(elementSave.BaseType)) { var baseElementSave = Gum.Managers.ObjectFinder.Self.GetElementSave(elementSave.BaseType); if(baseElementSave != null) { graphicalElement.SetStatesAndCategoriesRecursively(baseElementSave); } } // We need to set categories and states before calling SetGraphicalUiElement so that the states can be used foreach (var category in elementSave.Categories) { graphicalElement.AddCategory(category); } graphicalElement.AddStates(elementSave.States); }
public static StateSaveCategory GetStateSaveCategoryRecursively(this ElementSave element, string categoryName, out ElementSave categoryContainer) { var foundCategory = element.Categories.FirstOrDefault(item => item.Name == categoryName); if (foundCategory != null) { categoryContainer = element; return(foundCategory); } if (!string.IsNullOrEmpty(element.BaseType)) { var baseElement = ObjectFinder.Self.GetElementSave(element.BaseType); return(baseElement.GetStateSaveCategoryRecursively(categoryName, out categoryContainer)); } categoryContainer = null; return(null); }
public void HandleInstanceAdd(GumElement container, InstanceSave instance) { var glueProject = GluePluginState.Self.GlueProject; ///////////////////////Early Out/////////////////////// if (glueProject == null || GluePluginState.Self.InitializationState != InitializationState.Initialized) { return; } ////////////////////End Early Out///////////////////// var newNamedObjectSave = GumToGlueConverter.Self.ConvertInstance(instance); if (container is GumScreen) { var glueScreen = glueProject.GetScreenSave("Screens/" + container.Name); glueScreen.NamedObjects.Add(newNamedObjectSave); } else if (container is ComponentSave) { var glueEntity = glueProject.GetEntitySave("Entities/" + container.Name); glueEntity.NamedObjects.Add(newNamedObjectSave); } AdjustNewlyCreatedGumInstance(container, instance); // this may be a copied object, so it may already have variables. Need to loop through and apply them // Do we need to look at all states not just the default? Doing just default for now: var state = container.DefaultState; var variablesToHandle = state.Variables.Where(item => item.Name.StartsWith($"{instance.Name}.")); foreach (var variable in variablesToHandle) { VariableSetLogic.Self.SetVariable(container, instance, variable.GetRootName(), null); } FileManager.XmlSerialize(glueProject, GluePluginState.Self.GlueProjectFilePath.StandardizedCaseSensitive); }
private void GenerateAnimationEnumerables(ElementSave elementSave, ICodeBlock currentBlock) { currentBlock.Line("#region State Animations"); ElementAnimationsSave animations = GetAnimationsFor(elementSave); if(animations != null) { foreach(var animation in animations.Animations) { GenerateEnumerableFor(elementSave, currentBlock, animation, AbsoluteOrRelative.Absolute); GenerateEnumerableFor(elementSave, currentBlock, animation, AbsoluteOrRelative.Relative); GenerateAnimationMember(elementSave, currentBlock, animation, AbsoluteOrRelative.Absolute); GenerateAnimationMember(elementSave, currentBlock, animation, AbsoluteOrRelative.Relative); } } currentBlock.Line("#endregion"); }
private static void FillWithDefaultRecursively(ElementSave element, StateSave stateSave) { foreach (var variable in element.DefaultState.Variables) { var alreadyExists = stateSave.Variables.Any(item => item.Name == variable.Name); if (!alreadyExists) { stateSave.Variables.Add(variable); } } if (!string.IsNullOrEmpty(element.BaseType)) { var baseElement = ObjectFinder.Self.GetElementSave(element.BaseType); if (baseElement != null) { FillWithDefaultRecursively(baseElement, stateSave); } } }
public TreeNode GetTreeNodeFor(ElementSave elementSave) { if (elementSave == null) { return null; } else if (elementSave is ScreenSave) { return GetTreeNodeFor(elementSave as ScreenSave); } else if (elementSave is ComponentSave) { return GetTreeNodeFor(elementSave as ComponentSave); } else if (elementSave is StandardElementSave) { return GetTreeNodeFor(elementSave as StandardElementSave); } return null; }
public static bool IsParentASibling(this InstanceSave instanceSave, List <ElementWithState> elementStack) { if (instanceSave == null) { throw new ArgumentException("InstanceSave must not be null"); } RecursiveVariableFinder rvf = new RecursiveVariableFinder(instanceSave, elementStack); string parent = rvf.GetValue <string>("Parent"); bool found = false; if (!string.IsNullOrEmpty(parent) && parent != AvailableInstancesConverter.ScreenBoundsName) { ElementSave parentElement = instanceSave.ParentContainer; found = parentElement.Instances.Any(item => item.Name == parent); } return(found); }
public static string MemberNameInCode(this VariableSave variableSave, ElementSave container, Dictionary<string, string> replacements) { var rootName = variableSave.GetRootName(); var objectName = variableSave.SourceObject; if (replacements.ContainsKey(rootName)) { rootName = replacements[rootName]; } else { rootName = rootName.Replace(" ", "_"); } ElementSave throwaway1; StateSaveCategory throwaway2; // recursive is false because we only want to prepend "Current" if it's not an exposed variable if (variableSave.IsState(container, out throwaway1, out throwaway2, recursive:false)) { if (rootName == "State") { rootName = "CurrentVariableState"; } else { rootName = "Current" + rootName; } } if (string.IsNullOrEmpty(objectName)) { return rootName; } else { objectName = InstanceNameInCode( objectName); return objectName + '.' + rootName; } }
public static object GetValueFromThisOrBase(this ElementSave element, string variable, bool forceDefault = false) { StateSave stateToPullFrom = element.DefaultState; #if GUM if (element == SelectedState.Self.SelectedElement && SelectedState.Self.SelectedStateSave != null && !forceDefault) { stateToPullFrom = SelectedState.Self.SelectedStateSave; } #endif VariableSave variableSave = stateToPullFrom.GetVariableRecursive(variable); if (variableSave != null) { return(variableSave.Value); } else { return(null); } }
public EventInstanceMember(ElementSave element, InstanceSave instance, EventSave eventSave) { mElementSave = element; mEventSave = eventSave; if (!string.IsNullOrEmpty(eventSave.ExposedAsName)) { this.Name = eventSave.ExposedAsName; } else { this.Name = eventSave.Name; } if (instance != null) { this.DisplayName = eventSave.GetRootName(); } this.CustomSetEvent += HandlePropertyChanged; this.CustomGetEvent += HandlePropertyGet; this.CustomGetTypeEvent += HandleGetType; }
private static void RemoveDuplicateVariables(ElementSave element) { foreach (var state in element.AllStates) { List <string> alreadyVisitedVariables = new List <string>(); for (int i = 0; i < state.Variables.Count; i++) { string variableName = state.Variables[i].Name; if (alreadyVisitedVariables.Contains(variableName)) { state.Variables.RemoveAt(i); i--; } else { alreadyVisitedVariables.Add(variableName); } } } }
public static void CreateGraphicalComponent(this GraphicalUiElement graphicalElement, ElementSave elementSave, SystemManagers systemManagers) { IRenderable containedObject = null; bool handled = InstanceSaveExtensionMethods.TryHandleAsBaseType(elementSave.Name, systemManagers, out containedObject); if (handled) { graphicalElement.SetContainedObject(containedObject); } else { if (elementSave != null && elementSave is ComponentSave) { var baseElement = Gum.Managers.ObjectFinder.Self.GetElementSave(elementSave.BaseType); if (baseElement != null) { graphicalElement.CreateGraphicalComponent(baseElement, systemManagers); } } } }
public static VariableListSave GetVariableListFromThisOrBase(this InstanceSave instance, ElementSave parentContainer, string variable) { ElementSave instanceBase = ObjectFinder.Self.GetElementSave(instance.BaseType); VariableListSave variableListSave = parentContainer.DefaultState.GetVariableListSave(instance.Name + "." + variable); if (variableListSave == null) { variableListSave = instanceBase.DefaultState.GetVariableListSave(variable); } if (variableListSave != null && variableListSave.ValueAsIList == null) { // This can happen if there is a tunneled variable that is null VariableListSave possibleVariable = instanceBase.DefaultState.GetVariableListSave(variable); if (possibleVariable != null && possibleVariable.ValueAsIList != null) { variableListSave = possibleVariable; } } return(variableListSave); }
public StateSaveCategory AddCategory(ElementSave elementToAddTo, string name) { if (elementToAddTo == null) { throw new Exception("Could not add category " + name + " because no element is selected"); } StateSaveCategory category = new StateSaveCategory(); category.Name = name; elementToAddTo.Categories.Add(category); string categoryName = category.Name + "State"; elementToAddTo.DefaultState.Variables.Add(new VariableSave() { Name = categoryName, Type = categoryName, Value = null #if GUM , CustomTypeConverter = new Gum.PropertyGridHelpers.Converters.AvailableStatesConverter(category.Name) #endif }); elementToAddTo.DefaultState.Variables.Sort((first, second) => first.Name.CompareTo(second.Name)); return category; }
public void CallAfterElementSave(ElementSave elementSave) { if (AfterElementSave != null) { AfterElementSave(elementSave); } }
public void CallBeforeElementSave(ElementSave elementSave) { if (BeforeElementSave != null) { BeforeElementSave(elementSave); } }
public static FilePath GetFullPathXmlFile(this ElementSave elementSave) { return(elementSave.GetFullPathXmlFile(elementSave.Name)); }
private static VariableSave TryGetVariableFromStatesOnInstance(InstanceSave instance, string variable, ElementSave instanceBase, IEnumerable <StateSave> statesToPullFrom) { string stateVariableName; StateSave fallbackState; List <StateSave> statesToLoopThrough; VariableSave foundVariableSave = null; foreach (var stateCategory in instanceBase.Categories) { stateVariableName = stateCategory.Name + "State"; fallbackState = null; statesToLoopThrough = stateCategory.States; foundVariableSave = TryGetVariableFromStateOnInstance(instance, variable, statesToPullFrom, stateVariableName, fallbackState, statesToLoopThrough); } if (foundVariableSave == null) { stateVariableName = "State"; fallbackState = instanceBase.DefaultState; statesToLoopThrough = instanceBase.States; foundVariableSave = TryGetVariableFromStateOnInstance(instance, variable, statesToPullFrom, stateVariableName, fallbackState, statesToLoopThrough); } return(foundVariableSave); }
public void CallInstanceSelected(ElementSave elementSave, InstanceSave instance) { if (InstanceSelected != null) { InstanceSelected(elementSave, instance); } }
public void ReactToRenamed(ElementSave element, InstanceSave instance, string oldName) { if (instance == null) { List<ElementReference> listToSearch = null; if (element is ScreenSave) { listToSearch = ScreenReferences; } else if (element is ComponentSave) { listToSearch = ComponentReferences; } else if (element is StandardElementSave) { listToSearch = StandardElementReferences; } foreach (ElementReference reference in listToSearch) { if (reference.Name == oldName) { reference.Name = element.Name; } } } }
private void GenerateInterpolateTo(ElementSave elementSave, ICodeBlock codeBlock, IEnumerable<StateSave> states, string enumName) { string qualifiedEnum = GueDerivingClassCodeGenerator.GueRuntimeNamespace + "." + FlatRedBall.IO.FileManager.RemovePath( elementSave.Name) + "Runtime." + enumName; // Make this thing return the Tweener so the uer can customize it string parameters = qualifiedEnum + " fromState," + qualifiedEnum + " toState, double secondsToTake, " + "FlatRedBall.Glue.StateInterpolation.InterpolationType interpolationType, FlatRedBall.Glue.StateInterpolation.Easing easing, object owner = null"; codeBlock = codeBlock.Function("public FlatRedBall.Glue.StateInterpolation.Tweener", "InterpolateTo", parameters); { codeBlock.Line("FlatRedBall.Glue.StateInterpolation.Tweener tweener = new FlatRedBall.Glue.StateInterpolation.Tweener(from:0, to:1, duration:(float)secondsToTake, type:interpolationType, easing:easing );"); codeBlock.If("owner == null") .Line("tweener.Owner = this;") .End() .Else() .Line("tweener.Owner = owner;"); codeBlock.Line("tweener.PositionChanged = newPosition => this.InterpolateBetween(fromState, toState, newPosition);"); codeBlock.Line("tweener.Start();"); codeBlock.Line("StateInterpolationPlugin.TweenerManager.Self.Add(tweener);"); codeBlock.Line("return tweener;"); } }
public void CallExport(ElementSave elementSave) { if (Export != null) { Export(elementSave); } }
public static string GetFullPathXmlFile(this ElementSave instance) { return(instance.GetFullPathXmlFile(instance.Name)); }
private bool ContainsKey(Dictionary<VariableSave, InterpolationCharacteristic> dictionary, string member, ElementSave container) { foreach (KeyValuePair<VariableSave, InterpolationCharacteristic> kvp in dictionary) { if (kvp.Key.MemberNameInCode(container, mVariableNamesToReplaceForStates) == member) { return true; } } return false; }
private static bool AddAndModifyVariablesAccordingToDefault(ElementSave elementSave, StateSave defaultState) { bool wasModified = false; // Use States and not AllStates because we want to make sure we // have a default state. if (elementSave.States.Count == 0 && defaultState != null) { StateSave stateToAdd = defaultState.Clone(); elementSave.States.Add(stateToAdd); wasModified = true; } else if (elementSave.States.Count != 0 && defaultState != null) { // Replacing the default state: // Update March 16, 2012 // Used to replace but realized // it's better to not replace but // instead add variables that are not // already there. That way when the user // switches types the old information isn't // lost. //elementSave.States[0] = replacement; StateSave stateForNewType = defaultState.Clone(); foreach (VariableSave variableSave in stateForNewType.Variables) { VariableSave existingVariable = elementSave.DefaultState.GetVariableSave(variableSave.Name); if (existingVariable == null) { wasModified = true; elementSave.DefaultState.Variables.Add(variableSave.Clone()); } else { // All of these properties are only relevant to the // editor so we don't want to mark the object as modified // when these properties are set. existingVariable.Category = variableSave.Category; #if !WINDOWS_8 && !UWP existingVariable.CustomTypeConverter = variableSave.CustomTypeConverter; #endif existingVariable.ExcludedValuesForEnum.Clear(); existingVariable.ExcludedValuesForEnum.AddRange(variableSave.ExcludedValuesForEnum); // let's fix any values that may be incorrectly set from types if (existingVariable.Type == "float" && existingVariable.Value != null && (existingVariable.Value is float) == false) { float asFloat = 0.0f; try { asFloat = (float)System.Convert.ChangeType(existingVariable.Value, typeof(float)); } catch { // do nothing, we'll fall back to 0 } existingVariable.Value = asFloat; wasModified = true; } } } // We also need to add any VariableListSaves here foreach (VariableListSave variableList in stateForNewType.VariableLists) { VariableListSave existingList = elementSave.DefaultState.GetVariableListSave(variableList.Name); if (existingList == null) { wasModified = true; // this type doesn't have this list yet, so let's add it elementSave.DefaultState.VariableLists.Add(variableList.Clone()); } else { // See the VariableSave section on why we don't set // wasModified = true here existingList.Category = variableList.Category; } } foreach (var stateSaveCategory in elementSave.Categories) { VariableSave foundVariable = elementSave.DefaultState.Variables.FirstOrDefault(item => item.Name == stateSaveCategory.Name + "State"); if (foundVariable == null) { elementSave.DefaultState.Variables.Add(new VariableSave() { Name = stateSaveCategory.Name + "State", Type = "string", Value = null #if GUM , CustomTypeConverter = new Gum.PropertyGridHelpers.Converters.AvailableStatesConverter(stateSaveCategory.Name) #endif }); } else { #if GUM foundVariable.CustomTypeConverter = new Gum.PropertyGridHelpers.Converters.AvailableStatesConverter(stateSaveCategory.Name); #endif } } VariableSaveSorter vss = new VariableSaveSorter(); vss.ListOrderToMatch = defaultState.Variables; elementSave.DefaultState.Variables.Sort(vss); } else { // Let's give it an empty state so that it doesn't cause runtime problems // Nevermind, this causes problelms in Gum, and it should be okay to pass a null state here //elementSave.States.Add(new StateSave()); } return(wasModified); }
public ElementSave Clone() { ElementSave cloned = FileManager.CloneSaveObject(this); return(cloned); }
public static bool IsState(this VariableSave variableSave, ElementSave container, out ElementSave categoryContainer, out StateSaveCategory category, bool recursive = true) { category = null; categoryContainer = null; var variableName = variableSave.GetRootName(); ///////////////Early Out if (variableName.EndsWith("State") == false && string.IsNullOrEmpty(variableSave.SourceObject)) { return(false); } /////////////End early out // what about uncategorized string categoryName = null; if (variableName.EndsWith("State")) { categoryName = variableName.Substring(0, variableName.Length - "State".Length); } if (string.IsNullOrEmpty(variableSave.SourceObject) == false) { var instanceSave = container.GetInstance(variableSave.SourceObject); if (instanceSave != null) { var element = ObjectFinder.Self.GetElementSave(instanceSave.BaseType); if (element != null) { // let's try going recursively: var subVariable = element.DefaultState.Variables.FirstOrDefault(item => item.ExposedAsName == variableSave.GetRootName()); if (subVariable != null && recursive) { return(subVariable.IsState(element, out categoryContainer, out category)); } else { if (variableName == "State") { categoryContainer = element; category = null; return(true); } else { category = element.GetStateSaveCategoryRecursively(categoryName, out categoryContainer); return(category != null); } } } } } else { if (variableName == "State") { return(true); } else { category = container.GetStateSaveCategoryRecursively(categoryName, out categoryContainer); return(category != null); } } return(false); }
public void CallElementRename(ElementSave elementSave, string oldName) { if (ElementRename != null) { ElementRename(elementSave, oldName); } }
public static VariableSave GetVariableFromThisOrBase(this InstanceSave instance, List <ElementWithState> elementStack, RecursiveVariableFinder rvf, string variable, bool forceDefault, bool onlyIfSetsValue) { ElementSave instanceBase = ObjectFinder.Self.GetElementSave(instance.BaseType); List <StateSave> statesToPullFrom; StateSave defaultState; GetStatesToUse(instance, elementStack, forceDefault, instanceBase, rvf, out statesToPullFrom, out defaultState); VariableSave variableSave = null; // See if the variable is set by the container of the instance: foreach (var stateToPullFrom in statesToPullFrom) { var possibleVariable = stateToPullFrom.GetVariableSave(instance.Name + "." + variable); if (possibleVariable != null) { variableSave = possibleVariable; } } // non-default states can override the default state, so first // let's see if the selected state is non-default and has a value // for a given variable. If not, we'll fall back to the default. if ((variableSave == null || (onlyIfSetsValue && variableSave.SetsValue == false)) && !statesToPullFrom.Contains(defaultState)) { variableSave = defaultState.GetVariableSave(instance.Name + "." + variable); } // Still haven't found a variable yet, so look in the instanceBase if one exists if ((variableSave == null || (onlyIfSetsValue && (variableSave.SetsValue == false || variableSave.Value == null))) && instanceBase != null) { VariableSave foundVariableSave = TryGetVariableFromStatesOnInstance(instance, variable, instanceBase, statesToPullFrom); if (foundVariableSave != null) { variableSave = foundVariableSave; } } // I don't think we have to do this because we're going to copy over // the variables to all components on load. //if (variableSave == null && instanceBase != null && instanceBase is ComponentSave) //{ // variableSave = StandardElementsManager.Self.DefaultStates["Component"].GetVariableSave(variable); //} if (variableSave != null && variableSave.Value == null && instanceBase != null && onlyIfSetsValue) { // This can happen if there is a tunneled variable that is null VariableSave possibleVariable = instanceBase.DefaultState.GetVariableSave(variable); if (possibleVariable != null && possibleVariable.Value != null && (!onlyIfSetsValue || possibleVariable.SetsValue)) { variableSave = possibleVariable; } else if (!string.IsNullOrEmpty(instanceBase.BaseType)) { ElementSave element = ObjectFinder.Self.GetElementSave(instanceBase.BaseType); if (element != null) { variableSave = element.GetVariableFromThisOrBase(variable, forceDefault); } } } return(variableSave); }
public void CallElementSelected(ElementSave element) { if (ElementSelected != null) { ElementSelected(element); } }
private GraphicalUiElement CreateIpsoForElement(ElementSave elementSave) { GraphicalUiElement rootIpso = null; bool isScreen = elementSave is ScreenSave; rootIpso = new GraphicalUiElement(); rootIpso.Tag = elementSave; mGraphicalElements.Add(rootIpso); rootIpso.ElementSave = elementSave; if (isScreen == false) { // We used to not add the IPSO for the root element to the list of graphical elements // and this prevented selection. I'm not sure if this was intentionally left out or not // but I think it should be here mGraphicalElements.Add(rootIpso); rootIpso.CreateGraphicalComponent(elementSave, null); rootIpso.Component.Name = elementSave.Name; rootIpso.Component.Tag = elementSave; RecursiveVariableFinder rvf = new DataTypes.RecursiveVariableFinder(SelectedState.Self.SelectedStateSaveOrDefault); string guide = rvf.GetValue<string>("Guide"); SetGuideParent(null, rootIpso, guide, true); } foreach(var exposedVariable in elementSave.DefaultState.Variables.Where(item=> !string.IsNullOrEmpty(item.ExposedAsName) )) { rootIpso.AddExposedVariable(exposedVariable.ExposedAsName, exposedVariable.Name); } List<GraphicalUiElement> newlyAdded = new List<GraphicalUiElement>(); List<ElementWithState> elementStack = new List<ElementWithState>(); ElementWithState elementWithState = new ElementWithState(elementSave); if (elementSave == SelectedState.Self.SelectedElement) { if (SelectedState.Self.SelectedStateSave != null) { elementWithState.StateName = SelectedState.Self.SelectedStateSave.Name; } else { elementWithState.StateName = "Default"; } } elementStack.Add(elementWithState); // parallel screws up the ordering of objects, so we'll do it on the primary thread for now // and parallelize it later: //Parallel.ForEach(elementSave.Instances, instance => foreach (var instance in elementSave.Instances) { GraphicalUiElement child = CreateRepresentationForInstance(instance, null, elementStack, rootIpso); if (child == null) { // This can occur // if an instance references // a component that doesn't exist. // I don't think we need to do anything // here. } else { newlyAdded.Add(child); mGraphicalElements.Add(child); } } SetUpParentRelationship(newlyAdded, elementStack, elementSave.Instances); //); elementStack.Remove(elementStack.FirstOrDefault(item => item.Element == elementSave)); rootIpso.SetStatesAndCategoriesRecursively(elementSave); // First we need to the default state (and do so recursively) rootIpso.SetVariablesRecursively(elementSave, elementSave.DefaultState); // then we override it with the current state if one is set: if (SelectedState.Self.SelectedStateSave != elementSave.DefaultState && SelectedState.Self.SelectedStateSave != null) { var state = SelectedState.Self.SelectedStateSave; rootIpso.SetVariablesTopLevel(elementSave, state); } // I think this has to be *after* we set varaibles because that's where clipping gets set if (rootIpso != null) { rootIpso.AddToManagers(); if (rootIpso.ElementSave is ScreenSave) { // If it's a screen and it hasn't been added yet, we need to add it. foreach (var item in rootIpso.ContainedElements.Where(candidate=>candidate.Managers == null)) { item.AddToManagers(); } } } return rootIpso; }
public void CallInstanceDelete(ElementSave elementSave, InstanceSave instance) { if (InstanceDelete != null) { InstanceDelete(elementSave, instance); } }
public static ElementAnimationsViewModel FromSave(ElementAnimationsSave save, Gum.DataTypes.ElementSave element) { ElementAnimationsViewModel toReturn = new ElementAnimationsViewModel(); foreach (var animation in save.Animations) { var vm = AnimationViewModel.FromSave(animation, element); toReturn.Animations.Add(vm); } return(toReturn); }
public void CallVariableSet(ElementSave parentElement, InstanceSave instance, string changedMember, object oldValue) { if (VariableSet != null) { VariableSet(parentElement, instance, changedMember, oldValue); } }
private static void GetStatesToUse(InstanceSave instance, List <ElementWithState> elementStack, bool forceDefault, ElementSave instanceBase, RecursiveVariableFinder rvf, out List <StateSave> statesToPullFrom, out StateSave defaultState) { statesToPullFrom = null; defaultState = null; #if GUM if (SelectedState.Self.SelectedElement != null) { statesToPullFrom = new List <StateSave> { SelectedState.Self.SelectedElement.DefaultState }; defaultState = SelectedState.Self.SelectedElement.DefaultState; } #endif if (elementStack.Count != 0) { if (elementStack.Last().Element == null) { throw new InvalidOperationException("The ElementStack contains an ElementWithState with no Element"); } statesToPullFrom = elementStack.Last().AllStates.ToList(); defaultState = elementStack.Last().Element.DefaultState; } #if GUM if (elementStack.Count != 0 && elementStack.Last().Element == SelectedState.Self.SelectedElement && SelectedState.Self.SelectedStateSave != null && !forceDefault) { statesToPullFrom = new List <StateSave> { SelectedState.Self.SelectedStateSave }; } #endif }
public static bool IsState(this VariableSave variableSave, ElementSave container, out ElementSave categoryContainer, out StateSaveCategory category, bool recursive = true) { category = null; categoryContainer = null; var variableName = variableSave.GetRootName(); // This is called a lot so let's try to make it faster: bool endsWithState = variableName.Length >= 5 && variableName[variableName.Length - 1] == 'e' && variableName[variableName.Length - 2] == 't' && variableName[variableName.Length - 3] == 'a' && variableName[variableName.Length - 4] == 't' && variableName[variableName.Length - 5] == 'S'; ///////////////Early Out if (endsWithState == false && string.IsNullOrEmpty(variableSave.SourceObject)) { return(false); } /////////////End early out // what about uncategorized string categoryName = null; if (endsWithState) { categoryName = variableName.Substring(0, variableName.Length - "State".Length); } if (string.IsNullOrEmpty(variableSave.SourceObject) == false) { var instanceSave = container.GetInstance(variableSave.SourceObject); if (instanceSave != null) { var element = ObjectFinder.Self.GetElementSave(instanceSave.BaseType); if (element != null) { var defaultState = element.DefaultState; if (defaultState == null) { throw new NullReferenceException( $"Could not find a default state for {element} - this happens if the element wasn't initialized, or if its file was not loaded properly."); } // let's try going recursively: var subVariable = element.DefaultState.Variables.FirstOrDefault(item => item.ExposedAsName == variableSave.GetRootName()); if (subVariable != null && recursive) { return(subVariable.IsState(element, out categoryContainer, out category)); } else { if (variableName == "State") { categoryContainer = element; category = null; return(true); } else { category = element.GetStateSaveCategoryRecursively(categoryName, out categoryContainer); return(category != null); } } } } } else { if (variableName == "State") { return(true); } else { category = container.GetStateSaveCategoryRecursively(categoryName, out categoryContainer); return(category != null); } } return(false); }
/// <summary> /// Generates and saves the code for the passed Gum ElementSave (both generated and custom code template), /// but does not add the resulting .cs files to the VisualStudio project. /// </summary> /// <param name="element">The element to generate.</param> /// <returns>Information about what was generated and saved.</returns> public GenerationResult GenerateCodeFor(Gum.DataTypes.ElementSave element, CodeGenerationSavingBehavior savingBehavior = CodeGenerationSavingBehavior.AlwaysSave) { GenerationResult resultToReturn = new GenerationResult(); if (element == null) { throw new ArgumentNullException(nameof(element)); } string directoryToSave = GumRuntimesFolder; string generatedCode = mGueDerivingClassCodeGenerator.GenerateCodeFor(element); FilePath generatedSaveLocation = directoryToSave + element.Name + "Runtime.Generated.cs"; if (savingBehavior == CodeGenerationSavingBehavior.AlwaysSave) { resultToReturn.DidSaveGenerated = true; } else // if(savingBehavior == CodeGenerationSavingBehavior.SaveIfGeneratedDiffers) { // We only want to save this file if what we've just generated is different than what is already on disk: if (!generatedSaveLocation.Exists()) { resultToReturn.DidSaveGenerated = true; } else { var existingText = File.ReadAllText(generatedSaveLocation.FullPath); resultToReturn.DidSaveGenerated = existingText != generatedCode; } } string customCodeSaveLocation = directoryToSave + element.Name + "Runtime.cs"; // If it doesn't exist, overwrite it. If it does exist, don't overwrite it - we might lose // custom code. if (!System.IO.File.Exists(customCodeSaveLocation) && // Standard elements don't have CustomInit (element is StandardElementSave) == false) { resultToReturn.DidSaveCustom = true; } if (string.IsNullOrEmpty(generatedCode)) { resultToReturn.DidSaveCustom = false; resultToReturn.DidSaveGenerated = false; } if (resultToReturn.DidSaveGenerated) { // in case directory doesn't exist var directory = generatedSaveLocation.GetDirectoryContainingThis(); System.IO.Directory.CreateDirectory(directory.FullPath); GlueCommands.Self.TryMultipleTimes(() => System.IO.File.WriteAllText(generatedSaveLocation.FullPath, generatedCode)); } if (resultToReturn.DidSaveCustom) { var customCode = CustomCodeGenerator.Self.GetCustomCodeTemplateCode(element); GlueCommands.Self.TryMultipleTimes(() => System.IO.File.WriteAllText(customCodeSaveLocation, customCode)); } return(resultToReturn); }
public static TypeConverter GetTypeConverter(this VariableSave variableSave, ElementSave container = null) { ElementSave categoryContainer; StateSaveCategory category; if (variableSave.CustomTypeConverter != null) { return(variableSave.CustomTypeConverter); } else if (variableSave.IsFont) { return(new FontTypeConverter()); } else if (variableSave.Name == "Guide") { AvailableGuidesTypeConverter availableGuidesTypeConverter = new AvailableGuidesTypeConverter(); availableGuidesTypeConverter.GumProjectSave = ObjectFinder.Self.GumProjectSave; availableGuidesTypeConverter.ShowNewGuide = false; return(availableGuidesTypeConverter); } else if (variableSave.IsState(container, out categoryContainer, out category)) { string categoryName = null; if (category != null) { categoryName = category.Name; } AvailableStatesConverter converter = new AvailableStatesConverter(categoryName); converter.ElementSave = categoryContainer; return(converter); } else { // We should see if it's an exposed variable, and if so, let's look to the source object's type converters bool foundInRoot = false; if (!string.IsNullOrEmpty(variableSave.SourceObject) && container != null) { InstanceSave instance = container.GetInstance(variableSave.SourceObject); if (instance != null) { // see if the instance has a variable var foundElementSave = ObjectFinder.Self.GetRootStandardElementSave(instance); if (foundElementSave != null) { VariableSave rootVariableSave = foundElementSave.DefaultState.GetVariableSave(variableSave.GetRootName()); if (rootVariableSave != null) { return(rootVariableSave.GetTypeConverter((ElementSave)null)); } } } } } Type type = variableSave.GetRuntimeType(); return(variableSave.GetTypeConverter(type)); }
public static StateSaveCategory GetStateSaveCategoryRecursively(this ElementSave element, string categoryName) { ElementSave throwaway; return(GetStateSaveCategoryRecursively(element, categoryName, out throwaway)); }