ViewVariables can now edit Enums. The input field will accept either an enumeration label or a numerical value.

This commit is contained in:
Acruid
2019-08-22 13:43:00 -07:00
parent 97d8f7d936
commit 19d7cd4455
3 changed files with 99 additions and 0 deletions

View File

@@ -0,0 +1,62 @@
using System;
using System.Globalization;
using System.Reflection;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Shared.Maths;
using Robust.Shared.Utility;
namespace Robust.Client.ViewVariables.Editors
{
class ViewVariablesPropertyEditorEnum : ViewVariablesPropertyEditor
{
protected override Control MakeUI(object value)
{
DebugTools.Assert(value.GetType().IsEnum);
var enumVal = (Enum)value;
var enumType = value.GetType();
var enumStorageType = enumType.GetEnumUnderlyingType();
var hBox = new HBoxContainer
{
CustomMinimumSize = new Vector2(200, 0)
};
var lineEdit = new LineEdit
{
Text = enumVal.ToString(),
Editable = !ReadOnly,
SizeFlagsHorizontal = Control.SizeFlags.FillExpand
};
if (!ReadOnly)
{
lineEdit.OnTextEntered += e =>
{
var parseSig = new []{typeof(string), typeof(NumberStyles), typeof(CultureInfo), enumStorageType.MakeByRefType()};
var parseMethod = enumStorageType.GetMethod("TryParse", parseSig);
DebugTools.AssertNotNull(parseMethod);
var parameters = new object[] {e.Text, NumberStyles.Integer, CultureInfo.InvariantCulture, null};
var parseWorked = (bool)parseMethod.Invoke(null, parameters);
if (parseWorked) // textbox was the underlying type
{
DebugTools.AssertNotNull(parameters[3]);
ValueChanged(parameters[3]);
}
else if(EnumHelper.TryParse(enumType, e.Text, true, out var enumValue))
{
var underlyingVal = Convert.ChangeType(enumValue, enumStorageType);
ValueChanged(underlyingVal);
}
};
}
hBox.AddChild(lineEdit);
return hBox;
}
//TODO: https://github.com/dotnet/corefx/issues/692
}
}

View File

@@ -118,6 +118,11 @@ namespace Robust.Client.ViewVariables
return new ViewVariablesPropertyEditorString();
}
if (type.IsEnum)
{
return new ViewVariablesPropertyEditorEnum();
}
if (type == typeof(Vector2))
{
return new ViewVariablesPropertyEditorVector2(intVec: false);

View File

@@ -0,0 +1,32 @@
using System;
using System.Linq;
using System.Reflection;
namespace Robust.Shared.Utility
{
public static class EnumHelper
{
//TODO: This function is obsloete in .Net Core 3 https://github.com/dotnet/corefx/issues/692
//Credit: https://justinmchase.com/2010/07/09/non-generic-enumtryparse/
static MethodInfo enumTryParse;
static EnumHelper()
{
enumTryParse = typeof(Enum)
.GetMethods(BindingFlags.Public | BindingFlags.Static)
.First(m => m.Name == "TryParse" && m.GetParameters().Length == 3);
}
public static bool TryParse(Type enumType, string value, bool ignoreCase, out object enumValue)
{
var genericEnumTryParse = enumTryParse.MakeGenericMethod(enumType);
object[] args = { value, ignoreCase, Enum.ToObject(enumType, 0) };
var success = (bool)genericEnumTryParse.Invoke(null, args);
enumValue = args[2];
return success;
}
}
}